1 //===--- Sema.h - Semantic Analysis & AST Building --------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the Sema class, which performs semantic analysis and
13 //===----------------------------------------------------------------------===//
15 #ifndef LLVM_CLANG_SEMA_SEMA_H
16 #define LLVM_CLANG_SEMA_SEMA_H
18 #include "clang/AST/Attr.h"
19 #include "clang/AST/Availability.h"
20 #include "clang/AST/DeclarationName.h"
21 #include "clang/AST/DeclTemplate.h"
22 #include "clang/AST/Expr.h"
23 #include "clang/AST/ExprObjC.h"
24 #include "clang/AST/ExternalASTSource.h"
25 #include "clang/AST/LocInfoType.h"
26 #include "clang/AST/MangleNumberingContext.h"
27 #include "clang/AST/NSAPI.h"
28 #include "clang/AST/PrettyPrinter.h"
29 #include "clang/AST/StmtCXX.h"
30 #include "clang/AST/TypeLoc.h"
31 #include "clang/AST/TypeOrdering.h"
32 #include "clang/Basic/ExpressionTraits.h"
33 #include "clang/Basic/LangOptions.h"
34 #include "clang/Basic/Module.h"
35 #include "clang/Basic/OpenMPKinds.h"
36 #include "clang/Basic/PragmaKinds.h"
37 #include "clang/Basic/Specifiers.h"
38 #include "clang/Basic/TemplateKinds.h"
39 #include "clang/Basic/TypeTraits.h"
40 #include "clang/Sema/AnalysisBasedWarnings.h"
41 #include "clang/Sema/CleanupInfo.h"
42 #include "clang/Sema/DeclSpec.h"
43 #include "clang/Sema/ExternalSemaSource.h"
44 #include "clang/Sema/IdentifierResolver.h"
45 #include "clang/Sema/ObjCMethodList.h"
46 #include "clang/Sema/Ownership.h"
47 #include "clang/Sema/Scope.h"
48 #include "clang/Sema/ScopeInfo.h"
49 #include "clang/Sema/TypoCorrection.h"
50 #include "clang/Sema/Weak.h"
51 #include "llvm/ADT/ArrayRef.h"
52 #include "llvm/ADT/Optional.h"
53 #include "llvm/ADT/SetVector.h"
54 #include "llvm/ADT/SmallPtrSet.h"
55 #include "llvm/ADT/SmallVector.h"
56 #include "llvm/ADT/TinyPtrVector.h"
64 template <typename ValueT> struct DenseMapInfo;
65 template <typename ValueT, typename ValueInfoT> class DenseSet;
67 class InlineAsmIdentifierInfo;
74 class ASTMutationListener;
84 class CXXBindTemporaryExpr;
85 typedef SmallVector<CXXBaseSpecifier*, 4> CXXCastPath;
86 class CXXConstructorDecl;
87 class CXXConversionDecl;
89 class CXXDestructorDecl;
90 class CXXFieldCollector;
91 class CXXMemberCallExpr;
97 class ClassTemplateDecl;
98 class ClassTemplatePartialSpecializationDecl;
99 class ClassTemplateSpecializationDecl;
100 class VarTemplatePartialSpecializationDecl;
101 class CodeCompleteConsumer;
102 class CodeCompletionAllocator;
103 class CodeCompletionTUInfo;
104 class CodeCompletionResult;
105 class CoroutineBodyStmt;
107 class DeclAccessPair;
110 class DeclaratorDecl;
111 class DeducedTemplateArgument;
112 class DependentDiagnostic;
113 class DesignatedInitExpr;
116 class EnumConstantDecl;
122 class FunctionProtoType;
123 class FunctionTemplateDecl;
124 class ImplicitConversionSequence;
125 typedef MutableArrayRef<ImplicitConversionSequence> ConversionSequenceList;
127 class InitializationKind;
128 class InitializationSequence;
129 class InitializedEntity;
130 class IntegerLiteral;
134 class LocalInstantiationScope;
137 typedef ArrayRef<std::pair<IdentifierInfo *, SourceLocation>> ModuleIdPath;
139 class MultiLevelTemplateArgumentList;
141 class ObjCCategoryDecl;
142 class ObjCCategoryImplDecl;
143 class ObjCCompatibleAliasDecl;
144 class ObjCContainerDecl;
146 class ObjCImplementationDecl;
147 class ObjCInterfaceDecl;
149 template <class T> class ObjCList;
150 class ObjCMessageExpr;
151 class ObjCMethodDecl;
152 class ObjCPropertyDecl;
153 class ObjCProtocolDecl;
154 class OMPThreadPrivateDecl;
155 class OMPDeclareReductionDecl;
156 class OMPDeclareSimdDecl;
158 struct OverloadCandidate;
159 class OverloadCandidateSet;
164 class PseudoDestructorTypeStorage;
165 class PseudoObjectExpr;
167 class StandardConversionSequence;
171 class TemplateArgument;
172 class TemplateArgumentList;
173 class TemplateArgumentLoc;
175 class TemplateParameterList;
176 class TemplatePartialOrderingContext;
177 class TemplateTemplateParmDecl;
181 class TypedefNameDecl;
183 class TypoCorrectionConsumer;
185 class UnresolvedLookupExpr;
186 class UnresolvedMemberExpr;
187 class UnresolvedSetImpl;
188 class UnresolvedSetIterator;
190 class UsingShadowDecl;
193 class VarTemplateSpecializationDecl;
194 class VisibilityAttr;
195 class VisibleDeclConsumer;
196 class IndirectFieldDecl;
197 struct DeductionFailureInfo;
198 class TemplateSpecCandidateSet;
201 class AccessedEntity;
202 class BlockScopeInfo;
203 class CapturedRegionScopeInfo;
204 class CapturingScopeInfo;
205 class CompoundScopeInfo;
206 class DelayedDiagnostic;
207 class DelayedDiagnosticPool;
208 class FunctionScopeInfo;
209 class LambdaScopeInfo;
210 class PossiblyUnreachableDiag;
211 class TemplateDeductionInfo;
214 namespace threadSafety {
216 void threadSafetyCleanup(BeforeSet* Cache);
219 // FIXME: No way to easily map from TemplateTypeParmTypes to
220 // TemplateTypeParmDecls, so we have this horrible PointerUnion.
221 typedef std::pair<llvm::PointerUnion<const TemplateTypeParmType*, NamedDecl*>,
222 SourceLocation> UnexpandedParameterPack;
224 /// Describes whether we've seen any nullability information for the given
226 struct FileNullability {
227 /// The first pointer declarator (of any pointer kind) in the file that does
228 /// not have a corresponding nullability annotation.
229 SourceLocation PointerLoc;
231 /// Which kind of pointer declarator we saw.
234 /// Whether we saw any type nullability annotations in the given file.
235 bool SawTypeNullability = false;
238 /// A mapping from file IDs to a record of whether we've seen nullability
239 /// information in that file.
240 class FileNullabilityMap {
241 /// A mapping from file IDs to the nullability information for each file ID.
242 llvm::DenseMap<FileID, FileNullability> Map;
244 /// A single-element cache based on the file ID.
247 FileNullability Nullability;
251 FileNullability &operator[](FileID file) {
252 // Check the single-element cache.
253 if (file == Cache.File)
254 return Cache.Nullability;
256 // It's not in the single-element cache; flush the cache if we have one.
257 if (!Cache.File.isInvalid()) {
258 Map[Cache.File] = Cache.Nullability;
261 // Pull this entry into the cache.
263 Cache.Nullability = Map[file];
264 return Cache.Nullability;
268 /// Sema - This implements semantic analysis and AST building for C.
270 Sema(const Sema &) = delete;
271 void operator=(const Sema &) = delete;
273 ///\brief Source of additional semantic information.
274 ExternalSemaSource *ExternalSource;
276 ///\brief Whether Sema has generated a multiplexer and has to delete it.
277 bool isMultiplexExternalSource;
279 static bool mightHaveNonExternalLinkage(const DeclaratorDecl *FD);
281 bool isVisibleSlow(const NamedDecl *D);
283 bool shouldLinkPossiblyHiddenDecl(const NamedDecl *Old,
284 const NamedDecl *New) {
285 // We are about to link these. It is now safe to compute the linkage of
286 // the new decl. If the new decl has external linkage, we will
287 // link it with the hidden decl (which also has external linkage) and
288 // it will keep having external linkage. If it has internal linkage, we
289 // will not link it. Since it has no previous decls, it will remain
290 // with internal linkage.
291 return isVisible(Old) || New->isExternallyVisible();
293 bool shouldLinkPossiblyHiddenDecl(LookupResult &Old, const NamedDecl *New);
296 typedef OpaquePtr<DeclGroupRef> DeclGroupPtrTy;
297 typedef OpaquePtr<TemplateName> TemplateTy;
298 typedef OpaquePtr<QualType> TypeTy;
300 OpenCLOptions OpenCLFeatures;
301 FPOptions FPFeatures;
303 const LangOptions &LangOpts;
306 ASTConsumer &Consumer;
307 DiagnosticsEngine &Diags;
308 SourceManager &SourceMgr;
310 /// \brief Flag indicating whether or not to collect detailed statistics.
313 /// \brief Code-completion consumer.
314 CodeCompleteConsumer *CodeCompleter;
316 /// CurContext - This is the current declaration context of parsing.
317 DeclContext *CurContext;
319 /// \brief Generally null except when we temporarily switch decl contexts,
320 /// like in \see ActOnObjCTemporaryExitContainerContext.
321 DeclContext *OriginalLexicalContext;
323 /// VAListTagName - The declaration name corresponding to __va_list_tag.
324 /// This is used as part of a hack to omit that class from ADL results.
325 DeclarationName VAListTagName;
327 bool MSStructPragmaOn; // True when \#pragma ms_struct on
329 /// \brief Controls member pointer representation format under the MS ABI.
330 LangOptions::PragmaMSPointersToMembersKind
331 MSPointerToMemberRepresentationMethod;
333 /// Stack of active SEH __finally scopes. Can be empty.
334 SmallVector<Scope*, 2> CurrentSEHFinally;
336 /// \brief Source location for newly created implicit MSInheritanceAttrs
337 SourceLocation ImplicitMSInheritanceAttrLoc;
339 /// \brief pragma clang section kind
340 enum PragmaClangSectionKind {
348 enum PragmaClangSectionAction {
353 struct PragmaClangSection {
354 std::string SectionName;
356 SourceLocation PragmaLocation;
358 void Act(SourceLocation PragmaLocation,
359 PragmaClangSectionAction Action,
360 StringLiteral* Name);
363 PragmaClangSection PragmaClangBSSSection;
364 PragmaClangSection PragmaClangDataSection;
365 PragmaClangSection PragmaClangRodataSection;
366 PragmaClangSection PragmaClangTextSection;
368 enum PragmaMsStackAction {
369 PSK_Reset = 0x0, // #pragma ()
370 PSK_Set = 0x1, // #pragma (value)
371 PSK_Push = 0x2, // #pragma (push[, id])
372 PSK_Pop = 0x4, // #pragma (pop[, id])
373 PSK_Show = 0x8, // #pragma (show) -- only for "pack"!
374 PSK_Push_Set = PSK_Push | PSK_Set, // #pragma (push[, id], value)
375 PSK_Pop_Set = PSK_Pop | PSK_Set, // #pragma (pop[, id], value)
378 template<typename ValueType>
381 llvm::StringRef StackSlotLabel;
383 SourceLocation PragmaLocation;
384 Slot(llvm::StringRef StackSlotLabel,
386 SourceLocation PragmaLocation)
387 : StackSlotLabel(StackSlotLabel), Value(Value),
388 PragmaLocation(PragmaLocation) {}
390 void Act(SourceLocation PragmaLocation,
391 PragmaMsStackAction Action,
392 llvm::StringRef StackSlotLabel,
395 // MSVC seems to add artificial slots to #pragma stacks on entering a C++
396 // method body to restore the stacks on exit, so it works like this:
399 // #pragma <name>(push, InternalPragmaSlot, <current_pragma_value>)
401 // #pragma <name>(pop, InternalPragmaSlot)
404 // It works even with #pragma vtordisp, although MSVC doesn't support
405 // #pragma vtordisp(push [, id], n)
408 // Push / pop a named sentinel slot.
409 void SentinelAction(PragmaMsStackAction Action, StringRef Label) {
410 assert((Action == PSK_Push || Action == PSK_Pop) &&
411 "Can only push / pop #pragma stack sentinels!");
412 Act(CurrentPragmaLocation, Action, Label, CurrentValue);
416 explicit PragmaStack(const ValueType &Default)
417 : DefaultValue(Default), CurrentValue(Default) {}
419 SmallVector<Slot, 2> Stack;
420 ValueType DefaultValue; // Value used for PSK_Reset action.
421 ValueType CurrentValue;
422 SourceLocation CurrentPragmaLocation;
424 // FIXME: We should serialize / deserialize these if they occur in a PCH (but
425 // we shouldn't do so if they're in a module).
427 /// \brief Whether to insert vtordisps prior to virtual bases in the Microsoft
428 /// C++ ABI. Possible values are 0, 1, and 2, which mean:
430 /// 0: Suppress all vtordisps
431 /// 1: Insert vtordisps in the presence of vbase overrides and non-trivial
433 /// 2: Always insert vtordisps to support RTTI on partially constructed
435 PragmaStack<MSVtorDispAttr::Mode> VtorDispStack;
437 // Sentinel to represent when the stack is set to mac68k alignment.
438 static const unsigned kMac68kAlignmentSentinel = ~0U;
439 PragmaStack<unsigned> PackStack;
441 PragmaStack<StringLiteral *> DataSegStack;
442 PragmaStack<StringLiteral *> BSSSegStack;
443 PragmaStack<StringLiteral *> ConstSegStack;
444 PragmaStack<StringLiteral *> CodeSegStack;
446 // RAII object to push / pop sentinel slots for all MS #pragma stacks.
447 // Actions should be performed only if we enter / exit a C++ method body.
448 class PragmaStackSentinelRAII {
450 PragmaStackSentinelRAII(Sema &S, StringRef SlotLabel, bool ShouldAct);
451 ~PragmaStackSentinelRAII();
459 /// A mapping that describes the nullability we've seen in each header file.
460 FileNullabilityMap NullabilityMap;
462 /// Last section used with #pragma init_seg.
463 StringLiteral *CurInitSeg;
464 SourceLocation CurInitSegLoc;
466 /// VisContext - Manages the stack for \#pragma GCC visibility.
467 void *VisContext; // Really a "PragmaVisStack*"
469 /// \brief This represents the stack of attributes that were pushed by
470 /// \#pragma clang attribute.
471 struct PragmaAttributeEntry {
473 AttributeList *Attribute;
474 SmallVector<attr::SubjectMatchRule, 4> MatchRules;
477 SmallVector<PragmaAttributeEntry, 2> PragmaAttributeStack;
479 /// \brief The declaration that is currently receiving an attribute from the
480 /// #pragma attribute stack.
481 const Decl *PragmaAttributeCurrentTargetDecl;
483 /// \brief This represents the last location of a "#pragma clang optimize off"
484 /// directive if such a directive has not been closed by an "on" yet. If
485 /// optimizations are currently "on", this is set to an invalid location.
486 SourceLocation OptimizeOffPragmaLocation;
488 /// \brief Flag indicating if Sema is building a recovery call expression.
490 /// This flag is used to avoid building recovery call expressions
491 /// if Sema is already doing so, which would cause infinite recursions.
492 bool IsBuildingRecoveryCallExpr;
494 /// Used to control the generation of ExprWithCleanups.
497 /// ExprCleanupObjects - This is the stack of objects requiring
498 /// cleanup that are created by the current full expression. The
499 /// element type here is ExprWithCleanups::Object.
500 SmallVector<BlockDecl*, 8> ExprCleanupObjects;
502 /// \brief Store a list of either DeclRefExprs or MemberExprs
503 /// that contain a reference to a variable (constant) that may or may not
504 /// be odr-used in this Expr, and we won't know until all lvalue-to-rvalue
505 /// and discarded value conversions have been applied to all subexpressions
506 /// of the enclosing full expression. This is cleared at the end of each
508 llvm::SmallPtrSet<Expr*, 2> MaybeODRUseExprs;
510 /// \brief Stack containing information about each of the nested
511 /// function, block, and method scopes that are currently active.
513 /// This array is never empty. Clients should ignore the first
514 /// element, which is used to cache a single FunctionScopeInfo
515 /// that's used to parse every top-level function.
516 SmallVector<sema::FunctionScopeInfo *, 4> FunctionScopes;
518 typedef LazyVector<TypedefNameDecl *, ExternalSemaSource,
519 &ExternalSemaSource::ReadExtVectorDecls, 2, 2>
522 /// ExtVectorDecls - This is a list all the extended vector types. This allows
523 /// us to associate a raw vector type with one of the ext_vector type names.
524 /// This is only necessary for issuing pretty diagnostics.
525 ExtVectorDeclsType ExtVectorDecls;
527 /// FieldCollector - Collects CXXFieldDecls during parsing of C++ classes.
528 std::unique_ptr<CXXFieldCollector> FieldCollector;
530 typedef llvm::SmallSetVector<const NamedDecl*, 16> NamedDeclSetType;
532 /// \brief Set containing all declared private fields that are not used.
533 NamedDeclSetType UnusedPrivateFields;
535 /// \brief Set containing all typedefs that are likely unused.
536 llvm::SmallSetVector<const TypedefNameDecl *, 4>
537 UnusedLocalTypedefNameCandidates;
539 /// \brief Delete-expressions to be analyzed at the end of translation unit
541 /// This list contains class members, and locations of delete-expressions
542 /// that could not be proven as to whether they mismatch with new-expression
543 /// used in initializer of the field.
544 typedef std::pair<SourceLocation, bool> DeleteExprLoc;
545 typedef llvm::SmallVector<DeleteExprLoc, 4> DeleteLocs;
546 llvm::MapVector<FieldDecl *, DeleteLocs> DeleteExprs;
548 typedef llvm::SmallPtrSet<const CXXRecordDecl*, 8> RecordDeclSetTy;
550 /// PureVirtualClassDiagSet - a set of class declarations which we have
551 /// emitted a list of pure virtual functions. Used to prevent emitting the
552 /// same list more than once.
553 std::unique_ptr<RecordDeclSetTy> PureVirtualClassDiagSet;
555 /// ParsingInitForAutoVars - a set of declarations with auto types for which
556 /// we are currently parsing the initializer.
557 llvm::SmallPtrSet<const Decl*, 4> ParsingInitForAutoVars;
559 /// \brief Look for a locally scoped extern "C" declaration by the given name.
560 NamedDecl *findLocallyScopedExternCDecl(DeclarationName Name);
562 typedef LazyVector<VarDecl *, ExternalSemaSource,
563 &ExternalSemaSource::ReadTentativeDefinitions, 2, 2>
564 TentativeDefinitionsType;
566 /// \brief All the tentative definitions encountered in the TU.
567 TentativeDefinitionsType TentativeDefinitions;
569 typedef LazyVector<const DeclaratorDecl *, ExternalSemaSource,
570 &ExternalSemaSource::ReadUnusedFileScopedDecls, 2, 2>
571 UnusedFileScopedDeclsType;
573 /// \brief The set of file scoped decls seen so far that have not been used
574 /// and must warn if not used. Only contains the first declaration.
575 UnusedFileScopedDeclsType UnusedFileScopedDecls;
577 typedef LazyVector<CXXConstructorDecl *, ExternalSemaSource,
578 &ExternalSemaSource::ReadDelegatingConstructors, 2, 2>
579 DelegatingCtorDeclsType;
581 /// \brief All the delegating constructors seen so far in the file, used for
582 /// cycle detection at the end of the TU.
583 DelegatingCtorDeclsType DelegatingCtorDecls;
585 /// \brief All the overriding functions seen during a class definition
586 /// that had their exception spec checks delayed, plus the overridden
588 SmallVector<std::pair<const CXXMethodDecl*, const CXXMethodDecl*>, 2>
589 DelayedExceptionSpecChecks;
591 /// \brief All the members seen during a class definition which were both
592 /// explicitly defaulted and had explicitly-specified exception
593 /// specifications, along with the function type containing their
594 /// user-specified exception specification. Those exception specifications
595 /// were overridden with the default specifications, but we still need to
596 /// check whether they are compatible with the default specification, and
597 /// we can't do that until the nesting set of class definitions is complete.
598 SmallVector<std::pair<CXXMethodDecl*, const FunctionProtoType*>, 2>
599 DelayedDefaultedMemberExceptionSpecs;
601 typedef llvm::MapVector<const FunctionDecl *,
602 std::unique_ptr<LateParsedTemplate>>
603 LateParsedTemplateMapT;
604 LateParsedTemplateMapT LateParsedTemplateMap;
606 /// \brief Callback to the parser to parse templated functions when needed.
607 typedef void LateTemplateParserCB(void *P, LateParsedTemplate &LPT);
608 typedef void LateTemplateParserCleanupCB(void *P);
609 LateTemplateParserCB *LateTemplateParser;
610 LateTemplateParserCleanupCB *LateTemplateParserCleanup;
613 void SetLateTemplateParser(LateTemplateParserCB *LTP,
614 LateTemplateParserCleanupCB *LTPCleanup,
616 LateTemplateParser = LTP;
617 LateTemplateParserCleanup = LTPCleanup;
621 class DelayedDiagnostics;
623 class DelayedDiagnosticsState {
624 sema::DelayedDiagnosticPool *SavedPool;
625 friend class Sema::DelayedDiagnostics;
627 typedef DelayedDiagnosticsState ParsingDeclState;
628 typedef DelayedDiagnosticsState ProcessingContextState;
630 /// A class which encapsulates the logic for delaying diagnostics
631 /// during parsing and other processing.
632 class DelayedDiagnostics {
633 /// \brief The current pool of diagnostics into which delayed
634 /// diagnostics should go.
635 sema::DelayedDiagnosticPool *CurPool;
638 DelayedDiagnostics() : CurPool(nullptr) {}
640 /// Adds a delayed diagnostic.
641 void add(const sema::DelayedDiagnostic &diag); // in DelayedDiagnostic.h
643 /// Determines whether diagnostics should be delayed.
644 bool shouldDelayDiagnostics() { return CurPool != nullptr; }
646 /// Returns the current delayed-diagnostics pool.
647 sema::DelayedDiagnosticPool *getCurrentPool() const {
651 /// Enter a new scope. Access and deprecation diagnostics will be
652 /// collected in this pool.
653 DelayedDiagnosticsState push(sema::DelayedDiagnosticPool &pool) {
654 DelayedDiagnosticsState state;
655 state.SavedPool = CurPool;
660 /// Leave a delayed-diagnostic state that was previously pushed.
661 /// Do not emit any of the diagnostics. This is performed as part
662 /// of the bookkeeping of popping a pool "properly".
663 void popWithoutEmitting(DelayedDiagnosticsState state) {
664 CurPool = state.SavedPool;
667 /// Enter a new scope where access and deprecation diagnostics are
669 DelayedDiagnosticsState pushUndelayed() {
670 DelayedDiagnosticsState state;
671 state.SavedPool = CurPool;
676 /// Undo a previous pushUndelayed().
677 void popUndelayed(DelayedDiagnosticsState state) {
678 assert(CurPool == nullptr);
679 CurPool = state.SavedPool;
681 } DelayedDiagnostics;
683 /// A RAII object to temporarily push a declaration context.
687 DeclContext *SavedContext;
688 ProcessingContextState SavedContextState;
689 QualType SavedCXXThisTypeOverride;
692 ContextRAII(Sema &S, DeclContext *ContextToPush, bool NewThisContext = true)
693 : S(S), SavedContext(S.CurContext),
694 SavedContextState(S.DelayedDiagnostics.pushUndelayed()),
695 SavedCXXThisTypeOverride(S.CXXThisTypeOverride)
697 assert(ContextToPush && "pushing null context");
698 S.CurContext = ContextToPush;
700 S.CXXThisTypeOverride = QualType();
704 if (!SavedContext) return;
705 S.CurContext = SavedContext;
706 S.DelayedDiagnostics.popUndelayed(SavedContextState);
707 S.CXXThisTypeOverride = SavedCXXThisTypeOverride;
708 SavedContext = nullptr;
716 /// \brief RAII object to handle the state changes required to synthesize
718 class SynthesizedFunctionScope {
720 Sema::ContextRAII SavedContext;
721 bool PushedCodeSynthesisContext = false;
724 SynthesizedFunctionScope(Sema &S, DeclContext *DC)
725 : S(S), SavedContext(S, DC) {
726 S.PushFunctionScope();
727 S.PushExpressionEvaluationContext(
728 Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
729 if (auto *FD = dyn_cast<FunctionDecl>(DC))
730 FD->setWillHaveBody(true);
732 assert(isa<ObjCMethodDecl>(DC));
735 void addContextNote(SourceLocation UseLoc) {
736 assert(!PushedCodeSynthesisContext);
738 Sema::CodeSynthesisContext Ctx;
739 Ctx.Kind = Sema::CodeSynthesisContext::DefiningSynthesizedFunction;
740 Ctx.PointOfInstantiation = UseLoc;
741 Ctx.Entity = cast<Decl>(S.CurContext);
742 S.pushCodeSynthesisContext(Ctx);
744 PushedCodeSynthesisContext = true;
747 ~SynthesizedFunctionScope() {
748 if (PushedCodeSynthesisContext)
749 S.popCodeSynthesisContext();
750 if (auto *FD = dyn_cast<FunctionDecl>(S.CurContext))
751 FD->setWillHaveBody(false);
752 S.PopExpressionEvaluationContext();
753 S.PopFunctionScopeInfo();
757 /// WeakUndeclaredIdentifiers - Identifiers contained in
758 /// \#pragma weak before declared. rare. may alias another
759 /// identifier, declared or undeclared
760 llvm::MapVector<IdentifierInfo *, WeakInfo> WeakUndeclaredIdentifiers;
762 /// ExtnameUndeclaredIdentifiers - Identifiers contained in
763 /// \#pragma redefine_extname before declared. Used in Solaris system headers
764 /// to define functions that occur in multiple standards to call the version
765 /// in the currently selected standard.
766 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*> ExtnameUndeclaredIdentifiers;
769 /// \brief Load weak undeclared identifiers from the external source.
770 void LoadExternalWeakUndeclaredIdentifiers();
772 /// WeakTopLevelDecl - Translation-unit scoped declarations generated by
773 /// \#pragma weak during processing of other Decls.
774 /// I couldn't figure out a clean way to generate these in-line, so
775 /// we store them here and handle separately -- which is a hack.
776 /// It would be best to refactor this.
777 SmallVector<Decl*,2> WeakTopLevelDecl;
779 IdentifierResolver IdResolver;
781 /// Translation Unit Scope - useful to Objective-C actions that need
782 /// to lookup file scope declarations in the "ordinary" C decl namespace.
783 /// For example, user-defined classes, built-in "id" type, etc.
786 /// \brief The C++ "std" namespace, where the standard library resides.
787 LazyDeclPtr StdNamespace;
789 /// \brief The C++ "std::bad_alloc" class, which is defined by the C++
790 /// standard library.
791 LazyDeclPtr StdBadAlloc;
793 /// \brief The C++ "std::align_val_t" enum class, which is defined by the C++
794 /// standard library.
795 LazyDeclPtr StdAlignValT;
797 /// \brief The C++ "std::experimental" namespace, where the experimental parts
798 /// of the standard library resides.
799 NamespaceDecl *StdExperimentalNamespaceCache;
801 /// \brief The C++ "std::initializer_list" template, which is defined in
802 /// \<initializer_list>.
803 ClassTemplateDecl *StdInitializerList;
805 /// \brief The C++ "type_info" declaration, which is defined in \<typeinfo>.
806 RecordDecl *CXXTypeInfoDecl;
808 /// \brief The MSVC "_GUID" struct, which is defined in MSVC header files.
809 RecordDecl *MSVCGuidDecl;
811 /// \brief Caches identifiers/selectors for NSFoundation APIs.
812 std::unique_ptr<NSAPI> NSAPIObj;
814 /// \brief The declaration of the Objective-C NSNumber class.
815 ObjCInterfaceDecl *NSNumberDecl;
817 /// \brief The declaration of the Objective-C NSValue class.
818 ObjCInterfaceDecl *NSValueDecl;
820 /// \brief Pointer to NSNumber type (NSNumber *).
821 QualType NSNumberPointer;
823 /// \brief Pointer to NSValue type (NSValue *).
824 QualType NSValuePointer;
826 /// \brief The Objective-C NSNumber methods used to create NSNumber literals.
827 ObjCMethodDecl *NSNumberLiteralMethods[NSAPI::NumNSNumberLiteralMethods];
829 /// \brief The declaration of the Objective-C NSString class.
830 ObjCInterfaceDecl *NSStringDecl;
832 /// \brief Pointer to NSString type (NSString *).
833 QualType NSStringPointer;
835 /// \brief The declaration of the stringWithUTF8String: method.
836 ObjCMethodDecl *StringWithUTF8StringMethod;
838 /// \brief The declaration of the valueWithBytes:objCType: method.
839 ObjCMethodDecl *ValueWithBytesObjCTypeMethod;
841 /// \brief The declaration of the Objective-C NSArray class.
842 ObjCInterfaceDecl *NSArrayDecl;
844 /// \brief The declaration of the arrayWithObjects:count: method.
845 ObjCMethodDecl *ArrayWithObjectsMethod;
847 /// \brief The declaration of the Objective-C NSDictionary class.
848 ObjCInterfaceDecl *NSDictionaryDecl;
850 /// \brief The declaration of the dictionaryWithObjects:forKeys:count: method.
851 ObjCMethodDecl *DictionaryWithObjectsMethod;
853 /// \brief id<NSCopying> type.
854 QualType QIDNSCopying;
856 /// \brief will hold 'respondsToSelector:'
857 Selector RespondsToSelectorSel;
859 /// A flag to remember whether the implicit forms of operator new and delete
860 /// have been declared.
861 bool GlobalNewDeleteDeclared;
863 /// A flag to indicate that we're in a context that permits abstract
864 /// references to fields. This is really a
865 bool AllowAbstractFieldReference;
867 /// \brief Describes how the expressions currently being parsed are
868 /// evaluated at run-time, if at all.
869 enum class ExpressionEvaluationContext {
870 /// \brief The current expression and its subexpressions occur within an
871 /// unevaluated operand (C++11 [expr]p7), such as the subexpression of
872 /// \c sizeof, where the type of the expression may be significant but
873 /// no code will be generated to evaluate the value of the expression at
877 /// \brief The current expression occurs within a braced-init-list within
878 /// an unevaluated operand. This is mostly like a regular unevaluated
879 /// context, except that we still instantiate constexpr functions that are
880 /// referenced here so that we can perform narrowing checks correctly.
883 /// \brief The current expression occurs within a discarded statement.
884 /// This behaves largely similarly to an unevaluated operand in preventing
885 /// definitions from being required, but not in other ways.
888 /// \brief The current expression occurs within an unevaluated
889 /// operand that unconditionally permits abstract references to
890 /// fields, such as a SIZE operator in MS-style inline assembly.
893 /// \brief The current context is "potentially evaluated" in C++11 terms,
894 /// but the expression is evaluated at compile-time (like the values of
895 /// cases in a switch statement).
898 /// \brief The current expression is potentially evaluated at run time,
899 /// which means that code may be generated to evaluate the value of the
900 /// expression at run time.
901 PotentiallyEvaluated,
903 /// \brief The current expression is potentially evaluated, but any
904 /// declarations referenced inside that expression are only used if
905 /// in fact the current expression is used.
907 /// This value is used when parsing default function arguments, for which
908 /// we would like to provide diagnostics (e.g., passing non-POD arguments
909 /// through varargs) but do not want to mark declarations as "referenced"
910 /// until the default argument is used.
911 PotentiallyEvaluatedIfUsed
914 /// \brief Data structure used to record current or nested
915 /// expression evaluation contexts.
916 struct ExpressionEvaluationContextRecord {
917 /// \brief The expression evaluation context.
918 ExpressionEvaluationContext Context;
920 /// \brief Whether the enclosing context needed a cleanup.
921 CleanupInfo ParentCleanup;
923 /// \brief Whether we are in a decltype expression.
926 /// \brief The number of active cleanup objects when we entered
927 /// this expression evaluation context.
928 unsigned NumCleanupObjects;
930 /// \brief The number of typos encountered during this expression evaluation
931 /// context (i.e. the number of TypoExprs created).
934 llvm::SmallPtrSet<Expr*, 2> SavedMaybeODRUseExprs;
936 /// \brief The lambdas that are present within this context, if it
937 /// is indeed an unevaluated context.
938 SmallVector<LambdaExpr *, 2> Lambdas;
940 /// \brief The declaration that provides context for lambda expressions
941 /// and block literals if the normal declaration context does not
942 /// suffice, e.g., in a default function argument.
943 Decl *ManglingContextDecl;
945 /// \brief The context information used to mangle lambda expressions
946 /// and block literals within this context.
948 /// This mangling information is allocated lazily, since most contexts
949 /// do not have lambda expressions or block literals.
950 std::unique_ptr<MangleNumberingContext> MangleNumbering;
952 /// \brief If we are processing a decltype type, a set of call expressions
953 /// for which we have deferred checking the completeness of the return type.
954 SmallVector<CallExpr *, 8> DelayedDecltypeCalls;
956 /// \brief If we are processing a decltype type, a set of temporary binding
957 /// expressions for which we have deferred checking the destructor.
958 SmallVector<CXXBindTemporaryExpr *, 8> DelayedDecltypeBinds;
960 ExpressionEvaluationContextRecord(ExpressionEvaluationContext Context,
961 unsigned NumCleanupObjects,
962 CleanupInfo ParentCleanup,
963 Decl *ManglingContextDecl,
965 : Context(Context), ParentCleanup(ParentCleanup),
966 IsDecltype(IsDecltype), NumCleanupObjects(NumCleanupObjects),
968 ManglingContextDecl(ManglingContextDecl), MangleNumbering() { }
970 /// \brief Retrieve the mangling numbering context, used to consistently
971 /// number constructs like lambdas for mangling.
972 MangleNumberingContext &getMangleNumberingContext(ASTContext &Ctx);
974 bool isUnevaluated() const {
975 return Context == ExpressionEvaluationContext::Unevaluated ||
976 Context == ExpressionEvaluationContext::UnevaluatedAbstract ||
977 Context == ExpressionEvaluationContext::UnevaluatedList;
979 bool isConstantEvaluated() const {
980 return Context == ExpressionEvaluationContext::ConstantEvaluated;
984 /// A stack of expression evaluation contexts.
985 SmallVector<ExpressionEvaluationContextRecord, 8> ExprEvalContexts;
987 /// \brief Compute the mangling number context for a lambda expression or
990 /// \param DC - The DeclContext containing the lambda expression or
992 /// \param[out] ManglingContextDecl - Returns the ManglingContextDecl
993 /// associated with the context, if relevant.
994 MangleNumberingContext *getCurrentMangleNumberContext(
995 const DeclContext *DC,
996 Decl *&ManglingContextDecl);
999 /// SpecialMemberOverloadResult - The overloading result for a special member
1002 /// This is basically a wrapper around PointerIntPair. The lowest bits of the
1003 /// integer are used to determine whether overload resolution succeeded.
1004 class SpecialMemberOverloadResult {
1013 llvm::PointerIntPair<CXXMethodDecl*, 2> Pair;
1016 SpecialMemberOverloadResult() : Pair() {}
1017 SpecialMemberOverloadResult(CXXMethodDecl *MD)
1018 : Pair(MD, MD->isDeleted() ? NoMemberOrDeleted : Success) {}
1020 CXXMethodDecl *getMethod() const { return Pair.getPointer(); }
1021 void setMethod(CXXMethodDecl *MD) { Pair.setPointer(MD); }
1023 Kind getKind() const { return static_cast<Kind>(Pair.getInt()); }
1024 void setKind(Kind K) { Pair.setInt(K); }
1027 class SpecialMemberOverloadResultEntry
1028 : public llvm::FastFoldingSetNode,
1029 public SpecialMemberOverloadResult {
1031 SpecialMemberOverloadResultEntry(const llvm::FoldingSetNodeID &ID)
1032 : FastFoldingSetNode(ID)
1036 /// \brief A cache of special member function overload resolution results
1037 /// for C++ records.
1038 llvm::FoldingSet<SpecialMemberOverloadResultEntry> SpecialMemberCache;
1040 /// \brief A cache of the flags available in enumerations with the flag_bits
1042 mutable llvm::DenseMap<const EnumDecl*, llvm::APInt> FlagBitsCache;
1044 /// \brief The kind of translation unit we are processing.
1046 /// When we're processing a complete translation unit, Sema will perform
1047 /// end-of-translation-unit semantic tasks (such as creating
1048 /// initializers for tentative definitions in C) once parsing has
1049 /// completed. Modules and precompiled headers perform different kinds of
1051 TranslationUnitKind TUKind;
1053 llvm::BumpPtrAllocator BumpAlloc;
1055 /// \brief The number of SFINAE diagnostics that have been trapped.
1056 unsigned NumSFINAEErrors;
1058 typedef llvm::DenseMap<ParmVarDecl *, llvm::TinyPtrVector<ParmVarDecl *>>
1059 UnparsedDefaultArgInstantiationsMap;
1061 /// \brief A mapping from parameters with unparsed default arguments to the
1062 /// set of instantiations of each parameter.
1064 /// This mapping is a temporary data structure used when parsing
1065 /// nested class templates or nested classes of class templates,
1066 /// where we might end up instantiating an inner class before the
1067 /// default arguments of its methods have been parsed.
1068 UnparsedDefaultArgInstantiationsMap UnparsedDefaultArgInstantiations;
1070 // Contains the locations of the beginning of unparsed default
1071 // argument locations.
1072 llvm::DenseMap<ParmVarDecl *, SourceLocation> UnparsedDefaultArgLocs;
1074 /// UndefinedInternals - all the used, undefined objects which require a
1075 /// definition in this translation unit.
1076 llvm::MapVector<NamedDecl *, SourceLocation> UndefinedButUsed;
1078 /// Obtain a sorted list of functions that are undefined but ODR-used.
1079 void getUndefinedButUsed(
1080 SmallVectorImpl<std::pair<NamedDecl *, SourceLocation> > &Undefined);
1082 /// Retrieves list of suspicious delete-expressions that will be checked at
1083 /// the end of translation unit.
1084 const llvm::MapVector<FieldDecl *, DeleteLocs> &
1085 getMismatchingDeleteExpressions() const;
1087 typedef std::pair<ObjCMethodList, ObjCMethodList> GlobalMethods;
1088 typedef llvm::DenseMap<Selector, GlobalMethods> GlobalMethodPool;
1090 /// Method Pool - allows efficient lookup when typechecking messages to "id".
1091 /// We need to maintain a list, since selectors can have differing signatures
1092 /// across classes. In Cocoa, this happens to be extremely uncommon (only 1%
1093 /// of selectors are "overloaded").
1094 /// At the head of the list it is recorded whether there were 0, 1, or >= 2
1095 /// methods inside categories with a particular selector.
1096 GlobalMethodPool MethodPool;
1098 /// Method selectors used in a \@selector expression. Used for implementation
1100 llvm::MapVector<Selector, SourceLocation> ReferencedSelectors;
1102 /// Kinds of C++ special members.
1103 enum CXXSpecialMember {
1104 CXXDefaultConstructor,
1113 typedef std::pair<CXXRecordDecl*, CXXSpecialMember> SpecialMemberDecl;
1115 /// The C++ special members which we are currently in the process of
1116 /// declaring. If this process recursively triggers the declaration of the
1117 /// same special member, we should act as if it is not yet declared.
1118 llvm::SmallSet<SpecialMemberDecl, 4> SpecialMembersBeingDeclared;
1120 /// The function definitions which were renamed as part of typo-correction
1121 /// to match their respective declarations. We want to keep track of them
1122 /// to ensure that we don't emit a "redefinition" error if we encounter a
1123 /// correctly named definition after the renamed definition.
1124 llvm::SmallPtrSet<const NamedDecl *, 4> TypoCorrectedFunctionDefinitions;
1126 /// Stack of types that correspond to the parameter entities that are
1127 /// currently being copy-initialized. Can be empty.
1128 llvm::SmallVector<QualType, 4> CurrentParameterCopyTypes;
1130 void ReadMethodPool(Selector Sel);
1131 void updateOutOfDateSelector(Selector Sel);
1133 /// Private Helper predicate to check for 'self'.
1134 bool isSelfExpr(Expr *RExpr);
1135 bool isSelfExpr(Expr *RExpr, const ObjCMethodDecl *Method);
1137 /// \brief Cause the active diagnostic on the DiagosticsEngine to be
1138 /// emitted. This is closely coupled to the SemaDiagnosticBuilder class and
1139 /// should not be used elsewhere.
1140 void EmitCurrentDiagnostic(unsigned DiagID);
1142 /// Records and restores the FP_CONTRACT state on entry/exit of compound
1144 class FPContractStateRAII {
1146 FPContractStateRAII(Sema &S) : S(S), OldFPFeaturesState(S.FPFeatures) {}
1147 ~FPContractStateRAII() { S.FPFeatures = OldFPFeaturesState; }
1151 FPOptions OldFPFeaturesState;
1154 void addImplicitTypedef(StringRef Name, QualType T);
1157 Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer,
1158 TranslationUnitKind TUKind = TU_Complete,
1159 CodeCompleteConsumer *CompletionConsumer = nullptr);
1162 /// \brief Perform initialization that occurs after the parser has been
1163 /// initialized but before it parses anything.
1166 const LangOptions &getLangOpts() const { return LangOpts; }
1167 OpenCLOptions &getOpenCLOptions() { return OpenCLFeatures; }
1168 FPOptions &getFPOptions() { return FPFeatures; }
1170 DiagnosticsEngine &getDiagnostics() const { return Diags; }
1171 SourceManager &getSourceManager() const { return SourceMgr; }
1172 Preprocessor &getPreprocessor() const { return PP; }
1173 ASTContext &getASTContext() const { return Context; }
1174 ASTConsumer &getASTConsumer() const { return Consumer; }
1175 ASTMutationListener *getASTMutationListener() const;
1176 ExternalSemaSource* getExternalSource() const { return ExternalSource; }
1178 ///\brief Registers an external source. If an external source already exists,
1179 /// creates a multiplex external source and appends to it.
1181 ///\param[in] E - A non-null external sema source.
1183 void addExternalSource(ExternalSemaSource *E);
1185 void PrintStats() const;
1187 /// \brief Helper class that creates diagnostics with optional
1188 /// template instantiation stacks.
1190 /// This class provides a wrapper around the basic DiagnosticBuilder
1191 /// class that emits diagnostics. SemaDiagnosticBuilder is
1192 /// responsible for emitting the diagnostic (as DiagnosticBuilder
1193 /// does) and, if the diagnostic comes from inside a template
1194 /// instantiation, printing the template instantiation stack as
1196 class SemaDiagnosticBuilder : public DiagnosticBuilder {
1201 SemaDiagnosticBuilder(DiagnosticBuilder &DB, Sema &SemaRef, unsigned DiagID)
1202 : DiagnosticBuilder(DB), SemaRef(SemaRef), DiagID(DiagID) { }
1204 // This is a cunning lie. DiagnosticBuilder actually performs move
1205 // construction in its copy constructor (but due to varied uses, it's not
1206 // possible to conveniently express this as actual move construction). So
1207 // the default copy ctor here is fine, because the base class disables the
1208 // source anyway, so the user-defined ~SemaDiagnosticBuilder is a safe no-op
1209 // in that case anwyay.
1210 SemaDiagnosticBuilder(const SemaDiagnosticBuilder&) = default;
1212 ~SemaDiagnosticBuilder() {
1213 // If we aren't active, there is nothing to do.
1214 if (!isActive()) return;
1216 // Otherwise, we need to emit the diagnostic. First flush the underlying
1217 // DiagnosticBuilder data, and clear the diagnostic builder itself so it
1218 // won't emit the diagnostic in its own destructor.
1220 // This seems wasteful, in that as written the DiagnosticBuilder dtor will
1221 // do its own needless checks to see if the diagnostic needs to be
1222 // emitted. However, because we take care to ensure that the builder
1223 // objects never escape, a sufficiently smart compiler will be able to
1224 // eliminate that code.
1228 // Dispatch to Sema to emit the diagnostic.
1229 SemaRef.EmitCurrentDiagnostic(DiagID);
1232 /// Teach operator<< to produce an object of the correct type.
1233 template<typename T>
1234 friend const SemaDiagnosticBuilder &operator<<(
1235 const SemaDiagnosticBuilder &Diag, const T &Value) {
1236 const DiagnosticBuilder &BaseDiag = Diag;
1242 /// \brief Emit a diagnostic.
1243 SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID) {
1244 DiagnosticBuilder DB = Diags.Report(Loc, DiagID);
1245 return SemaDiagnosticBuilder(DB, *this, DiagID);
1248 /// \brief Emit a partial diagnostic.
1249 SemaDiagnosticBuilder Diag(SourceLocation Loc, const PartialDiagnostic& PD);
1251 /// \brief Build a partial diagnostic.
1252 PartialDiagnostic PDiag(unsigned DiagID = 0); // in SemaInternal.h
1254 bool findMacroSpelling(SourceLocation &loc, StringRef name);
1256 /// \brief Get a string to suggest for zero-initialization of a type.
1258 getFixItZeroInitializerForType(QualType T, SourceLocation Loc) const;
1259 std::string getFixItZeroLiteralForType(QualType T, SourceLocation Loc) const;
1261 /// \brief Calls \c Lexer::getLocForEndOfToken()
1262 SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset = 0);
1264 /// \brief Retrieve the module loader associated with the preprocessor.
1265 ModuleLoader &getModuleLoader() const;
1267 void emitAndClearUnusedLocalTypedefWarnings();
1269 void ActOnStartOfTranslationUnit();
1270 void ActOnEndOfTranslationUnit();
1272 void CheckDelegatingCtorCycles();
1274 Scope *getScopeForContext(DeclContext *Ctx);
1276 void PushFunctionScope();
1277 void PushBlockScope(Scope *BlockScope, BlockDecl *Block);
1278 sema::LambdaScopeInfo *PushLambdaScope();
1280 /// \brief This is used to inform Sema what the current TemplateParameterDepth
1281 /// is during Parsing. Currently it is used to pass on the depth
1282 /// when parsing generic lambda 'auto' parameters.
1283 void RecordParsingTemplateParameterDepth(unsigned Depth);
1285 void PushCapturedRegionScope(Scope *RegionScope, CapturedDecl *CD,
1287 CapturedRegionKind K);
1289 PopFunctionScopeInfo(const sema::AnalysisBasedWarnings::Policy *WP = nullptr,
1290 const Decl *D = nullptr,
1291 const BlockExpr *blkExpr = nullptr);
1293 sema::FunctionScopeInfo *getCurFunction() const {
1294 return FunctionScopes.back();
1297 sema::FunctionScopeInfo *getEnclosingFunction() const {
1298 if (FunctionScopes.empty())
1301 for (int e = FunctionScopes.size()-1; e >= 0; --e) {
1302 if (isa<sema::BlockScopeInfo>(FunctionScopes[e]))
1304 return FunctionScopes[e];
1309 template <typename ExprT>
1310 void recordUseOfEvaluatedWeak(const ExprT *E, bool IsRead=true) {
1311 if (!isUnevaluatedContext())
1312 getCurFunction()->recordUseOfWeak(E, IsRead);
1315 void PushCompoundScope();
1316 void PopCompoundScope();
1318 sema::CompoundScopeInfo &getCurCompoundScope() const;
1320 bool hasAnyUnrecoverableErrorsInThisFunction() const;
1322 /// \brief Retrieve the current block, if any.
1323 sema::BlockScopeInfo *getCurBlock();
1325 /// Retrieve the current lambda scope info, if any.
1326 /// \param IgnoreNonLambdaCapturingScope true if should find the top-most
1327 /// lambda scope info ignoring all inner capturing scopes that are not
1329 sema::LambdaScopeInfo *
1330 getCurLambda(bool IgnoreNonLambdaCapturingScope = false);
1332 /// \brief Retrieve the current generic lambda info, if any.
1333 sema::LambdaScopeInfo *getCurGenericLambda();
1335 /// \brief Retrieve the current captured region, if any.
1336 sema::CapturedRegionScopeInfo *getCurCapturedRegion();
1338 /// WeakTopLevelDeclDecls - access to \#pragma weak-generated Decls
1339 SmallVectorImpl<Decl *> &WeakTopLevelDecls() { return WeakTopLevelDecl; }
1341 void ActOnComment(SourceRange Comment);
1343 //===--------------------------------------------------------------------===//
1344 // Type Analysis / Processing: SemaType.cpp.
1347 QualType BuildQualifiedType(QualType T, SourceLocation Loc, Qualifiers Qs,
1348 const DeclSpec *DS = nullptr);
1349 QualType BuildQualifiedType(QualType T, SourceLocation Loc, unsigned CVRA,
1350 const DeclSpec *DS = nullptr);
1351 QualType BuildPointerType(QualType T,
1352 SourceLocation Loc, DeclarationName Entity);
1353 QualType BuildReferenceType(QualType T, bool LValueRef,
1354 SourceLocation Loc, DeclarationName Entity);
1355 QualType BuildArrayType(QualType T, ArrayType::ArraySizeModifier ASM,
1356 Expr *ArraySize, unsigned Quals,
1357 SourceRange Brackets, DeclarationName Entity);
1358 QualType BuildExtVectorType(QualType T, Expr *ArraySize,
1359 SourceLocation AttrLoc);
1361 bool CheckFunctionReturnType(QualType T, SourceLocation Loc);
1363 /// \brief Build a function type.
1365 /// This routine checks the function type according to C++ rules and
1366 /// under the assumption that the result type and parameter types have
1367 /// just been instantiated from a template. It therefore duplicates
1368 /// some of the behavior of GetTypeForDeclarator, but in a much
1369 /// simpler form that is only suitable for this narrow use case.
1371 /// \param T The return type of the function.
1373 /// \param ParamTypes The parameter types of the function. This array
1374 /// will be modified to account for adjustments to the types of the
1375 /// function parameters.
1377 /// \param Loc The location of the entity whose type involves this
1378 /// function type or, if there is no such entity, the location of the
1379 /// type that will have function type.
1381 /// \param Entity The name of the entity that involves the function
1384 /// \param EPI Extra information about the function type. Usually this will
1385 /// be taken from an existing function with the same prototype.
1387 /// \returns A suitable function type, if there are no errors. The
1388 /// unqualified type will always be a FunctionProtoType.
1389 /// Otherwise, returns a NULL type.
1390 QualType BuildFunctionType(QualType T,
1391 MutableArrayRef<QualType> ParamTypes,
1392 SourceLocation Loc, DeclarationName Entity,
1393 const FunctionProtoType::ExtProtoInfo &EPI);
1395 QualType BuildMemberPointerType(QualType T, QualType Class,
1397 DeclarationName Entity);
1398 QualType BuildBlockPointerType(QualType T,
1399 SourceLocation Loc, DeclarationName Entity);
1400 QualType BuildParenType(QualType T);
1401 QualType BuildAtomicType(QualType T, SourceLocation Loc);
1402 QualType BuildReadPipeType(QualType T,
1403 SourceLocation Loc);
1404 QualType BuildWritePipeType(QualType T,
1405 SourceLocation Loc);
1407 TypeSourceInfo *GetTypeForDeclarator(Declarator &D, Scope *S);
1408 TypeSourceInfo *GetTypeForDeclaratorCast(Declarator &D, QualType FromTy);
1409 TypeSourceInfo *GetTypeSourceInfoForDeclarator(Declarator &D, QualType T,
1410 TypeSourceInfo *ReturnTypeInfo);
1412 /// \brief Package the given type and TSI into a ParsedType.
1413 ParsedType CreateParsedType(QualType T, TypeSourceInfo *TInfo);
1414 DeclarationNameInfo GetNameForDeclarator(Declarator &D);
1415 DeclarationNameInfo GetNameFromUnqualifiedId(const UnqualifiedId &Name);
1416 static QualType GetTypeFromParser(ParsedType Ty,
1417 TypeSourceInfo **TInfo = nullptr);
1418 CanThrowResult canThrow(const Expr *E);
1419 const FunctionProtoType *ResolveExceptionSpec(SourceLocation Loc,
1420 const FunctionProtoType *FPT);
1421 void UpdateExceptionSpec(FunctionDecl *FD,
1422 const FunctionProtoType::ExceptionSpecInfo &ESI);
1423 bool CheckSpecifiedExceptionType(QualType &T, SourceRange Range);
1424 bool CheckDistantExceptionSpec(QualType T);
1425 bool CheckEquivalentExceptionSpec(FunctionDecl *Old, FunctionDecl *New);
1426 bool CheckEquivalentExceptionSpec(
1427 const FunctionProtoType *Old, SourceLocation OldLoc,
1428 const FunctionProtoType *New, SourceLocation NewLoc);
1429 bool CheckEquivalentExceptionSpec(
1430 const PartialDiagnostic &DiagID, const PartialDiagnostic & NoteID,
1431 const FunctionProtoType *Old, SourceLocation OldLoc,
1432 const FunctionProtoType *New, SourceLocation NewLoc);
1433 bool CheckExceptionSpecSubset(const PartialDiagnostic &DiagID,
1434 const PartialDiagnostic &NestedDiagID,
1435 const PartialDiagnostic &NoteID,
1436 const FunctionProtoType *Superset,
1437 SourceLocation SuperLoc,
1438 const FunctionProtoType *Subset,
1439 SourceLocation SubLoc);
1440 bool CheckParamExceptionSpec(const PartialDiagnostic &NestedDiagID,
1441 const PartialDiagnostic &NoteID,
1442 const FunctionProtoType *Target,
1443 SourceLocation TargetLoc,
1444 const FunctionProtoType *Source,
1445 SourceLocation SourceLoc);
1447 TypeResult ActOnTypeName(Scope *S, Declarator &D);
1449 /// \brief The parser has parsed the context-sensitive type 'instancetype'
1450 /// in an Objective-C message declaration. Return the appropriate type.
1451 ParsedType ActOnObjCInstanceType(SourceLocation Loc);
1453 /// \brief Abstract class used to diagnose incomplete types.
1454 struct TypeDiagnoser {
1457 virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) = 0;
1458 virtual ~TypeDiagnoser() {}
1461 static int getPrintable(int I) { return I; }
1462 static unsigned getPrintable(unsigned I) { return I; }
1463 static bool getPrintable(bool B) { return B; }
1464 static const char * getPrintable(const char *S) { return S; }
1465 static StringRef getPrintable(StringRef S) { return S; }
1466 static const std::string &getPrintable(const std::string &S) { return S; }
1467 static const IdentifierInfo *getPrintable(const IdentifierInfo *II) {
1470 static DeclarationName getPrintable(DeclarationName N) { return N; }
1471 static QualType getPrintable(QualType T) { return T; }
1472 static SourceRange getPrintable(SourceRange R) { return R; }
1473 static SourceRange getPrintable(SourceLocation L) { return L; }
1474 static SourceRange getPrintable(const Expr *E) { return E->getSourceRange(); }
1475 static SourceRange getPrintable(TypeLoc TL) { return TL.getSourceRange();}
1477 template <typename... Ts> class BoundTypeDiagnoser : public TypeDiagnoser {
1479 std::tuple<const Ts &...> Args;
1481 template <std::size_t... Is>
1482 void emit(const SemaDiagnosticBuilder &DB,
1483 llvm::index_sequence<Is...>) const {
1484 // Apply all tuple elements to the builder in order.
1485 bool Dummy[] = {false, (DB << getPrintable(std::get<Is>(Args)))...};
1490 BoundTypeDiagnoser(unsigned DiagID, const Ts &...Args)
1491 : TypeDiagnoser(), DiagID(DiagID), Args(Args...) {
1492 assert(DiagID != 0 && "no diagnostic for type diagnoser");
1495 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
1496 const SemaDiagnosticBuilder &DB = S.Diag(Loc, DiagID);
1497 emit(DB, llvm::index_sequence_for<Ts...>());
1503 bool RequireCompleteTypeImpl(SourceLocation Loc, QualType T,
1504 TypeDiagnoser *Diagnoser);
1506 struct ModuleScope {
1507 clang::Module *Module;
1508 VisibleModuleSet OuterVisibleModules;
1510 /// The modules we're currently parsing.
1511 llvm::SmallVector<ModuleScope, 16> ModuleScopes;
1513 /// Get the module whose scope we are currently within.
1514 Module *getCurrentModule() const {
1515 return ModuleScopes.empty() ? nullptr : ModuleScopes.back().Module;
1518 VisibleModuleSet VisibleModules;
1521 /// \brief Get the module owning an entity.
1522 Module *getOwningModule(Decl *Entity) { return Entity->getOwningModule(); }
1524 /// \brief Make a merged definition of an existing hidden definition \p ND
1525 /// visible at the specified location.
1526 void makeMergedDefinitionVisible(NamedDecl *ND);
1528 bool isModuleVisible(Module *M) { return VisibleModules.isVisible(M); }
1530 /// Determine whether a declaration is visible to name lookup.
1531 bool isVisible(const NamedDecl *D) {
1532 return !D->isHidden() || isVisibleSlow(D);
1535 /// Determine whether any declaration of an entity is visible.
1537 hasVisibleDeclaration(const NamedDecl *D,
1538 llvm::SmallVectorImpl<Module *> *Modules = nullptr) {
1539 return isVisible(D) || hasVisibleDeclarationSlow(D, Modules);
1541 bool hasVisibleDeclarationSlow(const NamedDecl *D,
1542 llvm::SmallVectorImpl<Module *> *Modules);
1544 bool hasVisibleMergedDefinition(NamedDecl *Def);
1545 bool hasMergedDefinitionInCurrentModule(NamedDecl *Def);
1547 /// Determine if \p D and \p Suggested have a structurally compatible
1548 /// layout as described in C11 6.2.7/1.
1549 bool hasStructuralCompatLayout(Decl *D, Decl *Suggested);
1551 /// Determine if \p D has a visible definition. If not, suggest a declaration
1552 /// that should be made visible to expose the definition.
1553 bool hasVisibleDefinition(NamedDecl *D, NamedDecl **Suggested,
1554 bool OnlyNeedComplete = false);
1555 bool hasVisibleDefinition(const NamedDecl *D) {
1557 return hasVisibleDefinition(const_cast<NamedDecl*>(D), &Hidden);
1560 /// Determine if the template parameter \p D has a visible default argument.
1562 hasVisibleDefaultArgument(const NamedDecl *D,
1563 llvm::SmallVectorImpl<Module *> *Modules = nullptr);
1565 /// Determine if there is a visible declaration of \p D that is an explicit
1566 /// specialization declaration for a specialization of a template. (For a
1567 /// member specialization, use hasVisibleMemberSpecialization.)
1568 bool hasVisibleExplicitSpecialization(
1569 const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr);
1571 /// Determine if there is a visible declaration of \p D that is a member
1572 /// specialization declaration (as opposed to an instantiated declaration).
1573 bool hasVisibleMemberSpecialization(
1574 const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr);
1576 /// Determine if \p A and \p B are equivalent internal linkage declarations
1577 /// from different modules, and thus an ambiguity error can be downgraded to
1578 /// an extension warning.
1579 bool isEquivalentInternalLinkageDeclaration(const NamedDecl *A,
1580 const NamedDecl *B);
1581 void diagnoseEquivalentInternalLinkageDeclarations(
1582 SourceLocation Loc, const NamedDecl *D,
1583 ArrayRef<const NamedDecl *> Equiv);
1585 bool isCompleteType(SourceLocation Loc, QualType T) {
1586 return !RequireCompleteTypeImpl(Loc, T, nullptr);
1588 bool RequireCompleteType(SourceLocation Loc, QualType T,
1589 TypeDiagnoser &Diagnoser);
1590 bool RequireCompleteType(SourceLocation Loc, QualType T,
1593 template <typename... Ts>
1594 bool RequireCompleteType(SourceLocation Loc, QualType T, unsigned DiagID,
1595 const Ts &...Args) {
1596 BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
1597 return RequireCompleteType(Loc, T, Diagnoser);
1600 void completeExprArrayBound(Expr *E);
1601 bool RequireCompleteExprType(Expr *E, TypeDiagnoser &Diagnoser);
1602 bool RequireCompleteExprType(Expr *E, unsigned DiagID);
1604 template <typename... Ts>
1605 bool RequireCompleteExprType(Expr *E, unsigned DiagID, const Ts &...Args) {
1606 BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
1607 return RequireCompleteExprType(E, Diagnoser);
1610 bool RequireLiteralType(SourceLocation Loc, QualType T,
1611 TypeDiagnoser &Diagnoser);
1612 bool RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID);
1614 template <typename... Ts>
1615 bool RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID,
1616 const Ts &...Args) {
1617 BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
1618 return RequireLiteralType(Loc, T, Diagnoser);
1621 QualType getElaboratedType(ElaboratedTypeKeyword Keyword,
1622 const CXXScopeSpec &SS, QualType T);
1624 QualType BuildTypeofExprType(Expr *E, SourceLocation Loc);
1625 /// If AsUnevaluated is false, E is treated as though it were an evaluated
1626 /// context, such as when building a type for decltype(auto).
1627 QualType BuildDecltypeType(Expr *E, SourceLocation Loc,
1628 bool AsUnevaluated = true);
1629 QualType BuildUnaryTransformType(QualType BaseType,
1630 UnaryTransformType::UTTKind UKind,
1631 SourceLocation Loc);
1633 //===--------------------------------------------------------------------===//
1634 // Symbol table / Decl tracking callbacks: SemaDecl.cpp.
1637 struct SkipBodyInfo {
1639 : ShouldSkip(false), CheckSameAsPrevious(false), Previous(nullptr),
1642 bool CheckSameAsPrevious;
1643 NamedDecl *Previous;
1647 DeclGroupPtrTy ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType = nullptr);
1649 void DiagnoseUseOfUnimplementedSelectors();
1651 bool isSimpleTypeSpecifier(tok::TokenKind Kind) const;
1653 ParsedType getTypeName(const IdentifierInfo &II, SourceLocation NameLoc,
1654 Scope *S, CXXScopeSpec *SS = nullptr,
1655 bool isClassName = false, bool HasTrailingDot = false,
1656 ParsedType ObjectType = nullptr,
1657 bool IsCtorOrDtorName = false,
1658 bool WantNontrivialTypeSourceInfo = false,
1659 bool IsClassTemplateDeductionContext = true,
1660 IdentifierInfo **CorrectedII = nullptr);
1661 TypeSpecifierType isTagName(IdentifierInfo &II, Scope *S);
1662 bool isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S);
1663 void DiagnoseUnknownTypeName(IdentifierInfo *&II,
1664 SourceLocation IILoc,
1667 ParsedType &SuggestedType,
1668 bool IsTemplateName = false);
1670 /// Attempt to behave like MSVC in situations where lookup of an unqualified
1671 /// type name has failed in a dependent context. In these situations, we
1672 /// automatically form a DependentTypeName that will retry lookup in a related
1673 /// scope during instantiation.
1674 ParsedType ActOnMSVCUnknownTypeName(const IdentifierInfo &II,
1675 SourceLocation NameLoc,
1676 bool IsTemplateTypeArg);
1678 /// \brief Describes the result of the name lookup and resolution performed
1679 /// by \c ClassifyName().
1680 enum NameClassificationKind {
1686 NC_NestedNameSpecifier,
1692 class NameClassification {
1693 NameClassificationKind Kind;
1695 TemplateName Template;
1697 const IdentifierInfo *Keyword;
1699 explicit NameClassification(NameClassificationKind Kind) : Kind(Kind) {}
1702 NameClassification(ExprResult Expr) : Kind(NC_Expression), Expr(Expr) {}
1704 NameClassification(ParsedType Type) : Kind(NC_Type), Type(Type) {}
1706 NameClassification(const IdentifierInfo *Keyword)
1707 : Kind(NC_Keyword), Keyword(Keyword) { }
1709 static NameClassification Error() {
1710 return NameClassification(NC_Error);
1713 static NameClassification Unknown() {
1714 return NameClassification(NC_Unknown);
1717 static NameClassification NestedNameSpecifier() {
1718 return NameClassification(NC_NestedNameSpecifier);
1721 static NameClassification TypeTemplate(TemplateName Name) {
1722 NameClassification Result(NC_TypeTemplate);
1723 Result.Template = Name;
1727 static NameClassification VarTemplate(TemplateName Name) {
1728 NameClassification Result(NC_VarTemplate);
1729 Result.Template = Name;
1733 static NameClassification FunctionTemplate(TemplateName Name) {
1734 NameClassification Result(NC_FunctionTemplate);
1735 Result.Template = Name;
1739 NameClassificationKind getKind() const { return Kind; }
1741 ParsedType getType() const {
1742 assert(Kind == NC_Type);
1746 ExprResult getExpression() const {
1747 assert(Kind == NC_Expression);
1751 TemplateName getTemplateName() const {
1752 assert(Kind == NC_TypeTemplate || Kind == NC_FunctionTemplate ||
1753 Kind == NC_VarTemplate);
1757 TemplateNameKind getTemplateNameKind() const {
1759 case NC_TypeTemplate:
1760 return TNK_Type_template;
1761 case NC_FunctionTemplate:
1762 return TNK_Function_template;
1763 case NC_VarTemplate:
1764 return TNK_Var_template;
1766 llvm_unreachable("unsupported name classification.");
1771 /// \brief Perform name lookup on the given name, classifying it based on
1772 /// the results of name lookup and the following token.
1774 /// This routine is used by the parser to resolve identifiers and help direct
1775 /// parsing. When the identifier cannot be found, this routine will attempt
1776 /// to correct the typo and classify based on the resulting name.
1778 /// \param S The scope in which we're performing name lookup.
1780 /// \param SS The nested-name-specifier that precedes the name.
1782 /// \param Name The identifier. If typo correction finds an alternative name,
1783 /// this pointer parameter will be updated accordingly.
1785 /// \param NameLoc The location of the identifier.
1787 /// \param NextToken The token following the identifier. Used to help
1788 /// disambiguate the name.
1790 /// \param IsAddressOfOperand True if this name is the operand of a unary
1791 /// address of ('&') expression, assuming it is classified as an
1794 /// \param CCC The correction callback, if typo correction is desired.
1796 ClassifyName(Scope *S, CXXScopeSpec &SS, IdentifierInfo *&Name,
1797 SourceLocation NameLoc, const Token &NextToken,
1798 bool IsAddressOfOperand,
1799 std::unique_ptr<CorrectionCandidateCallback> CCC = nullptr);
1801 /// Describes the detailed kind of a template name. Used in diagnostics.
1802 enum class TemplateNameKindForDiagnostics {
1807 TemplateTemplateParam,
1810 TemplateNameKindForDiagnostics
1811 getTemplateNameKindForDiagnostics(TemplateName Name);
1813 /// Determine whether it's plausible that E was intended to be a
1815 bool mightBeIntendedToBeTemplateName(ExprResult E) {
1816 if (!getLangOpts().CPlusPlus || E.isInvalid())
1818 if (auto *DRE = dyn_cast<DeclRefExpr>(E.get()))
1819 return !DRE->hasExplicitTemplateArgs();
1820 if (auto *ME = dyn_cast<MemberExpr>(E.get()))
1821 return !ME->hasExplicitTemplateArgs();
1822 // Any additional cases recognized here should also be handled by
1823 // diagnoseExprIntendedAsTemplateName.
1826 void diagnoseExprIntendedAsTemplateName(Scope *S, ExprResult TemplateName,
1827 SourceLocation Less,
1828 SourceLocation Greater);
1830 Decl *ActOnDeclarator(Scope *S, Declarator &D);
1832 NamedDecl *HandleDeclarator(Scope *S, Declarator &D,
1833 MultiTemplateParamsArg TemplateParameterLists);
1834 void RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S);
1835 bool DiagnoseClassNameShadow(DeclContext *DC, DeclarationNameInfo Info);
1836 bool diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
1837 DeclarationName Name,
1838 SourceLocation Loc);
1840 diagnoseIgnoredQualifiers(unsigned DiagID, unsigned Quals,
1841 SourceLocation FallbackLoc,
1842 SourceLocation ConstQualLoc = SourceLocation(),
1843 SourceLocation VolatileQualLoc = SourceLocation(),
1844 SourceLocation RestrictQualLoc = SourceLocation(),
1845 SourceLocation AtomicQualLoc = SourceLocation(),
1846 SourceLocation UnalignedQualLoc = SourceLocation());
1848 static bool adjustContextForLocalExternDecl(DeclContext *&DC);
1849 void DiagnoseFunctionSpecifiers(const DeclSpec &DS);
1850 NamedDecl *getShadowedDeclaration(const TypedefNameDecl *D,
1851 const LookupResult &R);
1852 NamedDecl *getShadowedDeclaration(const VarDecl *D, const LookupResult &R);
1853 void CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl,
1854 const LookupResult &R);
1855 void CheckShadow(Scope *S, VarDecl *D);
1857 /// Warn if 'E', which is an expression that is about to be modified, refers
1858 /// to a shadowing declaration.
1859 void CheckShadowingDeclModification(Expr *E, SourceLocation Loc);
1861 void DiagnoseShadowingLambdaDecls(const sema::LambdaScopeInfo *LSI);
1864 /// Map of current shadowing declarations to shadowed declarations. Warn if
1865 /// it looks like the user is trying to modify the shadowing declaration.
1866 llvm::DenseMap<const NamedDecl *, const NamedDecl *> ShadowingDecls;
1869 void CheckCastAlign(Expr *Op, QualType T, SourceRange TRange);
1870 void handleTagNumbering(const TagDecl *Tag, Scope *TagScope);
1871 void setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
1872 TypedefNameDecl *NewTD);
1873 void CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *D);
1874 NamedDecl* ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
1875 TypeSourceInfo *TInfo,
1876 LookupResult &Previous);
1877 NamedDecl* ActOnTypedefNameDecl(Scope* S, DeclContext* DC, TypedefNameDecl *D,
1878 LookupResult &Previous, bool &Redeclaration);
1879 NamedDecl *ActOnVariableDeclarator(Scope *S, Declarator &D, DeclContext *DC,
1880 TypeSourceInfo *TInfo,
1881 LookupResult &Previous,
1882 MultiTemplateParamsArg TemplateParamLists,
1884 ArrayRef<BindingDecl *> Bindings = None);
1886 ActOnDecompositionDeclarator(Scope *S, Declarator &D,
1887 MultiTemplateParamsArg TemplateParamLists);
1888 // Returns true if the variable declaration is a redeclaration
1889 bool CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous);
1890 void CheckVariableDeclarationType(VarDecl *NewVD);
1891 bool DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit,
1893 void CheckCompleteVariableDeclaration(VarDecl *VD);
1894 void CheckCompleteDecompositionDeclaration(DecompositionDecl *DD);
1895 void MaybeSuggestAddingStaticToDecl(const FunctionDecl *D);
1897 NamedDecl* ActOnFunctionDeclarator(Scope* S, Declarator& D, DeclContext* DC,
1898 TypeSourceInfo *TInfo,
1899 LookupResult &Previous,
1900 MultiTemplateParamsArg TemplateParamLists,
1902 bool AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD);
1904 bool CheckConstexprFunctionDecl(const FunctionDecl *FD);
1905 bool CheckConstexprFunctionBody(const FunctionDecl *FD, Stmt *Body);
1907 void DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD);
1908 void FindHiddenVirtualMethods(CXXMethodDecl *MD,
1909 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods);
1910 void NoteHiddenVirtualMethods(CXXMethodDecl *MD,
1911 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods);
1912 // Returns true if the function declaration is a redeclaration
1913 bool CheckFunctionDeclaration(Scope *S,
1914 FunctionDecl *NewFD, LookupResult &Previous,
1915 bool IsMemberSpecialization);
1916 bool shouldLinkDependentDeclWithPrevious(Decl *D, Decl *OldDecl);
1917 void CheckMain(FunctionDecl *FD, const DeclSpec &D);
1918 void CheckMSVCRTEntryPoint(FunctionDecl *FD);
1919 Decl *ActOnParamDeclarator(Scope *S, Declarator &D);
1920 ParmVarDecl *BuildParmVarDeclForTypedef(DeclContext *DC,
1923 ParmVarDecl *CheckParameter(DeclContext *DC, SourceLocation StartLoc,
1924 SourceLocation NameLoc, IdentifierInfo *Name,
1925 QualType T, TypeSourceInfo *TSInfo,
1927 void ActOnParamDefaultArgument(Decl *param,
1928 SourceLocation EqualLoc,
1930 void ActOnParamUnparsedDefaultArgument(Decl *param,
1931 SourceLocation EqualLoc,
1932 SourceLocation ArgLoc);
1933 void ActOnParamDefaultArgumentError(Decl *param, SourceLocation EqualLoc);
1934 bool SetParamDefaultArgument(ParmVarDecl *Param, Expr *DefaultArg,
1935 SourceLocation EqualLoc);
1937 void AddInitializerToDecl(Decl *dcl, Expr *init, bool DirectInit);
1938 void ActOnUninitializedDecl(Decl *dcl);
1939 void ActOnInitializerError(Decl *Dcl);
1941 void ActOnPureSpecifier(Decl *D, SourceLocation PureSpecLoc);
1942 void ActOnCXXForRangeDecl(Decl *D);
1943 StmtResult ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc,
1944 IdentifierInfo *Ident,
1945 ParsedAttributes &Attrs,
1946 SourceLocation AttrEnd);
1947 void SetDeclDeleted(Decl *dcl, SourceLocation DelLoc);
1948 void SetDeclDefaulted(Decl *dcl, SourceLocation DefaultLoc);
1949 void FinalizeDeclaration(Decl *D);
1950 DeclGroupPtrTy FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
1951 ArrayRef<Decl *> Group);
1952 DeclGroupPtrTy BuildDeclaratorGroup(MutableArrayRef<Decl *> Group);
1954 /// Should be called on all declarations that might have attached
1955 /// documentation comments.
1956 void ActOnDocumentableDecl(Decl *D);
1957 void ActOnDocumentableDecls(ArrayRef<Decl *> Group);
1959 void ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
1960 SourceLocation LocAfterDecls);
1961 void CheckForFunctionRedefinition(
1962 FunctionDecl *FD, const FunctionDecl *EffectiveDefinition = nullptr,
1963 SkipBodyInfo *SkipBody = nullptr);
1964 Decl *ActOnStartOfFunctionDef(Scope *S, Declarator &D,
1965 MultiTemplateParamsArg TemplateParamLists,
1966 SkipBodyInfo *SkipBody = nullptr);
1967 Decl *ActOnStartOfFunctionDef(Scope *S, Decl *D,
1968 SkipBodyInfo *SkipBody = nullptr);
1969 void ActOnStartOfObjCMethodDef(Scope *S, Decl *D);
1970 bool isObjCMethodDecl(Decl *D) {
1971 return D && isa<ObjCMethodDecl>(D);
1974 /// \brief Determine whether we can delay parsing the body of a function or
1975 /// function template until it is used, assuming we don't care about emitting
1976 /// code for that function.
1978 /// This will be \c false if we may need the body of the function in the
1979 /// middle of parsing an expression (where it's impractical to switch to
1980 /// parsing a different function), for instance, if it's constexpr in C++11
1981 /// or has an 'auto' return type in C++14. These cases are essentially bugs.
1982 bool canDelayFunctionBody(const Declarator &D);
1984 /// \brief Determine whether we can skip parsing the body of a function
1985 /// definition, assuming we don't care about analyzing its body or emitting
1986 /// code for that function.
1988 /// This will be \c false only if we may need the body of the function in
1989 /// order to parse the rest of the program (for instance, if it is
1990 /// \c constexpr in C++11 or has an 'auto' return type in C++14).
1991 bool canSkipFunctionBody(Decl *D);
1993 void computeNRVO(Stmt *Body, sema::FunctionScopeInfo *Scope);
1994 Decl *ActOnFinishFunctionBody(Decl *Decl, Stmt *Body);
1995 Decl *ActOnFinishFunctionBody(Decl *Decl, Stmt *Body, bool IsInstantiation);
1996 Decl *ActOnSkippedFunctionBody(Decl *Decl);
1997 void ActOnFinishInlineFunctionDef(FunctionDecl *D);
1999 /// ActOnFinishDelayedAttribute - Invoked when we have finished parsing an
2000 /// attribute for which parsing is delayed.
2001 void ActOnFinishDelayedAttribute(Scope *S, Decl *D, ParsedAttributes &Attrs);
2003 /// \brief Diagnose any unused parameters in the given sequence of
2004 /// ParmVarDecl pointers.
2005 void DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters);
2007 /// \brief Diagnose whether the size of parameters or return value of a
2008 /// function or obj-c method definition is pass-by-value and larger than a
2009 /// specified threshold.
2011 DiagnoseSizeOfParametersAndReturnValue(ArrayRef<ParmVarDecl *> Parameters,
2012 QualType ReturnTy, NamedDecl *D);
2014 void DiagnoseInvalidJumps(Stmt *Body);
2015 Decl *ActOnFileScopeAsmDecl(Expr *expr,
2016 SourceLocation AsmLoc,
2017 SourceLocation RParenLoc);
2019 /// \brief Handle a C++11 empty-declaration and attribute-declaration.
2020 Decl *ActOnEmptyDeclaration(Scope *S,
2021 AttributeList *AttrList,
2022 SourceLocation SemiLoc);
2024 enum class ModuleDeclKind {
2025 Module, ///< 'module X;'
2026 Partition, ///< 'module partition X;'
2027 Implementation, ///< 'module implementation X;'
2030 /// The parser has processed a module-declaration that begins the definition
2031 /// of a module interface or implementation.
2032 DeclGroupPtrTy ActOnModuleDecl(SourceLocation StartLoc,
2033 SourceLocation ModuleLoc, ModuleDeclKind MDK,
2036 /// \brief The parser has processed a module import declaration.
2038 /// \param AtLoc The location of the '@' symbol, if any.
2040 /// \param ImportLoc The location of the 'import' keyword.
2042 /// \param Path The module access path.
2043 DeclResult ActOnModuleImport(SourceLocation AtLoc, SourceLocation ImportLoc,
2046 /// \brief The parser has processed a module import translated from a
2047 /// #include or similar preprocessing directive.
2048 void ActOnModuleInclude(SourceLocation DirectiveLoc, Module *Mod);
2049 void BuildModuleInclude(SourceLocation DirectiveLoc, Module *Mod);
2051 /// \brief The parsed has entered a submodule.
2052 void ActOnModuleBegin(SourceLocation DirectiveLoc, Module *Mod);
2053 /// \brief The parser has left a submodule.
2054 void ActOnModuleEnd(SourceLocation DirectiveLoc, Module *Mod);
2056 /// \brief Create an implicit import of the given module at the given
2057 /// source location, for error recovery, if possible.
2059 /// This routine is typically used when an entity found by name lookup
2060 /// is actually hidden within a module that we know about but the user
2061 /// has forgotten to import.
2062 void createImplicitModuleImportForErrorRecovery(SourceLocation Loc,
2065 /// Kinds of missing import. Note, the values of these enumerators correspond
2066 /// to %select values in diagnostics.
2067 enum class MissingImportKind {
2071 ExplicitSpecialization,
2072 PartialSpecialization
2075 /// \brief Diagnose that the specified declaration needs to be visible but
2076 /// isn't, and suggest a module import that would resolve the problem.
2077 void diagnoseMissingImport(SourceLocation Loc, NamedDecl *Decl,
2078 MissingImportKind MIK, bool Recover = true);
2079 void diagnoseMissingImport(SourceLocation Loc, NamedDecl *Decl,
2080 SourceLocation DeclLoc, ArrayRef<Module *> Modules,
2081 MissingImportKind MIK, bool Recover);
2083 Decl *ActOnStartExportDecl(Scope *S, SourceLocation ExportLoc,
2084 SourceLocation LBraceLoc);
2085 Decl *ActOnFinishExportDecl(Scope *S, Decl *ExportDecl,
2086 SourceLocation RBraceLoc);
2088 /// \brief We've found a use of a templated declaration that would trigger an
2089 /// implicit instantiation. Check that any relevant explicit specializations
2090 /// and partial specializations are visible, and diagnose if not.
2091 void checkSpecializationVisibility(SourceLocation Loc, NamedDecl *Spec);
2093 /// \brief We've found a use of a template specialization that would select a
2094 /// partial specialization. Check that the partial specialization is visible,
2095 /// and diagnose if not.
2096 void checkPartialSpecializationVisibility(SourceLocation Loc,
2099 /// \brief Retrieve a suitable printing policy.
2100 PrintingPolicy getPrintingPolicy() const {
2101 return getPrintingPolicy(Context, PP);
2104 /// \brief Retrieve a suitable printing policy.
2105 static PrintingPolicy getPrintingPolicy(const ASTContext &Ctx,
2106 const Preprocessor &PP);
2109 void ActOnPopScope(SourceLocation Loc, Scope *S);
2110 void ActOnTranslationUnitScope(Scope *S);
2112 Decl *ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
2113 RecordDecl *&AnonRecord);
2114 Decl *ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
2115 MultiTemplateParamsArg TemplateParams,
2116 bool IsExplicitInstantiation,
2117 RecordDecl *&AnonRecord);
2119 Decl *BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
2122 const PrintingPolicy &Policy);
2124 Decl *BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
2125 RecordDecl *Record);
2127 /// Common ways to introduce type names without a tag for use in diagnostics.
2128 /// Keep in sync with err_tag_reference_non_tag.
2137 NTK_TypeAliasTemplate,
2138 NTK_TemplateTemplateArgument,
2141 /// Given a non-tag type declaration, returns an enum useful for indicating
2142 /// what kind of non-tag type this is.
2143 NonTagKind getNonTagTypeDeclKind(const Decl *D, TagTypeKind TTK);
2145 bool isAcceptableTagRedeclaration(const TagDecl *Previous,
2146 TagTypeKind NewTag, bool isDefinition,
2147 SourceLocation NewTagLoc,
2148 const IdentifierInfo *Name);
2151 TUK_Reference, // Reference to a tag: 'struct foo *X;'
2152 TUK_Declaration, // Fwd decl of a tag: 'struct foo;'
2153 TUK_Definition, // Definition of a tag: 'struct foo { int X; } Y;'
2154 TUK_Friend // Friend declaration: 'friend struct foo;'
2157 Decl *ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
2158 SourceLocation KWLoc, CXXScopeSpec &SS, IdentifierInfo *Name,
2159 SourceLocation NameLoc, AttributeList *Attr,
2160 AccessSpecifier AS, SourceLocation ModulePrivateLoc,
2161 MultiTemplateParamsArg TemplateParameterLists, bool &OwnedDecl,
2162 bool &IsDependent, SourceLocation ScopedEnumKWLoc,
2163 bool ScopedEnumUsesClassTag, TypeResult UnderlyingType,
2164 bool IsTypeSpecifier, bool IsTemplateParamOrArg,
2165 SkipBodyInfo *SkipBody = nullptr);
2167 Decl *ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
2168 unsigned TagSpec, SourceLocation TagLoc,
2170 IdentifierInfo *Name, SourceLocation NameLoc,
2171 AttributeList *Attr,
2172 MultiTemplateParamsArg TempParamLists);
2174 TypeResult ActOnDependentTag(Scope *S,
2177 const CXXScopeSpec &SS,
2178 IdentifierInfo *Name,
2179 SourceLocation TagLoc,
2180 SourceLocation NameLoc);
2182 void ActOnDefs(Scope *S, Decl *TagD, SourceLocation DeclStart,
2183 IdentifierInfo *ClassName,
2184 SmallVectorImpl<Decl *> &Decls);
2185 Decl *ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
2186 Declarator &D, Expr *BitfieldWidth);
2188 FieldDecl *HandleField(Scope *S, RecordDecl *TagD, SourceLocation DeclStart,
2189 Declarator &D, Expr *BitfieldWidth,
2190 InClassInitStyle InitStyle,
2191 AccessSpecifier AS);
2192 MSPropertyDecl *HandleMSProperty(Scope *S, RecordDecl *TagD,
2193 SourceLocation DeclStart,
2194 Declarator &D, Expr *BitfieldWidth,
2195 InClassInitStyle InitStyle,
2197 AttributeList *MSPropertyAttr);
2199 FieldDecl *CheckFieldDecl(DeclarationName Name, QualType T,
2200 TypeSourceInfo *TInfo,
2201 RecordDecl *Record, SourceLocation Loc,
2202 bool Mutable, Expr *BitfieldWidth,
2203 InClassInitStyle InitStyle,
2204 SourceLocation TSSL,
2205 AccessSpecifier AS, NamedDecl *PrevDecl,
2206 Declarator *D = nullptr);
2208 bool CheckNontrivialField(FieldDecl *FD);
2209 void DiagnoseNontrivial(const CXXRecordDecl *Record, CXXSpecialMember CSM);
2210 bool SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
2211 bool Diagnose = false);
2212 CXXSpecialMember getSpecialMember(const CXXMethodDecl *MD);
2213 void ActOnLastBitfield(SourceLocation DeclStart,
2214 SmallVectorImpl<Decl *> &AllIvarDecls);
2215 Decl *ActOnIvar(Scope *S, SourceLocation DeclStart,
2216 Declarator &D, Expr *BitfieldWidth,
2217 tok::ObjCKeywordKind visibility);
2219 // This is used for both record definitions and ObjC interface declarations.
2220 void ActOnFields(Scope* S, SourceLocation RecLoc, Decl *TagDecl,
2221 ArrayRef<Decl *> Fields,
2222 SourceLocation LBrac, SourceLocation RBrac,
2223 AttributeList *AttrList);
2225 /// ActOnTagStartDefinition - Invoked when we have entered the
2226 /// scope of a tag's definition (e.g., for an enumeration, class,
2227 /// struct, or union).
2228 void ActOnTagStartDefinition(Scope *S, Decl *TagDecl);
2230 /// Perform ODR-like check for C/ObjC when merging tag types from modules.
2231 /// Differently from C++, actually parse the body and reject / error out
2232 /// in case of a structural mismatch.
2233 bool ActOnDuplicateDefinition(DeclSpec &DS, Decl *Prev,
2234 SkipBodyInfo &SkipBody);
2236 typedef void *SkippedDefinitionContext;
2238 /// \brief Invoked when we enter a tag definition that we're skipping.
2239 SkippedDefinitionContext ActOnTagStartSkippedDefinition(Scope *S, Decl *TD);
2241 Decl *ActOnObjCContainerStartDefinition(Decl *IDecl);
2243 /// ActOnStartCXXMemberDeclarations - Invoked when we have parsed a
2244 /// C++ record definition's base-specifiers clause and are starting its
2245 /// member declarations.
2246 void ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagDecl,
2247 SourceLocation FinalLoc,
2248 bool IsFinalSpelledSealed,
2249 SourceLocation LBraceLoc);
2251 /// ActOnTagFinishDefinition - Invoked once we have finished parsing
2252 /// the definition of a tag (enumeration, class, struct, or union).
2253 void ActOnTagFinishDefinition(Scope *S, Decl *TagDecl,
2254 SourceRange BraceRange);
2256 void ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context);
2258 void ActOnObjCContainerFinishDefinition();
2260 /// \brief Invoked when we must temporarily exit the objective-c container
2261 /// scope for parsing/looking-up C constructs.
2263 /// Must be followed by a call to \see ActOnObjCReenterContainerContext
2264 void ActOnObjCTemporaryExitContainerContext(DeclContext *DC);
2265 void ActOnObjCReenterContainerContext(DeclContext *DC);
2267 /// ActOnTagDefinitionError - Invoked when there was an unrecoverable
2268 /// error parsing the definition of a tag.
2269 void ActOnTagDefinitionError(Scope *S, Decl *TagDecl);
2271 EnumConstantDecl *CheckEnumConstant(EnumDecl *Enum,
2272 EnumConstantDecl *LastEnumConst,
2273 SourceLocation IdLoc,
2276 bool CheckEnumUnderlyingType(TypeSourceInfo *TI);
2277 bool CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
2278 QualType EnumUnderlyingTy,
2279 bool EnumUnderlyingIsImplicit,
2280 const EnumDecl *Prev);
2282 /// Determine whether the body of an anonymous enumeration should be skipped.
2283 /// \param II The name of the first enumerator.
2284 SkipBodyInfo shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II,
2285 SourceLocation IILoc);
2287 Decl *ActOnEnumConstant(Scope *S, Decl *EnumDecl, Decl *LastEnumConstant,
2288 SourceLocation IdLoc, IdentifierInfo *Id,
2289 AttributeList *Attrs, SourceLocation EqualLoc,
2291 void ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange,
2293 ArrayRef<Decl *> Elements,
2294 Scope *S, AttributeList *Attr);
2296 DeclContext *getContainingDC(DeclContext *DC);
2298 /// Set the current declaration context until it gets popped.
2299 void PushDeclContext(Scope *S, DeclContext *DC);
2300 void PopDeclContext();
2302 /// EnterDeclaratorContext - Used when we must lookup names in the context
2303 /// of a declarator's nested name specifier.
2304 void EnterDeclaratorContext(Scope *S, DeclContext *DC);
2305 void ExitDeclaratorContext(Scope *S);
2307 /// Push the parameters of D, which must be a function, into scope.
2308 void ActOnReenterFunctionContext(Scope* S, Decl* D);
2309 void ActOnExitFunctionContext();
2311 DeclContext *getFunctionLevelDeclContext();
2313 /// getCurFunctionDecl - If inside of a function body, this returns a pointer
2314 /// to the function decl for the function being parsed. If we're currently
2315 /// in a 'block', this returns the containing context.
2316 FunctionDecl *getCurFunctionDecl();
2318 /// getCurMethodDecl - If inside of a method body, this returns a pointer to
2319 /// the method decl for the method being parsed. If we're currently
2320 /// in a 'block', this returns the containing context.
2321 ObjCMethodDecl *getCurMethodDecl();
2323 /// getCurFunctionOrMethodDecl - Return the Decl for the current ObjC method
2324 /// or C function we're in, otherwise return null. If we're currently
2325 /// in a 'block', this returns the containing context.
2326 NamedDecl *getCurFunctionOrMethodDecl();
2328 /// Add this decl to the scope shadowed decl chains.
2329 void PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext = true);
2331 /// \brief Make the given externally-produced declaration visible at the
2332 /// top level scope.
2334 /// \param D The externally-produced declaration to push.
2336 /// \param Name The name of the externally-produced declaration.
2337 void pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name);
2339 /// isDeclInScope - If 'Ctx' is a function/method, isDeclInScope returns true
2340 /// if 'D' is in Scope 'S', otherwise 'S' is ignored and isDeclInScope returns
2341 /// true if 'D' belongs to the given declaration context.
2343 /// \param AllowInlineNamespace If \c true, allow the declaration to be in the
2344 /// enclosing namespace set of the context, rather than contained
2345 /// directly within it.
2346 bool isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S = nullptr,
2347 bool AllowInlineNamespace = false);
2349 /// Finds the scope corresponding to the given decl context, if it
2350 /// happens to be an enclosing scope. Otherwise return NULL.
2351 static Scope *getScopeForDeclContext(Scope *S, DeclContext *DC);
2353 /// Subroutines of ActOnDeclarator().
2354 TypedefDecl *ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
2355 TypeSourceInfo *TInfo);
2356 bool isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New);
2358 /// \brief Describes the kind of merge to perform for availability
2359 /// attributes (including "deprecated", "unavailable", and "availability").
2360 enum AvailabilityMergeKind {
2361 /// \brief Don't merge availability attributes at all.
2363 /// \brief Merge availability attributes for a redeclaration, which requires
2366 /// \brief Merge availability attributes for an override, which requires
2367 /// an exact match or a weakening of constraints.
2369 /// \brief Merge availability attributes for an implementation of
2370 /// a protocol requirement.
2371 AMK_ProtocolImplementation,
2374 /// Attribute merging methods. Return true if a new attribute was added.
2375 AvailabilityAttr *mergeAvailabilityAttr(NamedDecl *D, SourceRange Range,
2376 IdentifierInfo *Platform,
2378 VersionTuple Introduced,
2379 VersionTuple Deprecated,
2380 VersionTuple Obsoleted,
2383 bool IsStrict, StringRef Replacement,
2384 AvailabilityMergeKind AMK,
2385 unsigned AttrSpellingListIndex);
2386 TypeVisibilityAttr *mergeTypeVisibilityAttr(Decl *D, SourceRange Range,
2387 TypeVisibilityAttr::VisibilityType Vis,
2388 unsigned AttrSpellingListIndex);
2389 VisibilityAttr *mergeVisibilityAttr(Decl *D, SourceRange Range,
2390 VisibilityAttr::VisibilityType Vis,
2391 unsigned AttrSpellingListIndex);
2392 UuidAttr *mergeUuidAttr(Decl *D, SourceRange Range,
2393 unsigned AttrSpellingListIndex, StringRef Uuid);
2394 DLLImportAttr *mergeDLLImportAttr(Decl *D, SourceRange Range,
2395 unsigned AttrSpellingListIndex);
2396 DLLExportAttr *mergeDLLExportAttr(Decl *D, SourceRange Range,
2397 unsigned AttrSpellingListIndex);
2399 mergeMSInheritanceAttr(Decl *D, SourceRange Range, bool BestCase,
2400 unsigned AttrSpellingListIndex,
2401 MSInheritanceAttr::Spelling SemanticSpelling);
2402 FormatAttr *mergeFormatAttr(Decl *D, SourceRange Range,
2403 IdentifierInfo *Format, int FormatIdx,
2404 int FirstArg, unsigned AttrSpellingListIndex);
2405 SectionAttr *mergeSectionAttr(Decl *D, SourceRange Range, StringRef Name,
2406 unsigned AttrSpellingListIndex);
2407 AlwaysInlineAttr *mergeAlwaysInlineAttr(Decl *D, SourceRange Range,
2408 IdentifierInfo *Ident,
2409 unsigned AttrSpellingListIndex);
2410 MinSizeAttr *mergeMinSizeAttr(Decl *D, SourceRange Range,
2411 unsigned AttrSpellingListIndex);
2412 OptimizeNoneAttr *mergeOptimizeNoneAttr(Decl *D, SourceRange Range,
2413 unsigned AttrSpellingListIndex);
2414 InternalLinkageAttr *mergeInternalLinkageAttr(Decl *D, SourceRange Range,
2415 IdentifierInfo *Ident,
2416 unsigned AttrSpellingListIndex);
2417 CommonAttr *mergeCommonAttr(Decl *D, SourceRange Range, IdentifierInfo *Ident,
2418 unsigned AttrSpellingListIndex);
2420 void mergeDeclAttributes(NamedDecl *New, Decl *Old,
2421 AvailabilityMergeKind AMK = AMK_Redeclaration);
2422 void MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New,
2423 LookupResult &OldDecls);
2424 bool MergeFunctionDecl(FunctionDecl *New, NamedDecl *&Old, Scope *S,
2425 bool MergeTypeWithOld);
2426 bool MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
2427 Scope *S, bool MergeTypeWithOld);
2428 void mergeObjCMethodDecls(ObjCMethodDecl *New, ObjCMethodDecl *Old);
2429 void MergeVarDecl(VarDecl *New, LookupResult &Previous);
2430 void MergeVarDeclTypes(VarDecl *New, VarDecl *Old, bool MergeTypeWithOld);
2431 void MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old);
2432 bool checkVarDeclRedefinition(VarDecl *OldDefn, VarDecl *NewDefn);
2433 void notePreviousDefinition(const NamedDecl *Old, SourceLocation New);
2434 bool MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old, Scope *S);
2436 // AssignmentAction - This is used by all the assignment diagnostic functions
2437 // to represent what is actually causing the operation
2438 enum AssignmentAction {
2446 AA_Passing_CFAudited
2449 /// C++ Overloading.
2451 /// This is a legitimate overload: the existing declarations are
2452 /// functions or function templates with different signatures.
2455 /// This is not an overload because the signature exactly matches
2456 /// an existing declaration.
2459 /// This is not an overload because the lookup results contain a
2463 OverloadKind CheckOverload(Scope *S,
2465 const LookupResult &OldDecls,
2466 NamedDecl *&OldDecl,
2467 bool IsForUsingDecl);
2468 bool IsOverload(FunctionDecl *New, FunctionDecl *Old, bool IsForUsingDecl,
2469 bool ConsiderCudaAttrs = true);
2471 /// \brief Checks availability of the function depending on the current
2472 /// function context.Inside an unavailable function,unavailability is ignored.
2474 /// \returns true if \p FD is unavailable and current context is inside
2475 /// an available function, false otherwise.
2476 bool isFunctionConsideredUnavailable(FunctionDecl *FD);
2478 ImplicitConversionSequence
2479 TryImplicitConversion(Expr *From, QualType ToType,
2480 bool SuppressUserConversions,
2482 bool InOverloadResolution,
2484 bool AllowObjCWritebackConversion);
2486 bool IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType);
2487 bool IsFloatingPointPromotion(QualType FromType, QualType ToType);
2488 bool IsComplexPromotion(QualType FromType, QualType ToType);
2489 bool IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
2490 bool InOverloadResolution,
2491 QualType& ConvertedType, bool &IncompatibleObjC);
2492 bool isObjCPointerConversion(QualType FromType, QualType ToType,
2493 QualType& ConvertedType, bool &IncompatibleObjC);
2494 bool isObjCWritebackConversion(QualType FromType, QualType ToType,
2495 QualType &ConvertedType);
2496 bool IsBlockPointerConversion(QualType FromType, QualType ToType,
2497 QualType& ConvertedType);
2498 bool FunctionParamTypesAreEqual(const FunctionProtoType *OldType,
2499 const FunctionProtoType *NewType,
2500 unsigned *ArgPos = nullptr);
2501 void HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
2502 QualType FromType, QualType ToType);
2504 void maybeExtendBlockObject(ExprResult &E);
2505 CastKind PrepareCastToObjCObjectPointer(ExprResult &E);
2506 bool CheckPointerConversion(Expr *From, QualType ToType,
2508 CXXCastPath& BasePath,
2509 bool IgnoreBaseAccess,
2510 bool Diagnose = true);
2511 bool IsMemberPointerConversion(Expr *From, QualType FromType, QualType ToType,
2512 bool InOverloadResolution,
2513 QualType &ConvertedType);
2514 bool CheckMemberPointerConversion(Expr *From, QualType ToType,
2516 CXXCastPath &BasePath,
2517 bool IgnoreBaseAccess);
2518 bool IsQualificationConversion(QualType FromType, QualType ToType,
2519 bool CStyle, bool &ObjCLifetimeConversion);
2520 bool IsFunctionConversion(QualType FromType, QualType ToType,
2521 QualType &ResultTy);
2522 bool DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType);
2523 bool isSameOrCompatibleFunctionType(CanQualType Param, CanQualType Arg);
2525 ExprResult PerformMoveOrCopyInitialization(const InitializedEntity &Entity,
2526 const VarDecl *NRVOCandidate,
2527 QualType ResultType,
2529 bool AllowNRVO = true);
2531 bool CanPerformCopyInitialization(const InitializedEntity &Entity,
2533 ExprResult PerformCopyInitialization(const InitializedEntity &Entity,
2534 SourceLocation EqualLoc,
2536 bool TopLevelOfInitList = false,
2537 bool AllowExplicit = false);
2538 ExprResult PerformObjectArgumentInitialization(Expr *From,
2539 NestedNameSpecifier *Qualifier,
2540 NamedDecl *FoundDecl,
2541 CXXMethodDecl *Method);
2543 ExprResult PerformContextuallyConvertToBool(Expr *From);
2544 ExprResult PerformContextuallyConvertToObjCPointer(Expr *From);
2546 /// Contexts in which a converted constant expression is required.
2548 CCEK_CaseValue, ///< Expression in a case label.
2549 CCEK_Enumerator, ///< Enumerator value with fixed underlying type.
2550 CCEK_TemplateArg, ///< Value of a non-type template parameter.
2551 CCEK_NewExpr, ///< Constant expression in a noptr-new-declarator.
2552 CCEK_ConstexprIf ///< Condition in a constexpr if statement.
2554 ExprResult CheckConvertedConstantExpression(Expr *From, QualType T,
2555 llvm::APSInt &Value, CCEKind CCE);
2556 ExprResult CheckConvertedConstantExpression(Expr *From, QualType T,
2557 APValue &Value, CCEKind CCE);
2559 /// \brief Abstract base class used to perform a contextual implicit
2560 /// conversion from an expression to any type passing a filter.
2561 class ContextualImplicitConverter {
2564 bool SuppressConversion;
2566 ContextualImplicitConverter(bool Suppress = false,
2567 bool SuppressConversion = false)
2568 : Suppress(Suppress), SuppressConversion(SuppressConversion) {}
2570 /// \brief Determine whether the specified type is a valid destination type
2571 /// for this conversion.
2572 virtual bool match(QualType T) = 0;
2574 /// \brief Emits a diagnostic complaining that the expression does not have
2575 /// integral or enumeration type.
2576 virtual SemaDiagnosticBuilder
2577 diagnoseNoMatch(Sema &S, SourceLocation Loc, QualType T) = 0;
2579 /// \brief Emits a diagnostic when the expression has incomplete class type.
2580 virtual SemaDiagnosticBuilder
2581 diagnoseIncomplete(Sema &S, SourceLocation Loc, QualType T) = 0;
2583 /// \brief Emits a diagnostic when the only matching conversion function
2585 virtual SemaDiagnosticBuilder diagnoseExplicitConv(
2586 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) = 0;
2588 /// \brief Emits a note for the explicit conversion function.
2589 virtual SemaDiagnosticBuilder
2590 noteExplicitConv(Sema &S, CXXConversionDecl *Conv, QualType ConvTy) = 0;
2592 /// \brief Emits a diagnostic when there are multiple possible conversion
2594 virtual SemaDiagnosticBuilder
2595 diagnoseAmbiguous(Sema &S, SourceLocation Loc, QualType T) = 0;
2597 /// \brief Emits a note for one of the candidate conversions.
2598 virtual SemaDiagnosticBuilder
2599 noteAmbiguous(Sema &S, CXXConversionDecl *Conv, QualType ConvTy) = 0;
2601 /// \brief Emits a diagnostic when we picked a conversion function
2602 /// (for cases when we are not allowed to pick a conversion function).
2603 virtual SemaDiagnosticBuilder diagnoseConversion(
2604 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) = 0;
2606 virtual ~ContextualImplicitConverter() {}
2609 class ICEConvertDiagnoser : public ContextualImplicitConverter {
2610 bool AllowScopedEnumerations;
2613 ICEConvertDiagnoser(bool AllowScopedEnumerations,
2614 bool Suppress, bool SuppressConversion)
2615 : ContextualImplicitConverter(Suppress, SuppressConversion),
2616 AllowScopedEnumerations(AllowScopedEnumerations) {}
2618 /// Match an integral or (possibly scoped) enumeration type.
2619 bool match(QualType T) override;
2621 SemaDiagnosticBuilder
2622 diagnoseNoMatch(Sema &S, SourceLocation Loc, QualType T) override {
2623 return diagnoseNotInt(S, Loc, T);
2626 /// \brief Emits a diagnostic complaining that the expression does not have
2627 /// integral or enumeration type.
2628 virtual SemaDiagnosticBuilder
2629 diagnoseNotInt(Sema &S, SourceLocation Loc, QualType T) = 0;
2632 /// Perform a contextual implicit conversion.
2633 ExprResult PerformContextualImplicitConversion(
2634 SourceLocation Loc, Expr *FromE, ContextualImplicitConverter &Converter);
2637 enum ObjCSubscriptKind {
2642 ObjCSubscriptKind CheckSubscriptingKind(Expr *FromE);
2644 // Note that LK_String is intentionally after the other literals, as
2645 // this is used for diagnostics logic.
2646 enum ObjCLiteralKind {
2655 ObjCLiteralKind CheckLiteralKind(Expr *FromE);
2657 ExprResult PerformObjectMemberConversion(Expr *From,
2658 NestedNameSpecifier *Qualifier,
2659 NamedDecl *FoundDecl,
2662 // Members have to be NamespaceDecl* or TranslationUnitDecl*.
2663 // TODO: make this is a typesafe union.
2664 typedef llvm::SmallSetVector<DeclContext *, 16> AssociatedNamespaceSet;
2665 typedef llvm::SmallSetVector<CXXRecordDecl *, 16> AssociatedClassSet;
2667 void AddOverloadCandidate(FunctionDecl *Function,
2668 DeclAccessPair FoundDecl,
2669 ArrayRef<Expr *> Args,
2670 OverloadCandidateSet &CandidateSet,
2671 bool SuppressUserConversions = false,
2672 bool PartialOverloading = false,
2673 bool AllowExplicit = false,
2674 ConversionSequenceList EarlyConversions = None);
2675 void AddFunctionCandidates(const UnresolvedSetImpl &Functions,
2676 ArrayRef<Expr *> Args,
2677 OverloadCandidateSet &CandidateSet,
2678 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr,
2679 bool SuppressUserConversions = false,
2680 bool PartialOverloading = false);
2681 void AddMethodCandidate(DeclAccessPair FoundDecl,
2682 QualType ObjectType,
2683 Expr::Classification ObjectClassification,
2684 ArrayRef<Expr *> Args,
2685 OverloadCandidateSet& CandidateSet,
2686 bool SuppressUserConversion = false);
2687 void AddMethodCandidate(CXXMethodDecl *Method,
2688 DeclAccessPair FoundDecl,
2689 CXXRecordDecl *ActingContext, QualType ObjectType,
2690 Expr::Classification ObjectClassification,
2691 ArrayRef<Expr *> Args,
2692 OverloadCandidateSet& CandidateSet,
2693 bool SuppressUserConversions = false,
2694 bool PartialOverloading = false,
2695 ConversionSequenceList EarlyConversions = None);
2696 void AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
2697 DeclAccessPair FoundDecl,
2698 CXXRecordDecl *ActingContext,
2699 TemplateArgumentListInfo *ExplicitTemplateArgs,
2700 QualType ObjectType,
2701 Expr::Classification ObjectClassification,
2702 ArrayRef<Expr *> Args,
2703 OverloadCandidateSet& CandidateSet,
2704 bool SuppressUserConversions = false,
2705 bool PartialOverloading = false);
2706 void AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
2707 DeclAccessPair FoundDecl,
2708 TemplateArgumentListInfo *ExplicitTemplateArgs,
2709 ArrayRef<Expr *> Args,
2710 OverloadCandidateSet& CandidateSet,
2711 bool SuppressUserConversions = false,
2712 bool PartialOverloading = false);
2713 bool CheckNonDependentConversions(FunctionTemplateDecl *FunctionTemplate,
2714 ArrayRef<QualType> ParamTypes,
2715 ArrayRef<Expr *> Args,
2716 OverloadCandidateSet &CandidateSet,
2717 ConversionSequenceList &Conversions,
2718 bool SuppressUserConversions,
2719 CXXRecordDecl *ActingContext = nullptr,
2720 QualType ObjectType = QualType(),
2721 Expr::Classification
2722 ObjectClassification = {});
2723 void AddConversionCandidate(CXXConversionDecl *Conversion,
2724 DeclAccessPair FoundDecl,
2725 CXXRecordDecl *ActingContext,
2726 Expr *From, QualType ToType,
2727 OverloadCandidateSet& CandidateSet,
2728 bool AllowObjCConversionOnExplicit);
2729 void AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
2730 DeclAccessPair FoundDecl,
2731 CXXRecordDecl *ActingContext,
2732 Expr *From, QualType ToType,
2733 OverloadCandidateSet &CandidateSet,
2734 bool AllowObjCConversionOnExplicit);
2735 void AddSurrogateCandidate(CXXConversionDecl *Conversion,
2736 DeclAccessPair FoundDecl,
2737 CXXRecordDecl *ActingContext,
2738 const FunctionProtoType *Proto,
2739 Expr *Object, ArrayRef<Expr *> Args,
2740 OverloadCandidateSet& CandidateSet);
2741 void AddMemberOperatorCandidates(OverloadedOperatorKind Op,
2742 SourceLocation OpLoc, ArrayRef<Expr *> Args,
2743 OverloadCandidateSet& CandidateSet,
2744 SourceRange OpRange = SourceRange());
2745 void AddBuiltinCandidate(QualType *ParamTys, ArrayRef<Expr *> Args,
2746 OverloadCandidateSet& CandidateSet,
2747 bool IsAssignmentOperator = false,
2748 unsigned NumContextualBoolArguments = 0);
2749 void AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
2750 SourceLocation OpLoc, ArrayRef<Expr *> Args,
2751 OverloadCandidateSet& CandidateSet);
2752 void AddArgumentDependentLookupCandidates(DeclarationName Name,
2754 ArrayRef<Expr *> Args,
2755 TemplateArgumentListInfo *ExplicitTemplateArgs,
2756 OverloadCandidateSet& CandidateSet,
2757 bool PartialOverloading = false);
2759 // Emit as a 'note' the specific overload candidate
2760 void NoteOverloadCandidate(NamedDecl *Found, FunctionDecl *Fn,
2761 QualType DestType = QualType(),
2762 bool TakingAddress = false);
2764 // Emit as a series of 'note's all template and non-templates identified by
2765 // the expression Expr
2766 void NoteAllOverloadCandidates(Expr *E, QualType DestType = QualType(),
2767 bool TakingAddress = false);
2769 /// Check the enable_if expressions on the given function. Returns the first
2770 /// failing attribute, or NULL if they were all successful.
2771 EnableIfAttr *CheckEnableIf(FunctionDecl *Function, ArrayRef<Expr *> Args,
2772 bool MissingImplicitThis = false);
2774 /// Emit diagnostics for the diagnose_if attributes on Function, ignoring any
2775 /// non-ArgDependent DiagnoseIfAttrs.
2777 /// Argument-dependent diagnose_if attributes should be checked each time a
2778 /// function is used as a direct callee of a function call.
2780 /// Returns true if any errors were emitted.
2781 bool diagnoseArgDependentDiagnoseIfAttrs(const FunctionDecl *Function,
2782 const Expr *ThisArg,
2783 ArrayRef<const Expr *> Args,
2784 SourceLocation Loc);
2786 /// Emit diagnostics for the diagnose_if attributes on Function, ignoring any
2787 /// ArgDependent DiagnoseIfAttrs.
2789 /// Argument-independent diagnose_if attributes should be checked on every use
2792 /// Returns true if any errors were emitted.
2793 bool diagnoseArgIndependentDiagnoseIfAttrs(const NamedDecl *ND,
2794 SourceLocation Loc);
2796 /// Returns whether the given function's address can be taken or not,
2797 /// optionally emitting a diagnostic if the address can't be taken.
2799 /// Returns false if taking the address of the function is illegal.
2800 bool checkAddressOfFunctionIsAvailable(const FunctionDecl *Function,
2801 bool Complain = false,
2802 SourceLocation Loc = SourceLocation());
2804 // [PossiblyAFunctionType] --> [Return]
2805 // NonFunctionType --> NonFunctionType
2807 // R (*)(A) --> R (A)
2808 // R (&)(A) --> R (A)
2809 // R (S::*)(A) --> R (A)
2810 QualType ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType);
2813 ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
2814 QualType TargetType,
2816 DeclAccessPair &Found,
2817 bool *pHadMultipleCandidates = nullptr);
2820 resolveAddressOfOnlyViableOverloadCandidate(Expr *E,
2821 DeclAccessPair &FoundResult);
2823 bool resolveAndFixAddressOfOnlyViableOverloadCandidate(
2824 ExprResult &SrcExpr, bool DoFunctionPointerConversion = false);
2827 ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
2828 bool Complain = false,
2829 DeclAccessPair *Found = nullptr);
2831 bool ResolveAndFixSingleFunctionTemplateSpecialization(
2832 ExprResult &SrcExpr,
2833 bool DoFunctionPointerConverion = false,
2834 bool Complain = false,
2835 SourceRange OpRangeForComplaining = SourceRange(),
2836 QualType DestTypeForComplaining = QualType(),
2837 unsigned DiagIDForComplaining = 0);
2840 Expr *FixOverloadedFunctionReference(Expr *E,
2841 DeclAccessPair FoundDecl,
2843 ExprResult FixOverloadedFunctionReference(ExprResult,
2844 DeclAccessPair FoundDecl,
2847 void AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
2848 ArrayRef<Expr *> Args,
2849 OverloadCandidateSet &CandidateSet,
2850 bool PartialOverloading = false);
2852 // An enum used to represent the different possible results of building a
2853 // range-based for loop.
2854 enum ForRangeStatus {
2856 FRS_NoViableFunction,
2857 FRS_DiagnosticIssued
2860 ForRangeStatus BuildForRangeBeginEndCall(SourceLocation Loc,
2861 SourceLocation RangeLoc,
2862 const DeclarationNameInfo &NameInfo,
2863 LookupResult &MemberLookup,
2864 OverloadCandidateSet *CandidateSet,
2865 Expr *Range, ExprResult *CallExpr);
2867 ExprResult BuildOverloadedCallExpr(Scope *S, Expr *Fn,
2868 UnresolvedLookupExpr *ULE,
2869 SourceLocation LParenLoc,
2871 SourceLocation RParenLoc,
2873 bool AllowTypoCorrection=true,
2874 bool CalleesAddressIsTaken=false);
2876 bool buildOverloadedCallSet(Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE,
2877 MultiExprArg Args, SourceLocation RParenLoc,
2878 OverloadCandidateSet *CandidateSet,
2879 ExprResult *Result);
2881 ExprResult CreateOverloadedUnaryOp(SourceLocation OpLoc,
2882 UnaryOperatorKind Opc,
2883 const UnresolvedSetImpl &Fns,
2886 ExprResult CreateOverloadedBinOp(SourceLocation OpLoc,
2887 BinaryOperatorKind Opc,
2888 const UnresolvedSetImpl &Fns,
2889 Expr *LHS, Expr *RHS);
2891 ExprResult CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
2892 SourceLocation RLoc,
2893 Expr *Base,Expr *Idx);
2896 BuildCallToMemberFunction(Scope *S, Expr *MemExpr,
2897 SourceLocation LParenLoc,
2899 SourceLocation RParenLoc);
2901 BuildCallToObjectOfClassType(Scope *S, Expr *Object, SourceLocation LParenLoc,
2903 SourceLocation RParenLoc);
2905 ExprResult BuildOverloadedArrowExpr(Scope *S, Expr *Base,
2906 SourceLocation OpLoc,
2907 bool *NoArrowOperatorFound = nullptr);
2909 /// CheckCallReturnType - Checks that a call expression's return type is
2910 /// complete. Returns true on failure. The location passed in is the location
2911 /// that best represents the call.
2912 bool CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
2913 CallExpr *CE, FunctionDecl *FD);
2915 /// Helpers for dealing with blocks and functions.
2916 bool CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters,
2917 bool CheckParameterNames);
2918 void CheckCXXDefaultArguments(FunctionDecl *FD);
2919 void CheckExtraCXXDefaultArguments(Declarator &D);
2920 Scope *getNonFieldDeclScope(Scope *S);
2922 /// \name Name lookup
2924 /// These routines provide name lookup that is used during semantic
2925 /// analysis to resolve the various kinds of names (identifiers,
2926 /// overloaded operator names, constructor names, etc.) into zero or
2927 /// more declarations within a particular scope. The major entry
2928 /// points are LookupName, which performs unqualified name lookup,
2929 /// and LookupQualifiedName, which performs qualified name lookup.
2931 /// All name lookup is performed based on some specific criteria,
2932 /// which specify what names will be visible to name lookup and how
2933 /// far name lookup should work. These criteria are important both
2934 /// for capturing language semantics (certain lookups will ignore
2935 /// certain names, for example) and for performance, since name
2936 /// lookup is often a bottleneck in the compilation of C++. Name
2937 /// lookup criteria is specified via the LookupCriteria enumeration.
2939 /// The results of name lookup can vary based on the kind of name
2940 /// lookup performed, the current language, and the translation
2941 /// unit. In C, for example, name lookup will either return nothing
2942 /// (no entity found) or a single declaration. In C++, name lookup
2943 /// can additionally refer to a set of overloaded functions or
2944 /// result in an ambiguity. All of the possible results of name
2945 /// lookup are captured by the LookupResult class, which provides
2946 /// the ability to distinguish among them.
2949 /// @brief Describes the kind of name lookup to perform.
2950 enum LookupNameKind {
2951 /// Ordinary name lookup, which finds ordinary names (functions,
2952 /// variables, typedefs, etc.) in C and most kinds of names
2953 /// (functions, variables, members, types, etc.) in C++.
2954 LookupOrdinaryName = 0,
2955 /// Tag name lookup, which finds the names of enums, classes,
2956 /// structs, and unions.
2958 /// Label name lookup.
2960 /// Member name lookup, which finds the names of
2961 /// class/struct/union members.
2963 /// Look up of an operator name (e.g., operator+) for use with
2964 /// operator overloading. This lookup is similar to ordinary name
2965 /// lookup, but will ignore any declarations that are class members.
2967 /// Look up of a name that precedes the '::' scope resolution
2968 /// operator in C++. This lookup completely ignores operator, object,
2969 /// function, and enumerator names (C++ [basic.lookup.qual]p1).
2970 LookupNestedNameSpecifierName,
2971 /// Look up a namespace name within a C++ using directive or
2972 /// namespace alias definition, ignoring non-namespace names (C++
2973 /// [basic.lookup.udir]p1).
2974 LookupNamespaceName,
2975 /// Look up all declarations in a scope with the given name,
2976 /// including resolved using declarations. This is appropriate
2977 /// for checking redeclarations for a using declaration.
2978 LookupUsingDeclName,
2979 /// Look up an ordinary name that is going to be redeclared as a
2980 /// name with linkage. This lookup ignores any declarations that
2981 /// are outside of the current scope unless they have linkage. See
2982 /// C99 6.2.2p4-5 and C++ [basic.link]p6.
2983 LookupRedeclarationWithLinkage,
2984 /// Look up a friend of a local class. This lookup does not look
2985 /// outside the innermost non-class scope. See C++11 [class.friend]p11.
2986 LookupLocalFriendName,
2987 /// Look up the name of an Objective-C protocol.
2988 LookupObjCProtocolName,
2989 /// Look up implicit 'self' parameter of an objective-c method.
2990 LookupObjCImplicitSelfParam,
2991 /// \brief Look up the name of an OpenMP user-defined reduction operation.
2992 LookupOMPReductionName,
2993 /// \brief Look up any declaration with any name.
2997 /// \brief Specifies whether (or how) name lookup is being performed for a
2998 /// redeclaration (vs. a reference).
2999 enum RedeclarationKind {
3000 /// \brief The lookup is a reference to this name that is not for the
3001 /// purpose of redeclaring the name.
3002 NotForRedeclaration = 0,
3003 /// \brief The lookup results will be used for redeclaration of a name,
3004 /// if an entity by that name already exists.
3008 /// \brief The possible outcomes of name lookup for a literal operator.
3009 enum LiteralOperatorLookupResult {
3010 /// \brief The lookup resulted in an error.
3012 /// \brief The lookup found a single 'cooked' literal operator, which
3013 /// expects a normal literal to be built and passed to it.
3015 /// \brief The lookup found a single 'raw' literal operator, which expects
3016 /// a string literal containing the spelling of the literal token.
3018 /// \brief The lookup found an overload set of literal operator templates,
3019 /// which expect the characters of the spelling of the literal token to be
3020 /// passed as a non-type template argument pack.
3022 /// \brief The lookup found an overload set of literal operator templates,
3023 /// which expect the character type and characters of the spelling of the
3024 /// string literal token to be passed as template arguments.
3028 SpecialMemberOverloadResult LookupSpecialMember(CXXRecordDecl *D,
3029 CXXSpecialMember SM,
3036 typedef std::function<void(const TypoCorrection &)> TypoDiagnosticGenerator;
3037 typedef std::function<ExprResult(Sema &, TypoExpr *, TypoCorrection)>
3038 TypoRecoveryCallback;
3041 bool CppLookupName(LookupResult &R, Scope *S);
3043 struct TypoExprState {
3044 std::unique_ptr<TypoCorrectionConsumer> Consumer;
3045 TypoDiagnosticGenerator DiagHandler;
3046 TypoRecoveryCallback RecoveryHandler;
3048 TypoExprState(TypoExprState &&other) noexcept;
3049 TypoExprState &operator=(TypoExprState &&other) noexcept;
3052 /// \brief The set of unhandled TypoExprs and their associated state.
3053 llvm::MapVector<TypoExpr *, TypoExprState> DelayedTypos;
3055 /// \brief Creates a new TypoExpr AST node.
3056 TypoExpr *createDelayedTypo(std::unique_ptr<TypoCorrectionConsumer> TCC,
3057 TypoDiagnosticGenerator TDG,
3058 TypoRecoveryCallback TRC);
3060 // \brief The set of known/encountered (unique, canonicalized) NamespaceDecls.
3062 // The boolean value will be true to indicate that the namespace was loaded
3063 // from an AST/PCH file, or false otherwise.
3064 llvm::MapVector<NamespaceDecl*, bool> KnownNamespaces;
3066 /// \brief Whether we have already loaded known namespaces from an extenal
3068 bool LoadedExternalKnownNamespaces;
3070 /// \brief Helper for CorrectTypo and CorrectTypoDelayed used to create and
3071 /// populate a new TypoCorrectionConsumer. Returns nullptr if typo correction
3072 /// should be skipped entirely.
3073 std::unique_ptr<TypoCorrectionConsumer>
3074 makeTypoCorrectionConsumer(const DeclarationNameInfo &Typo,
3075 Sema::LookupNameKind LookupKind, Scope *S,
3077 std::unique_ptr<CorrectionCandidateCallback> CCC,
3078 DeclContext *MemberContext, bool EnteringContext,
3079 const ObjCObjectPointerType *OPT,
3080 bool ErrorRecovery);
3083 const TypoExprState &getTypoExprState(TypoExpr *TE) const;
3085 /// \brief Clears the state of the given TypoExpr.
3086 void clearDelayedTypo(TypoExpr *TE);
3088 /// \brief Look up a name, looking for a single declaration. Return
3089 /// null if the results were absent, ambiguous, or overloaded.
3091 /// It is preferable to use the elaborated form and explicitly handle
3092 /// ambiguity and overloaded.
3093 NamedDecl *LookupSingleName(Scope *S, DeclarationName Name,
3095 LookupNameKind NameKind,
3096 RedeclarationKind Redecl
3097 = NotForRedeclaration);
3098 bool LookupName(LookupResult &R, Scope *S,
3099 bool AllowBuiltinCreation = false);
3100 bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
3101 bool InUnqualifiedLookup = false);
3102 bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
3104 bool LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS,
3105 bool AllowBuiltinCreation = false,
3106 bool EnteringContext = false);
3107 ObjCProtocolDecl *LookupProtocol(IdentifierInfo *II, SourceLocation IdLoc,
3108 RedeclarationKind Redecl
3109 = NotForRedeclaration);
3110 bool LookupInSuper(LookupResult &R, CXXRecordDecl *Class);
3112 void LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S,
3113 QualType T1, QualType T2,
3114 UnresolvedSetImpl &Functions);
3116 LabelDecl *LookupOrCreateLabel(IdentifierInfo *II, SourceLocation IdentLoc,
3117 SourceLocation GnuLabelLoc = SourceLocation());
3119 DeclContextLookupResult LookupConstructors(CXXRecordDecl *Class);
3120 CXXConstructorDecl *LookupDefaultConstructor(CXXRecordDecl *Class);
3121 CXXConstructorDecl *LookupCopyingConstructor(CXXRecordDecl *Class,
3123 CXXMethodDecl *LookupCopyingAssignment(CXXRecordDecl *Class, unsigned Quals,
3124 bool RValueThis, unsigned ThisQuals);
3125 CXXConstructorDecl *LookupMovingConstructor(CXXRecordDecl *Class,
3127 CXXMethodDecl *LookupMovingAssignment(CXXRecordDecl *Class, unsigned Quals,
3128 bool RValueThis, unsigned ThisQuals);
3129 CXXDestructorDecl *LookupDestructor(CXXRecordDecl *Class);
3131 bool checkLiteralOperatorId(const CXXScopeSpec &SS, const UnqualifiedId &Id);
3132 LiteralOperatorLookupResult LookupLiteralOperator(Scope *S, LookupResult &R,
3133 ArrayRef<QualType> ArgTys,
3136 bool AllowStringTemplate);
3137 bool isKnownName(StringRef name);
3139 void ArgumentDependentLookup(DeclarationName Name, SourceLocation Loc,
3140 ArrayRef<Expr *> Args, ADLResult &Functions);
3142 void LookupVisibleDecls(Scope *S, LookupNameKind Kind,
3143 VisibleDeclConsumer &Consumer,
3144 bool IncludeGlobalScope = true);
3145 void LookupVisibleDecls(DeclContext *Ctx, LookupNameKind Kind,
3146 VisibleDeclConsumer &Consumer,
3147 bool IncludeGlobalScope = true,
3148 bool IncludeDependentBases = false);
3150 enum CorrectTypoKind {
3151 CTK_NonError, // CorrectTypo used in a non error recovery situation.
3152 CTK_ErrorRecovery // CorrectTypo used in normal error recovery.
3155 TypoCorrection CorrectTypo(const DeclarationNameInfo &Typo,
3156 Sema::LookupNameKind LookupKind,
3157 Scope *S, CXXScopeSpec *SS,
3158 std::unique_ptr<CorrectionCandidateCallback> CCC,
3159 CorrectTypoKind Mode,
3160 DeclContext *MemberContext = nullptr,
3161 bool EnteringContext = false,
3162 const ObjCObjectPointerType *OPT = nullptr,
3163 bool RecordFailure = true);
3165 TypoExpr *CorrectTypoDelayed(const DeclarationNameInfo &Typo,
3166 Sema::LookupNameKind LookupKind, Scope *S,
3168 std::unique_ptr<CorrectionCandidateCallback> CCC,
3169 TypoDiagnosticGenerator TDG,
3170 TypoRecoveryCallback TRC, CorrectTypoKind Mode,
3171 DeclContext *MemberContext = nullptr,
3172 bool EnteringContext = false,
3173 const ObjCObjectPointerType *OPT = nullptr);
3175 /// \brief Process any TypoExprs in the given Expr and its children,
3176 /// generating diagnostics as appropriate and returning a new Expr if there
3177 /// were typos that were all successfully corrected and ExprError if one or
3178 /// more typos could not be corrected.
3180 /// \param E The Expr to check for TypoExprs.
3182 /// \param InitDecl A VarDecl to avoid because the Expr being corrected is its
3185 /// \param Filter A function applied to a newly rebuilt Expr to determine if
3186 /// it is an acceptable/usable result from a single combination of typo
3187 /// corrections. As long as the filter returns ExprError, different
3188 /// combinations of corrections will be tried until all are exhausted.
3190 CorrectDelayedTyposInExpr(Expr *E, VarDecl *InitDecl = nullptr,
3191 llvm::function_ref<ExprResult(Expr *)> Filter =
3192 [](Expr *E) -> ExprResult { return E; });
3195 CorrectDelayedTyposInExpr(Expr *E,
3196 llvm::function_ref<ExprResult(Expr *)> Filter) {
3197 return CorrectDelayedTyposInExpr(E, nullptr, Filter);
3201 CorrectDelayedTyposInExpr(ExprResult ER, VarDecl *InitDecl = nullptr,
3202 llvm::function_ref<ExprResult(Expr *)> Filter =
3203 [](Expr *E) -> ExprResult { return E; }) {
3204 return ER.isInvalid() ? ER : CorrectDelayedTyposInExpr(ER.get(), Filter);
3208 CorrectDelayedTyposInExpr(ExprResult ER,
3209 llvm::function_ref<ExprResult(Expr *)> Filter) {
3210 return CorrectDelayedTyposInExpr(ER, nullptr, Filter);
3213 void diagnoseTypo(const TypoCorrection &Correction,
3214 const PartialDiagnostic &TypoDiag,
3215 bool ErrorRecovery = true);
3217 void diagnoseTypo(const TypoCorrection &Correction,
3218 const PartialDiagnostic &TypoDiag,
3219 const PartialDiagnostic &PrevNote,
3220 bool ErrorRecovery = true);
3222 void MarkTypoCorrectedFunctionDefinition(const NamedDecl *F);
3224 void FindAssociatedClassesAndNamespaces(SourceLocation InstantiationLoc,
3225 ArrayRef<Expr *> Args,
3226 AssociatedNamespaceSet &AssociatedNamespaces,
3227 AssociatedClassSet &AssociatedClasses);
3229 void FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S,
3230 bool ConsiderLinkage, bool AllowInlineNamespace);
3232 void DiagnoseAmbiguousLookup(LookupResult &Result);
3235 ObjCInterfaceDecl *getObjCInterfaceDecl(IdentifierInfo *&Id,
3236 SourceLocation IdLoc,
3237 bool TypoCorrection = false);
3238 NamedDecl *LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID,
3239 Scope *S, bool ForRedeclaration,
3240 SourceLocation Loc);
3241 NamedDecl *ImplicitlyDefineFunction(SourceLocation Loc, IdentifierInfo &II,
3243 void AddKnownFunctionAttributes(FunctionDecl *FD);
3245 // More parsing and symbol table subroutines.
3247 void ProcessPragmaWeak(Scope *S, Decl *D);
3248 // Decl attributes - this routine is the top level dispatcher.
3249 void ProcessDeclAttributes(Scope *S, Decl *D, const Declarator &PD);
3250 // Helper for delayed processing of attributes.
3251 void ProcessDeclAttributeDelayed(Decl *D, const AttributeList *AttrList);
3252 void ProcessDeclAttributeList(Scope *S, Decl *D, const AttributeList *AL,
3253 bool IncludeCXX11Attributes = true);
3254 bool ProcessAccessDeclAttributeList(AccessSpecDecl *ASDecl,
3255 const AttributeList *AttrList);
3257 void checkUnusedDeclAttributes(Declarator &D);
3259 /// Determine if type T is a valid subject for a nonnull and similar
3260 /// attributes. By default, we look through references (the behavior used by
3261 /// nonnull), but if the second parameter is true, then we treat a reference
3263 bool isValidPointerAttrType(QualType T, bool RefOkay = false);
3265 bool CheckRegparmAttr(const AttributeList &attr, unsigned &value);
3266 bool CheckCallingConvAttr(const AttributeList &attr, CallingConv &CC,
3267 const FunctionDecl *FD = nullptr);
3268 bool CheckNoReturnAttr(const AttributeList &attr);
3269 bool CheckNoCallerSavedRegsAttr(const AttributeList &attr);
3270 bool checkStringLiteralArgumentAttr(const AttributeList &Attr,
3271 unsigned ArgNum, StringRef &Str,
3272 SourceLocation *ArgLocation = nullptr);
3273 bool checkSectionName(SourceLocation LiteralLoc, StringRef Str);
3274 void checkTargetAttr(SourceLocation LiteralLoc, StringRef Str);
3275 bool checkMSInheritanceAttrOnDefinition(
3276 CXXRecordDecl *RD, SourceRange Range, bool BestCase,
3277 MSInheritanceAttr::Spelling SemanticSpelling);
3279 void CheckAlignasUnderalignment(Decl *D);
3281 /// Adjust the calling convention of a method to be the ABI default if it
3282 /// wasn't specified explicitly. This handles method types formed from
3283 /// function type typedefs and typename template arguments.
3284 void adjustMemberFunctionCC(QualType &T, bool IsStatic, bool IsCtorOrDtor,
3285 SourceLocation Loc);
3287 // Check if there is an explicit attribute, but only look through parens.
3288 // The intent is to look for an attribute on the current declarator, but not
3289 // one that came from a typedef.
3290 bool hasExplicitCallingConv(QualType &T);
3292 /// Get the outermost AttributedType node that sets a calling convention.
3293 /// Valid types should not have multiple attributes with different CCs.
3294 const AttributedType *getCallingConvAttributedType(QualType T) const;
3296 /// Check whether a nullability type specifier can be added to the given
3299 /// \param type The type to which the nullability specifier will be
3300 /// added. On success, this type will be updated appropriately.
3302 /// \param nullability The nullability specifier to add.
3304 /// \param nullabilityLoc The location of the nullability specifier.
3306 /// \param isContextSensitive Whether this nullability specifier was
3307 /// written as a context-sensitive keyword (in an Objective-C
3308 /// method) or an Objective-C property attribute, rather than as an
3309 /// underscored type specifier.
3311 /// \param allowArrayTypes Whether to accept nullability specifiers on an
3312 /// array type (e.g., because it will decay to a pointer).
3314 /// \returns true if nullability cannot be applied, false otherwise.
3315 bool checkNullabilityTypeSpecifier(QualType &type, NullabilityKind nullability,
3316 SourceLocation nullabilityLoc,
3317 bool isContextSensitive,
3318 bool allowArrayTypes);
3320 /// \brief Stmt attributes - this routine is the top level dispatcher.
3321 StmtResult ProcessStmtAttributes(Stmt *Stmt, AttributeList *Attrs,
3324 void WarnConflictingTypedMethods(ObjCMethodDecl *Method,
3325 ObjCMethodDecl *MethodDecl,
3326 bool IsProtocolMethodDecl);
3328 void CheckConflictingOverridingMethod(ObjCMethodDecl *Method,
3329 ObjCMethodDecl *Overridden,
3330 bool IsProtocolMethodDecl);
3332 /// WarnExactTypedMethods - This routine issues a warning if method
3333 /// implementation declaration matches exactly that of its declaration.
3334 void WarnExactTypedMethods(ObjCMethodDecl *Method,
3335 ObjCMethodDecl *MethodDecl,
3336 bool IsProtocolMethodDecl);
3338 typedef llvm::SmallPtrSet<Selector, 8> SelectorSet;
3340 /// CheckImplementationIvars - This routine checks if the instance variables
3341 /// listed in the implelementation match those listed in the interface.
3342 void CheckImplementationIvars(ObjCImplementationDecl *ImpDecl,
3343 ObjCIvarDecl **Fields, unsigned nIvars,
3344 SourceLocation Loc);
3346 /// ImplMethodsVsClassMethods - This is main routine to warn if any method
3347 /// remains unimplemented in the class or category \@implementation.
3348 void ImplMethodsVsClassMethods(Scope *S, ObjCImplDecl* IMPDecl,
3349 ObjCContainerDecl* IDecl,
3350 bool IncompleteImpl = false);
3352 /// DiagnoseUnimplementedProperties - This routine warns on those properties
3353 /// which must be implemented by this implementation.
3354 void DiagnoseUnimplementedProperties(Scope *S, ObjCImplDecl* IMPDecl,
3355 ObjCContainerDecl *CDecl,
3356 bool SynthesizeProperties);
3358 /// Diagnose any null-resettable synthesized setters.
3359 void diagnoseNullResettableSynthesizedSetters(const ObjCImplDecl *impDecl);
3361 /// DefaultSynthesizeProperties - This routine default synthesizes all
3362 /// properties which must be synthesized in the class's \@implementation.
3363 void DefaultSynthesizeProperties(Scope *S, ObjCImplDecl *IMPDecl,
3364 ObjCInterfaceDecl *IDecl,
3365 SourceLocation AtEnd);
3366 void DefaultSynthesizeProperties(Scope *S, Decl *D, SourceLocation AtEnd);
3368 /// IvarBacksCurrentMethodAccessor - This routine returns 'true' if 'IV' is
3369 /// an ivar synthesized for 'Method' and 'Method' is a property accessor
3370 /// declared in class 'IFace'.
3371 bool IvarBacksCurrentMethodAccessor(ObjCInterfaceDecl *IFace,
3372 ObjCMethodDecl *Method, ObjCIvarDecl *IV);
3374 /// DiagnoseUnusedBackingIvarInAccessor - Issue an 'unused' warning if ivar which
3375 /// backs the property is not used in the property's accessor.
3376 void DiagnoseUnusedBackingIvarInAccessor(Scope *S,
3377 const ObjCImplementationDecl *ImplD);
3379 /// GetIvarBackingPropertyAccessor - If method is a property setter/getter and
3380 /// it property has a backing ivar, returns this ivar; otherwise, returns NULL.
3381 /// It also returns ivar's property on success.
3382 ObjCIvarDecl *GetIvarBackingPropertyAccessor(const ObjCMethodDecl *Method,
3383 const ObjCPropertyDecl *&PDecl) const;
3385 /// Called by ActOnProperty to handle \@property declarations in
3386 /// class extensions.
3387 ObjCPropertyDecl *HandlePropertyInClassExtension(Scope *S,
3388 SourceLocation AtLoc,
3389 SourceLocation LParenLoc,
3390 FieldDeclarator &FD,
3392 SourceLocation GetterNameLoc,
3394 SourceLocation SetterNameLoc,
3395 const bool isReadWrite,
3396 unsigned &Attributes,
3397 const unsigned AttributesAsWritten,
3399 TypeSourceInfo *TSI,
3400 tok::ObjCKeywordKind MethodImplKind);
3402 /// Called by ActOnProperty and HandlePropertyInClassExtension to
3403 /// handle creating the ObjcPropertyDecl for a category or \@interface.
3404 ObjCPropertyDecl *CreatePropertyDecl(Scope *S,
3405 ObjCContainerDecl *CDecl,
3406 SourceLocation AtLoc,
3407 SourceLocation LParenLoc,
3408 FieldDeclarator &FD,
3410 SourceLocation GetterNameLoc,
3412 SourceLocation SetterNameLoc,
3413 const bool isReadWrite,
3414 const unsigned Attributes,
3415 const unsigned AttributesAsWritten,
3417 TypeSourceInfo *TSI,
3418 tok::ObjCKeywordKind MethodImplKind,
3419 DeclContext *lexicalDC = nullptr);
3421 /// AtomicPropertySetterGetterRules - This routine enforces the rule (via
3422 /// warning) when atomic property has one but not the other user-declared
3423 /// setter or getter.
3424 void AtomicPropertySetterGetterRules(ObjCImplDecl* IMPDecl,
3425 ObjCInterfaceDecl* IDecl);
3427 void DiagnoseOwningPropertyGetterSynthesis(const ObjCImplementationDecl *D);
3429 void DiagnoseMissingDesignatedInitOverrides(
3430 const ObjCImplementationDecl *ImplD,
3431 const ObjCInterfaceDecl *IFD);
3433 void DiagnoseDuplicateIvars(ObjCInterfaceDecl *ID, ObjCInterfaceDecl *SID);
3435 enum MethodMatchStrategy {
3440 /// MatchTwoMethodDeclarations - Checks if two methods' type match and returns
3441 /// true, or false, accordingly.
3442 bool MatchTwoMethodDeclarations(const ObjCMethodDecl *Method,
3443 const ObjCMethodDecl *PrevMethod,
3444 MethodMatchStrategy strategy = MMS_strict);
3446 /// MatchAllMethodDeclarations - Check methods declaraed in interface or
3447 /// or protocol against those declared in their implementations.
3448 void MatchAllMethodDeclarations(const SelectorSet &InsMap,
3449 const SelectorSet &ClsMap,
3450 SelectorSet &InsMapSeen,
3451 SelectorSet &ClsMapSeen,
3452 ObjCImplDecl* IMPDecl,
3453 ObjCContainerDecl* IDecl,
3454 bool &IncompleteImpl,
3455 bool ImmediateClass,
3456 bool WarnCategoryMethodImpl=false);
3458 /// CheckCategoryVsClassMethodMatches - Checks that methods implemented in
3459 /// category matches with those implemented in its primary class and
3460 /// warns each time an exact match is found.
3461 void CheckCategoryVsClassMethodMatches(ObjCCategoryImplDecl *CatIMP);
3463 /// \brief Add the given method to the list of globally-known methods.
3464 void addMethodToGlobalList(ObjCMethodList *List, ObjCMethodDecl *Method);
3467 /// AddMethodToGlobalPool - Add an instance or factory method to the global
3468 /// pool. See descriptoin of AddInstanceMethodToGlobalPool.
3469 void AddMethodToGlobalPool(ObjCMethodDecl *Method, bool impl, bool instance);
3471 /// LookupMethodInGlobalPool - Returns the instance or factory method and
3472 /// optionally warns if there are multiple signatures.
3473 ObjCMethodDecl *LookupMethodInGlobalPool(Selector Sel, SourceRange R,
3474 bool receiverIdOrClass,
3478 /// \brief - Returns instance or factory methods in global method pool for
3479 /// given selector. It checks the desired kind first, if none is found, and
3480 /// parameter checkTheOther is set, it then checks the other kind. If no such
3481 /// method or only one method is found, function returns false; otherwise, it
3484 CollectMultipleMethodsInGlobalPool(Selector Sel,
3485 SmallVectorImpl<ObjCMethodDecl*>& Methods,
3486 bool InstanceFirst, bool CheckTheOther,
3487 const ObjCObjectType *TypeBound = nullptr);
3490 AreMultipleMethodsInGlobalPool(Selector Sel, ObjCMethodDecl *BestMethod,
3491 SourceRange R, bool receiverIdOrClass,
3492 SmallVectorImpl<ObjCMethodDecl*>& Methods);
3495 DiagnoseMultipleMethodInGlobalPool(SmallVectorImpl<ObjCMethodDecl*> &Methods,
3496 Selector Sel, SourceRange R,
3497 bool receiverIdOrClass);
3500 /// \brief - Returns a selector which best matches given argument list or
3501 /// nullptr if none could be found
3502 ObjCMethodDecl *SelectBestMethod(Selector Sel, MultiExprArg Args,
3504 SmallVectorImpl<ObjCMethodDecl*>& Methods);
3507 /// \brief Record the typo correction failure and return an empty correction.
3508 TypoCorrection FailedCorrection(IdentifierInfo *Typo, SourceLocation TypoLoc,
3509 bool RecordFailure = true) {
3511 TypoCorrectionFailures[Typo].insert(TypoLoc);
3512 return TypoCorrection();
3516 /// AddInstanceMethodToGlobalPool - All instance methods in a translation
3517 /// unit are added to a global pool. This allows us to efficiently associate
3518 /// a selector with a method declaraation for purposes of typechecking
3519 /// messages sent to "id" (where the class of the object is unknown).
3520 void AddInstanceMethodToGlobalPool(ObjCMethodDecl *Method, bool impl=false) {
3521 AddMethodToGlobalPool(Method, impl, /*instance*/true);
3524 /// AddFactoryMethodToGlobalPool - Same as above, but for factory methods.
3525 void AddFactoryMethodToGlobalPool(ObjCMethodDecl *Method, bool impl=false) {
3526 AddMethodToGlobalPool(Method, impl, /*instance*/false);
3529 /// AddAnyMethodToGlobalPool - Add any method, instance or factory to global
3531 void AddAnyMethodToGlobalPool(Decl *D);
3533 /// LookupInstanceMethodInGlobalPool - Returns the method and warns if
3534 /// there are multiple signatures.
3535 ObjCMethodDecl *LookupInstanceMethodInGlobalPool(Selector Sel, SourceRange R,
3536 bool receiverIdOrClass=false) {
3537 return LookupMethodInGlobalPool(Sel, R, receiverIdOrClass,
3541 /// LookupFactoryMethodInGlobalPool - Returns the method and warns if
3542 /// there are multiple signatures.
3543 ObjCMethodDecl *LookupFactoryMethodInGlobalPool(Selector Sel, SourceRange R,
3544 bool receiverIdOrClass=false) {
3545 return LookupMethodInGlobalPool(Sel, R, receiverIdOrClass,
3549 const ObjCMethodDecl *SelectorsForTypoCorrection(Selector Sel,
3550 QualType ObjectType=QualType());
3551 /// LookupImplementedMethodInGlobalPool - Returns the method which has an
3553 ObjCMethodDecl *LookupImplementedMethodInGlobalPool(Selector Sel);
3555 /// CollectIvarsToConstructOrDestruct - Collect those ivars which require
3557 void CollectIvarsToConstructOrDestruct(ObjCInterfaceDecl *OI,
3558 SmallVectorImpl<ObjCIvarDecl*> &Ivars);
3560 //===--------------------------------------------------------------------===//
3561 // Statement Parsing Callbacks: SemaStmt.cpp.
3565 FullExprArg() : E(nullptr) { }
3566 FullExprArg(Sema &actions) : E(nullptr) { }
3568 ExprResult release() {
3572 Expr *get() const { return E; }
3574 Expr *operator->() {
3579 // FIXME: No need to make the entire Sema class a friend when it's just
3580 // Sema::MakeFullExpr that needs access to the constructor below.
3583 explicit FullExprArg(Expr *expr) : E(expr) {}
3588 FullExprArg MakeFullExpr(Expr *Arg) {
3589 return MakeFullExpr(Arg, Arg ? Arg->getExprLoc() : SourceLocation());
3591 FullExprArg MakeFullExpr(Expr *Arg, SourceLocation CC) {
3592 return FullExprArg(ActOnFinishFullExpr(Arg, CC).get());
3594 FullExprArg MakeFullDiscardedValueExpr(Expr *Arg) {
3596 ActOnFinishFullExpr(Arg, Arg ? Arg->getExprLoc() : SourceLocation(),
3597 /*DiscardedValue*/ true);
3598 return FullExprArg(FE.get());
3601 StmtResult ActOnExprStmt(ExprResult Arg);
3602 StmtResult ActOnExprStmtError();
3604 StmtResult ActOnNullStmt(SourceLocation SemiLoc,
3605 bool HasLeadingEmptyMacro = false);
3607 void ActOnStartOfCompoundStmt();
3608 void ActOnFinishOfCompoundStmt();
3609 StmtResult ActOnCompoundStmt(SourceLocation L, SourceLocation R,
3610 ArrayRef<Stmt *> Elts, bool isStmtExpr);
3612 /// \brief A RAII object to enter scope of a compound statement.
3613 class CompoundScopeRAII {
3615 CompoundScopeRAII(Sema &S): S(S) {
3616 S.ActOnStartOfCompoundStmt();
3619 ~CompoundScopeRAII() {
3620 S.ActOnFinishOfCompoundStmt();
3627 /// An RAII helper that pops function a function scope on exit.
3628 struct FunctionScopeRAII {
3631 FunctionScopeRAII(Sema &S) : S(S), Active(true) {}
3632 ~FunctionScopeRAII() {
3634 S.PopFunctionScopeInfo();
3636 void disable() { Active = false; }
3639 StmtResult ActOnDeclStmt(DeclGroupPtrTy Decl,
3640 SourceLocation StartLoc,
3641 SourceLocation EndLoc);
3642 void ActOnForEachDeclStmt(DeclGroupPtrTy Decl);
3643 StmtResult ActOnForEachLValueExpr(Expr *E);
3644 StmtResult ActOnCaseStmt(SourceLocation CaseLoc, Expr *LHSVal,
3645 SourceLocation DotDotDotLoc, Expr *RHSVal,
3646 SourceLocation ColonLoc);
3647 void ActOnCaseStmtBody(Stmt *CaseStmt, Stmt *SubStmt);
3649 StmtResult ActOnDefaultStmt(SourceLocation DefaultLoc,
3650 SourceLocation ColonLoc,
3651 Stmt *SubStmt, Scope *CurScope);
3652 StmtResult ActOnLabelStmt(SourceLocation IdentLoc, LabelDecl *TheDecl,
3653 SourceLocation ColonLoc, Stmt *SubStmt);
3655 StmtResult ActOnAttributedStmt(SourceLocation AttrLoc,
3656 ArrayRef<const Attr*> Attrs,
3659 class ConditionResult;
3660 StmtResult ActOnIfStmt(SourceLocation IfLoc, bool IsConstexpr,
3662 ConditionResult Cond, Stmt *ThenVal,
3663 SourceLocation ElseLoc, Stmt *ElseVal);
3664 StmtResult BuildIfStmt(SourceLocation IfLoc, bool IsConstexpr,
3666 ConditionResult Cond, Stmt *ThenVal,
3667 SourceLocation ElseLoc, Stmt *ElseVal);
3668 StmtResult ActOnStartOfSwitchStmt(SourceLocation SwitchLoc,
3670 ConditionResult Cond);
3671 StmtResult ActOnFinishSwitchStmt(SourceLocation SwitchLoc,
3672 Stmt *Switch, Stmt *Body);
3673 StmtResult ActOnWhileStmt(SourceLocation WhileLoc, ConditionResult Cond,
3675 StmtResult ActOnDoStmt(SourceLocation DoLoc, Stmt *Body,
3676 SourceLocation WhileLoc, SourceLocation CondLParen,
3677 Expr *Cond, SourceLocation CondRParen);
3679 StmtResult ActOnForStmt(SourceLocation ForLoc,
3680 SourceLocation LParenLoc,
3682 ConditionResult Second,
3684 SourceLocation RParenLoc,
3686 ExprResult CheckObjCForCollectionOperand(SourceLocation forLoc,
3688 StmtResult ActOnObjCForCollectionStmt(SourceLocation ForColLoc,
3689 Stmt *First, Expr *collection,
3690 SourceLocation RParenLoc);
3691 StmtResult FinishObjCForCollectionStmt(Stmt *ForCollection, Stmt *Body);
3693 enum BuildForRangeKind {
3694 /// Initial building of a for-range statement.
3696 /// Instantiation or recovery rebuild of a for-range statement. Don't
3697 /// attempt any typo-correction.
3699 /// Determining whether a for-range statement could be built. Avoid any
3700 /// unnecessary or irreversible actions.
3704 StmtResult ActOnCXXForRangeStmt(Scope *S, SourceLocation ForLoc,
3705 SourceLocation CoawaitLoc,
3707 SourceLocation ColonLoc, Expr *Collection,
3708 SourceLocation RParenLoc,
3709 BuildForRangeKind Kind);
3710 StmtResult BuildCXXForRangeStmt(SourceLocation ForLoc,
3711 SourceLocation CoawaitLoc,
3712 SourceLocation ColonLoc,
3713 Stmt *RangeDecl, Stmt *Begin, Stmt *End,
3714 Expr *Cond, Expr *Inc,
3716 SourceLocation RParenLoc,
3717 BuildForRangeKind Kind);
3718 StmtResult FinishCXXForRangeStmt(Stmt *ForRange, Stmt *Body);
3720 StmtResult ActOnGotoStmt(SourceLocation GotoLoc,
3721 SourceLocation LabelLoc,
3722 LabelDecl *TheDecl);
3723 StmtResult ActOnIndirectGotoStmt(SourceLocation GotoLoc,
3724 SourceLocation StarLoc,
3726 StmtResult ActOnContinueStmt(SourceLocation ContinueLoc, Scope *CurScope);
3727 StmtResult ActOnBreakStmt(SourceLocation BreakLoc, Scope *CurScope);
3729 void ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope,
3730 CapturedRegionKind Kind, unsigned NumParams);
3731 typedef std::pair<StringRef, QualType> CapturedParamNameType;
3732 void ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope,
3733 CapturedRegionKind Kind,
3734 ArrayRef<CapturedParamNameType> Params);
3735 StmtResult ActOnCapturedRegionEnd(Stmt *S);
3736 void ActOnCapturedRegionError();
3737 RecordDecl *CreateCapturedStmtRecordDecl(CapturedDecl *&CD,
3739 unsigned NumParams);
3740 VarDecl *getCopyElisionCandidate(QualType ReturnType, Expr *E,
3741 bool AllowParamOrMoveConstructible);
3742 bool isCopyElisionCandidate(QualType ReturnType, const VarDecl *VD,
3743 bool AllowParamOrMoveConstructible);
3745 StmtResult ActOnReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp,
3747 StmtResult BuildReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp);
3748 StmtResult ActOnCapScopeReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp);
3750 StmtResult ActOnGCCAsmStmt(SourceLocation AsmLoc, bool IsSimple,
3751 bool IsVolatile, unsigned NumOutputs,
3752 unsigned NumInputs, IdentifierInfo **Names,
3753 MultiExprArg Constraints, MultiExprArg Exprs,
3754 Expr *AsmString, MultiExprArg Clobbers,
3755 SourceLocation RParenLoc);
3757 ExprResult LookupInlineAsmIdentifier(CXXScopeSpec &SS,
3758 SourceLocation TemplateKWLoc,
3760 llvm::InlineAsmIdentifierInfo &Info,
3761 bool IsUnevaluatedContext);
3762 bool LookupInlineAsmField(StringRef Base, StringRef Member,
3763 unsigned &Offset, SourceLocation AsmLoc);
3764 ExprResult LookupInlineAsmVarDeclField(Expr *RefExpr, StringRef Member,
3765 llvm::InlineAsmIdentifierInfo &Info,
3766 SourceLocation AsmLoc);
3767 StmtResult ActOnMSAsmStmt(SourceLocation AsmLoc, SourceLocation LBraceLoc,
3768 ArrayRef<Token> AsmToks,
3769 StringRef AsmString,
3770 unsigned NumOutputs, unsigned NumInputs,
3771 ArrayRef<StringRef> Constraints,
3772 ArrayRef<StringRef> Clobbers,
3773 ArrayRef<Expr*> Exprs,
3774 SourceLocation EndLoc);
3775 LabelDecl *GetOrCreateMSAsmLabel(StringRef ExternalLabelName,
3776 SourceLocation Location,
3779 VarDecl *BuildObjCExceptionDecl(TypeSourceInfo *TInfo, QualType ExceptionType,
3780 SourceLocation StartLoc,
3781 SourceLocation IdLoc, IdentifierInfo *Id,
3782 bool Invalid = false);
3784 Decl *ActOnObjCExceptionDecl(Scope *S, Declarator &D);
3786 StmtResult ActOnObjCAtCatchStmt(SourceLocation AtLoc, SourceLocation RParen,
3787 Decl *Parm, Stmt *Body);
3789 StmtResult ActOnObjCAtFinallyStmt(SourceLocation AtLoc, Stmt *Body);
3791 StmtResult ActOnObjCAtTryStmt(SourceLocation AtLoc, Stmt *Try,
3792 MultiStmtArg Catch, Stmt *Finally);
3794 StmtResult BuildObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw);
3795 StmtResult ActOnObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw,
3797 ExprResult ActOnObjCAtSynchronizedOperand(SourceLocation atLoc,
3799 StmtResult ActOnObjCAtSynchronizedStmt(SourceLocation AtLoc,
3803 StmtResult ActOnObjCAutoreleasePoolStmt(SourceLocation AtLoc, Stmt *Body);
3805 VarDecl *BuildExceptionDeclaration(Scope *S, TypeSourceInfo *TInfo,
3806 SourceLocation StartLoc,
3807 SourceLocation IdLoc,
3808 IdentifierInfo *Id);
3810 Decl *ActOnExceptionDeclarator(Scope *S, Declarator &D);
3812 StmtResult ActOnCXXCatchBlock(SourceLocation CatchLoc,
3813 Decl *ExDecl, Stmt *HandlerBlock);
3814 StmtResult ActOnCXXTryBlock(SourceLocation TryLoc, Stmt *TryBlock,
3815 ArrayRef<Stmt *> Handlers);
3817 StmtResult ActOnSEHTryBlock(bool IsCXXTry, // try (true) or __try (false) ?
3818 SourceLocation TryLoc, Stmt *TryBlock,
3820 StmtResult ActOnSEHExceptBlock(SourceLocation Loc,
3823 void ActOnStartSEHFinallyBlock();
3824 void ActOnAbortSEHFinallyBlock();
3825 StmtResult ActOnFinishSEHFinallyBlock(SourceLocation Loc, Stmt *Block);
3826 StmtResult ActOnSEHLeaveStmt(SourceLocation Loc, Scope *CurScope);
3828 void DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock);
3830 bool ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const;
3832 /// \brief If it's a file scoped decl that must warn if not used, keep track
3834 void MarkUnusedFileScopedDecl(const DeclaratorDecl *D);
3836 /// DiagnoseUnusedExprResult - If the statement passed in is an expression
3837 /// whose result is unused, warn.
3838 void DiagnoseUnusedExprResult(const Stmt *S);
3839 void DiagnoseUnusedNestedTypedefs(const RecordDecl *D);
3840 void DiagnoseUnusedDecl(const NamedDecl *ND);
3842 /// Emit \p DiagID if statement located on \p StmtLoc has a suspicious null
3843 /// statement as a \p Body, and it is located on the same line.
3845 /// This helps prevent bugs due to typos, such as:
3848 void DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
3852 /// Warn if a for/while loop statement \p S, which is followed by
3853 /// \p PossibleBody, has a suspicious null statement as a body.
3854 void DiagnoseEmptyLoopBody(const Stmt *S,
3855 const Stmt *PossibleBody);
3857 /// Warn if a value is moved to itself.
3858 void DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
3859 SourceLocation OpLoc);
3861 /// \brief Warn if we're implicitly casting from a _Nullable pointer type to a
3863 void diagnoseNullableToNonnullConversion(QualType DstType, QualType SrcType,
3864 SourceLocation Loc);
3866 /// Warn when implicitly casting 0 to nullptr.
3867 void diagnoseZeroToNullptrConversion(CastKind Kind, const Expr *E);
3869 ParsingDeclState PushParsingDeclaration(sema::DelayedDiagnosticPool &pool) {
3870 return DelayedDiagnostics.push(pool);
3872 void PopParsingDeclaration(ParsingDeclState state, Decl *decl);
3874 typedef ProcessingContextState ParsingClassState;
3875 ParsingClassState PushParsingClass() {
3876 return DelayedDiagnostics.pushUndelayed();
3878 void PopParsingClass(ParsingClassState state) {
3879 DelayedDiagnostics.popUndelayed(state);
3882 void redelayDiagnostics(sema::DelayedDiagnosticPool &pool);
3884 void DiagnoseAvailabilityOfDecl(NamedDecl *D, SourceLocation Loc,
3885 const ObjCInterfaceDecl *UnknownObjCClass,
3886 bool ObjCPropertyAccess,
3887 bool AvoidPartialAvailabilityChecks = false);
3889 bool makeUnavailableInSystemHeader(SourceLocation loc,
3890 UnavailableAttr::ImplicitReason reason);
3892 /// \brief Issue any -Wunguarded-availability warnings in \c FD
3893 void DiagnoseUnguardedAvailabilityViolations(Decl *FD);
3895 //===--------------------------------------------------------------------===//
3896 // Expression Parsing Callbacks: SemaExpr.cpp.
3898 bool CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid);
3899 bool DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc,
3900 const ObjCInterfaceDecl *UnknownObjCClass = nullptr,
3901 bool ObjCPropertyAccess = false,
3902 bool AvoidPartialAvailabilityChecks = false);
3903 void NoteDeletedFunction(FunctionDecl *FD);
3904 void NoteDeletedInheritingConstructor(CXXConstructorDecl *CD);
3905 std::string getDeletedOrUnavailableSuffix(const FunctionDecl *FD);
3906 bool DiagnosePropertyAccessorMismatch(ObjCPropertyDecl *PD,
3907 ObjCMethodDecl *Getter,
3908 SourceLocation Loc);
3909 void DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
3910 ArrayRef<Expr *> Args);
3912 void PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
3913 Decl *LambdaContextDecl = nullptr,
3914 bool IsDecltype = false);
3915 enum ReuseLambdaContextDecl_t { ReuseLambdaContextDecl };
3916 void PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
3917 ReuseLambdaContextDecl_t,
3918 bool IsDecltype = false);
3919 void PopExpressionEvaluationContext();
3921 void DiscardCleanupsInEvaluationContext();
3923 ExprResult TransformToPotentiallyEvaluated(Expr *E);
3924 ExprResult HandleExprEvaluationContextForTypeof(Expr *E);
3926 ExprResult ActOnConstantExpression(ExprResult Res);
3928 // Functions for marking a declaration referenced. These functions also
3929 // contain the relevant logic for marking if a reference to a function or
3930 // variable is an odr-use (in the C++11 sense). There are separate variants
3931 // for expressions referring to a decl; these exist because odr-use marking
3932 // needs to be delayed for some constant variables when we build one of the
3933 // named expressions.
3935 // MightBeOdrUse indicates whether the use could possibly be an odr-use, and
3936 // should usually be true. This only needs to be set to false if the lack of
3937 // odr-use cannot be determined from the current context (for instance,
3938 // because the name denotes a virtual function and was written without an
3939 // explicit nested-name-specifier).
3940 void MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, bool MightBeOdrUse);
3941 void MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func,
3942 bool MightBeOdrUse = true);
3943 void MarkVariableReferenced(SourceLocation Loc, VarDecl *Var);
3944 void MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base = nullptr);
3945 void MarkMemberReferenced(MemberExpr *E);
3947 void UpdateMarkingForLValueToRValue(Expr *E);
3948 void CleanupVarDeclMarking();
3950 enum TryCaptureKind {
3951 TryCapture_Implicit, TryCapture_ExplicitByVal, TryCapture_ExplicitByRef
3954 /// \brief Try to capture the given variable.
3956 /// \param Var The variable to capture.
3958 /// \param Loc The location at which the capture occurs.
3960 /// \param Kind The kind of capture, which may be implicit (for either a
3961 /// block or a lambda), or explicit by-value or by-reference (for a lambda).
3963 /// \param EllipsisLoc The location of the ellipsis, if one is provided in
3964 /// an explicit lambda capture.
3966 /// \param BuildAndDiagnose Whether we are actually supposed to add the
3967 /// captures or diagnose errors. If false, this routine merely check whether
3968 /// the capture can occur without performing the capture itself or complaining
3969 /// if the variable cannot be captured.
3971 /// \param CaptureType Will be set to the type of the field used to capture
3972 /// this variable in the innermost block or lambda. Only valid when the
3973 /// variable can be captured.
3975 /// \param DeclRefType Will be set to the type of a reference to the capture
3976 /// from within the current scope. Only valid when the variable can be
3979 /// \param FunctionScopeIndexToStopAt If non-null, it points to the index
3980 /// of the FunctionScopeInfo stack beyond which we do not attempt to capture.
3981 /// This is useful when enclosing lambdas must speculatively capture
3982 /// variables that may or may not be used in certain specializations of
3983 /// a nested generic lambda.
3985 /// \returns true if an error occurred (i.e., the variable cannot be
3986 /// captured) and false if the capture succeeded.
3987 bool tryCaptureVariable(VarDecl *Var, SourceLocation Loc, TryCaptureKind Kind,
3988 SourceLocation EllipsisLoc, bool BuildAndDiagnose,
3989 QualType &CaptureType,
3990 QualType &DeclRefType,
3991 const unsigned *const FunctionScopeIndexToStopAt);
3993 /// \brief Try to capture the given variable.
3994 bool tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
3995 TryCaptureKind Kind = TryCapture_Implicit,
3996 SourceLocation EllipsisLoc = SourceLocation());
3998 /// \brief Checks if the variable must be captured.
3999 bool NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc);
4001 /// \brief Given a variable, determine the type that a reference to that
4002 /// variable will have in the given scope.
4003 QualType getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc);
4005 /// Mark all of the declarations referenced within a particular AST node as
4006 /// referenced. Used when template instantiation instantiates a non-dependent
4007 /// type -- entities referenced by the type are now referenced.
4008 void MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T);
4009 void MarkDeclarationsReferencedInExpr(Expr *E,
4010 bool SkipLocalVariables = false);
4012 /// \brief Try to recover by turning the given expression into a
4013 /// call. Returns true if recovery was attempted or an error was
4014 /// emitted; this may also leave the ExprResult invalid.
4015 bool tryToRecoverWithCall(ExprResult &E, const PartialDiagnostic &PD,
4016 bool ForceComplain = false,
4017 bool (*IsPlausibleResult)(QualType) = nullptr);
4019 /// \brief Figure out if an expression could be turned into a call.
4020 bool tryExprAsCall(Expr &E, QualType &ZeroArgCallReturnTy,
4021 UnresolvedSetImpl &NonTemplateOverloads);
4023 /// \brief Conditionally issue a diagnostic based on the current
4024 /// evaluation context.
4026 /// \param Statement If Statement is non-null, delay reporting the
4027 /// diagnostic until the function body is parsed, and then do a basic
4028 /// reachability analysis to determine if the statement is reachable.
4029 /// If it is unreachable, the diagnostic will not be emitted.
4030 bool DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
4031 const PartialDiagnostic &PD);
4033 // Primary Expressions.
4034 SourceRange getExprRange(Expr *E) const;
4036 ExprResult ActOnIdExpression(
4037 Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
4038 UnqualifiedId &Id, bool HasTrailingLParen, bool IsAddressOfOperand,
4039 std::unique_ptr<CorrectionCandidateCallback> CCC = nullptr,
4040 bool IsInlineAsmIdentifier = false, Token *KeywordReplacement = nullptr);
4042 void DecomposeUnqualifiedId(const UnqualifiedId &Id,
4043 TemplateArgumentListInfo &Buffer,
4044 DeclarationNameInfo &NameInfo,
4045 const TemplateArgumentListInfo *&TemplateArgs);
4048 DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
4049 std::unique_ptr<CorrectionCandidateCallback> CCC,
4050 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr,
4051 ArrayRef<Expr *> Args = None, TypoExpr **Out = nullptr);
4053 ExprResult LookupInObjCMethod(LookupResult &LookUp, Scope *S,
4055 bool AllowBuiltinCreation=false);
4057 ExprResult ActOnDependentIdExpression(const CXXScopeSpec &SS,
4058 SourceLocation TemplateKWLoc,
4059 const DeclarationNameInfo &NameInfo,
4060 bool isAddressOfOperand,
4061 const TemplateArgumentListInfo *TemplateArgs);
4063 ExprResult BuildDeclRefExpr(ValueDecl *D, QualType Ty,
4066 const CXXScopeSpec *SS = nullptr);
4068 BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
4069 const DeclarationNameInfo &NameInfo,
4070 const CXXScopeSpec *SS = nullptr,
4071 NamedDecl *FoundD = nullptr,
4072 const TemplateArgumentListInfo *TemplateArgs = nullptr);
4074 BuildAnonymousStructUnionMemberReference(
4075 const CXXScopeSpec &SS,
4076 SourceLocation nameLoc,
4077 IndirectFieldDecl *indirectField,
4078 DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_none),
4079 Expr *baseObjectExpr = nullptr,
4080 SourceLocation opLoc = SourceLocation());
4082 ExprResult BuildPossibleImplicitMemberExpr(const CXXScopeSpec &SS,
4083 SourceLocation TemplateKWLoc,
4085 const TemplateArgumentListInfo *TemplateArgs,
4087 ExprResult BuildImplicitMemberExpr(const CXXScopeSpec &SS,
4088 SourceLocation TemplateKWLoc,
4090 const TemplateArgumentListInfo *TemplateArgs,
4091 bool IsDefiniteInstance,
4093 bool UseArgumentDependentLookup(const CXXScopeSpec &SS,
4094 const LookupResult &R,
4095 bool HasTrailingLParen);
4098 BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS,
4099 const DeclarationNameInfo &NameInfo,
4100 bool IsAddressOfOperand, const Scope *S,
4101 TypeSourceInfo **RecoveryTSI = nullptr);
4103 ExprResult BuildDependentDeclRefExpr(const CXXScopeSpec &SS,
4104 SourceLocation TemplateKWLoc,
4105 const DeclarationNameInfo &NameInfo,
4106 const TemplateArgumentListInfo *TemplateArgs);
4108 ExprResult BuildDeclarationNameExpr(const CXXScopeSpec &SS,
4111 bool AcceptInvalidDecl = false);
4112 ExprResult BuildDeclarationNameExpr(
4113 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
4114 NamedDecl *FoundD = nullptr,
4115 const TemplateArgumentListInfo *TemplateArgs = nullptr,
4116 bool AcceptInvalidDecl = false);
4118 ExprResult BuildLiteralOperatorCall(LookupResult &R,
4119 DeclarationNameInfo &SuffixInfo,
4120 ArrayRef<Expr *> Args,
4121 SourceLocation LitEndLoc,
4122 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr);
4124 ExprResult BuildPredefinedExpr(SourceLocation Loc,
4125 PredefinedExpr::IdentType IT);
4126 ExprResult ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind);
4127 ExprResult ActOnIntegerConstant(SourceLocation Loc, uint64_t Val);
4129 bool CheckLoopHintExpr(Expr *E, SourceLocation Loc);
4131 ExprResult ActOnNumericConstant(const Token &Tok, Scope *UDLScope = nullptr);
4132 ExprResult ActOnCharacterConstant(const Token &Tok,
4133 Scope *UDLScope = nullptr);
4134 ExprResult ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E);
4135 ExprResult ActOnParenListExpr(SourceLocation L,
4139 /// ActOnStringLiteral - The specified tokens were lexed as pasted string
4140 /// fragments (e.g. "foo" "bar" L"baz").
4141 ExprResult ActOnStringLiteral(ArrayRef<Token> StringToks,
4142 Scope *UDLScope = nullptr);
4144 ExprResult ActOnGenericSelectionExpr(SourceLocation KeyLoc,
4145 SourceLocation DefaultLoc,
4146 SourceLocation RParenLoc,
4147 Expr *ControllingExpr,
4148 ArrayRef<ParsedType> ArgTypes,
4149 ArrayRef<Expr *> ArgExprs);
4150 ExprResult CreateGenericSelectionExpr(SourceLocation KeyLoc,
4151 SourceLocation DefaultLoc,
4152 SourceLocation RParenLoc,
4153 Expr *ControllingExpr,
4154 ArrayRef<TypeSourceInfo *> Types,
4155 ArrayRef<Expr *> Exprs);
4157 // Binary/Unary Operators. 'Tok' is the token for the operator.
4158 ExprResult CreateBuiltinUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc,
4160 ExprResult BuildUnaryOp(Scope *S, SourceLocation OpLoc,
4161 UnaryOperatorKind Opc, Expr *Input);
4162 ExprResult ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
4163 tok::TokenKind Op, Expr *Input);
4165 QualType CheckAddressOfOperand(ExprResult &Operand, SourceLocation OpLoc);
4167 ExprResult CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
4168 SourceLocation OpLoc,
4169 UnaryExprOrTypeTrait ExprKind,
4171 ExprResult CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
4172 UnaryExprOrTypeTrait ExprKind);
4174 ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
4175 UnaryExprOrTypeTrait ExprKind,
4176 bool IsType, void *TyOrEx,
4177 SourceRange ArgRange);
4179 ExprResult CheckPlaceholderExpr(Expr *E);
4180 bool CheckVecStepExpr(Expr *E);
4182 bool CheckUnaryExprOrTypeTraitOperand(Expr *E, UnaryExprOrTypeTrait ExprKind);
4183 bool CheckUnaryExprOrTypeTraitOperand(QualType ExprType, SourceLocation OpLoc,
4184 SourceRange ExprRange,
4185 UnaryExprOrTypeTrait ExprKind);
4186 ExprResult ActOnSizeofParameterPackExpr(Scope *S,
4187 SourceLocation OpLoc,
4188 IdentifierInfo &Name,
4189 SourceLocation NameLoc,
4190 SourceLocation RParenLoc);
4191 ExprResult ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
4192 tok::TokenKind Kind, Expr *Input);
4194 ExprResult ActOnArraySubscriptExpr(Scope *S, Expr *Base, SourceLocation LLoc,
4195 Expr *Idx, SourceLocation RLoc);
4196 ExprResult CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
4197 Expr *Idx, SourceLocation RLoc);
4198 ExprResult ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc,
4199 Expr *LowerBound, SourceLocation ColonLoc,
4200 Expr *Length, SourceLocation RBLoc);
4202 // This struct is for use by ActOnMemberAccess to allow
4203 // BuildMemberReferenceExpr to be able to reinvoke ActOnMemberAccess after
4204 // changing the access operator from a '.' to a '->' (to see if that is the
4205 // change needed to fix an error about an unknown member, e.g. when the class
4206 // defines a custom operator->).
4207 struct ActOnMemberAccessExtraArgs {
4213 ExprResult BuildMemberReferenceExpr(
4214 Expr *Base, QualType BaseType, SourceLocation OpLoc, bool IsArrow,
4215 CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
4216 NamedDecl *FirstQualifierInScope, const DeclarationNameInfo &NameInfo,
4217 const TemplateArgumentListInfo *TemplateArgs,
4219 ActOnMemberAccessExtraArgs *ExtraArgs = nullptr);
4222 BuildMemberReferenceExpr(Expr *Base, QualType BaseType, SourceLocation OpLoc,
4223 bool IsArrow, const CXXScopeSpec &SS,
4224 SourceLocation TemplateKWLoc,
4225 NamedDecl *FirstQualifierInScope, LookupResult &R,
4226 const TemplateArgumentListInfo *TemplateArgs,
4228 bool SuppressQualifierCheck = false,
4229 ActOnMemberAccessExtraArgs *ExtraArgs = nullptr);
4231 ExprResult BuildFieldReferenceExpr(Expr *BaseExpr, bool IsArrow,
4232 SourceLocation OpLoc,
4233 const CXXScopeSpec &SS, FieldDecl *Field,
4234 DeclAccessPair FoundDecl,
4235 const DeclarationNameInfo &MemberNameInfo);
4237 ExprResult PerformMemberExprBaseConversion(Expr *Base, bool IsArrow);
4239 bool CheckQualifiedMemberReference(Expr *BaseExpr, QualType BaseType,
4240 const CXXScopeSpec &SS,
4241 const LookupResult &R);
4243 ExprResult ActOnDependentMemberExpr(Expr *Base, QualType BaseType,
4244 bool IsArrow, SourceLocation OpLoc,
4245 const CXXScopeSpec &SS,
4246 SourceLocation TemplateKWLoc,
4247 NamedDecl *FirstQualifierInScope,
4248 const DeclarationNameInfo &NameInfo,
4249 const TemplateArgumentListInfo *TemplateArgs);
4251 ExprResult ActOnMemberAccessExpr(Scope *S, Expr *Base,
4252 SourceLocation OpLoc,
4253 tok::TokenKind OpKind,
4255 SourceLocation TemplateKWLoc,
4256 UnqualifiedId &Member,
4259 void ActOnDefaultCtorInitializers(Decl *CDtorDecl);
4260 bool ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
4261 FunctionDecl *FDecl,
4262 const FunctionProtoType *Proto,
4263 ArrayRef<Expr *> Args,
4264 SourceLocation RParenLoc,
4265 bool ExecConfig = false);
4266 void CheckStaticArrayArgument(SourceLocation CallLoc,
4268 const Expr *ArgExpr);
4270 /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
4271 /// This provides the location of the left/right parens and a list of comma
4273 ExprResult ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
4274 MultiExprArg ArgExprs, SourceLocation RParenLoc,
4275 Expr *ExecConfig = nullptr,
4276 bool IsExecConfig = false);
4277 ExprResult BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
4278 SourceLocation LParenLoc,
4279 ArrayRef<Expr *> Arg,
4280 SourceLocation RParenLoc,
4281 Expr *Config = nullptr,
4282 bool IsExecConfig = false);
4284 ExprResult ActOnCUDAExecConfigExpr(Scope *S, SourceLocation LLLLoc,
4285 MultiExprArg ExecConfig,
4286 SourceLocation GGGLoc);
4288 ExprResult ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
4289 Declarator &D, ParsedType &Ty,
4290 SourceLocation RParenLoc, Expr *CastExpr);
4291 ExprResult BuildCStyleCastExpr(SourceLocation LParenLoc,
4293 SourceLocation RParenLoc,
4295 CastKind PrepareScalarCast(ExprResult &src, QualType destType);
4297 /// \brief Build an altivec or OpenCL literal.
4298 ExprResult BuildVectorLiteral(SourceLocation LParenLoc,
4299 SourceLocation RParenLoc, Expr *E,
4300 TypeSourceInfo *TInfo);
4302 ExprResult MaybeConvertParenListExprToParenExpr(Scope *S, Expr *ME);
4304 ExprResult ActOnCompoundLiteral(SourceLocation LParenLoc,
4306 SourceLocation RParenLoc,
4309 ExprResult BuildCompoundLiteralExpr(SourceLocation LParenLoc,
4310 TypeSourceInfo *TInfo,
4311 SourceLocation RParenLoc,
4314 ExprResult ActOnInitList(SourceLocation LBraceLoc,
4315 MultiExprArg InitArgList,
4316 SourceLocation RBraceLoc);
4318 ExprResult ActOnDesignatedInitializer(Designation &Desig,
4324 static BinaryOperatorKind ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind);
4327 ExprResult ActOnBinOp(Scope *S, SourceLocation TokLoc,
4328 tok::TokenKind Kind, Expr *LHSExpr, Expr *RHSExpr);
4329 ExprResult BuildBinOp(Scope *S, SourceLocation OpLoc,
4330 BinaryOperatorKind Opc, Expr *LHSExpr, Expr *RHSExpr);
4331 ExprResult CreateBuiltinBinOp(SourceLocation OpLoc, BinaryOperatorKind Opc,
4332 Expr *LHSExpr, Expr *RHSExpr);
4334 void DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc);
4336 /// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
4337 /// in the case of a the GNU conditional expr extension.
4338 ExprResult ActOnConditionalOp(SourceLocation QuestionLoc,
4339 SourceLocation ColonLoc,
4340 Expr *CondExpr, Expr *LHSExpr, Expr *RHSExpr);
4342 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
4343 ExprResult ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
4344 LabelDecl *TheDecl);
4346 void ActOnStartStmtExpr();
4347 ExprResult ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
4348 SourceLocation RPLoc); // "({..})"
4349 void ActOnStmtExprError();
4351 // __builtin_offsetof(type, identifier(.identifier|[expr])*)
4352 struct OffsetOfComponent {
4353 SourceLocation LocStart, LocEnd;
4354 bool isBrackets; // true if [expr], false if .ident
4356 IdentifierInfo *IdentInfo;
4361 /// __builtin_offsetof(type, a.b[123][456].c)
4362 ExprResult BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
4363 TypeSourceInfo *TInfo,
4364 ArrayRef<OffsetOfComponent> Components,
4365 SourceLocation RParenLoc);
4366 ExprResult ActOnBuiltinOffsetOf(Scope *S,
4367 SourceLocation BuiltinLoc,
4368 SourceLocation TypeLoc,
4369 ParsedType ParsedArgTy,
4370 ArrayRef<OffsetOfComponent> Components,
4371 SourceLocation RParenLoc);
4373 // __builtin_choose_expr(constExpr, expr1, expr2)
4374 ExprResult ActOnChooseExpr(SourceLocation BuiltinLoc,
4375 Expr *CondExpr, Expr *LHSExpr,
4376 Expr *RHSExpr, SourceLocation RPLoc);
4378 // __builtin_va_arg(expr, type)
4379 ExprResult ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty,
4380 SourceLocation RPLoc);
4381 ExprResult BuildVAArgExpr(SourceLocation BuiltinLoc, Expr *E,
4382 TypeSourceInfo *TInfo, SourceLocation RPLoc);
4385 ExprResult ActOnGNUNullExpr(SourceLocation TokenLoc);
4387 bool CheckCaseExpression(Expr *E);
4389 /// \brief Describes the result of an "if-exists" condition check.
4390 enum IfExistsResult {
4391 /// \brief The symbol exists.
4394 /// \brief The symbol does not exist.
4397 /// \brief The name is a dependent name, so the results will differ
4398 /// from one instantiation to the next.
4401 /// \brief An error occurred.
4406 CheckMicrosoftIfExistsSymbol(Scope *S, CXXScopeSpec &SS,
4407 const DeclarationNameInfo &TargetNameInfo);
4410 CheckMicrosoftIfExistsSymbol(Scope *S, SourceLocation KeywordLoc,
4411 bool IsIfExists, CXXScopeSpec &SS,
4412 UnqualifiedId &Name);
4414 StmtResult BuildMSDependentExistsStmt(SourceLocation KeywordLoc,
4416 NestedNameSpecifierLoc QualifierLoc,
4417 DeclarationNameInfo NameInfo,
4419 StmtResult ActOnMSDependentExistsStmt(SourceLocation KeywordLoc,
4421 CXXScopeSpec &SS, UnqualifiedId &Name,
4424 //===------------------------- "Block" Extension ------------------------===//
4426 /// ActOnBlockStart - This callback is invoked when a block literal is
4428 void ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope);
4430 /// ActOnBlockArguments - This callback allows processing of block arguments.
4431 /// If there are no arguments, this is still invoked.
4432 void ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
4435 /// ActOnBlockError - If there is an error parsing a block, this callback
4436 /// is invoked to pop the information about the block from the action impl.
4437 void ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope);
4439 /// ActOnBlockStmtExpr - This is called when the body of a block statement
4440 /// literal was successfully completed. ^(int x){...}
4441 ExprResult ActOnBlockStmtExpr(SourceLocation CaretLoc, Stmt *Body,
4444 //===---------------------------- Clang Extensions ----------------------===//
4446 /// __builtin_convertvector(...)
4447 ExprResult ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy,
4448 SourceLocation BuiltinLoc,
4449 SourceLocation RParenLoc);
4451 //===---------------------------- OpenCL Features -----------------------===//
4453 /// __builtin_astype(...)
4454 ExprResult ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
4455 SourceLocation BuiltinLoc,
4456 SourceLocation RParenLoc);
4458 //===---------------------------- C++ Features --------------------------===//
4460 // Act on C++ namespaces
4461 Decl *ActOnStartNamespaceDef(Scope *S, SourceLocation InlineLoc,
4462 SourceLocation NamespaceLoc,
4463 SourceLocation IdentLoc,
4464 IdentifierInfo *Ident,
4465 SourceLocation LBrace,
4466 AttributeList *AttrList,
4467 UsingDirectiveDecl * &UsingDecl);
4468 void ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace);
4470 NamespaceDecl *getStdNamespace() const;
4471 NamespaceDecl *getOrCreateStdNamespace();
4473 NamespaceDecl *lookupStdExperimentalNamespace();
4475 CXXRecordDecl *getStdBadAlloc() const;
4476 EnumDecl *getStdAlignValT() const;
4478 /// \brief Tests whether Ty is an instance of std::initializer_list and, if
4479 /// it is and Element is not NULL, assigns the element type to Element.
4480 bool isStdInitializerList(QualType Ty, QualType *Element);
4482 /// \brief Looks for the std::initializer_list template and instantiates it
4483 /// with Element, or emits an error if it's not found.
4485 /// \returns The instantiated template, or null on error.
4486 QualType BuildStdInitializerList(QualType Element, SourceLocation Loc);
4488 /// \brief Determine whether Ctor is an initializer-list constructor, as
4489 /// defined in [dcl.init.list]p2.
4490 bool isInitListConstructor(const FunctionDecl *Ctor);
4492 Decl *ActOnUsingDirective(Scope *CurScope,
4493 SourceLocation UsingLoc,
4494 SourceLocation NamespcLoc,
4496 SourceLocation IdentLoc,
4497 IdentifierInfo *NamespcName,
4498 AttributeList *AttrList);
4500 void PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir);
4502 Decl *ActOnNamespaceAliasDef(Scope *CurScope,
4503 SourceLocation NamespaceLoc,
4504 SourceLocation AliasLoc,
4505 IdentifierInfo *Alias,
4507 SourceLocation IdentLoc,
4508 IdentifierInfo *Ident);
4510 void HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow);
4511 bool CheckUsingShadowDecl(UsingDecl *UD, NamedDecl *Target,
4512 const LookupResult &PreviousDecls,
4513 UsingShadowDecl *&PrevShadow);
4514 UsingShadowDecl *BuildUsingShadowDecl(Scope *S, UsingDecl *UD,
4516 UsingShadowDecl *PrevDecl);
4518 bool CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
4519 bool HasTypenameKeyword,
4520 const CXXScopeSpec &SS,
4521 SourceLocation NameLoc,
4522 const LookupResult &Previous);
4523 bool CheckUsingDeclQualifier(SourceLocation UsingLoc,
4525 const CXXScopeSpec &SS,
4526 const DeclarationNameInfo &NameInfo,
4527 SourceLocation NameLoc);
4529 NamedDecl *BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
4530 SourceLocation UsingLoc,
4531 bool HasTypenameKeyword,
4532 SourceLocation TypenameLoc,
4534 DeclarationNameInfo NameInfo,
4535 SourceLocation EllipsisLoc,
4536 AttributeList *AttrList,
4537 bool IsInstantiation);
4538 NamedDecl *BuildUsingPackDecl(NamedDecl *InstantiatedFrom,
4539 ArrayRef<NamedDecl *> Expansions);
4541 bool CheckInheritingConstructorUsingDecl(UsingDecl *UD);
4543 /// Given a derived-class using shadow declaration for a constructor and the
4544 /// correspnding base class constructor, find or create the implicit
4545 /// synthesized derived class constructor to use for this initialization.
4546 CXXConstructorDecl *
4547 findInheritingConstructor(SourceLocation Loc, CXXConstructorDecl *BaseCtor,
4548 ConstructorUsingShadowDecl *DerivedShadow);
4550 Decl *ActOnUsingDeclaration(Scope *CurScope,
4552 SourceLocation UsingLoc,
4553 SourceLocation TypenameLoc,
4555 UnqualifiedId &Name,
4556 SourceLocation EllipsisLoc,
4557 AttributeList *AttrList);
4558 Decl *ActOnAliasDeclaration(Scope *CurScope,
4560 MultiTemplateParamsArg TemplateParams,
4561 SourceLocation UsingLoc,
4562 UnqualifiedId &Name,
4563 AttributeList *AttrList,
4565 Decl *DeclFromDeclSpec);
4567 /// BuildCXXConstructExpr - Creates a complete call to a constructor,
4568 /// including handling of its default argument expressions.
4570 /// \param ConstructKind - a CXXConstructExpr::ConstructionKind
4572 BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
4573 NamedDecl *FoundDecl,
4574 CXXConstructorDecl *Constructor, MultiExprArg Exprs,
4575 bool HadMultipleCandidates, bool IsListInitialization,
4576 bool IsStdInitListInitialization,
4577 bool RequiresZeroInit, unsigned ConstructKind,
4578 SourceRange ParenRange);
4580 /// Build a CXXConstructExpr whose constructor has already been resolved if
4581 /// it denotes an inherited constructor.
4583 BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
4584 CXXConstructorDecl *Constructor, bool Elidable,
4586 bool HadMultipleCandidates, bool IsListInitialization,
4587 bool IsStdInitListInitialization,
4588 bool RequiresZeroInit, unsigned ConstructKind,
4589 SourceRange ParenRange);
4591 // FIXME: Can we remove this and have the above BuildCXXConstructExpr check if
4592 // the constructor can be elidable?
4594 BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
4595 NamedDecl *FoundDecl,
4596 CXXConstructorDecl *Constructor, bool Elidable,
4597 MultiExprArg Exprs, bool HadMultipleCandidates,
4598 bool IsListInitialization,
4599 bool IsStdInitListInitialization, bool RequiresZeroInit,
4600 unsigned ConstructKind, SourceRange ParenRange);
4602 ExprResult BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field);
4605 /// Instantiate or parse a C++ default argument expression as necessary.
4606 /// Return true on error.
4607 bool CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD,
4608 ParmVarDecl *Param);
4610 /// BuildCXXDefaultArgExpr - Creates a CXXDefaultArgExpr, instantiating
4611 /// the default expr if needed.
4612 ExprResult BuildCXXDefaultArgExpr(SourceLocation CallLoc,
4614 ParmVarDecl *Param);
4616 /// FinalizeVarWithDestructor - Prepare for calling destructor on the
4617 /// constructed variable.
4618 void FinalizeVarWithDestructor(VarDecl *VD, const RecordType *DeclInitType);
4620 /// \brief Helper class that collects exception specifications for
4621 /// implicitly-declared special member functions.
4622 class ImplicitExceptionSpecification {
4623 // Pointer to allow copying
4625 // We order exception specifications thus:
4626 // noexcept is the most restrictive, but is only used in C++11.
4627 // throw() comes next.
4628 // Then a throw(collected exceptions)
4629 // Finally no specification, which is expressed as noexcept(false).
4630 // throw(...) is used instead if any called function uses it.
4631 ExceptionSpecificationType ComputedEST;
4632 llvm::SmallPtrSet<CanQualType, 4> ExceptionsSeen;
4633 SmallVector<QualType, 4> Exceptions;
4635 void ClearExceptions() {
4636 ExceptionsSeen.clear();
4641 explicit ImplicitExceptionSpecification(Sema &Self)
4642 : Self(&Self), ComputedEST(EST_BasicNoexcept) {
4643 if (!Self.getLangOpts().CPlusPlus11)
4644 ComputedEST = EST_DynamicNone;
4647 /// \brief Get the computed exception specification type.
4648 ExceptionSpecificationType getExceptionSpecType() const {
4649 assert(ComputedEST != EST_ComputedNoexcept &&
4650 "noexcept(expr) should not be a possible result");
4654 /// \brief The number of exceptions in the exception specification.
4655 unsigned size() const { return Exceptions.size(); }
4657 /// \brief The set of exceptions in the exception specification.
4658 const QualType *data() const { return Exceptions.data(); }
4660 /// \brief Integrate another called method into the collected data.
4661 void CalledDecl(SourceLocation CallLoc, const CXXMethodDecl *Method);
4663 /// \brief Integrate an invoked expression into the collected data.
4664 void CalledExpr(Expr *E);
4666 /// \brief Overwrite an EPI's exception specification with this
4667 /// computed exception specification.
4668 FunctionProtoType::ExceptionSpecInfo getExceptionSpec() const {
4669 FunctionProtoType::ExceptionSpecInfo ESI;
4670 ESI.Type = getExceptionSpecType();
4671 if (ESI.Type == EST_Dynamic) {
4672 ESI.Exceptions = Exceptions;
4673 } else if (ESI.Type == EST_None) {
4674 /// C++11 [except.spec]p14:
4675 /// The exception-specification is noexcept(false) if the set of
4676 /// potential exceptions of the special member function contains "any"
4677 ESI.Type = EST_ComputedNoexcept;
4678 ESI.NoexceptExpr = Self->ActOnCXXBoolLiteral(SourceLocation(),
4679 tok::kw_false).get();
4685 /// \brief Determine what sort of exception specification a defaulted
4686 /// copy constructor of a class will have.
4687 ImplicitExceptionSpecification
4688 ComputeDefaultedDefaultCtorExceptionSpec(SourceLocation Loc,
4691 /// \brief Determine what sort of exception specification a defaulted
4692 /// default constructor of a class will have, and whether the parameter
4694 ImplicitExceptionSpecification
4695 ComputeDefaultedCopyCtorExceptionSpec(CXXMethodDecl *MD);
4697 /// \brief Determine what sort of exception specification a defautled
4698 /// copy assignment operator of a class will have, and whether the
4699 /// parameter will be const.
4700 ImplicitExceptionSpecification
4701 ComputeDefaultedCopyAssignmentExceptionSpec(CXXMethodDecl *MD);
4703 /// \brief Determine what sort of exception specification a defaulted move
4704 /// constructor of a class will have.
4705 ImplicitExceptionSpecification
4706 ComputeDefaultedMoveCtorExceptionSpec(CXXMethodDecl *MD);
4708 /// \brief Determine what sort of exception specification a defaulted move
4709 /// assignment operator of a class will have.
4710 ImplicitExceptionSpecification
4711 ComputeDefaultedMoveAssignmentExceptionSpec(CXXMethodDecl *MD);
4713 /// \brief Determine what sort of exception specification a defaulted
4714 /// destructor of a class will have.
4715 ImplicitExceptionSpecification
4716 ComputeDefaultedDtorExceptionSpec(CXXMethodDecl *MD);
4718 /// \brief Determine what sort of exception specification an inheriting
4719 /// constructor of a class will have.
4720 ImplicitExceptionSpecification
4721 ComputeInheritingCtorExceptionSpec(SourceLocation Loc,
4722 CXXConstructorDecl *CD);
4724 /// \brief Evaluate the implicit exception specification for a defaulted
4725 /// special member function.
4726 void EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD);
4728 /// \brief Check the given exception-specification and update the
4729 /// exception specification information with the results.
4730 void checkExceptionSpecification(bool IsTopLevel,
4731 ExceptionSpecificationType EST,
4732 ArrayRef<ParsedType> DynamicExceptions,
4733 ArrayRef<SourceRange> DynamicExceptionRanges,
4735 SmallVectorImpl<QualType> &Exceptions,
4736 FunctionProtoType::ExceptionSpecInfo &ESI);
4738 /// \brief Determine if we're in a case where we need to (incorrectly) eagerly
4739 /// parse an exception specification to work around a libstdc++ bug.
4740 bool isLibstdcxxEagerExceptionSpecHack(const Declarator &D);
4742 /// \brief Add an exception-specification to the given member function
4743 /// (or member function template). The exception-specification was parsed
4744 /// after the method itself was declared.
4745 void actOnDelayedExceptionSpecification(Decl *Method,
4746 ExceptionSpecificationType EST,
4747 SourceRange SpecificationRange,
4748 ArrayRef<ParsedType> DynamicExceptions,
4749 ArrayRef<SourceRange> DynamicExceptionRanges,
4750 Expr *NoexceptExpr);
4752 class InheritedConstructorInfo;
4754 /// \brief Determine if a special member function should have a deleted
4755 /// definition when it is defaulted.
4756 bool ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
4757 InheritedConstructorInfo *ICI = nullptr,
4758 bool Diagnose = false);
4760 /// \brief Declare the implicit default constructor for the given class.
4762 /// \param ClassDecl The class declaration into which the implicit
4763 /// default constructor will be added.
4765 /// \returns The implicitly-declared default constructor.
4766 CXXConstructorDecl *DeclareImplicitDefaultConstructor(
4767 CXXRecordDecl *ClassDecl);
4769 /// DefineImplicitDefaultConstructor - Checks for feasibility of
4770 /// defining this constructor as the default constructor.
4771 void DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
4772 CXXConstructorDecl *Constructor);
4774 /// \brief Declare the implicit destructor for the given class.
4776 /// \param ClassDecl The class declaration into which the implicit
4777 /// destructor will be added.
4779 /// \returns The implicitly-declared destructor.
4780 CXXDestructorDecl *DeclareImplicitDestructor(CXXRecordDecl *ClassDecl);
4782 /// DefineImplicitDestructor - Checks for feasibility of
4783 /// defining this destructor as the default destructor.
4784 void DefineImplicitDestructor(SourceLocation CurrentLocation,
4785 CXXDestructorDecl *Destructor);
4787 /// \brief Build an exception spec for destructors that don't have one.
4789 /// C++11 says that user-defined destructors with no exception spec get one
4790 /// that looks as if the destructor was implicitly declared.
4791 void AdjustDestructorExceptionSpec(CXXRecordDecl *ClassDecl,
4792 CXXDestructorDecl *Destructor);
4794 /// \brief Define the specified inheriting constructor.
4795 void DefineInheritingConstructor(SourceLocation UseLoc,
4796 CXXConstructorDecl *Constructor);
4798 /// \brief Declare the implicit copy constructor for the given class.
4800 /// \param ClassDecl The class declaration into which the implicit
4801 /// copy constructor will be added.
4803 /// \returns The implicitly-declared copy constructor.
4804 CXXConstructorDecl *DeclareImplicitCopyConstructor(CXXRecordDecl *ClassDecl);
4806 /// DefineImplicitCopyConstructor - Checks for feasibility of
4807 /// defining this constructor as the copy constructor.
4808 void DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
4809 CXXConstructorDecl *Constructor);
4811 /// \brief Declare the implicit move constructor for the given class.
4813 /// \param ClassDecl The Class declaration into which the implicit
4814 /// move constructor will be added.
4816 /// \returns The implicitly-declared move constructor, or NULL if it wasn't
4818 CXXConstructorDecl *DeclareImplicitMoveConstructor(CXXRecordDecl *ClassDecl);
4820 /// DefineImplicitMoveConstructor - Checks for feasibility of
4821 /// defining this constructor as the move constructor.
4822 void DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
4823 CXXConstructorDecl *Constructor);
4825 /// \brief Declare the implicit copy assignment operator for the given class.
4827 /// \param ClassDecl The class declaration into which the implicit
4828 /// copy assignment operator will be added.
4830 /// \returns The implicitly-declared copy assignment operator.
4831 CXXMethodDecl *DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl);
4833 /// \brief Defines an implicitly-declared copy assignment operator.
4834 void DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
4835 CXXMethodDecl *MethodDecl);
4837 /// \brief Declare the implicit move assignment operator for the given class.
4839 /// \param ClassDecl The Class declaration into which the implicit
4840 /// move assignment operator will be added.
4842 /// \returns The implicitly-declared move assignment operator, or NULL if it
4843 /// wasn't declared.
4844 CXXMethodDecl *DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl);
4846 /// \brief Defines an implicitly-declared move assignment operator.
4847 void DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
4848 CXXMethodDecl *MethodDecl);
4850 /// \brief Force the declaration of any implicitly-declared members of this
4852 void ForceDeclarationOfImplicitMembers(CXXRecordDecl *Class);
4854 /// \brief Check a completed declaration of an implicit special member.
4855 void CheckImplicitSpecialMemberDeclaration(Scope *S, FunctionDecl *FD);
4857 /// \brief Determine whether the given function is an implicitly-deleted
4858 /// special member function.
4859 bool isImplicitlyDeleted(FunctionDecl *FD);
4861 /// \brief Check whether 'this' shows up in the type of a static member
4862 /// function after the (naturally empty) cv-qualifier-seq would be.
4864 /// \returns true if an error occurred.
4865 bool checkThisInStaticMemberFunctionType(CXXMethodDecl *Method);
4867 /// \brief Whether this' shows up in the exception specification of a static
4868 /// member function.
4869 bool checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method);
4871 /// \brief Check whether 'this' shows up in the attributes of the given
4872 /// static member function.
4874 /// \returns true if an error occurred.
4875 bool checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method);
4877 /// MaybeBindToTemporary - If the passed in expression has a record type with
4878 /// a non-trivial destructor, this will return CXXBindTemporaryExpr. Otherwise
4879 /// it simply returns the passed in expression.
4880 ExprResult MaybeBindToTemporary(Expr *E);
4882 bool CompleteConstructorCall(CXXConstructorDecl *Constructor,
4883 MultiExprArg ArgsPtr,
4885 SmallVectorImpl<Expr*> &ConvertedArgs,
4886 bool AllowExplicit = false,
4887 bool IsListInitialization = false);
4889 ParsedType getInheritingConstructorName(CXXScopeSpec &SS,
4890 SourceLocation NameLoc,
4891 IdentifierInfo &Name);
4893 ParsedType getDestructorName(SourceLocation TildeLoc,
4894 IdentifierInfo &II, SourceLocation NameLoc,
4895 Scope *S, CXXScopeSpec &SS,
4896 ParsedType ObjectType,
4897 bool EnteringContext);
4899 ParsedType getDestructorTypeForDecltype(const DeclSpec &DS,
4900 ParsedType ObjectType);
4902 // Checks that reinterpret casts don't have undefined behavior.
4903 void CheckCompatibleReinterpretCast(QualType SrcType, QualType DestType,
4904 bool IsDereference, SourceRange Range);
4906 /// ActOnCXXNamedCast - Parse {dynamic,static,reinterpret,const}_cast's.
4907 ExprResult ActOnCXXNamedCast(SourceLocation OpLoc,
4908 tok::TokenKind Kind,
4909 SourceLocation LAngleBracketLoc,
4911 SourceLocation RAngleBracketLoc,
4912 SourceLocation LParenLoc,
4914 SourceLocation RParenLoc);
4916 ExprResult BuildCXXNamedCast(SourceLocation OpLoc,
4917 tok::TokenKind Kind,
4920 SourceRange AngleBrackets,
4921 SourceRange Parens);
4923 ExprResult BuildCXXTypeId(QualType TypeInfoType,
4924 SourceLocation TypeidLoc,
4925 TypeSourceInfo *Operand,
4926 SourceLocation RParenLoc);
4927 ExprResult BuildCXXTypeId(QualType TypeInfoType,
4928 SourceLocation TypeidLoc,
4930 SourceLocation RParenLoc);
4932 /// ActOnCXXTypeid - Parse typeid( something ).
4933 ExprResult ActOnCXXTypeid(SourceLocation OpLoc,
4934 SourceLocation LParenLoc, bool isType,
4936 SourceLocation RParenLoc);
4938 ExprResult BuildCXXUuidof(QualType TypeInfoType,
4939 SourceLocation TypeidLoc,
4940 TypeSourceInfo *Operand,
4941 SourceLocation RParenLoc);
4942 ExprResult BuildCXXUuidof(QualType TypeInfoType,
4943 SourceLocation TypeidLoc,
4945 SourceLocation RParenLoc);
4947 /// ActOnCXXUuidof - Parse __uuidof( something ).
4948 ExprResult ActOnCXXUuidof(SourceLocation OpLoc,
4949 SourceLocation LParenLoc, bool isType,
4951 SourceLocation RParenLoc);
4953 /// \brief Handle a C++1z fold-expression: ( expr op ... op expr ).
4954 ExprResult ActOnCXXFoldExpr(SourceLocation LParenLoc, Expr *LHS,
4955 tok::TokenKind Operator,
4956 SourceLocation EllipsisLoc, Expr *RHS,
4957 SourceLocation RParenLoc);
4958 ExprResult BuildCXXFoldExpr(SourceLocation LParenLoc, Expr *LHS,
4959 BinaryOperatorKind Operator,
4960 SourceLocation EllipsisLoc, Expr *RHS,
4961 SourceLocation RParenLoc);
4962 ExprResult BuildEmptyCXXFoldExpr(SourceLocation EllipsisLoc,
4963 BinaryOperatorKind Operator);
4965 //// ActOnCXXThis - Parse 'this' pointer.
4966 ExprResult ActOnCXXThis(SourceLocation loc);
4968 /// \brief Try to retrieve the type of the 'this' pointer.
4970 /// \returns The type of 'this', if possible. Otherwise, returns a NULL type.
4971 QualType getCurrentThisType();
4973 /// \brief When non-NULL, the C++ 'this' expression is allowed despite the
4974 /// current context not being a non-static member function. In such cases,
4975 /// this provides the type used for 'this'.
4976 QualType CXXThisTypeOverride;
4978 /// \brief RAII object used to temporarily allow the C++ 'this' expression
4979 /// to be used, with the given qualifiers on the current class type.
4980 class CXXThisScopeRAII {
4982 QualType OldCXXThisTypeOverride;
4986 /// \brief Introduce a new scope where 'this' may be allowed (when enabled),
4987 /// using the given declaration (which is either a class template or a
4988 /// class) along with the given qualifiers.
4989 /// along with the qualifiers placed on '*this'.
4990 CXXThisScopeRAII(Sema &S, Decl *ContextDecl, unsigned CXXThisTypeQuals,
4991 bool Enabled = true);
4993 ~CXXThisScopeRAII();
4996 /// \brief Make sure the value of 'this' is actually available in the current
4997 /// context, if it is a potentially evaluated context.
4999 /// \param Loc The location at which the capture of 'this' occurs.
5001 /// \param Explicit Whether 'this' is explicitly captured in a lambda
5004 /// \param FunctionScopeIndexToStopAt If non-null, it points to the index
5005 /// of the FunctionScopeInfo stack beyond which we do not attempt to capture.
5006 /// This is useful when enclosing lambdas must speculatively capture
5007 /// 'this' that may or may not be used in certain specializations of
5008 /// a nested generic lambda (depending on whether the name resolves to
5009 /// a non-static member function or a static function).
5010 /// \return returns 'true' if failed, 'false' if success.
5011 bool CheckCXXThisCapture(SourceLocation Loc, bool Explicit = false,
5012 bool BuildAndDiagnose = true,
5013 const unsigned *const FunctionScopeIndexToStopAt = nullptr,
5014 bool ByCopy = false);
5016 /// \brief Determine whether the given type is the type of *this that is used
5017 /// outside of the body of a member function for a type that is currently
5019 bool isThisOutsideMemberFunctionBody(QualType BaseType);
5021 /// ActOnCXXBoolLiteral - Parse {true,false} literals.
5022 ExprResult ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind);
5025 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
5026 ExprResult ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind);
5029 ActOnObjCAvailabilityCheckExpr(llvm::ArrayRef<AvailabilitySpec> AvailSpecs,
5030 SourceLocation AtLoc, SourceLocation RParen);
5032 /// ActOnCXXNullPtrLiteral - Parse 'nullptr'.
5033 ExprResult ActOnCXXNullPtrLiteral(SourceLocation Loc);
5035 //// ActOnCXXThrow - Parse throw expressions.
5036 ExprResult ActOnCXXThrow(Scope *S, SourceLocation OpLoc, Expr *expr);
5037 ExprResult BuildCXXThrow(SourceLocation OpLoc, Expr *Ex,
5038 bool IsThrownVarInScope);
5039 bool CheckCXXThrowOperand(SourceLocation ThrowLoc, QualType ThrowTy, Expr *E);
5041 /// ActOnCXXTypeConstructExpr - Parse construction of a specified type.
5042 /// Can be interpreted either as function-style casting ("int(x)")
5043 /// or class type construction ("ClassType(x,y,z)")
5044 /// or creation of a value-initialized type ("int()").
5045 ExprResult ActOnCXXTypeConstructExpr(ParsedType TypeRep,
5046 SourceLocation LParenLoc,
5048 SourceLocation RParenLoc);
5050 ExprResult BuildCXXTypeConstructExpr(TypeSourceInfo *Type,
5051 SourceLocation LParenLoc,
5053 SourceLocation RParenLoc);
5055 /// ActOnCXXNew - Parsed a C++ 'new' expression.
5056 ExprResult ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
5057 SourceLocation PlacementLParen,
5058 MultiExprArg PlacementArgs,
5059 SourceLocation PlacementRParen,
5060 SourceRange TypeIdParens, Declarator &D,
5062 ExprResult BuildCXXNew(SourceRange Range, bool UseGlobal,
5063 SourceLocation PlacementLParen,
5064 MultiExprArg PlacementArgs,
5065 SourceLocation PlacementRParen,
5066 SourceRange TypeIdParens,
5068 TypeSourceInfo *AllocTypeInfo,
5070 SourceRange DirectInitRange,
5073 bool CheckAllocatedType(QualType AllocType, SourceLocation Loc,
5075 bool FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,
5076 bool UseGlobal, QualType AllocType, bool IsArray,
5077 bool &PassAlignment, MultiExprArg PlaceArgs,
5078 FunctionDecl *&OperatorNew,
5079 FunctionDecl *&OperatorDelete);
5080 void DeclareGlobalNewDelete();
5081 void DeclareGlobalAllocationFunction(DeclarationName Name, QualType Return,
5082 ArrayRef<QualType> Params);
5084 bool FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD,
5085 DeclarationName Name, FunctionDecl* &Operator,
5086 bool Diagnose = true);
5087 FunctionDecl *FindUsualDeallocationFunction(SourceLocation StartLoc,
5088 bool CanProvideSize,
5090 DeclarationName Name);
5091 FunctionDecl *FindDeallocationFunctionForDestructor(SourceLocation StartLoc,
5094 /// ActOnCXXDelete - Parsed a C++ 'delete' expression
5095 ExprResult ActOnCXXDelete(SourceLocation StartLoc,
5096 bool UseGlobal, bool ArrayForm,
5098 void CheckVirtualDtorCall(CXXDestructorDecl *dtor, SourceLocation Loc,
5099 bool IsDelete, bool CallCanBeVirtual,
5100 bool WarnOnNonAbstractTypes,
5101 SourceLocation DtorLoc);
5103 ExprResult ActOnNoexceptExpr(SourceLocation KeyLoc, SourceLocation LParen,
5104 Expr *Operand, SourceLocation RParen);
5105 ExprResult BuildCXXNoexceptExpr(SourceLocation KeyLoc, Expr *Operand,
5106 SourceLocation RParen);
5108 /// \brief Parsed one of the type trait support pseudo-functions.
5109 ExprResult ActOnTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
5110 ArrayRef<ParsedType> Args,
5111 SourceLocation RParenLoc);
5112 ExprResult BuildTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
5113 ArrayRef<TypeSourceInfo *> Args,
5114 SourceLocation RParenLoc);
5116 /// ActOnArrayTypeTrait - Parsed one of the binary type trait support
5117 /// pseudo-functions.
5118 ExprResult ActOnArrayTypeTrait(ArrayTypeTrait ATT,
5119 SourceLocation KWLoc,
5122 SourceLocation RParen);
5124 ExprResult BuildArrayTypeTrait(ArrayTypeTrait ATT,
5125 SourceLocation KWLoc,
5126 TypeSourceInfo *TSInfo,
5128 SourceLocation RParen);
5130 /// ActOnExpressionTrait - Parsed one of the unary type trait support
5131 /// pseudo-functions.
5132 ExprResult ActOnExpressionTrait(ExpressionTrait OET,
5133 SourceLocation KWLoc,
5135 SourceLocation RParen);
5137 ExprResult BuildExpressionTrait(ExpressionTrait OET,
5138 SourceLocation KWLoc,
5140 SourceLocation RParen);
5142 ExprResult ActOnStartCXXMemberReference(Scope *S,
5144 SourceLocation OpLoc,
5145 tok::TokenKind OpKind,
5146 ParsedType &ObjectType,
5147 bool &MayBePseudoDestructor);
5149 ExprResult BuildPseudoDestructorExpr(Expr *Base,
5150 SourceLocation OpLoc,
5151 tok::TokenKind OpKind,
5152 const CXXScopeSpec &SS,
5153 TypeSourceInfo *ScopeType,
5154 SourceLocation CCLoc,
5155 SourceLocation TildeLoc,
5156 PseudoDestructorTypeStorage DestroyedType);
5158 ExprResult ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
5159 SourceLocation OpLoc,
5160 tok::TokenKind OpKind,
5162 UnqualifiedId &FirstTypeName,
5163 SourceLocation CCLoc,
5164 SourceLocation TildeLoc,
5165 UnqualifiedId &SecondTypeName);
5167 ExprResult ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
5168 SourceLocation OpLoc,
5169 tok::TokenKind OpKind,
5170 SourceLocation TildeLoc,
5171 const DeclSpec& DS);
5173 /// MaybeCreateExprWithCleanups - If the current full-expression
5174 /// requires any cleanups, surround it with a ExprWithCleanups node.
5175 /// Otherwise, just returns the passed-in expression.
5176 Expr *MaybeCreateExprWithCleanups(Expr *SubExpr);
5177 Stmt *MaybeCreateStmtWithCleanups(Stmt *SubStmt);
5178 ExprResult MaybeCreateExprWithCleanups(ExprResult SubExpr);
5180 MaterializeTemporaryExpr *
5181 CreateMaterializeTemporaryExpr(QualType T, Expr *Temporary,
5182 bool BoundToLvalueReference);
5184 ExprResult ActOnFinishFullExpr(Expr *Expr) {
5185 return ActOnFinishFullExpr(Expr, Expr ? Expr->getExprLoc()
5186 : SourceLocation());
5188 ExprResult ActOnFinishFullExpr(Expr *Expr, SourceLocation CC,
5189 bool DiscardedValue = false,
5190 bool IsConstexpr = false,
5191 bool IsLambdaInitCaptureInitializer = false);
5192 StmtResult ActOnFinishFullStmt(Stmt *Stmt);
5194 // Marks SS invalid if it represents an incomplete type.
5195 bool RequireCompleteDeclContext(CXXScopeSpec &SS, DeclContext *DC);
5197 DeclContext *computeDeclContext(QualType T);
5198 DeclContext *computeDeclContext(const CXXScopeSpec &SS,
5199 bool EnteringContext = false);
5200 bool isDependentScopeSpecifier(const CXXScopeSpec &SS);
5201 CXXRecordDecl *getCurrentInstantiationOf(NestedNameSpecifier *NNS);
5203 /// \brief The parser has parsed a global nested-name-specifier '::'.
5205 /// \param CCLoc The location of the '::'.
5207 /// \param SS The nested-name-specifier, which will be updated in-place
5208 /// to reflect the parsed nested-name-specifier.
5210 /// \returns true if an error occurred, false otherwise.
5211 bool ActOnCXXGlobalScopeSpecifier(SourceLocation CCLoc, CXXScopeSpec &SS);
5213 /// \brief The parser has parsed a '__super' nested-name-specifier.
5215 /// \param SuperLoc The location of the '__super' keyword.
5217 /// \param ColonColonLoc The location of the '::'.
5219 /// \param SS The nested-name-specifier, which will be updated in-place
5220 /// to reflect the parsed nested-name-specifier.
5222 /// \returns true if an error occurred, false otherwise.
5223 bool ActOnSuperScopeSpecifier(SourceLocation SuperLoc,
5224 SourceLocation ColonColonLoc, CXXScopeSpec &SS);
5226 bool isAcceptableNestedNameSpecifier(const NamedDecl *SD,
5227 bool *CanCorrect = nullptr);
5228 NamedDecl *FindFirstQualifierInScope(Scope *S, NestedNameSpecifier *NNS);
5230 /// \brief Keeps information about an identifier in a nested-name-spec.
5232 struct NestedNameSpecInfo {
5233 /// \brief The type of the object, if we're parsing nested-name-specifier in
5234 /// a member access expression.
5235 ParsedType ObjectType;
5237 /// \brief The identifier preceding the '::'.
5238 IdentifierInfo *Identifier;
5240 /// \brief The location of the identifier.
5241 SourceLocation IdentifierLoc;
5243 /// \brief The location of the '::'.
5244 SourceLocation CCLoc;
5246 /// \brief Creates info object for the most typical case.
5247 NestedNameSpecInfo(IdentifierInfo *II, SourceLocation IdLoc,
5248 SourceLocation ColonColonLoc, ParsedType ObjectType = ParsedType())
5249 : ObjectType(ObjectType), Identifier(II), IdentifierLoc(IdLoc),
5250 CCLoc(ColonColonLoc) {
5253 NestedNameSpecInfo(IdentifierInfo *II, SourceLocation IdLoc,
5254 SourceLocation ColonColonLoc, QualType ObjectType)
5255 : ObjectType(ParsedType::make(ObjectType)), Identifier(II),
5256 IdentifierLoc(IdLoc), CCLoc(ColonColonLoc) {
5260 bool isNonTypeNestedNameSpecifier(Scope *S, CXXScopeSpec &SS,
5261 NestedNameSpecInfo &IdInfo);
5263 bool BuildCXXNestedNameSpecifier(Scope *S,
5264 NestedNameSpecInfo &IdInfo,
5265 bool EnteringContext,
5267 NamedDecl *ScopeLookupResult,
5268 bool ErrorRecoveryLookup,
5269 bool *IsCorrectedToColon = nullptr,
5270 bool OnlyNamespace = false);
5272 /// \brief The parser has parsed a nested-name-specifier 'identifier::'.
5274 /// \param S The scope in which this nested-name-specifier occurs.
5276 /// \param IdInfo Parser information about an identifier in the
5277 /// nested-name-spec.
5279 /// \param EnteringContext Whether we're entering the context nominated by
5280 /// this nested-name-specifier.
5282 /// \param SS The nested-name-specifier, which is both an input
5283 /// parameter (the nested-name-specifier before this type) and an
5284 /// output parameter (containing the full nested-name-specifier,
5285 /// including this new type).
5287 /// \param ErrorRecoveryLookup If true, then this method is called to improve
5288 /// error recovery. In this case do not emit error message.
5290 /// \param IsCorrectedToColon If not null, suggestions to replace '::' -> ':'
5291 /// are allowed. The bool value pointed by this parameter is set to 'true'
5292 /// if the identifier is treated as if it was followed by ':', not '::'.
5294 /// \param OnlyNamespace If true, only considers namespaces in lookup.
5296 /// \returns true if an error occurred, false otherwise.
5297 bool ActOnCXXNestedNameSpecifier(Scope *S,
5298 NestedNameSpecInfo &IdInfo,
5299 bool EnteringContext,
5301 bool ErrorRecoveryLookup = false,
5302 bool *IsCorrectedToColon = nullptr,
5303 bool OnlyNamespace = false);
5305 ExprResult ActOnDecltypeExpression(Expr *E);
5307 bool ActOnCXXNestedNameSpecifierDecltype(CXXScopeSpec &SS,
5309 SourceLocation ColonColonLoc);
5311 bool IsInvalidUnlessNestedName(Scope *S, CXXScopeSpec &SS,
5312 NestedNameSpecInfo &IdInfo,
5313 bool EnteringContext);
5315 /// \brief The parser has parsed a nested-name-specifier
5316 /// 'template[opt] template-name < template-args >::'.
5318 /// \param S The scope in which this nested-name-specifier occurs.
5320 /// \param SS The nested-name-specifier, which is both an input
5321 /// parameter (the nested-name-specifier before this type) and an
5322 /// output parameter (containing the full nested-name-specifier,
5323 /// including this new type).
5325 /// \param TemplateKWLoc the location of the 'template' keyword, if any.
5326 /// \param TemplateName the template name.
5327 /// \param TemplateNameLoc The location of the template name.
5328 /// \param LAngleLoc The location of the opening angle bracket ('<').
5329 /// \param TemplateArgs The template arguments.
5330 /// \param RAngleLoc The location of the closing angle bracket ('>').
5331 /// \param CCLoc The location of the '::'.
5333 /// \param EnteringContext Whether we're entering the context of the
5334 /// nested-name-specifier.
5337 /// \returns true if an error occurred, false otherwise.
5338 bool ActOnCXXNestedNameSpecifier(Scope *S,
5340 SourceLocation TemplateKWLoc,
5341 TemplateTy TemplateName,
5342 SourceLocation TemplateNameLoc,
5343 SourceLocation LAngleLoc,
5344 ASTTemplateArgsPtr TemplateArgs,
5345 SourceLocation RAngleLoc,
5346 SourceLocation CCLoc,
5347 bool EnteringContext);
5349 /// \brief Given a C++ nested-name-specifier, produce an annotation value
5350 /// that the parser can use later to reconstruct the given
5351 /// nested-name-specifier.
5353 /// \param SS A nested-name-specifier.
5355 /// \returns A pointer containing all of the information in the
5356 /// nested-name-specifier \p SS.
5357 void *SaveNestedNameSpecifierAnnotation(CXXScopeSpec &SS);
5359 /// \brief Given an annotation pointer for a nested-name-specifier, restore
5360 /// the nested-name-specifier structure.
5362 /// \param Annotation The annotation pointer, produced by
5363 /// \c SaveNestedNameSpecifierAnnotation().
5365 /// \param AnnotationRange The source range corresponding to the annotation.
5367 /// \param SS The nested-name-specifier that will be updated with the contents
5368 /// of the annotation pointer.
5369 void RestoreNestedNameSpecifierAnnotation(void *Annotation,
5370 SourceRange AnnotationRange,
5373 bool ShouldEnterDeclaratorScope(Scope *S, const CXXScopeSpec &SS);
5375 /// ActOnCXXEnterDeclaratorScope - Called when a C++ scope specifier (global
5376 /// scope or nested-name-specifier) is parsed, part of a declarator-id.
5377 /// After this method is called, according to [C++ 3.4.3p3], names should be
5378 /// looked up in the declarator-id's scope, until the declarator is parsed and
5379 /// ActOnCXXExitDeclaratorScope is called.
5380 /// The 'SS' should be a non-empty valid CXXScopeSpec.
5381 bool ActOnCXXEnterDeclaratorScope(Scope *S, CXXScopeSpec &SS);
5383 /// ActOnCXXExitDeclaratorScope - Called when a declarator that previously
5384 /// invoked ActOnCXXEnterDeclaratorScope(), is finished. 'SS' is the same
5385 /// CXXScopeSpec that was passed to ActOnCXXEnterDeclaratorScope as well.
5386 /// Used to indicate that names should revert to being looked up in the
5388 void ActOnCXXExitDeclaratorScope(Scope *S, const CXXScopeSpec &SS);
5390 /// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse an
5391 /// initializer for the declaration 'Dcl'.
5392 /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
5393 /// static data member of class X, names should be looked up in the scope of
5395 void ActOnCXXEnterDeclInitializer(Scope *S, Decl *Dcl);
5397 /// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
5398 /// initializer for the declaration 'Dcl'.
5399 void ActOnCXXExitDeclInitializer(Scope *S, Decl *Dcl);
5401 /// \brief Create a new lambda closure type.
5402 CXXRecordDecl *createLambdaClosureType(SourceRange IntroducerRange,
5403 TypeSourceInfo *Info,
5404 bool KnownDependent,
5405 LambdaCaptureDefault CaptureDefault);
5407 /// \brief Start the definition of a lambda expression.
5408 CXXMethodDecl *startLambdaDefinition(CXXRecordDecl *Class,
5409 SourceRange IntroducerRange,
5410 TypeSourceInfo *MethodType,
5411 SourceLocation EndLoc,
5412 ArrayRef<ParmVarDecl *> Params,
5413 bool IsConstexprSpecified);
5415 /// \brief Endow the lambda scope info with the relevant properties.
5416 void buildLambdaScope(sema::LambdaScopeInfo *LSI,
5417 CXXMethodDecl *CallOperator,
5418 SourceRange IntroducerRange,
5419 LambdaCaptureDefault CaptureDefault,
5420 SourceLocation CaptureDefaultLoc,
5421 bool ExplicitParams,
5422 bool ExplicitResultType,
5425 /// \brief Perform initialization analysis of the init-capture and perform
5426 /// any implicit conversions such as an lvalue-to-rvalue conversion if
5427 /// not being used to initialize a reference.
5428 ParsedType actOnLambdaInitCaptureInitialization(
5429 SourceLocation Loc, bool ByRef, IdentifierInfo *Id,
5430 LambdaCaptureInitKind InitKind, Expr *&Init) {
5431 return ParsedType::make(buildLambdaInitCaptureInitialization(
5432 Loc, ByRef, Id, InitKind != LambdaCaptureInitKind::CopyInit, Init));
5434 QualType buildLambdaInitCaptureInitialization(SourceLocation Loc, bool ByRef,
5436 bool DirectInit, Expr *&Init);
5438 /// \brief Create a dummy variable within the declcontext of the lambda's
5439 /// call operator, for name lookup purposes for a lambda init capture.
5441 /// CodeGen handles emission of lambda captures, ignoring these dummy
5442 /// variables appropriately.
5443 VarDecl *createLambdaInitCaptureVarDecl(SourceLocation Loc,
5444 QualType InitCaptureType,
5446 unsigned InitStyle, Expr *Init);
5448 /// \brief Build the implicit field for an init-capture.
5449 FieldDecl *buildInitCaptureField(sema::LambdaScopeInfo *LSI, VarDecl *Var);
5451 /// \brief Note that we have finished the explicit captures for the
5453 void finishLambdaExplicitCaptures(sema::LambdaScopeInfo *LSI);
5455 /// \brief Introduce the lambda parameters into scope.
5456 void addLambdaParameters(CXXMethodDecl *CallOperator, Scope *CurScope);
5458 /// \brief Deduce a block or lambda's return type based on the return
5459 /// statements present in the body.
5460 void deduceClosureReturnType(sema::CapturingScopeInfo &CSI);
5462 /// ActOnStartOfLambdaDefinition - This is called just before we start
5463 /// parsing the body of a lambda; it analyzes the explicit captures and
5464 /// arguments, and sets up various data-structures for the body of the
5466 void ActOnStartOfLambdaDefinition(LambdaIntroducer &Intro,
5467 Declarator &ParamInfo, Scope *CurScope);
5469 /// ActOnLambdaError - If there is an error parsing a lambda, this callback
5470 /// is invoked to pop the information about the lambda.
5471 void ActOnLambdaError(SourceLocation StartLoc, Scope *CurScope,
5472 bool IsInstantiation = false);
5474 /// ActOnLambdaExpr - This is called when the body of a lambda expression
5475 /// was successfully completed.
5476 ExprResult ActOnLambdaExpr(SourceLocation StartLoc, Stmt *Body,
5479 /// \brief Does copying/destroying the captured variable have side effects?
5480 bool CaptureHasSideEffects(const sema::LambdaScopeInfo::Capture &From);
5482 /// \brief Diagnose if an explicit lambda capture is unused.
5483 void DiagnoseUnusedLambdaCapture(const sema::LambdaScopeInfo::Capture &From);
5485 /// \brief Complete a lambda-expression having processed and attached the
5487 ExprResult BuildLambdaExpr(SourceLocation StartLoc, SourceLocation EndLoc,
5488 sema::LambdaScopeInfo *LSI);
5490 /// \brief Define the "body" of the conversion from a lambda object to a
5491 /// function pointer.
5493 /// This routine doesn't actually define a sensible body; rather, it fills
5494 /// in the initialization expression needed to copy the lambda object into
5495 /// the block, and IR generation actually generates the real body of the
5496 /// block pointer conversion.
5497 void DefineImplicitLambdaToFunctionPointerConversion(
5498 SourceLocation CurrentLoc, CXXConversionDecl *Conv);
5500 /// \brief Define the "body" of the conversion from a lambda object to a
5503 /// This routine doesn't actually define a sensible body; rather, it fills
5504 /// in the initialization expression needed to copy the lambda object into
5505 /// the block, and IR generation actually generates the real body of the
5506 /// block pointer conversion.
5507 void DefineImplicitLambdaToBlockPointerConversion(SourceLocation CurrentLoc,
5508 CXXConversionDecl *Conv);
5510 ExprResult BuildBlockForLambdaConversion(SourceLocation CurrentLocation,
5511 SourceLocation ConvLocation,
5512 CXXConversionDecl *Conv,
5515 // ParseObjCStringLiteral - Parse Objective-C string literals.
5516 ExprResult ParseObjCStringLiteral(SourceLocation *AtLocs,
5517 ArrayRef<Expr *> Strings);
5519 ExprResult BuildObjCStringLiteral(SourceLocation AtLoc, StringLiteral *S);
5521 /// BuildObjCNumericLiteral - builds an ObjCBoxedExpr AST node for the
5522 /// numeric literal expression. Type of the expression will be "NSNumber *"
5523 /// or "id" if NSNumber is unavailable.
5524 ExprResult BuildObjCNumericLiteral(SourceLocation AtLoc, Expr *Number);
5525 ExprResult ActOnObjCBoolLiteral(SourceLocation AtLoc, SourceLocation ValueLoc,
5527 ExprResult BuildObjCArrayLiteral(SourceRange SR, MultiExprArg Elements);
5529 /// BuildObjCBoxedExpr - builds an ObjCBoxedExpr AST node for the
5530 /// '@' prefixed parenthesized expression. The type of the expression will
5531 /// either be "NSNumber *", "NSString *" or "NSValue *" depending on the type
5532 /// of ValueType, which is allowed to be a built-in numeric type, "char *",
5533 /// "const char *" or C structure with attribute 'objc_boxable'.
5534 ExprResult BuildObjCBoxedExpr(SourceRange SR, Expr *ValueExpr);
5536 ExprResult BuildObjCSubscriptExpression(SourceLocation RB, Expr *BaseExpr,
5538 ObjCMethodDecl *getterMethod,
5539 ObjCMethodDecl *setterMethod);
5541 ExprResult BuildObjCDictionaryLiteral(SourceRange SR,
5542 MutableArrayRef<ObjCDictionaryElement> Elements);
5544 ExprResult BuildObjCEncodeExpression(SourceLocation AtLoc,
5545 TypeSourceInfo *EncodedTypeInfo,
5546 SourceLocation RParenLoc);
5547 ExprResult BuildCXXMemberCallExpr(Expr *Exp, NamedDecl *FoundDecl,
5548 CXXConversionDecl *Method,
5549 bool HadMultipleCandidates);
5551 ExprResult ParseObjCEncodeExpression(SourceLocation AtLoc,
5552 SourceLocation EncodeLoc,
5553 SourceLocation LParenLoc,
5555 SourceLocation RParenLoc);
5557 /// ParseObjCSelectorExpression - Build selector expression for \@selector
5558 ExprResult ParseObjCSelectorExpression(Selector Sel,
5559 SourceLocation AtLoc,
5560 SourceLocation SelLoc,
5561 SourceLocation LParenLoc,
5562 SourceLocation RParenLoc,
5563 bool WarnMultipleSelectors);
5565 /// ParseObjCProtocolExpression - Build protocol expression for \@protocol
5566 ExprResult ParseObjCProtocolExpression(IdentifierInfo * ProtocolName,
5567 SourceLocation AtLoc,
5568 SourceLocation ProtoLoc,
5569 SourceLocation LParenLoc,
5570 SourceLocation ProtoIdLoc,
5571 SourceLocation RParenLoc);
5573 //===--------------------------------------------------------------------===//
5576 Decl *ActOnStartLinkageSpecification(Scope *S,
5577 SourceLocation ExternLoc,
5579 SourceLocation LBraceLoc);
5580 Decl *ActOnFinishLinkageSpecification(Scope *S,
5582 SourceLocation RBraceLoc);
5585 //===--------------------------------------------------------------------===//
5588 bool isCurrentClassName(const IdentifierInfo &II, Scope *S,
5589 const CXXScopeSpec *SS = nullptr);
5590 bool isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS);
5592 bool ActOnAccessSpecifier(AccessSpecifier Access,
5593 SourceLocation ASLoc,
5594 SourceLocation ColonLoc,
5595 AttributeList *Attrs = nullptr);
5597 NamedDecl *ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS,
5599 MultiTemplateParamsArg TemplateParameterLists,
5600 Expr *BitfieldWidth, const VirtSpecifiers &VS,
5601 InClassInitStyle InitStyle);
5603 void ActOnStartCXXInClassMemberInitializer();
5604 void ActOnFinishCXXInClassMemberInitializer(Decl *VarDecl,
5605 SourceLocation EqualLoc,
5608 MemInitResult ActOnMemInitializer(Decl *ConstructorD,
5611 IdentifierInfo *MemberOrBase,
5612 ParsedType TemplateTypeTy,
5614 SourceLocation IdLoc,
5615 SourceLocation LParenLoc,
5616 ArrayRef<Expr *> Args,
5617 SourceLocation RParenLoc,
5618 SourceLocation EllipsisLoc);
5620 MemInitResult ActOnMemInitializer(Decl *ConstructorD,
5623 IdentifierInfo *MemberOrBase,
5624 ParsedType TemplateTypeTy,
5626 SourceLocation IdLoc,
5628 SourceLocation EllipsisLoc);
5630 MemInitResult BuildMemInitializer(Decl *ConstructorD,
5633 IdentifierInfo *MemberOrBase,
5634 ParsedType TemplateTypeTy,
5636 SourceLocation IdLoc,
5638 SourceLocation EllipsisLoc);
5640 MemInitResult BuildMemberInitializer(ValueDecl *Member,
5642 SourceLocation IdLoc);
5644 MemInitResult BuildBaseInitializer(QualType BaseType,
5645 TypeSourceInfo *BaseTInfo,
5647 CXXRecordDecl *ClassDecl,
5648 SourceLocation EllipsisLoc);
5650 MemInitResult BuildDelegatingInitializer(TypeSourceInfo *TInfo,
5652 CXXRecordDecl *ClassDecl);
5654 bool SetDelegatingInitializer(CXXConstructorDecl *Constructor,
5655 CXXCtorInitializer *Initializer);
5657 bool SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
5658 ArrayRef<CXXCtorInitializer *> Initializers = None);
5660 void SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation);
5663 /// MarkBaseAndMemberDestructorsReferenced - Given a record decl,
5664 /// mark all the non-trivial destructors of its members and bases as
5666 void MarkBaseAndMemberDestructorsReferenced(SourceLocation Loc,
5667 CXXRecordDecl *Record);
5669 /// \brief The list of classes whose vtables have been used within
5670 /// this translation unit, and the source locations at which the
5671 /// first use occurred.
5672 typedef std::pair<CXXRecordDecl*, SourceLocation> VTableUse;
5674 /// \brief The list of vtables that are required but have not yet been
5676 SmallVector<VTableUse, 16> VTableUses;
5678 /// \brief The set of classes whose vtables have been used within
5679 /// this translation unit, and a bit that will be true if the vtable is
5680 /// required to be emitted (otherwise, it should be emitted only if needed
5681 /// by code generation).
5682 llvm::DenseMap<CXXRecordDecl *, bool> VTablesUsed;
5684 /// \brief Load any externally-stored vtable uses.
5685 void LoadExternalVTableUses();
5687 /// \brief Note that the vtable for the given class was used at the
5689 void MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
5690 bool DefinitionRequired = false);
5692 /// \brief Mark the exception specifications of all virtual member functions
5693 /// in the given class as needed.
5694 void MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
5695 const CXXRecordDecl *RD);
5697 /// MarkVirtualMembersReferenced - Will mark all members of the given
5698 /// CXXRecordDecl referenced.
5699 void MarkVirtualMembersReferenced(SourceLocation Loc,
5700 const CXXRecordDecl *RD);
5702 /// \brief Define all of the vtables that have been used in this
5703 /// translation unit and reference any virtual members used by those
5706 /// \returns true if any work was done, false otherwise.
5707 bool DefineUsedVTables();
5709 void AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl);
5711 void ActOnMemInitializers(Decl *ConstructorDecl,
5712 SourceLocation ColonLoc,
5713 ArrayRef<CXXCtorInitializer*> MemInits,
5716 /// \brief Check class-level dllimport/dllexport attribute. The caller must
5717 /// ensure that referenceDLLExportedClassMethods is called some point later
5718 /// when all outer classes of Class are complete.
5719 void checkClassLevelDLLAttribute(CXXRecordDecl *Class);
5721 void referenceDLLExportedClassMethods();
5723 void propagateDLLAttrToBaseClassTemplate(
5724 CXXRecordDecl *Class, Attr *ClassAttr,
5725 ClassTemplateSpecializationDecl *BaseTemplateSpec,
5726 SourceLocation BaseLoc);
5728 void CheckCompletedCXXClass(CXXRecordDecl *Record);
5729 void ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
5731 SourceLocation LBrac,
5732 SourceLocation RBrac,
5733 AttributeList *AttrList);
5734 void ActOnFinishCXXMemberDecls();
5735 void ActOnFinishCXXNonNestedClass(Decl *D);
5737 void ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param);
5738 unsigned ActOnReenterTemplateScope(Scope *S, Decl *Template);
5739 void ActOnStartDelayedMemberDeclarations(Scope *S, Decl *Record);
5740 void ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *Method);
5741 void ActOnDelayedCXXMethodParameter(Scope *S, Decl *Param);
5742 void ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *Record);
5743 void ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *Method);
5744 void ActOnFinishDelayedMemberInitializers(Decl *Record);
5745 void MarkAsLateParsedTemplate(FunctionDecl *FD, Decl *FnD,
5746 CachedTokens &Toks);
5747 void UnmarkAsLateParsedTemplate(FunctionDecl *FD);
5748 bool IsInsideALocalClassWithinATemplateFunction();
5750 Decl *ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
5752 Expr *AssertMessageExpr,
5753 SourceLocation RParenLoc);
5754 Decl *BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
5756 StringLiteral *AssertMessageExpr,
5757 SourceLocation RParenLoc,
5760 FriendDecl *CheckFriendTypeDecl(SourceLocation LocStart,
5761 SourceLocation FriendLoc,
5762 TypeSourceInfo *TSInfo);
5763 Decl *ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
5764 MultiTemplateParamsArg TemplateParams);
5765 NamedDecl *ActOnFriendFunctionDecl(Scope *S, Declarator &D,
5766 MultiTemplateParamsArg TemplateParams);
5768 QualType CheckConstructorDeclarator(Declarator &D, QualType R,
5770 void CheckConstructor(CXXConstructorDecl *Constructor);
5771 QualType CheckDestructorDeclarator(Declarator &D, QualType R,
5773 bool CheckDestructor(CXXDestructorDecl *Destructor);
5774 void CheckConversionDeclarator(Declarator &D, QualType &R,
5776 Decl *ActOnConversionDeclarator(CXXConversionDecl *Conversion);
5777 void CheckDeductionGuideDeclarator(Declarator &D, QualType &R,
5779 void CheckDeductionGuideTemplate(FunctionTemplateDecl *TD);
5781 void CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD);
5782 void CheckExplicitlyDefaultedMemberExceptionSpec(CXXMethodDecl *MD,
5783 const FunctionProtoType *T);
5784 void CheckDelayedMemberExceptionSpecs();
5786 //===--------------------------------------------------------------------===//
5787 // C++ Derived Classes
5790 /// ActOnBaseSpecifier - Parsed a base specifier
5791 CXXBaseSpecifier *CheckBaseSpecifier(CXXRecordDecl *Class,
5792 SourceRange SpecifierRange,
5793 bool Virtual, AccessSpecifier Access,
5794 TypeSourceInfo *TInfo,
5795 SourceLocation EllipsisLoc);
5797 BaseResult ActOnBaseSpecifier(Decl *classdecl,
5798 SourceRange SpecifierRange,
5799 ParsedAttributes &Attrs,
5800 bool Virtual, AccessSpecifier Access,
5801 ParsedType basetype,
5802 SourceLocation BaseLoc,
5803 SourceLocation EllipsisLoc);
5805 bool AttachBaseSpecifiers(CXXRecordDecl *Class,
5806 MutableArrayRef<CXXBaseSpecifier *> Bases);
5807 void ActOnBaseSpecifiers(Decl *ClassDecl,
5808 MutableArrayRef<CXXBaseSpecifier *> Bases);
5810 bool IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base);
5811 bool IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base,
5812 CXXBasePaths &Paths);
5814 // FIXME: I don't like this name.
5815 void BuildBasePathArray(const CXXBasePaths &Paths, CXXCastPath &BasePath);
5817 bool CheckDerivedToBaseConversion(QualType Derived, QualType Base,
5818 SourceLocation Loc, SourceRange Range,
5819 CXXCastPath *BasePath = nullptr,
5820 bool IgnoreAccess = false);
5821 bool CheckDerivedToBaseConversion(QualType Derived, QualType Base,
5822 unsigned InaccessibleBaseID,
5823 unsigned AmbigiousBaseConvID,
5824 SourceLocation Loc, SourceRange Range,
5825 DeclarationName Name,
5826 CXXCastPath *BasePath,
5827 bool IgnoreAccess = false);
5829 std::string getAmbiguousPathsDisplayString(CXXBasePaths &Paths);
5831 bool CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
5832 const CXXMethodDecl *Old);
5834 /// CheckOverridingFunctionReturnType - Checks whether the return types are
5835 /// covariant, according to C++ [class.virtual]p5.
5836 bool CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
5837 const CXXMethodDecl *Old);
5839 /// CheckOverridingFunctionExceptionSpec - Checks whether the exception
5840 /// spec is a subset of base spec.
5841 bool CheckOverridingFunctionExceptionSpec(const CXXMethodDecl *New,
5842 const CXXMethodDecl *Old);
5844 bool CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange);
5846 /// CheckOverrideControl - Check C++11 override control semantics.
5847 void CheckOverrideControl(NamedDecl *D);
5849 /// DiagnoseAbsenceOfOverrideControl - Diagnose if 'override' keyword was
5850 /// not used in the declaration of an overriding method.
5851 void DiagnoseAbsenceOfOverrideControl(NamedDecl *D);
5853 /// CheckForFunctionMarkedFinal - Checks whether a virtual member function
5854 /// overrides a virtual member function marked 'final', according to
5855 /// C++11 [class.virtual]p4.
5856 bool CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
5857 const CXXMethodDecl *Old);
5860 //===--------------------------------------------------------------------===//
5861 // C++ Access Control
5871 bool SetMemberAccessSpecifier(NamedDecl *MemberDecl,
5872 NamedDecl *PrevMemberDecl,
5873 AccessSpecifier LexicalAS);
5875 AccessResult CheckUnresolvedMemberAccess(UnresolvedMemberExpr *E,
5876 DeclAccessPair FoundDecl);
5877 AccessResult CheckUnresolvedLookupAccess(UnresolvedLookupExpr *E,
5878 DeclAccessPair FoundDecl);
5879 AccessResult CheckAllocationAccess(SourceLocation OperatorLoc,
5880 SourceRange PlacementRange,
5881 CXXRecordDecl *NamingClass,
5882 DeclAccessPair FoundDecl,
5883 bool Diagnose = true);
5884 AccessResult CheckConstructorAccess(SourceLocation Loc,
5885 CXXConstructorDecl *D,
5886 DeclAccessPair FoundDecl,
5887 const InitializedEntity &Entity,
5888 bool IsCopyBindingRefToTemp = false);
5889 AccessResult CheckConstructorAccess(SourceLocation Loc,
5890 CXXConstructorDecl *D,
5891 DeclAccessPair FoundDecl,
5892 const InitializedEntity &Entity,
5893 const PartialDiagnostic &PDiag);
5894 AccessResult CheckDestructorAccess(SourceLocation Loc,
5895 CXXDestructorDecl *Dtor,
5896 const PartialDiagnostic &PDiag,
5897 QualType objectType = QualType());
5898 AccessResult CheckFriendAccess(NamedDecl *D);
5899 AccessResult CheckMemberAccess(SourceLocation UseLoc,
5900 CXXRecordDecl *NamingClass,
5901 DeclAccessPair Found);
5902 AccessResult CheckMemberOperatorAccess(SourceLocation Loc,
5905 DeclAccessPair FoundDecl);
5906 AccessResult CheckAddressOfMemberAccess(Expr *OvlExpr,
5907 DeclAccessPair FoundDecl);
5908 AccessResult CheckBaseClassAccess(SourceLocation AccessLoc,
5909 QualType Base, QualType Derived,
5910 const CXXBasePath &Path,
5912 bool ForceCheck = false,
5913 bool ForceUnprivileged = false);
5914 void CheckLookupAccess(const LookupResult &R);
5915 bool IsSimplyAccessible(NamedDecl *decl, DeclContext *Ctx);
5916 bool isSpecialMemberAccessibleForDeletion(CXXMethodDecl *decl,
5917 AccessSpecifier access,
5918 QualType objectType);
5920 void HandleDependentAccessCheck(const DependentDiagnostic &DD,
5921 const MultiLevelTemplateArgumentList &TemplateArgs);
5922 void PerformDependentDiagnostics(const DeclContext *Pattern,
5923 const MultiLevelTemplateArgumentList &TemplateArgs);
5925 void HandleDelayedAccessCheck(sema::DelayedDiagnostic &DD, Decl *Ctx);
5927 /// \brief When true, access checking violations are treated as SFINAE
5928 /// failures rather than hard errors.
5929 bool AccessCheckingSFINAE;
5931 enum AbstractDiagSelID {
5935 AbstractVariableType,
5938 AbstractSynthesizedIvarType,
5942 bool isAbstractType(SourceLocation Loc, QualType T);
5943 bool RequireNonAbstractType(SourceLocation Loc, QualType T,
5944 TypeDiagnoser &Diagnoser);
5945 template <typename... Ts>
5946 bool RequireNonAbstractType(SourceLocation Loc, QualType T, unsigned DiagID,
5947 const Ts &...Args) {
5948 BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
5949 return RequireNonAbstractType(Loc, T, Diagnoser);
5952 void DiagnoseAbstractType(const CXXRecordDecl *RD);
5954 //===--------------------------------------------------------------------===//
5955 // C++ Overloaded Operators [C++ 13.5]
5958 bool CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl);
5960 bool CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl);
5962 //===--------------------------------------------------------------------===//
5963 // C++ Templates [C++ 14]
5965 void FilterAcceptableTemplateNames(LookupResult &R,
5966 bool AllowFunctionTemplates = true);
5967 bool hasAnyAcceptableTemplateNames(LookupResult &R,
5968 bool AllowFunctionTemplates = true);
5970 void LookupTemplateName(LookupResult &R, Scope *S, CXXScopeSpec &SS,
5971 QualType ObjectType, bool EnteringContext,
5972 bool &MemberOfUnknownSpecialization);
5974 TemplateNameKind isTemplateName(Scope *S,
5976 bool hasTemplateKeyword,
5977 UnqualifiedId &Name,
5978 ParsedType ObjectType,
5979 bool EnteringContext,
5980 TemplateTy &Template,
5981 bool &MemberOfUnknownSpecialization);
5983 /// Determine whether a particular identifier might be the name in a C++1z
5984 /// deduction-guide declaration.
5985 bool isDeductionGuideName(Scope *S, const IdentifierInfo &Name,
5986 SourceLocation NameLoc,
5987 ParsedTemplateTy *Template = nullptr);
5989 bool DiagnoseUnknownTemplateName(const IdentifierInfo &II,
5990 SourceLocation IILoc,
5992 const CXXScopeSpec *SS,
5993 TemplateTy &SuggestedTemplate,
5994 TemplateNameKind &SuggestedKind);
5996 bool DiagnoseUninstantiableTemplate(SourceLocation PointOfInstantiation,
5997 NamedDecl *Instantiation,
5998 bool InstantiatedFromMember,
5999 const NamedDecl *Pattern,
6000 const NamedDecl *PatternDef,
6001 TemplateSpecializationKind TSK,
6002 bool Complain = true);
6004 void DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl);
6005 TemplateDecl *AdjustDeclIfTemplate(Decl *&Decl);
6007 Decl *ActOnTypeParameter(Scope *S, bool Typename,
6008 SourceLocation EllipsisLoc,
6009 SourceLocation KeyLoc,
6010 IdentifierInfo *ParamName,
6011 SourceLocation ParamNameLoc,
6012 unsigned Depth, unsigned Position,
6013 SourceLocation EqualLoc,
6014 ParsedType DefaultArg);
6016 QualType CheckNonTypeTemplateParameterType(TypeSourceInfo *&TSI,
6017 SourceLocation Loc);
6018 QualType CheckNonTypeTemplateParameterType(QualType T, SourceLocation Loc);
6020 Decl *ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
6023 SourceLocation EqualLoc,
6025 Decl *ActOnTemplateTemplateParameter(Scope *S,
6026 SourceLocation TmpLoc,
6027 TemplateParameterList *Params,
6028 SourceLocation EllipsisLoc,
6029 IdentifierInfo *ParamName,
6030 SourceLocation ParamNameLoc,
6033 SourceLocation EqualLoc,
6034 ParsedTemplateArgument DefaultArg);
6036 TemplateParameterList *
6037 ActOnTemplateParameterList(unsigned Depth,
6038 SourceLocation ExportLoc,
6039 SourceLocation TemplateLoc,
6040 SourceLocation LAngleLoc,
6041 ArrayRef<Decl *> Params,
6042 SourceLocation RAngleLoc,
6043 Expr *RequiresClause);
6045 /// \brief The context in which we are checking a template parameter list.
6046 enum TemplateParamListContext {
6049 TPC_FunctionTemplate,
6050 TPC_ClassTemplateMember,
6051 TPC_FriendClassTemplate,
6052 TPC_FriendFunctionTemplate,
6053 TPC_FriendFunctionTemplateDefinition,
6054 TPC_TypeAliasTemplate
6057 bool CheckTemplateParameterList(TemplateParameterList *NewParams,
6058 TemplateParameterList *OldParams,
6059 TemplateParamListContext TPC);
6060 TemplateParameterList *MatchTemplateParametersToScopeSpecifier(
6061 SourceLocation DeclStartLoc, SourceLocation DeclLoc,
6062 const CXXScopeSpec &SS, TemplateIdAnnotation *TemplateId,
6063 ArrayRef<TemplateParameterList *> ParamLists,
6064 bool IsFriend, bool &IsMemberSpecialization, bool &Invalid);
6066 DeclResult CheckClassTemplate(Scope *S, unsigned TagSpec, TagUseKind TUK,
6067 SourceLocation KWLoc, CXXScopeSpec &SS,
6068 IdentifierInfo *Name, SourceLocation NameLoc,
6069 AttributeList *Attr,
6070 TemplateParameterList *TemplateParams,
6072 SourceLocation ModulePrivateLoc,
6073 SourceLocation FriendLoc,
6074 unsigned NumOuterTemplateParamLists,
6075 TemplateParameterList **OuterTemplateParamLists,
6076 SkipBodyInfo *SkipBody = nullptr);
6078 TemplateArgumentLoc getTrivialTemplateArgumentLoc(const TemplateArgument &Arg,
6080 SourceLocation Loc);
6082 void translateTemplateArguments(const ASTTemplateArgsPtr &In,
6083 TemplateArgumentListInfo &Out);
6085 void NoteAllFoundTemplates(TemplateName Name);
6087 QualType CheckTemplateIdType(TemplateName Template,
6088 SourceLocation TemplateLoc,
6089 TemplateArgumentListInfo &TemplateArgs);
6092 ActOnTemplateIdType(CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
6093 TemplateTy Template, IdentifierInfo *TemplateII,
6094 SourceLocation TemplateIILoc,
6095 SourceLocation LAngleLoc,
6096 ASTTemplateArgsPtr TemplateArgs,
6097 SourceLocation RAngleLoc,
6098 bool IsCtorOrDtorName = false,
6099 bool IsClassName = false);
6101 /// \brief Parsed an elaborated-type-specifier that refers to a template-id,
6102 /// such as \c class T::template apply<U>.
6103 TypeResult ActOnTagTemplateIdType(TagUseKind TUK,
6104 TypeSpecifierType TagSpec,
6105 SourceLocation TagLoc,
6107 SourceLocation TemplateKWLoc,
6108 TemplateTy TemplateD,
6109 SourceLocation TemplateLoc,
6110 SourceLocation LAngleLoc,
6111 ASTTemplateArgsPtr TemplateArgsIn,
6112 SourceLocation RAngleLoc);
6114 DeclResult ActOnVarTemplateSpecialization(
6115 Scope *S, Declarator &D, TypeSourceInfo *DI,
6116 SourceLocation TemplateKWLoc, TemplateParameterList *TemplateParams,
6117 StorageClass SC, bool IsPartialSpecialization);
6119 DeclResult CheckVarTemplateId(VarTemplateDecl *Template,
6120 SourceLocation TemplateLoc,
6121 SourceLocation TemplateNameLoc,
6122 const TemplateArgumentListInfo &TemplateArgs);
6124 ExprResult CheckVarTemplateId(const CXXScopeSpec &SS,
6125 const DeclarationNameInfo &NameInfo,
6126 VarTemplateDecl *Template,
6127 SourceLocation TemplateLoc,
6128 const TemplateArgumentListInfo *TemplateArgs);
6130 ExprResult BuildTemplateIdExpr(const CXXScopeSpec &SS,
6131 SourceLocation TemplateKWLoc,
6134 const TemplateArgumentListInfo *TemplateArgs);
6136 ExprResult BuildQualifiedTemplateIdExpr(CXXScopeSpec &SS,
6137 SourceLocation TemplateKWLoc,
6138 const DeclarationNameInfo &NameInfo,
6139 const TemplateArgumentListInfo *TemplateArgs);
6141 TemplateNameKind ActOnDependentTemplateName(
6142 Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
6143 UnqualifiedId &Name, ParsedType ObjectType, bool EnteringContext,
6144 TemplateTy &Template, bool AllowInjectedClassName = false);
6147 ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec, TagUseKind TUK,
6148 SourceLocation KWLoc,
6149 SourceLocation ModulePrivateLoc,
6150 TemplateIdAnnotation &TemplateId,
6151 AttributeList *Attr,
6152 MultiTemplateParamsArg TemplateParameterLists,
6153 SkipBodyInfo *SkipBody = nullptr);
6155 bool CheckTemplatePartialSpecializationArgs(SourceLocation Loc,
6156 TemplateDecl *PrimaryTemplate,
6157 unsigned NumExplicitArgs,
6158 ArrayRef<TemplateArgument> Args);
6159 void CheckTemplatePartialSpecialization(
6160 ClassTemplatePartialSpecializationDecl *Partial);
6161 void CheckTemplatePartialSpecialization(
6162 VarTemplatePartialSpecializationDecl *Partial);
6164 Decl *ActOnTemplateDeclarator(Scope *S,
6165 MultiTemplateParamsArg TemplateParameterLists,
6169 CheckSpecializationInstantiationRedecl(SourceLocation NewLoc,
6170 TemplateSpecializationKind NewTSK,
6171 NamedDecl *PrevDecl,
6172 TemplateSpecializationKind PrevTSK,
6173 SourceLocation PrevPtOfInstantiation,
6176 bool CheckDependentFunctionTemplateSpecialization(FunctionDecl *FD,
6177 const TemplateArgumentListInfo &ExplicitTemplateArgs,
6178 LookupResult &Previous);
6180 bool CheckFunctionTemplateSpecialization(FunctionDecl *FD,
6181 TemplateArgumentListInfo *ExplicitTemplateArgs,
6182 LookupResult &Previous);
6183 bool CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous);
6184 void CompleteMemberSpecialization(NamedDecl *Member, LookupResult &Previous);
6187 ActOnExplicitInstantiation(Scope *S,
6188 SourceLocation ExternLoc,
6189 SourceLocation TemplateLoc,
6191 SourceLocation KWLoc,
6192 const CXXScopeSpec &SS,
6193 TemplateTy Template,
6194 SourceLocation TemplateNameLoc,
6195 SourceLocation LAngleLoc,
6196 ASTTemplateArgsPtr TemplateArgs,
6197 SourceLocation RAngleLoc,
6198 AttributeList *Attr);
6201 ActOnExplicitInstantiation(Scope *S,
6202 SourceLocation ExternLoc,
6203 SourceLocation TemplateLoc,
6205 SourceLocation KWLoc,
6207 IdentifierInfo *Name,
6208 SourceLocation NameLoc,
6209 AttributeList *Attr);
6211 DeclResult ActOnExplicitInstantiation(Scope *S,
6212 SourceLocation ExternLoc,
6213 SourceLocation TemplateLoc,
6217 SubstDefaultTemplateArgumentIfAvailable(TemplateDecl *Template,
6218 SourceLocation TemplateLoc,
6219 SourceLocation RAngleLoc,
6221 SmallVectorImpl<TemplateArgument>
6223 bool &HasDefaultArg);
6225 /// \brief Specifies the context in which a particular template
6226 /// argument is being checked.
6227 enum CheckTemplateArgumentKind {
6228 /// \brief The template argument was specified in the code or was
6229 /// instantiated with some deduced template arguments.
6232 /// \brief The template argument was deduced via template argument
6236 /// \brief The template argument was deduced from an array bound
6237 /// via template argument deduction.
6238 CTAK_DeducedFromArrayBound
6241 bool CheckTemplateArgument(NamedDecl *Param,
6242 TemplateArgumentLoc &Arg,
6243 NamedDecl *Template,
6244 SourceLocation TemplateLoc,
6245 SourceLocation RAngleLoc,
6246 unsigned ArgumentPackIndex,
6247 SmallVectorImpl<TemplateArgument> &Converted,
6248 CheckTemplateArgumentKind CTAK = CTAK_Specified);
6250 /// \brief Check that the given template arguments can be be provided to
6251 /// the given template, converting the arguments along the way.
6253 /// \param Template The template to which the template arguments are being
6256 /// \param TemplateLoc The location of the template name in the source.
6258 /// \param TemplateArgs The list of template arguments. If the template is
6259 /// a template template parameter, this function may extend the set of
6260 /// template arguments to also include substituted, defaulted template
6263 /// \param PartialTemplateArgs True if the list of template arguments is
6264 /// intentionally partial, e.g., because we're checking just the initial
6265 /// set of template arguments.
6267 /// \param Converted Will receive the converted, canonicalized template
6270 /// \param UpdateArgsWithConversions If \c true, update \p TemplateArgs to
6271 /// contain the converted forms of the template arguments as written.
6272 /// Otherwise, \p TemplateArgs will not be modified.
6274 /// \returns true if an error occurred, false otherwise.
6275 bool CheckTemplateArgumentList(TemplateDecl *Template,
6276 SourceLocation TemplateLoc,
6277 TemplateArgumentListInfo &TemplateArgs,
6278 bool PartialTemplateArgs,
6279 SmallVectorImpl<TemplateArgument> &Converted,
6280 bool UpdateArgsWithConversions = true);
6282 bool CheckTemplateTypeArgument(TemplateTypeParmDecl *Param,
6283 TemplateArgumentLoc &Arg,
6284 SmallVectorImpl<TemplateArgument> &Converted);
6286 bool CheckTemplateArgument(TemplateTypeParmDecl *Param,
6287 TypeSourceInfo *Arg);
6288 ExprResult CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
6289 QualType InstantiatedParamType, Expr *Arg,
6290 TemplateArgument &Converted,
6291 CheckTemplateArgumentKind CTAK = CTAK_Specified);
6292 bool CheckTemplateArgument(TemplateTemplateParmDecl *Param,
6293 TemplateArgumentLoc &Arg,
6294 unsigned ArgumentPackIndex);
6297 BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg,
6299 SourceLocation Loc);
6301 BuildExpressionFromIntegralTemplateArgument(const TemplateArgument &Arg,
6302 SourceLocation Loc);
6304 /// \brief Enumeration describing how template parameter lists are compared
6306 enum TemplateParameterListEqualKind {
6307 /// \brief We are matching the template parameter lists of two templates
6308 /// that might be redeclarations.
6311 /// template<typename T> struct X;
6312 /// template<typename T> struct X;
6316 /// \brief We are matching the template parameter lists of two template
6317 /// template parameters as part of matching the template parameter lists
6318 /// of two templates that might be redeclarations.
6321 /// template<template<int I> class TT> struct X;
6322 /// template<template<int Value> class Other> struct X;
6324 TPL_TemplateTemplateParmMatch,
6326 /// \brief We are matching the template parameter lists of a template
6327 /// template argument against the template parameter lists of a template
6328 /// template parameter.
6331 /// template<template<int Value> class Metafun> struct X;
6332 /// template<int Value> struct integer_c;
6333 /// X<integer_c> xic;
6335 TPL_TemplateTemplateArgumentMatch
6338 bool TemplateParameterListsAreEqual(TemplateParameterList *New,
6339 TemplateParameterList *Old,
6341 TemplateParameterListEqualKind Kind,
6342 SourceLocation TemplateArgLoc
6343 = SourceLocation());
6345 bool CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams);
6347 /// \brief Called when the parser has parsed a C++ typename
6348 /// specifier, e.g., "typename T::type".
6350 /// \param S The scope in which this typename type occurs.
6351 /// \param TypenameLoc the location of the 'typename' keyword
6352 /// \param SS the nested-name-specifier following the typename (e.g., 'T::').
6353 /// \param II the identifier we're retrieving (e.g., 'type' in the example).
6354 /// \param IdLoc the location of the identifier.
6356 ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
6357 const CXXScopeSpec &SS, const IdentifierInfo &II,
6358 SourceLocation IdLoc);
6360 /// \brief Called when the parser has parsed a C++ typename
6361 /// specifier that ends in a template-id, e.g.,
6362 /// "typename MetaFun::template apply<T1, T2>".
6364 /// \param S The scope in which this typename type occurs.
6365 /// \param TypenameLoc the location of the 'typename' keyword
6366 /// \param SS the nested-name-specifier following the typename (e.g., 'T::').
6367 /// \param TemplateLoc the location of the 'template' keyword, if any.
6368 /// \param TemplateName The template name.
6369 /// \param TemplateII The identifier used to name the template.
6370 /// \param TemplateIILoc The location of the template name.
6371 /// \param LAngleLoc The location of the opening angle bracket ('<').
6372 /// \param TemplateArgs The template arguments.
6373 /// \param RAngleLoc The location of the closing angle bracket ('>').
6375 ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
6376 const CXXScopeSpec &SS,
6377 SourceLocation TemplateLoc,
6378 TemplateTy TemplateName,
6379 IdentifierInfo *TemplateII,
6380 SourceLocation TemplateIILoc,
6381 SourceLocation LAngleLoc,
6382 ASTTemplateArgsPtr TemplateArgs,
6383 SourceLocation RAngleLoc);
6385 QualType CheckTypenameType(ElaboratedTypeKeyword Keyword,
6386 SourceLocation KeywordLoc,
6387 NestedNameSpecifierLoc QualifierLoc,
6388 const IdentifierInfo &II,
6389 SourceLocation IILoc);
6391 TypeSourceInfo *RebuildTypeInCurrentInstantiation(TypeSourceInfo *T,
6393 DeclarationName Name);
6394 bool RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS);
6396 ExprResult RebuildExprInCurrentInstantiation(Expr *E);
6397 bool RebuildTemplateParamsInCurrentInstantiation(
6398 TemplateParameterList *Params);
6401 getTemplateArgumentBindingsText(const TemplateParameterList *Params,
6402 const TemplateArgumentList &Args);
6405 getTemplateArgumentBindingsText(const TemplateParameterList *Params,
6406 const TemplateArgument *Args,
6409 //===--------------------------------------------------------------------===//
6410 // C++ Variadic Templates (C++0x [temp.variadic])
6411 //===--------------------------------------------------------------------===//
6413 /// Determine whether an unexpanded parameter pack might be permitted in this
6414 /// location. Useful for error recovery.
6415 bool isUnexpandedParameterPackPermitted();
6417 /// \brief The context in which an unexpanded parameter pack is
6418 /// being diagnosed.
6420 /// Note that the values of this enumeration line up with the first
6421 /// argument to the \c err_unexpanded_parameter_pack diagnostic.
6422 enum UnexpandedParameterPackContext {
6423 /// \brief An arbitrary expression.
6424 UPPC_Expression = 0,
6426 /// \brief The base type of a class type.
6429 /// \brief The type of an arbitrary declaration.
6430 UPPC_DeclarationType,
6432 /// \brief The type of a data member.
6433 UPPC_DataMemberType,
6435 /// \brief The size of a bit-field.
6438 /// \brief The expression in a static assertion.
6439 UPPC_StaticAssertExpression,
6441 /// \brief The fixed underlying type of an enumeration.
6442 UPPC_FixedUnderlyingType,
6444 /// \brief The enumerator value.
6445 UPPC_EnumeratorValue,
6447 /// \brief A using declaration.
6448 UPPC_UsingDeclaration,
6450 /// \brief A friend declaration.
6451 UPPC_FriendDeclaration,
6453 /// \brief A declaration qualifier.
6454 UPPC_DeclarationQualifier,
6456 /// \brief An initializer.
6459 /// \brief A default argument.
6460 UPPC_DefaultArgument,
6462 /// \brief The type of a non-type template parameter.
6463 UPPC_NonTypeTemplateParameterType,
6465 /// \brief The type of an exception.
6468 /// \brief Partial specialization.
6469 UPPC_PartialSpecialization,
6471 /// \brief Microsoft __if_exists.
6474 /// \brief Microsoft __if_not_exists.
6477 /// \brief Lambda expression.
6480 /// \brief Block expression,
6484 /// \brief Diagnose unexpanded parameter packs.
6486 /// \param Loc The location at which we should emit the diagnostic.
6488 /// \param UPPC The context in which we are diagnosing unexpanded
6489 /// parameter packs.
6491 /// \param Unexpanded the set of unexpanded parameter packs.
6493 /// \returns true if an error occurred, false otherwise.
6494 bool DiagnoseUnexpandedParameterPacks(SourceLocation Loc,
6495 UnexpandedParameterPackContext UPPC,
6496 ArrayRef<UnexpandedParameterPack> Unexpanded);
6498 /// \brief If the given type contains an unexpanded parameter pack,
6499 /// diagnose the error.
6501 /// \param Loc The source location where a diagnostc should be emitted.
6503 /// \param T The type that is being checked for unexpanded parameter
6506 /// \returns true if an error occurred, false otherwise.
6507 bool DiagnoseUnexpandedParameterPack(SourceLocation Loc, TypeSourceInfo *T,
6508 UnexpandedParameterPackContext UPPC);
6510 /// \brief If the given expression contains an unexpanded parameter
6511 /// pack, diagnose the error.
6513 /// \param E The expression that is being checked for unexpanded
6514 /// parameter packs.
6516 /// \returns true if an error occurred, false otherwise.
6517 bool DiagnoseUnexpandedParameterPack(Expr *E,
6518 UnexpandedParameterPackContext UPPC = UPPC_Expression);
6520 /// \brief If the given nested-name-specifier contains an unexpanded
6521 /// parameter pack, diagnose the error.
6523 /// \param SS The nested-name-specifier that is being checked for
6524 /// unexpanded parameter packs.
6526 /// \returns true if an error occurred, false otherwise.
6527 bool DiagnoseUnexpandedParameterPack(const CXXScopeSpec &SS,
6528 UnexpandedParameterPackContext UPPC);
6530 /// \brief If the given name contains an unexpanded parameter pack,
6531 /// diagnose the error.
6533 /// \param NameInfo The name (with source location information) that
6534 /// is being checked for unexpanded parameter packs.
6536 /// \returns true if an error occurred, false otherwise.
6537 bool DiagnoseUnexpandedParameterPack(const DeclarationNameInfo &NameInfo,
6538 UnexpandedParameterPackContext UPPC);
6540 /// \brief If the given template name contains an unexpanded parameter pack,
6541 /// diagnose the error.
6543 /// \param Loc The location of the template name.
6545 /// \param Template The template name that is being checked for unexpanded
6546 /// parameter packs.
6548 /// \returns true if an error occurred, false otherwise.
6549 bool DiagnoseUnexpandedParameterPack(SourceLocation Loc,
6550 TemplateName Template,
6551 UnexpandedParameterPackContext UPPC);
6553 /// \brief If the given template argument contains an unexpanded parameter
6554 /// pack, diagnose the error.
6556 /// \param Arg The template argument that is being checked for unexpanded
6557 /// parameter packs.
6559 /// \returns true if an error occurred, false otherwise.
6560 bool DiagnoseUnexpandedParameterPack(TemplateArgumentLoc Arg,
6561 UnexpandedParameterPackContext UPPC);
6563 /// \brief Collect the set of unexpanded parameter packs within the given
6564 /// template argument.
6566 /// \param Arg The template argument that will be traversed to find
6567 /// unexpanded parameter packs.
6568 void collectUnexpandedParameterPacks(TemplateArgument Arg,
6569 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
6571 /// \brief Collect the set of unexpanded parameter packs within the given
6572 /// template argument.
6574 /// \param Arg The template argument that will be traversed to find
6575 /// unexpanded parameter packs.
6576 void collectUnexpandedParameterPacks(TemplateArgumentLoc Arg,
6577 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
6579 /// \brief Collect the set of unexpanded parameter packs within the given
6582 /// \param T The type that will be traversed to find
6583 /// unexpanded parameter packs.
6584 void collectUnexpandedParameterPacks(QualType T,
6585 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
6587 /// \brief Collect the set of unexpanded parameter packs within the given
6590 /// \param TL The type that will be traversed to find
6591 /// unexpanded parameter packs.
6592 void collectUnexpandedParameterPacks(TypeLoc TL,
6593 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
6595 /// \brief Collect the set of unexpanded parameter packs within the given
6596 /// nested-name-specifier.
6598 /// \param NNS The nested-name-specifier that will be traversed to find
6599 /// unexpanded parameter packs.
6600 void collectUnexpandedParameterPacks(NestedNameSpecifierLoc NNS,
6601 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
6603 /// \brief Collect the set of unexpanded parameter packs within the given
6606 /// \param NameInfo The name that will be traversed to find
6607 /// unexpanded parameter packs.
6608 void collectUnexpandedParameterPacks(const DeclarationNameInfo &NameInfo,
6609 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
6611 /// \brief Invoked when parsing a template argument followed by an
6612 /// ellipsis, which creates a pack expansion.
6614 /// \param Arg The template argument preceding the ellipsis, which
6615 /// may already be invalid.
6617 /// \param EllipsisLoc The location of the ellipsis.
6618 ParsedTemplateArgument ActOnPackExpansion(const ParsedTemplateArgument &Arg,
6619 SourceLocation EllipsisLoc);
6621 /// \brief Invoked when parsing a type followed by an ellipsis, which
6622 /// creates a pack expansion.
6624 /// \param Type The type preceding the ellipsis, which will become
6625 /// the pattern of the pack expansion.
6627 /// \param EllipsisLoc The location of the ellipsis.
6628 TypeResult ActOnPackExpansion(ParsedType Type, SourceLocation EllipsisLoc);
6630 /// \brief Construct a pack expansion type from the pattern of the pack
6632 TypeSourceInfo *CheckPackExpansion(TypeSourceInfo *Pattern,
6633 SourceLocation EllipsisLoc,
6634 Optional<unsigned> NumExpansions);
6636 /// \brief Construct a pack expansion type from the pattern of the pack
6638 QualType CheckPackExpansion(QualType Pattern,
6639 SourceRange PatternRange,
6640 SourceLocation EllipsisLoc,
6641 Optional<unsigned> NumExpansions);
6643 /// \brief Invoked when parsing an expression followed by an ellipsis, which
6644 /// creates a pack expansion.
6646 /// \param Pattern The expression preceding the ellipsis, which will become
6647 /// the pattern of the pack expansion.
6649 /// \param EllipsisLoc The location of the ellipsis.
6650 ExprResult ActOnPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc);
6652 /// \brief Invoked when parsing an expression followed by an ellipsis, which
6653 /// creates a pack expansion.
6655 /// \param Pattern The expression preceding the ellipsis, which will become
6656 /// the pattern of the pack expansion.
6658 /// \param EllipsisLoc The location of the ellipsis.
6659 ExprResult CheckPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc,
6660 Optional<unsigned> NumExpansions);
6662 /// \brief Determine whether we could expand a pack expansion with the
6663 /// given set of parameter packs into separate arguments by repeatedly
6664 /// transforming the pattern.
6666 /// \param EllipsisLoc The location of the ellipsis that identifies the
6669 /// \param PatternRange The source range that covers the entire pattern of
6670 /// the pack expansion.
6672 /// \param Unexpanded The set of unexpanded parameter packs within the
6675 /// \param ShouldExpand Will be set to \c true if the transformer should
6676 /// expand the corresponding pack expansions into separate arguments. When
6677 /// set, \c NumExpansions must also be set.
6679 /// \param RetainExpansion Whether the caller should add an unexpanded
6680 /// pack expansion after all of the expanded arguments. This is used
6681 /// when extending explicitly-specified template argument packs per
6682 /// C++0x [temp.arg.explicit]p9.
6684 /// \param NumExpansions The number of separate arguments that will be in
6685 /// the expanded form of the corresponding pack expansion. This is both an
6686 /// input and an output parameter, which can be set by the caller if the
6687 /// number of expansions is known a priori (e.g., due to a prior substitution)
6688 /// and will be set by the callee when the number of expansions is known.
6689 /// The callee must set this value when \c ShouldExpand is \c true; it may
6690 /// set this value in other cases.
6692 /// \returns true if an error occurred (e.g., because the parameter packs
6693 /// are to be instantiated with arguments of different lengths), false
6694 /// otherwise. If false, \c ShouldExpand (and possibly \c NumExpansions)
6696 bool CheckParameterPacksForExpansion(SourceLocation EllipsisLoc,
6697 SourceRange PatternRange,
6698 ArrayRef<UnexpandedParameterPack> Unexpanded,
6699 const MultiLevelTemplateArgumentList &TemplateArgs,
6701 bool &RetainExpansion,
6702 Optional<unsigned> &NumExpansions);
6704 /// \brief Determine the number of arguments in the given pack expansion
6707 /// This routine assumes that the number of arguments in the expansion is
6708 /// consistent across all of the unexpanded parameter packs in its pattern.
6710 /// Returns an empty Optional if the type can't be expanded.
6711 Optional<unsigned> getNumArgumentsInExpansion(QualType T,
6712 const MultiLevelTemplateArgumentList &TemplateArgs);
6714 /// \brief Determine whether the given declarator contains any unexpanded
6715 /// parameter packs.
6717 /// This routine is used by the parser to disambiguate function declarators
6718 /// with an ellipsis prior to the ')', e.g.,
6724 /// To determine whether we have an (unnamed) function parameter pack or
6725 /// a variadic function.
6727 /// \returns true if the declarator contains any unexpanded parameter packs,
6728 /// false otherwise.
6729 bool containsUnexpandedParameterPacks(Declarator &D);
6731 /// \brief Returns the pattern of the pack expansion for a template argument.
6733 /// \param OrigLoc The template argument to expand.
6735 /// \param Ellipsis Will be set to the location of the ellipsis.
6737 /// \param NumExpansions Will be set to the number of expansions that will
6738 /// be generated from this pack expansion, if known a priori.
6739 TemplateArgumentLoc getTemplateArgumentPackExpansionPattern(
6740 TemplateArgumentLoc OrigLoc,
6741 SourceLocation &Ellipsis,
6742 Optional<unsigned> &NumExpansions) const;
6744 /// Given a template argument that contains an unexpanded parameter pack, but
6745 /// which has already been substituted, attempt to determine the number of
6746 /// elements that will be produced once this argument is fully-expanded.
6748 /// This is intended for use when transforming 'sizeof...(Arg)' in order to
6749 /// avoid actually expanding the pack where possible.
6750 Optional<unsigned> getFullyPackExpandedSize(TemplateArgument Arg);
6752 //===--------------------------------------------------------------------===//
6753 // C++ Template Argument Deduction (C++ [temp.deduct])
6754 //===--------------------------------------------------------------------===//
6756 /// Adjust the type \p ArgFunctionType to match the calling convention,
6757 /// noreturn, and optionally the exception specification of \p FunctionType.
6758 /// Deduction often wants to ignore these properties when matching function
6760 QualType adjustCCAndNoReturn(QualType ArgFunctionType, QualType FunctionType,
6761 bool AdjustExceptionSpec = false);
6763 /// \brief Describes the result of template argument deduction.
6765 /// The TemplateDeductionResult enumeration describes the result of
6766 /// template argument deduction, as returned from
6767 /// DeduceTemplateArguments(). The separate TemplateDeductionInfo
6768 /// structure provides additional information about the results of
6769 /// template argument deduction, e.g., the deduced template argument
6770 /// list (if successful) or the specific template parameters or
6771 /// deduced arguments that were involved in the failure.
6772 enum TemplateDeductionResult {
6773 /// \brief Template argument deduction was successful.
6775 /// \brief The declaration was invalid; do nothing.
6777 /// \brief Template argument deduction exceeded the maximum template
6778 /// instantiation depth (which has already been diagnosed).
6779 TDK_InstantiationDepth,
6780 /// \brief Template argument deduction did not deduce a value
6781 /// for every template parameter.
6783 /// \brief Template argument deduction produced inconsistent
6784 /// deduced values for the given template parameter.
6786 /// \brief Template argument deduction failed due to inconsistent
6787 /// cv-qualifiers on a template parameter type that would
6788 /// otherwise be deduced, e.g., we tried to deduce T in "const T"
6789 /// but were given a non-const "X".
6791 /// \brief Substitution of the deduced template argument values
6792 /// resulted in an error.
6793 TDK_SubstitutionFailure,
6794 /// \brief After substituting deduced template arguments, a dependent
6795 /// parameter type did not match the corresponding argument.
6796 TDK_DeducedMismatch,
6797 /// \brief After substituting deduced template arguments, an element of
6798 /// a dependent parameter type did not match the corresponding element
6799 /// of the corresponding argument (when deducing from an initializer list).
6800 TDK_DeducedMismatchNested,
6801 /// \brief A non-depnedent component of the parameter did not match the
6802 /// corresponding component of the argument.
6803 TDK_NonDeducedMismatch,
6804 /// \brief When performing template argument deduction for a function
6805 /// template, there were too many call arguments.
6806 TDK_TooManyArguments,
6807 /// \brief When performing template argument deduction for a function
6808 /// template, there were too few call arguments.
6809 TDK_TooFewArguments,
6810 /// \brief The explicitly-specified template arguments were not valid
6811 /// template arguments for the given template.
6812 TDK_InvalidExplicitArguments,
6813 /// \brief Checking non-dependent argument conversions failed.
6814 TDK_NonDependentConversionFailure,
6815 /// \brief Deduction failed; that's all we know.
6816 TDK_MiscellaneousDeductionFailure,
6817 /// \brief CUDA Target attributes do not match.
6818 TDK_CUDATargetMismatch
6821 TemplateDeductionResult
6822 DeduceTemplateArguments(ClassTemplatePartialSpecializationDecl *Partial,
6823 const TemplateArgumentList &TemplateArgs,
6824 sema::TemplateDeductionInfo &Info);
6826 TemplateDeductionResult
6827 DeduceTemplateArguments(VarTemplatePartialSpecializationDecl *Partial,
6828 const TemplateArgumentList &TemplateArgs,
6829 sema::TemplateDeductionInfo &Info);
6831 TemplateDeductionResult SubstituteExplicitTemplateArguments(
6832 FunctionTemplateDecl *FunctionTemplate,
6833 TemplateArgumentListInfo &ExplicitTemplateArgs,
6834 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
6835 SmallVectorImpl<QualType> &ParamTypes, QualType *FunctionType,
6836 sema::TemplateDeductionInfo &Info);
6838 /// brief A function argument from which we performed template argument
6839 // deduction for a call.
6840 struct OriginalCallArg {
6841 OriginalCallArg(QualType OriginalParamType, bool DecomposedParam,
6842 unsigned ArgIdx, QualType OriginalArgType)
6843 : OriginalParamType(OriginalParamType),
6844 DecomposedParam(DecomposedParam), ArgIdx(ArgIdx),
6845 OriginalArgType(OriginalArgType) {}
6847 QualType OriginalParamType;
6848 bool DecomposedParam;
6850 QualType OriginalArgType;
6853 TemplateDeductionResult FinishTemplateArgumentDeduction(
6854 FunctionTemplateDecl *FunctionTemplate,
6855 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
6856 unsigned NumExplicitlySpecified, FunctionDecl *&Specialization,
6857 sema::TemplateDeductionInfo &Info,
6858 SmallVectorImpl<OriginalCallArg> const *OriginalCallArgs = nullptr,
6859 bool PartialOverloading = false,
6860 llvm::function_ref<bool()> CheckNonDependent = []{ return false; });
6862 TemplateDeductionResult DeduceTemplateArguments(
6863 FunctionTemplateDecl *FunctionTemplate,
6864 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
6865 FunctionDecl *&Specialization, sema::TemplateDeductionInfo &Info,
6866 bool PartialOverloading,
6867 llvm::function_ref<bool(ArrayRef<QualType>)> CheckNonDependent);
6869 TemplateDeductionResult
6870 DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
6871 TemplateArgumentListInfo *ExplicitTemplateArgs,
6872 QualType ArgFunctionType,
6873 FunctionDecl *&Specialization,
6874 sema::TemplateDeductionInfo &Info,
6875 bool IsAddressOfFunction = false);
6877 TemplateDeductionResult
6878 DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
6880 CXXConversionDecl *&Specialization,
6881 sema::TemplateDeductionInfo &Info);
6883 TemplateDeductionResult
6884 DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
6885 TemplateArgumentListInfo *ExplicitTemplateArgs,
6886 FunctionDecl *&Specialization,
6887 sema::TemplateDeductionInfo &Info,
6888 bool IsAddressOfFunction = false);
6890 /// \brief Substitute Replacement for \p auto in \p TypeWithAuto
6891 QualType SubstAutoType(QualType TypeWithAuto, QualType Replacement);
6892 /// \brief Substitute Replacement for auto in TypeWithAuto
6893 TypeSourceInfo* SubstAutoTypeSourceInfo(TypeSourceInfo *TypeWithAuto,
6894 QualType Replacement);
6895 /// \brief Completely replace the \c auto in \p TypeWithAuto by
6896 /// \p Replacement. This does not retain any \c auto type sugar.
6897 QualType ReplaceAutoType(QualType TypeWithAuto, QualType Replacement);
6899 /// \brief Result type of DeduceAutoType.
6900 enum DeduceAutoResult {
6903 DAR_FailedAlreadyDiagnosed
6907 DeduceAutoType(TypeSourceInfo *AutoType, Expr *&Initializer, QualType &Result,
6908 Optional<unsigned> DependentDeductionDepth = None);
6910 DeduceAutoType(TypeLoc AutoTypeLoc, Expr *&Initializer, QualType &Result,
6911 Optional<unsigned> DependentDeductionDepth = None);
6912 void DiagnoseAutoDeductionFailure(VarDecl *VDecl, Expr *Init);
6913 bool DeduceReturnType(FunctionDecl *FD, SourceLocation Loc,
6914 bool Diagnose = true);
6916 /// \brief Declare implicit deduction guides for a class template if we've
6917 /// not already done so.
6918 void DeclareImplicitDeductionGuides(TemplateDecl *Template,
6919 SourceLocation Loc);
6921 QualType DeduceTemplateSpecializationFromInitializer(
6922 TypeSourceInfo *TInfo, const InitializedEntity &Entity,
6923 const InitializationKind &Kind, MultiExprArg Init);
6925 QualType deduceVarTypeFromInitializer(VarDecl *VDecl, DeclarationName Name,
6926 QualType Type, TypeSourceInfo *TSI,
6927 SourceRange Range, bool DirectInit,
6930 TypeLoc getReturnTypeLoc(FunctionDecl *FD) const;
6932 bool DeduceFunctionTypeFromReturnExpr(FunctionDecl *FD,
6933 SourceLocation ReturnLoc,
6934 Expr *&RetExpr, AutoType *AT);
6936 FunctionTemplateDecl *getMoreSpecializedTemplate(FunctionTemplateDecl *FT1,
6937 FunctionTemplateDecl *FT2,
6939 TemplatePartialOrderingContext TPOC,
6940 unsigned NumCallArguments1,
6941 unsigned NumCallArguments2);
6942 UnresolvedSetIterator
6943 getMostSpecialized(UnresolvedSetIterator SBegin, UnresolvedSetIterator SEnd,
6944 TemplateSpecCandidateSet &FailedCandidates,
6946 const PartialDiagnostic &NoneDiag,
6947 const PartialDiagnostic &AmbigDiag,
6948 const PartialDiagnostic &CandidateDiag,
6949 bool Complain = true, QualType TargetType = QualType());
6951 ClassTemplatePartialSpecializationDecl *
6952 getMoreSpecializedPartialSpecialization(
6953 ClassTemplatePartialSpecializationDecl *PS1,
6954 ClassTemplatePartialSpecializationDecl *PS2,
6955 SourceLocation Loc);
6957 bool isMoreSpecializedThanPrimary(ClassTemplatePartialSpecializationDecl *T,
6958 sema::TemplateDeductionInfo &Info);
6960 VarTemplatePartialSpecializationDecl *getMoreSpecializedPartialSpecialization(
6961 VarTemplatePartialSpecializationDecl *PS1,
6962 VarTemplatePartialSpecializationDecl *PS2, SourceLocation Loc);
6964 bool isMoreSpecializedThanPrimary(VarTemplatePartialSpecializationDecl *T,
6965 sema::TemplateDeductionInfo &Info);
6967 bool isTemplateTemplateParameterAtLeastAsSpecializedAs(
6968 TemplateParameterList *P, TemplateDecl *AArg, SourceLocation Loc);
6970 void MarkUsedTemplateParameters(const TemplateArgumentList &TemplateArgs,
6973 llvm::SmallBitVector &Used);
6974 void MarkDeducedTemplateParameters(
6975 const FunctionTemplateDecl *FunctionTemplate,
6976 llvm::SmallBitVector &Deduced) {
6977 return MarkDeducedTemplateParameters(Context, FunctionTemplate, Deduced);
6979 static void MarkDeducedTemplateParameters(ASTContext &Ctx,
6980 const FunctionTemplateDecl *FunctionTemplate,
6981 llvm::SmallBitVector &Deduced);
6983 //===--------------------------------------------------------------------===//
6984 // C++ Template Instantiation
6987 MultiLevelTemplateArgumentList
6988 getTemplateInstantiationArgs(NamedDecl *D,
6989 const TemplateArgumentList *Innermost = nullptr,
6990 bool RelativeToPrimary = false,
6991 const FunctionDecl *Pattern = nullptr);
6993 /// A context in which code is being synthesized (where a source location
6994 /// alone is not sufficient to identify the context). This covers template
6995 /// instantiation and various forms of implicitly-generated functions.
6996 struct CodeSynthesisContext {
6997 /// \brief The kind of template instantiation we are performing
6998 enum SynthesisKind {
6999 /// We are instantiating a template declaration. The entity is
7000 /// the declaration we're instantiating (e.g., a CXXRecordDecl).
7001 TemplateInstantiation,
7003 /// We are instantiating a default argument for a template
7004 /// parameter. The Entity is the template parameter whose argument is
7005 /// being instantiated, the Template is the template, and the
7006 /// TemplateArgs/NumTemplateArguments provide the template arguments as
7008 DefaultTemplateArgumentInstantiation,
7010 /// We are instantiating a default argument for a function.
7011 /// The Entity is the ParmVarDecl, and TemplateArgs/NumTemplateArgs
7012 /// provides the template arguments as specified.
7013 DefaultFunctionArgumentInstantiation,
7015 /// We are substituting explicit template arguments provided for
7016 /// a function template. The entity is a FunctionTemplateDecl.
7017 ExplicitTemplateArgumentSubstitution,
7019 /// We are substituting template argument determined as part of
7020 /// template argument deduction for either a class template
7021 /// partial specialization or a function template. The
7022 /// Entity is either a {Class|Var}TemplatePartialSpecializationDecl or
7024 DeducedTemplateArgumentSubstitution,
7026 /// We are substituting prior template arguments into a new
7027 /// template parameter. The template parameter itself is either a
7028 /// NonTypeTemplateParmDecl or a TemplateTemplateParmDecl.
7029 PriorTemplateArgumentSubstitution,
7031 /// We are checking the validity of a default template argument that
7032 /// has been used when naming a template-id.
7033 DefaultTemplateArgumentChecking,
7035 /// We are instantiating the exception specification for a function
7036 /// template which was deferred until it was needed.
7037 ExceptionSpecInstantiation,
7039 /// We are declaring an implicit special member function.
7040 DeclaringSpecialMember,
7042 /// We are defining a synthesized function (such as a defaulted special
7044 DefiningSynthesizedFunction,
7047 /// \brief Was the enclosing context a non-instantiation SFINAE context?
7048 bool SavedInNonInstantiationSFINAEContext;
7050 /// \brief The point of instantiation or synthesis within the source code.
7051 SourceLocation PointOfInstantiation;
7053 /// \brief The entity that is being synthesized.
7056 /// \brief The template (or partial specialization) in which we are
7057 /// performing the instantiation, for substitutions of prior template
7059 NamedDecl *Template;
7061 /// \brief The list of template arguments we are substituting, if they
7062 /// are not part of the entity.
7063 const TemplateArgument *TemplateArgs;
7065 // FIXME: Wrap this union around more members, or perhaps store the
7066 // kind-specific members in the RAII object owning the context.
7068 /// \brief The number of template arguments in TemplateArgs.
7069 unsigned NumTemplateArgs;
7071 /// \brief The special member being declared or defined.
7072 CXXSpecialMember SpecialMember;
7075 ArrayRef<TemplateArgument> template_arguments() const {
7076 assert(Kind != DeclaringSpecialMember);
7077 return {TemplateArgs, NumTemplateArgs};
7080 /// \brief The template deduction info object associated with the
7081 /// substitution or checking of explicit or deduced template arguments.
7082 sema::TemplateDeductionInfo *DeductionInfo;
7084 /// \brief The source range that covers the construct that cause
7085 /// the instantiation, e.g., the template-id that causes a class
7086 /// template instantiation.
7087 SourceRange InstantiationRange;
7089 CodeSynthesisContext()
7090 : Kind(TemplateInstantiation), Entity(nullptr), Template(nullptr),
7091 TemplateArgs(nullptr), NumTemplateArgs(0), DeductionInfo(nullptr) {}
7093 /// \brief Determines whether this template is an actual instantiation
7094 /// that should be counted toward the maximum instantiation depth.
7095 bool isInstantiationRecord() const;
7098 /// \brief List of active code synthesis contexts.
7100 /// This vector is treated as a stack. As synthesis of one entity requires
7101 /// synthesis of another, additional contexts are pushed onto the stack.
7102 SmallVector<CodeSynthesisContext, 16> CodeSynthesisContexts;
7104 /// Specializations whose definitions are currently being instantiated.
7105 llvm::DenseSet<std::pair<Decl *, unsigned>> InstantiatingSpecializations;
7107 /// Non-dependent types used in templates that have already been instantiated
7108 /// by some template instantiation.
7109 llvm::DenseSet<QualType> InstantiatedNonDependentTypes;
7111 /// \brief Extra modules inspected when performing a lookup during a template
7112 /// instantiation. Computed lazily.
7113 SmallVector<Module*, 16> CodeSynthesisContextLookupModules;
7115 /// \brief Cache of additional modules that should be used for name lookup
7116 /// within the current template instantiation. Computed lazily; use
7117 /// getLookupModules() to get a complete set.
7118 llvm::DenseSet<Module*> LookupModulesCache;
7120 /// \brief Get the set of additional modules that should be checked during
7121 /// name lookup. A module and its imports become visible when instanting a
7122 /// template defined within it.
7123 llvm::DenseSet<Module*> &getLookupModules();
7125 /// \brief Map from the most recent declaration of a namespace to the most
7126 /// recent visible declaration of that namespace.
7127 llvm::DenseMap<NamedDecl*, NamedDecl*> VisibleNamespaceCache;
7129 /// \brief Whether we are in a SFINAE context that is not associated with
7130 /// template instantiation.
7132 /// This is used when setting up a SFINAE trap (\c see SFINAETrap) outside
7133 /// of a template instantiation or template argument deduction.
7134 bool InNonInstantiationSFINAEContext;
7136 /// \brief The number of \p CodeSynthesisContexts that are not template
7137 /// instantiations and, therefore, should not be counted as part of the
7138 /// instantiation depth.
7140 /// When the instantiation depth reaches the user-configurable limit
7141 /// \p LangOptions::InstantiationDepth we will abort instantiation.
7142 // FIXME: Should we have a similar limit for other forms of synthesis?
7143 unsigned NonInstantiationEntries;
7145 /// \brief The depth of the context stack at the point when the most recent
7146 /// error or warning was produced.
7148 /// This value is used to suppress printing of redundant context stacks
7149 /// when there are multiple errors or warnings in the same instantiation.
7150 // FIXME: Does this belong in Sema? It's tough to implement it anywhere else.
7151 unsigned LastEmittedCodeSynthesisContextDepth = 0;
7153 /// \brief The current index into pack expansion arguments that will be
7154 /// used for substitution of parameter packs.
7156 /// The pack expansion index will be -1 to indicate that parameter packs
7157 /// should be instantiated as themselves. Otherwise, the index specifies
7158 /// which argument within the parameter pack will be used for substitution.
7159 int ArgumentPackSubstitutionIndex;
7161 /// \brief RAII object used to change the argument pack substitution index
7162 /// within a \c Sema object.
7164 /// See \c ArgumentPackSubstitutionIndex for more information.
7165 class ArgumentPackSubstitutionIndexRAII {
7167 int OldSubstitutionIndex;
7170 ArgumentPackSubstitutionIndexRAII(Sema &Self, int NewSubstitutionIndex)
7171 : Self(Self), OldSubstitutionIndex(Self.ArgumentPackSubstitutionIndex) {
7172 Self.ArgumentPackSubstitutionIndex = NewSubstitutionIndex;
7175 ~ArgumentPackSubstitutionIndexRAII() {
7176 Self.ArgumentPackSubstitutionIndex = OldSubstitutionIndex;
7180 friend class ArgumentPackSubstitutionRAII;
7182 /// \brief For each declaration that involved template argument deduction, the
7183 /// set of diagnostics that were suppressed during that template argument
7186 /// FIXME: Serialize this structure to the AST file.
7187 typedef llvm::DenseMap<Decl *, SmallVector<PartialDiagnosticAt, 1> >
7188 SuppressedDiagnosticsMap;
7189 SuppressedDiagnosticsMap SuppressedDiagnostics;
7191 /// \brief A stack object to be created when performing template
7194 /// Construction of an object of type \c InstantiatingTemplate
7195 /// pushes the current instantiation onto the stack of active
7196 /// instantiations. If the size of this stack exceeds the maximum
7197 /// number of recursive template instantiations, construction
7198 /// produces an error and evaluates true.
7200 /// Destruction of this object will pop the named instantiation off
7202 struct InstantiatingTemplate {
7203 /// \brief Note that we are instantiating a class template,
7204 /// function template, variable template, alias template,
7205 /// or a member thereof.
7206 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
7208 SourceRange InstantiationRange = SourceRange());
7210 struct ExceptionSpecification {};
7211 /// \brief Note that we are instantiating an exception specification
7212 /// of a function template.
7213 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
7214 FunctionDecl *Entity, ExceptionSpecification,
7215 SourceRange InstantiationRange = SourceRange());
7217 /// \brief Note that we are instantiating a default argument in a
7219 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
7220 TemplateParameter Param, TemplateDecl *Template,
7221 ArrayRef<TemplateArgument> TemplateArgs,
7222 SourceRange InstantiationRange = SourceRange());
7224 /// \brief Note that we are substituting either explicitly-specified or
7225 /// deduced template arguments during function template argument deduction.
7226 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
7227 FunctionTemplateDecl *FunctionTemplate,
7228 ArrayRef<TemplateArgument> TemplateArgs,
7229 CodeSynthesisContext::SynthesisKind Kind,
7230 sema::TemplateDeductionInfo &DeductionInfo,
7231 SourceRange InstantiationRange = SourceRange());
7233 /// \brief Note that we are instantiating as part of template
7234 /// argument deduction for a class template declaration.
7235 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
7236 TemplateDecl *Template,
7237 ArrayRef<TemplateArgument> TemplateArgs,
7238 sema::TemplateDeductionInfo &DeductionInfo,
7239 SourceRange InstantiationRange = SourceRange());
7241 /// \brief Note that we are instantiating as part of template
7242 /// argument deduction for a class template partial
7244 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
7245 ClassTemplatePartialSpecializationDecl *PartialSpec,
7246 ArrayRef<TemplateArgument> TemplateArgs,
7247 sema::TemplateDeductionInfo &DeductionInfo,
7248 SourceRange InstantiationRange = SourceRange());
7250 /// \brief Note that we are instantiating as part of template
7251 /// argument deduction for a variable template partial
7253 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
7254 VarTemplatePartialSpecializationDecl *PartialSpec,
7255 ArrayRef<TemplateArgument> TemplateArgs,
7256 sema::TemplateDeductionInfo &DeductionInfo,
7257 SourceRange InstantiationRange = SourceRange());
7259 /// \brief Note that we are instantiating a default argument for a function
7261 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
7263 ArrayRef<TemplateArgument> TemplateArgs,
7264 SourceRange InstantiationRange = SourceRange());
7266 /// \brief Note that we are substituting prior template arguments into a
7267 /// non-type parameter.
7268 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
7269 NamedDecl *Template,
7270 NonTypeTemplateParmDecl *Param,
7271 ArrayRef<TemplateArgument> TemplateArgs,
7272 SourceRange InstantiationRange);
7274 /// \brief Note that we are substituting prior template arguments into a
7275 /// template template parameter.
7276 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
7277 NamedDecl *Template,
7278 TemplateTemplateParmDecl *Param,
7279 ArrayRef<TemplateArgument> TemplateArgs,
7280 SourceRange InstantiationRange);
7282 /// \brief Note that we are checking the default template argument
7283 /// against the template parameter for a given template-id.
7284 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
7285 TemplateDecl *Template,
7287 ArrayRef<TemplateArgument> TemplateArgs,
7288 SourceRange InstantiationRange);
7291 /// \brief Note that we have finished instantiating this template.
7294 ~InstantiatingTemplate() { Clear(); }
7296 /// \brief Determines whether we have exceeded the maximum
7297 /// recursive template instantiations.
7298 bool isInvalid() const { return Invalid; }
7300 /// \brief Determine whether we are already instantiating this
7301 /// specialization in some surrounding active instantiation.
7302 bool isAlreadyInstantiating() const { return AlreadyInstantiating; }
7307 bool AlreadyInstantiating;
7308 bool CheckInstantiationDepth(SourceLocation PointOfInstantiation,
7309 SourceRange InstantiationRange);
7311 InstantiatingTemplate(
7312 Sema &SemaRef, CodeSynthesisContext::SynthesisKind Kind,
7313 SourceLocation PointOfInstantiation, SourceRange InstantiationRange,
7314 Decl *Entity, NamedDecl *Template = nullptr,
7315 ArrayRef<TemplateArgument> TemplateArgs = None,
7316 sema::TemplateDeductionInfo *DeductionInfo = nullptr);
7318 InstantiatingTemplate(const InstantiatingTemplate&) = delete;
7320 InstantiatingTemplate&
7321 operator=(const InstantiatingTemplate&) = delete;
7324 void pushCodeSynthesisContext(CodeSynthesisContext Ctx);
7325 void popCodeSynthesisContext();
7327 /// Determine whether we are currently performing template instantiation.
7328 bool inTemplateInstantiation() const {
7329 return CodeSynthesisContexts.size() > NonInstantiationEntries;
7332 void PrintContextStack() {
7333 if (!CodeSynthesisContexts.empty() &&
7334 CodeSynthesisContexts.size() != LastEmittedCodeSynthesisContextDepth) {
7335 PrintInstantiationStack();
7336 LastEmittedCodeSynthesisContextDepth = CodeSynthesisContexts.size();
7338 if (PragmaAttributeCurrentTargetDecl)
7339 PrintPragmaAttributeInstantiationPoint();
7341 void PrintInstantiationStack();
7343 void PrintPragmaAttributeInstantiationPoint();
7345 /// \brief Determines whether we are currently in a context where
7346 /// template argument substitution failures are not considered
7349 /// \returns An empty \c Optional if we're not in a SFINAE context.
7350 /// Otherwise, contains a pointer that, if non-NULL, contains the nearest
7351 /// template-deduction context object, which can be used to capture
7352 /// diagnostics that will be suppressed.
7353 Optional<sema::TemplateDeductionInfo *> isSFINAEContext() const;
7355 /// \brief Determines whether we are currently in a context that
7356 /// is not evaluated as per C++ [expr] p5.
7357 bool isUnevaluatedContext() const {
7358 assert(!ExprEvalContexts.empty() &&
7359 "Must be in an expression evaluation context");
7360 return ExprEvalContexts.back().isUnevaluated();
7363 /// \brief RAII class used to determine whether SFINAE has
7364 /// trapped any errors that occur during template argument
7368 unsigned PrevSFINAEErrors;
7369 bool PrevInNonInstantiationSFINAEContext;
7370 bool PrevAccessCheckingSFINAE;
7373 explicit SFINAETrap(Sema &SemaRef, bool AccessCheckingSFINAE = false)
7374 : SemaRef(SemaRef), PrevSFINAEErrors(SemaRef.NumSFINAEErrors),
7375 PrevInNonInstantiationSFINAEContext(
7376 SemaRef.InNonInstantiationSFINAEContext),
7377 PrevAccessCheckingSFINAE(SemaRef.AccessCheckingSFINAE)
7379 if (!SemaRef.isSFINAEContext())
7380 SemaRef.InNonInstantiationSFINAEContext = true;
7381 SemaRef.AccessCheckingSFINAE = AccessCheckingSFINAE;
7385 SemaRef.NumSFINAEErrors = PrevSFINAEErrors;
7386 SemaRef.InNonInstantiationSFINAEContext
7387 = PrevInNonInstantiationSFINAEContext;
7388 SemaRef.AccessCheckingSFINAE = PrevAccessCheckingSFINAE;
7391 /// \brief Determine whether any SFINAE errors have been trapped.
7392 bool hasErrorOccurred() const {
7393 return SemaRef.NumSFINAEErrors > PrevSFINAEErrors;
7397 /// \brief RAII class used to indicate that we are performing provisional
7398 /// semantic analysis to determine the validity of a construct, so
7399 /// typo-correction and diagnostics in the immediate context (not within
7400 /// implicitly-instantiated templates) should be suppressed.
7401 class TentativeAnalysisScope {
7403 // FIXME: Using a SFINAETrap for this is a hack.
7405 bool PrevDisableTypoCorrection;
7407 explicit TentativeAnalysisScope(Sema &SemaRef)
7408 : SemaRef(SemaRef), Trap(SemaRef, true),
7409 PrevDisableTypoCorrection(SemaRef.DisableTypoCorrection) {
7410 SemaRef.DisableTypoCorrection = true;
7412 ~TentativeAnalysisScope() {
7413 SemaRef.DisableTypoCorrection = PrevDisableTypoCorrection;
7417 /// \brief The current instantiation scope used to store local
7419 LocalInstantiationScope *CurrentInstantiationScope;
7421 /// \brief Tracks whether we are in a context where typo correction is
7423 bool DisableTypoCorrection;
7425 /// \brief The number of typos corrected by CorrectTypo.
7426 unsigned TyposCorrected;
7428 typedef llvm::SmallSet<SourceLocation, 2> SrcLocSet;
7429 typedef llvm::DenseMap<IdentifierInfo *, SrcLocSet> IdentifierSourceLocations;
7431 /// \brief A cache containing identifiers for which typo correction failed and
7432 /// their locations, so that repeated attempts to correct an identifier in a
7433 /// given location are ignored if typo correction already failed for it.
7434 IdentifierSourceLocations TypoCorrectionFailures;
7436 /// \brief Worker object for performing CFG-based warnings.
7437 sema::AnalysisBasedWarnings AnalysisWarnings;
7438 threadSafety::BeforeSet *ThreadSafetyDeclCache;
7440 /// \brief An entity for which implicit template instantiation is required.
7442 /// The source location associated with the declaration is the first place in
7443 /// the source code where the declaration was "used". It is not necessarily
7444 /// the point of instantiation (which will be either before or after the
7445 /// namespace-scope declaration that triggered this implicit instantiation),
7446 /// However, it is the location that diagnostics should generally refer to,
7447 /// because users will need to know what code triggered the instantiation.
7448 typedef std::pair<ValueDecl *, SourceLocation> PendingImplicitInstantiation;
7450 /// \brief The queue of implicit template instantiations that are required
7451 /// but have not yet been performed.
7452 std::deque<PendingImplicitInstantiation> PendingInstantiations;
7454 class GlobalEagerInstantiationScope {
7456 GlobalEagerInstantiationScope(Sema &S, bool Enabled)
7457 : S(S), Enabled(Enabled) {
7458 if (!Enabled) return;
7460 SavedPendingInstantiations.swap(S.PendingInstantiations);
7461 SavedVTableUses.swap(S.VTableUses);
7466 S.DefineUsedVTables();
7467 S.PerformPendingInstantiations();
7471 ~GlobalEagerInstantiationScope() {
7472 if (!Enabled) return;
7474 // Restore the set of pending vtables.
7475 assert(S.VTableUses.empty() &&
7476 "VTableUses should be empty before it is discarded.");
7477 S.VTableUses.swap(SavedVTableUses);
7479 // Restore the set of pending implicit instantiations.
7480 assert(S.PendingInstantiations.empty() &&
7481 "PendingInstantiations should be empty before it is discarded.");
7482 S.PendingInstantiations.swap(SavedPendingInstantiations);
7487 SmallVector<VTableUse, 16> SavedVTableUses;
7488 std::deque<PendingImplicitInstantiation> SavedPendingInstantiations;
7492 /// \brief The queue of implicit template instantiations that are required
7493 /// and must be performed within the current local scope.
7495 /// This queue is only used for member functions of local classes in
7496 /// templates, which must be instantiated in the same scope as their
7497 /// enclosing function, so that they can reference function-local
7498 /// types, static variables, enumerators, etc.
7499 std::deque<PendingImplicitInstantiation> PendingLocalImplicitInstantiations;
7501 class LocalEagerInstantiationScope {
7503 LocalEagerInstantiationScope(Sema &S) : S(S) {
7504 SavedPendingLocalImplicitInstantiations.swap(
7505 S.PendingLocalImplicitInstantiations);
7508 void perform() { S.PerformPendingInstantiations(/*LocalOnly=*/true); }
7510 ~LocalEagerInstantiationScope() {
7511 assert(S.PendingLocalImplicitInstantiations.empty() &&
7512 "there shouldn't be any pending local implicit instantiations");
7513 SavedPendingLocalImplicitInstantiations.swap(
7514 S.PendingLocalImplicitInstantiations);
7519 std::deque<PendingImplicitInstantiation>
7520 SavedPendingLocalImplicitInstantiations;
7523 /// A helper class for building up ExtParameterInfos.
7524 class ExtParameterInfoBuilder {
7525 SmallVector<FunctionProtoType::ExtParameterInfo, 16> Infos;
7526 bool HasInteresting = false;
7529 /// Set the ExtParameterInfo for the parameter at the given index,
7531 void set(unsigned index, FunctionProtoType::ExtParameterInfo info) {
7532 assert(Infos.size() <= index);
7533 Infos.resize(index);
7534 Infos.push_back(info);
7536 if (!HasInteresting)
7537 HasInteresting = (info != FunctionProtoType::ExtParameterInfo());
7540 /// Return a pointer (suitable for setting in an ExtProtoInfo) to the
7541 /// ExtParameterInfo array we've built up.
7542 const FunctionProtoType::ExtParameterInfo *
7543 getPointerOrNull(unsigned numParams) {
7544 if (!HasInteresting) return nullptr;
7545 Infos.resize(numParams);
7546 return Infos.data();
7550 void PerformPendingInstantiations(bool LocalOnly = false);
7552 TypeSourceInfo *SubstType(TypeSourceInfo *T,
7553 const MultiLevelTemplateArgumentList &TemplateArgs,
7554 SourceLocation Loc, DeclarationName Entity,
7555 bool AllowDeducedTST = false);
7557 QualType SubstType(QualType T,
7558 const MultiLevelTemplateArgumentList &TemplateArgs,
7559 SourceLocation Loc, DeclarationName Entity);
7561 TypeSourceInfo *SubstType(TypeLoc TL,
7562 const MultiLevelTemplateArgumentList &TemplateArgs,
7563 SourceLocation Loc, DeclarationName Entity);
7565 TypeSourceInfo *SubstFunctionDeclType(TypeSourceInfo *T,
7566 const MultiLevelTemplateArgumentList &TemplateArgs,
7568 DeclarationName Entity,
7569 CXXRecordDecl *ThisContext,
7570 unsigned ThisTypeQuals);
7571 void SubstExceptionSpec(FunctionDecl *New, const FunctionProtoType *Proto,
7572 const MultiLevelTemplateArgumentList &Args);
7573 bool SubstExceptionSpec(SourceLocation Loc,
7574 FunctionProtoType::ExceptionSpecInfo &ESI,
7575 SmallVectorImpl<QualType> &ExceptionStorage,
7576 const MultiLevelTemplateArgumentList &Args);
7577 ParmVarDecl *SubstParmVarDecl(ParmVarDecl *D,
7578 const MultiLevelTemplateArgumentList &TemplateArgs,
7579 int indexAdjustment,
7580 Optional<unsigned> NumExpansions,
7581 bool ExpectParameterPack);
7582 bool SubstParmTypes(SourceLocation Loc, ArrayRef<ParmVarDecl *> Params,
7583 const FunctionProtoType::ExtParameterInfo *ExtParamInfos,
7584 const MultiLevelTemplateArgumentList &TemplateArgs,
7585 SmallVectorImpl<QualType> &ParamTypes,
7586 SmallVectorImpl<ParmVarDecl *> *OutParams,
7587 ExtParameterInfoBuilder &ParamInfos);
7588 ExprResult SubstExpr(Expr *E,
7589 const MultiLevelTemplateArgumentList &TemplateArgs);
7591 /// \brief Substitute the given template arguments into a list of
7592 /// expressions, expanding pack expansions if required.
7594 /// \param Exprs The list of expressions to substitute into.
7596 /// \param IsCall Whether this is some form of call, in which case
7597 /// default arguments will be dropped.
7599 /// \param TemplateArgs The set of template arguments to substitute.
7601 /// \param Outputs Will receive all of the substituted arguments.
7603 /// \returns true if an error occurred, false otherwise.
7604 bool SubstExprs(ArrayRef<Expr *> Exprs, bool IsCall,
7605 const MultiLevelTemplateArgumentList &TemplateArgs,
7606 SmallVectorImpl<Expr *> &Outputs);
7608 StmtResult SubstStmt(Stmt *S,
7609 const MultiLevelTemplateArgumentList &TemplateArgs);
7611 Decl *SubstDecl(Decl *D, DeclContext *Owner,
7612 const MultiLevelTemplateArgumentList &TemplateArgs);
7614 ExprResult SubstInitializer(Expr *E,
7615 const MultiLevelTemplateArgumentList &TemplateArgs,
7616 bool CXXDirectInit);
7619 SubstBaseSpecifiers(CXXRecordDecl *Instantiation,
7620 CXXRecordDecl *Pattern,
7621 const MultiLevelTemplateArgumentList &TemplateArgs);
7624 InstantiateClass(SourceLocation PointOfInstantiation,
7625 CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern,
7626 const MultiLevelTemplateArgumentList &TemplateArgs,
7627 TemplateSpecializationKind TSK,
7628 bool Complain = true);
7630 bool InstantiateEnum(SourceLocation PointOfInstantiation,
7631 EnumDecl *Instantiation, EnumDecl *Pattern,
7632 const MultiLevelTemplateArgumentList &TemplateArgs,
7633 TemplateSpecializationKind TSK);
7635 bool InstantiateInClassInitializer(
7636 SourceLocation PointOfInstantiation, FieldDecl *Instantiation,
7637 FieldDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs);
7639 struct LateInstantiatedAttribute {
7640 const Attr *TmplAttr;
7641 LocalInstantiationScope *Scope;
7644 LateInstantiatedAttribute(const Attr *A, LocalInstantiationScope *S,
7646 : TmplAttr(A), Scope(S), NewDecl(D)
7649 typedef SmallVector<LateInstantiatedAttribute, 16> LateInstantiatedAttrVec;
7651 void InstantiateAttrs(const MultiLevelTemplateArgumentList &TemplateArgs,
7652 const Decl *Pattern, Decl *Inst,
7653 LateInstantiatedAttrVec *LateAttrs = nullptr,
7654 LocalInstantiationScope *OuterMostScope = nullptr);
7657 InstantiateAttrsForDecl(const MultiLevelTemplateArgumentList &TemplateArgs,
7658 const Decl *Pattern, Decl *Inst,
7659 LateInstantiatedAttrVec *LateAttrs = nullptr,
7660 LocalInstantiationScope *OuterMostScope = nullptr);
7662 bool usesPartialOrExplicitSpecialization(
7663 SourceLocation Loc, ClassTemplateSpecializationDecl *ClassTemplateSpec);
7666 InstantiateClassTemplateSpecialization(SourceLocation PointOfInstantiation,
7667 ClassTemplateSpecializationDecl *ClassTemplateSpec,
7668 TemplateSpecializationKind TSK,
7669 bool Complain = true);
7671 void InstantiateClassMembers(SourceLocation PointOfInstantiation,
7672 CXXRecordDecl *Instantiation,
7673 const MultiLevelTemplateArgumentList &TemplateArgs,
7674 TemplateSpecializationKind TSK);
7676 void InstantiateClassTemplateSpecializationMembers(
7677 SourceLocation PointOfInstantiation,
7678 ClassTemplateSpecializationDecl *ClassTemplateSpec,
7679 TemplateSpecializationKind TSK);
7681 NestedNameSpecifierLoc
7682 SubstNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS,
7683 const MultiLevelTemplateArgumentList &TemplateArgs);
7686 SubstDeclarationNameInfo(const DeclarationNameInfo &NameInfo,
7687 const MultiLevelTemplateArgumentList &TemplateArgs);
7689 SubstTemplateName(NestedNameSpecifierLoc QualifierLoc, TemplateName Name,
7691 const MultiLevelTemplateArgumentList &TemplateArgs);
7692 bool Subst(const TemplateArgumentLoc *Args, unsigned NumArgs,
7693 TemplateArgumentListInfo &Result,
7694 const MultiLevelTemplateArgumentList &TemplateArgs);
7696 void InstantiateExceptionSpec(SourceLocation PointOfInstantiation,
7697 FunctionDecl *Function);
7698 void InstantiateFunctionDefinition(SourceLocation PointOfInstantiation,
7699 FunctionDecl *Function,
7700 bool Recursive = false,
7701 bool DefinitionRequired = false,
7702 bool AtEndOfTU = false);
7703 VarTemplateSpecializationDecl *BuildVarTemplateInstantiation(
7704 VarTemplateDecl *VarTemplate, VarDecl *FromVar,
7705 const TemplateArgumentList &TemplateArgList,
7706 const TemplateArgumentListInfo &TemplateArgsInfo,
7707 SmallVectorImpl<TemplateArgument> &Converted,
7708 SourceLocation PointOfInstantiation, void *InsertPos,
7709 LateInstantiatedAttrVec *LateAttrs = nullptr,
7710 LocalInstantiationScope *StartingScope = nullptr);
7711 VarTemplateSpecializationDecl *CompleteVarTemplateSpecializationDecl(
7712 VarTemplateSpecializationDecl *VarSpec, VarDecl *PatternDecl,
7713 const MultiLevelTemplateArgumentList &TemplateArgs);
7715 BuildVariableInstantiation(VarDecl *NewVar, VarDecl *OldVar,
7716 const MultiLevelTemplateArgumentList &TemplateArgs,
7717 LateInstantiatedAttrVec *LateAttrs,
7719 LocalInstantiationScope *StartingScope,
7720 bool InstantiatingVarTemplate = false);
7721 void InstantiateVariableInitializer(
7722 VarDecl *Var, VarDecl *OldVar,
7723 const MultiLevelTemplateArgumentList &TemplateArgs);
7724 void InstantiateVariableDefinition(SourceLocation PointOfInstantiation,
7725 VarDecl *Var, bool Recursive = false,
7726 bool DefinitionRequired = false,
7727 bool AtEndOfTU = false);
7728 void InstantiateStaticDataMemberDefinition(
7729 SourceLocation PointOfInstantiation,
7731 bool Recursive = false,
7732 bool DefinitionRequired = false);
7734 void InstantiateMemInitializers(CXXConstructorDecl *New,
7735 const CXXConstructorDecl *Tmpl,
7736 const MultiLevelTemplateArgumentList &TemplateArgs);
7738 NamedDecl *FindInstantiatedDecl(SourceLocation Loc, NamedDecl *D,
7739 const MultiLevelTemplateArgumentList &TemplateArgs,
7740 bool FindingInstantiatedContext = false);
7741 DeclContext *FindInstantiatedContext(SourceLocation Loc, DeclContext *DC,
7742 const MultiLevelTemplateArgumentList &TemplateArgs);
7744 // Objective-C declarations.
7745 enum ObjCContainerKind {
7752 OCK_CategoryImplementation
7754 ObjCContainerKind getObjCContainerKind() const;
7756 DeclResult actOnObjCTypeParam(Scope *S,
7757 ObjCTypeParamVariance variance,
7758 SourceLocation varianceLoc,
7760 IdentifierInfo *paramName,
7761 SourceLocation paramLoc,
7762 SourceLocation colonLoc,
7763 ParsedType typeBound);
7765 ObjCTypeParamList *actOnObjCTypeParamList(Scope *S, SourceLocation lAngleLoc,
7766 ArrayRef<Decl *> typeParams,
7767 SourceLocation rAngleLoc);
7768 void popObjCTypeParamList(Scope *S, ObjCTypeParamList *typeParamList);
7770 Decl *ActOnStartClassInterface(Scope *S,
7771 SourceLocation AtInterfaceLoc,
7772 IdentifierInfo *ClassName,
7773 SourceLocation ClassLoc,
7774 ObjCTypeParamList *typeParamList,
7775 IdentifierInfo *SuperName,
7776 SourceLocation SuperLoc,
7777 ArrayRef<ParsedType> SuperTypeArgs,
7778 SourceRange SuperTypeArgsRange,
7779 Decl * const *ProtoRefs,
7780 unsigned NumProtoRefs,
7781 const SourceLocation *ProtoLocs,
7782 SourceLocation EndProtoLoc,
7783 AttributeList *AttrList);
7785 void ActOnSuperClassOfClassInterface(Scope *S,
7786 SourceLocation AtInterfaceLoc,
7787 ObjCInterfaceDecl *IDecl,
7788 IdentifierInfo *ClassName,
7789 SourceLocation ClassLoc,
7790 IdentifierInfo *SuperName,
7791 SourceLocation SuperLoc,
7792 ArrayRef<ParsedType> SuperTypeArgs,
7793 SourceRange SuperTypeArgsRange);
7795 void ActOnTypedefedProtocols(SmallVectorImpl<Decl *> &ProtocolRefs,
7796 SmallVectorImpl<SourceLocation> &ProtocolLocs,
7797 IdentifierInfo *SuperName,
7798 SourceLocation SuperLoc);
7800 Decl *ActOnCompatibilityAlias(
7801 SourceLocation AtCompatibilityAliasLoc,
7802 IdentifierInfo *AliasName, SourceLocation AliasLocation,
7803 IdentifierInfo *ClassName, SourceLocation ClassLocation);
7805 bool CheckForwardProtocolDeclarationForCircularDependency(
7806 IdentifierInfo *PName,
7807 SourceLocation &PLoc, SourceLocation PrevLoc,
7808 const ObjCList<ObjCProtocolDecl> &PList);
7810 Decl *ActOnStartProtocolInterface(
7811 SourceLocation AtProtoInterfaceLoc,
7812 IdentifierInfo *ProtocolName, SourceLocation ProtocolLoc,
7813 Decl * const *ProtoRefNames, unsigned NumProtoRefs,
7814 const SourceLocation *ProtoLocs,
7815 SourceLocation EndProtoLoc,
7816 AttributeList *AttrList);
7818 Decl *ActOnStartCategoryInterface(SourceLocation AtInterfaceLoc,
7819 IdentifierInfo *ClassName,
7820 SourceLocation ClassLoc,
7821 ObjCTypeParamList *typeParamList,
7822 IdentifierInfo *CategoryName,
7823 SourceLocation CategoryLoc,
7824 Decl * const *ProtoRefs,
7825 unsigned NumProtoRefs,
7826 const SourceLocation *ProtoLocs,
7827 SourceLocation EndProtoLoc,
7828 AttributeList *AttrList);
7830 Decl *ActOnStartClassImplementation(
7831 SourceLocation AtClassImplLoc,
7832 IdentifierInfo *ClassName, SourceLocation ClassLoc,
7833 IdentifierInfo *SuperClassname,
7834 SourceLocation SuperClassLoc);
7836 Decl *ActOnStartCategoryImplementation(SourceLocation AtCatImplLoc,
7837 IdentifierInfo *ClassName,
7838 SourceLocation ClassLoc,
7839 IdentifierInfo *CatName,
7840 SourceLocation CatLoc);
7842 DeclGroupPtrTy ActOnFinishObjCImplementation(Decl *ObjCImpDecl,
7843 ArrayRef<Decl *> Decls);
7845 DeclGroupPtrTy ActOnForwardClassDeclaration(SourceLocation Loc,
7846 IdentifierInfo **IdentList,
7847 SourceLocation *IdentLocs,
7848 ArrayRef<ObjCTypeParamList *> TypeParamLists,
7851 DeclGroupPtrTy ActOnForwardProtocolDeclaration(SourceLocation AtProtoclLoc,
7852 ArrayRef<IdentifierLocPair> IdentList,
7853 AttributeList *attrList);
7855 void FindProtocolDeclaration(bool WarnOnDeclarations, bool ForObjCContainer,
7856 ArrayRef<IdentifierLocPair> ProtocolId,
7857 SmallVectorImpl<Decl *> &Protocols);
7859 void DiagnoseTypeArgsAndProtocols(IdentifierInfo *ProtocolId,
7860 SourceLocation ProtocolLoc,
7861 IdentifierInfo *TypeArgId,
7862 SourceLocation TypeArgLoc,
7863 bool SelectProtocolFirst = false);
7865 /// Given a list of identifiers (and their locations), resolve the
7866 /// names to either Objective-C protocol qualifiers or type
7867 /// arguments, as appropriate.
7868 void actOnObjCTypeArgsOrProtocolQualifiers(
7870 ParsedType baseType,
7871 SourceLocation lAngleLoc,
7872 ArrayRef<IdentifierInfo *> identifiers,
7873 ArrayRef<SourceLocation> identifierLocs,
7874 SourceLocation rAngleLoc,
7875 SourceLocation &typeArgsLAngleLoc,
7876 SmallVectorImpl<ParsedType> &typeArgs,
7877 SourceLocation &typeArgsRAngleLoc,
7878 SourceLocation &protocolLAngleLoc,
7879 SmallVectorImpl<Decl *> &protocols,
7880 SourceLocation &protocolRAngleLoc,
7881 bool warnOnIncompleteProtocols);
7883 /// Build a an Objective-C protocol-qualified 'id' type where no
7884 /// base type was specified.
7885 TypeResult actOnObjCProtocolQualifierType(
7886 SourceLocation lAngleLoc,
7887 ArrayRef<Decl *> protocols,
7888 ArrayRef<SourceLocation> protocolLocs,
7889 SourceLocation rAngleLoc);
7891 /// Build a specialized and/or protocol-qualified Objective-C type.
7892 TypeResult actOnObjCTypeArgsAndProtocolQualifiers(
7895 ParsedType BaseType,
7896 SourceLocation TypeArgsLAngleLoc,
7897 ArrayRef<ParsedType> TypeArgs,
7898 SourceLocation TypeArgsRAngleLoc,
7899 SourceLocation ProtocolLAngleLoc,
7900 ArrayRef<Decl *> Protocols,
7901 ArrayRef<SourceLocation> ProtocolLocs,
7902 SourceLocation ProtocolRAngleLoc);
7904 /// Build an Objective-C type parameter type.
7905 QualType BuildObjCTypeParamType(const ObjCTypeParamDecl *Decl,
7906 SourceLocation ProtocolLAngleLoc,
7907 ArrayRef<ObjCProtocolDecl *> Protocols,
7908 ArrayRef<SourceLocation> ProtocolLocs,
7909 SourceLocation ProtocolRAngleLoc,
7910 bool FailOnError = false);
7912 /// Build an Objective-C object pointer type.
7913 QualType BuildObjCObjectType(QualType BaseType,
7915 SourceLocation TypeArgsLAngleLoc,
7916 ArrayRef<TypeSourceInfo *> TypeArgs,
7917 SourceLocation TypeArgsRAngleLoc,
7918 SourceLocation ProtocolLAngleLoc,
7919 ArrayRef<ObjCProtocolDecl *> Protocols,
7920 ArrayRef<SourceLocation> ProtocolLocs,
7921 SourceLocation ProtocolRAngleLoc,
7922 bool FailOnError = false);
7924 /// Check the application of the Objective-C '__kindof' qualifier to
7926 bool checkObjCKindOfType(QualType &type, SourceLocation loc);
7928 /// Ensure attributes are consistent with type.
7929 /// \param [in, out] Attributes The attributes to check; they will
7930 /// be modified to be consistent with \p PropertyTy.
7931 void CheckObjCPropertyAttributes(Decl *PropertyPtrTy,
7933 unsigned &Attributes,
7934 bool propertyInPrimaryClass);
7936 /// Process the specified property declaration and create decls for the
7937 /// setters and getters as needed.
7938 /// \param property The property declaration being processed
7939 void ProcessPropertyDecl(ObjCPropertyDecl *property);
7942 void DiagnosePropertyMismatch(ObjCPropertyDecl *Property,
7943 ObjCPropertyDecl *SuperProperty,
7944 const IdentifierInfo *Name,
7945 bool OverridingProtocolProperty);
7947 void DiagnoseClassExtensionDupMethods(ObjCCategoryDecl *CAT,
7948 ObjCInterfaceDecl *ID);
7950 Decl *ActOnAtEnd(Scope *S, SourceRange AtEnd,
7951 ArrayRef<Decl *> allMethods = None,
7952 ArrayRef<DeclGroupPtrTy> allTUVars = None);
7954 Decl *ActOnProperty(Scope *S, SourceLocation AtLoc,
7955 SourceLocation LParenLoc,
7956 FieldDeclarator &FD, ObjCDeclSpec &ODS,
7957 Selector GetterSel, Selector SetterSel,
7958 tok::ObjCKeywordKind MethodImplKind,
7959 DeclContext *lexicalDC = nullptr);
7961 Decl *ActOnPropertyImplDecl(Scope *S,
7962 SourceLocation AtLoc,
7963 SourceLocation PropertyLoc,
7965 IdentifierInfo *PropertyId,
7966 IdentifierInfo *PropertyIvar,
7967 SourceLocation PropertyIvarLoc,
7968 ObjCPropertyQueryKind QueryKind);
7970 enum ObjCSpecialMethodKind {
7976 OSMK_NonRetainingInit
7979 struct ObjCArgInfo {
7980 IdentifierInfo *Name;
7981 SourceLocation NameLoc;
7982 // The Type is null if no type was specified, and the DeclSpec is invalid
7985 ObjCDeclSpec DeclSpec;
7987 /// ArgAttrs - Attribute list for this argument.
7988 AttributeList *ArgAttrs;
7991 Decl *ActOnMethodDeclaration(
7993 SourceLocation BeginLoc, // location of the + or -.
7994 SourceLocation EndLoc, // location of the ; or {.
7995 tok::TokenKind MethodType,
7996 ObjCDeclSpec &ReturnQT, ParsedType ReturnType,
7997 ArrayRef<SourceLocation> SelectorLocs, Selector Sel,
7998 // optional arguments. The number of types/arguments is obtained
7999 // from the Sel.getNumArgs().
8000 ObjCArgInfo *ArgInfo,
8001 DeclaratorChunk::ParamInfo *CParamInfo, unsigned CNumArgs, // c-style args
8002 AttributeList *AttrList, tok::ObjCKeywordKind MethodImplKind,
8003 bool isVariadic, bool MethodDefinition);
8005 ObjCMethodDecl *LookupMethodInQualifiedType(Selector Sel,
8006 const ObjCObjectPointerType *OPT,
8008 ObjCMethodDecl *LookupMethodInObjectType(Selector Sel, QualType Ty,
8011 bool CheckARCMethodDecl(ObjCMethodDecl *method);
8012 bool inferObjCARCLifetime(ValueDecl *decl);
8015 HandleExprPropertyRefExpr(const ObjCObjectPointerType *OPT,
8017 SourceLocation OpLoc,
8018 DeclarationName MemberName,
8019 SourceLocation MemberLoc,
8020 SourceLocation SuperLoc, QualType SuperType,
8024 ActOnClassPropertyRefExpr(IdentifierInfo &receiverName,
8025 IdentifierInfo &propertyName,
8026 SourceLocation receiverNameLoc,
8027 SourceLocation propertyNameLoc);
8029 ObjCMethodDecl *tryCaptureObjCSelf(SourceLocation Loc);
8031 /// \brief Describes the kind of message expression indicated by a message
8032 /// send that starts with an identifier.
8033 enum ObjCMessageKind {
8034 /// \brief The message is sent to 'super'.
8036 /// \brief The message is an instance message.
8037 ObjCInstanceMessage,
8038 /// \brief The message is a class message, and the identifier is a type
8043 ObjCMessageKind getObjCMessageKind(Scope *S,
8044 IdentifierInfo *Name,
8045 SourceLocation NameLoc,
8047 bool HasTrailingDot,
8048 ParsedType &ReceiverType);
8050 ExprResult ActOnSuperMessage(Scope *S, SourceLocation SuperLoc,
8052 SourceLocation LBracLoc,
8053 ArrayRef<SourceLocation> SelectorLocs,
8054 SourceLocation RBracLoc,
8057 ExprResult BuildClassMessage(TypeSourceInfo *ReceiverTypeInfo,
8058 QualType ReceiverType,
8059 SourceLocation SuperLoc,
8061 ObjCMethodDecl *Method,
8062 SourceLocation LBracLoc,
8063 ArrayRef<SourceLocation> SelectorLocs,
8064 SourceLocation RBracLoc,
8066 bool isImplicit = false);
8068 ExprResult BuildClassMessageImplicit(QualType ReceiverType,
8069 bool isSuperReceiver,
8072 ObjCMethodDecl *Method,
8075 ExprResult ActOnClassMessage(Scope *S,
8076 ParsedType Receiver,
8078 SourceLocation LBracLoc,
8079 ArrayRef<SourceLocation> SelectorLocs,
8080 SourceLocation RBracLoc,
8083 ExprResult BuildInstanceMessage(Expr *Receiver,
8084 QualType ReceiverType,
8085 SourceLocation SuperLoc,
8087 ObjCMethodDecl *Method,
8088 SourceLocation LBracLoc,
8089 ArrayRef<SourceLocation> SelectorLocs,
8090 SourceLocation RBracLoc,
8092 bool isImplicit = false);
8094 ExprResult BuildInstanceMessageImplicit(Expr *Receiver,
8095 QualType ReceiverType,
8098 ObjCMethodDecl *Method,
8101 ExprResult ActOnInstanceMessage(Scope *S,
8104 SourceLocation LBracLoc,
8105 ArrayRef<SourceLocation> SelectorLocs,
8106 SourceLocation RBracLoc,
8109 ExprResult BuildObjCBridgedCast(SourceLocation LParenLoc,
8110 ObjCBridgeCastKind Kind,
8111 SourceLocation BridgeKeywordLoc,
8112 TypeSourceInfo *TSInfo,
8115 ExprResult ActOnObjCBridgedCast(Scope *S,
8116 SourceLocation LParenLoc,
8117 ObjCBridgeCastKind Kind,
8118 SourceLocation BridgeKeywordLoc,
8120 SourceLocation RParenLoc,
8123 void CheckTollFreeBridgeCast(QualType castType, Expr *castExpr);
8125 void CheckObjCBridgeRelatedCast(QualType castType, Expr *castExpr);
8127 bool CheckTollFreeBridgeStaticCast(QualType castType, Expr *castExpr,
8130 bool checkObjCBridgeRelatedComponents(SourceLocation Loc,
8131 QualType DestType, QualType SrcType,
8132 ObjCInterfaceDecl *&RelatedClass,
8133 ObjCMethodDecl *&ClassMethod,
8134 ObjCMethodDecl *&InstanceMethod,
8135 TypedefNameDecl *&TDNDecl,
8136 bool CfToNs, bool Diagnose = true);
8138 bool CheckObjCBridgeRelatedConversions(SourceLocation Loc,
8139 QualType DestType, QualType SrcType,
8140 Expr *&SrcExpr, bool Diagnose = true);
8142 bool ConversionToObjCStringLiteralCheck(QualType DstType, Expr *&SrcExpr,
8143 bool Diagnose = true);
8145 bool checkInitMethod(ObjCMethodDecl *method, QualType receiverTypeIfCall);
8147 /// \brief Check whether the given new method is a valid override of the
8148 /// given overridden method, and set any properties that should be inherited.
8149 void CheckObjCMethodOverride(ObjCMethodDecl *NewMethod,
8150 const ObjCMethodDecl *Overridden);
8152 /// \brief Describes the compatibility of a result type with its method.
8153 enum ResultTypeCompatibilityKind {
8159 void CheckObjCMethodOverrides(ObjCMethodDecl *ObjCMethod,
8160 ObjCInterfaceDecl *CurrentClass,
8161 ResultTypeCompatibilityKind RTC);
8163 enum PragmaOptionsAlignKind {
8164 POAK_Native, // #pragma options align=native
8165 POAK_Natural, // #pragma options align=natural
8166 POAK_Packed, // #pragma options align=packed
8167 POAK_Power, // #pragma options align=power
8168 POAK_Mac68k, // #pragma options align=mac68k
8169 POAK_Reset // #pragma options align=reset
8172 /// ActOnPragmaClangSection - Called on well formed \#pragma clang section
8173 void ActOnPragmaClangSection(SourceLocation PragmaLoc,
8174 PragmaClangSectionAction Action,
8175 PragmaClangSectionKind SecKind, StringRef SecName);
8177 /// ActOnPragmaOptionsAlign - Called on well formed \#pragma options align.
8178 void ActOnPragmaOptionsAlign(PragmaOptionsAlignKind Kind,
8179 SourceLocation PragmaLoc);
8181 /// ActOnPragmaPack - Called on well formed \#pragma pack(...).
8182 void ActOnPragmaPack(SourceLocation PragmaLoc, PragmaMsStackAction Action,
8183 StringRef SlotLabel, Expr *Alignment);
8185 /// ActOnPragmaMSStruct - Called on well formed \#pragma ms_struct [on|off].
8186 void ActOnPragmaMSStruct(PragmaMSStructKind Kind);
8188 /// ActOnPragmaMSComment - Called on well formed
8189 /// \#pragma comment(kind, "arg").
8190 void ActOnPragmaMSComment(SourceLocation CommentLoc, PragmaMSCommentKind Kind,
8193 /// ActOnPragmaMSPointersToMembers - called on well formed \#pragma
8194 /// pointers_to_members(representation method[, general purpose
8195 /// representation]).
8196 void ActOnPragmaMSPointersToMembers(
8197 LangOptions::PragmaMSPointersToMembersKind Kind,
8198 SourceLocation PragmaLoc);
8200 /// \brief Called on well formed \#pragma vtordisp().
8201 void ActOnPragmaMSVtorDisp(PragmaMsStackAction Action,
8202 SourceLocation PragmaLoc,
8203 MSVtorDispAttr::Mode Value);
8205 enum PragmaSectionKind {
8212 bool UnifySection(StringRef SectionName,
8214 DeclaratorDecl *TheDecl);
8215 bool UnifySection(StringRef SectionName,
8217 SourceLocation PragmaSectionLocation);
8219 /// \brief Called on well formed \#pragma bss_seg/data_seg/const_seg/code_seg.
8220 void ActOnPragmaMSSeg(SourceLocation PragmaLocation,
8221 PragmaMsStackAction Action,
8222 llvm::StringRef StackSlotLabel,
8223 StringLiteral *SegmentName,
8224 llvm::StringRef PragmaName);
8226 /// \brief Called on well formed \#pragma section().
8227 void ActOnPragmaMSSection(SourceLocation PragmaLocation,
8228 int SectionFlags, StringLiteral *SegmentName);
8230 /// \brief Called on well-formed \#pragma init_seg().
8231 void ActOnPragmaMSInitSeg(SourceLocation PragmaLocation,
8232 StringLiteral *SegmentName);
8234 /// \brief Called on #pragma clang __debug dump II
8235 void ActOnPragmaDump(Scope *S, SourceLocation Loc, IdentifierInfo *II);
8237 /// ActOnPragmaDetectMismatch - Call on well-formed \#pragma detect_mismatch
8238 void ActOnPragmaDetectMismatch(SourceLocation Loc, StringRef Name,
8241 /// ActOnPragmaUnused - Called on well-formed '\#pragma unused'.
8242 void ActOnPragmaUnused(const Token &Identifier,
8244 SourceLocation PragmaLoc);
8246 /// ActOnPragmaVisibility - Called on well formed \#pragma GCC visibility... .
8247 void ActOnPragmaVisibility(const IdentifierInfo* VisType,
8248 SourceLocation PragmaLoc);
8250 NamedDecl *DeclClonePragmaWeak(NamedDecl *ND, IdentifierInfo *II,
8251 SourceLocation Loc);
8252 void DeclApplyPragmaWeak(Scope *S, NamedDecl *ND, WeakInfo &W);
8254 /// ActOnPragmaWeakID - Called on well formed \#pragma weak ident.
8255 void ActOnPragmaWeakID(IdentifierInfo* WeakName,
8256 SourceLocation PragmaLoc,
8257 SourceLocation WeakNameLoc);
8259 /// ActOnPragmaRedefineExtname - Called on well formed
8260 /// \#pragma redefine_extname oldname newname.
8261 void ActOnPragmaRedefineExtname(IdentifierInfo* WeakName,
8262 IdentifierInfo* AliasName,
8263 SourceLocation PragmaLoc,
8264 SourceLocation WeakNameLoc,
8265 SourceLocation AliasNameLoc);
8267 /// ActOnPragmaWeakAlias - Called on well formed \#pragma weak ident = ident.
8268 void ActOnPragmaWeakAlias(IdentifierInfo* WeakName,
8269 IdentifierInfo* AliasName,
8270 SourceLocation PragmaLoc,
8271 SourceLocation WeakNameLoc,
8272 SourceLocation AliasNameLoc);
8274 /// ActOnPragmaFPContract - Called on well formed
8275 /// \#pragma {STDC,OPENCL} FP_CONTRACT and
8276 /// \#pragma clang fp contract
8277 void ActOnPragmaFPContract(LangOptions::FPContractModeKind FPC);
8279 /// AddAlignmentAttributesForRecord - Adds any needed alignment attributes to
8280 /// a the record decl, to handle '\#pragma pack' and '\#pragma options align'.
8281 void AddAlignmentAttributesForRecord(RecordDecl *RD);
8283 /// AddMsStructLayoutForRecord - Adds ms_struct layout attribute to record.
8284 void AddMsStructLayoutForRecord(RecordDecl *RD);
8286 /// FreePackedContext - Deallocate and null out PackContext.
8287 void FreePackedContext();
8289 /// PushNamespaceVisibilityAttr - Note that we've entered a
8290 /// namespace with a visibility attribute.
8291 void PushNamespaceVisibilityAttr(const VisibilityAttr *Attr,
8292 SourceLocation Loc);
8294 /// AddPushedVisibilityAttribute - If '\#pragma GCC visibility' was used,
8295 /// add an appropriate visibility attribute.
8296 void AddPushedVisibilityAttribute(Decl *RD);
8298 /// PopPragmaVisibility - Pop the top element of the visibility stack; used
8299 /// for '\#pragma GCC visibility' and visibility attributes on namespaces.
8300 void PopPragmaVisibility(bool IsNamespaceEnd, SourceLocation EndLoc);
8302 /// FreeVisContext - Deallocate and null out VisContext.
8303 void FreeVisContext();
8305 /// AddCFAuditedAttribute - Check whether we're currently within
8306 /// '\#pragma clang arc_cf_code_audited' and, if so, consider adding
8307 /// the appropriate attribute.
8308 void AddCFAuditedAttribute(Decl *D);
8310 /// \brief Called on well-formed '\#pragma clang attribute push'.
8311 void ActOnPragmaAttributePush(AttributeList &Attribute,
8312 SourceLocation PragmaLoc,
8313 attr::ParsedSubjectMatchRuleSet Rules);
8315 /// \brief Called on well-formed '\#pragma clang attribute pop'.
8316 void ActOnPragmaAttributePop(SourceLocation PragmaLoc);
8318 /// \brief Adds the attributes that have been specified using the
8319 /// '\#pragma clang attribute push' directives to the given declaration.
8320 void AddPragmaAttributes(Scope *S, Decl *D);
8322 void DiagnoseUnterminatedPragmaAttribute();
8324 /// \brief Called on well formed \#pragma clang optimize.
8325 void ActOnPragmaOptimize(bool On, SourceLocation PragmaLoc);
8327 /// \brief Get the location for the currently active "\#pragma clang optimize
8328 /// off". If this location is invalid, then the state of the pragma is "on".
8329 SourceLocation getOptimizeOffPragmaLocation() const {
8330 return OptimizeOffPragmaLocation;
8333 /// \brief Only called on function definitions; if there is a pragma in scope
8334 /// with the effect of a range-based optnone, consider marking the function
8335 /// with attribute optnone.
8336 void AddRangeBasedOptnone(FunctionDecl *FD);
8338 /// \brief Adds the 'optnone' attribute to the function declaration if there
8339 /// are no conflicts; Loc represents the location causing the 'optnone'
8340 /// attribute to be added (usually because of a pragma).
8341 void AddOptnoneAttributeIfNoConflicts(FunctionDecl *FD, SourceLocation Loc);
8343 /// AddAlignedAttr - Adds an aligned attribute to a particular declaration.
8344 void AddAlignedAttr(SourceRange AttrRange, Decl *D, Expr *E,
8345 unsigned SpellingListIndex, bool IsPackExpansion);
8346 void AddAlignedAttr(SourceRange AttrRange, Decl *D, TypeSourceInfo *T,
8347 unsigned SpellingListIndex, bool IsPackExpansion);
8349 /// AddAssumeAlignedAttr - Adds an assume_aligned attribute to a particular
8351 void AddAssumeAlignedAttr(SourceRange AttrRange, Decl *D, Expr *E, Expr *OE,
8352 unsigned SpellingListIndex);
8354 /// AddAllocAlignAttr - Adds an alloc_align attribute to a particular
8356 void AddAllocAlignAttr(SourceRange AttrRange, Decl *D, Expr *ParamExpr,
8357 unsigned SpellingListIndex);
8359 /// AddAlignValueAttr - Adds an align_value attribute to a particular
8361 void AddAlignValueAttr(SourceRange AttrRange, Decl *D, Expr *E,
8362 unsigned SpellingListIndex);
8364 /// AddLaunchBoundsAttr - Adds a launch_bounds attribute to a particular
8366 void AddLaunchBoundsAttr(SourceRange AttrRange, Decl *D, Expr *MaxThreads,
8367 Expr *MinBlocks, unsigned SpellingListIndex);
8369 /// AddModeAttr - Adds a mode attribute to a particular declaration.
8370 void AddModeAttr(SourceRange AttrRange, Decl *D, IdentifierInfo *Name,
8371 unsigned SpellingListIndex, bool InInstantiation = false);
8373 void AddParameterABIAttr(SourceRange AttrRange, Decl *D,
8374 ParameterABI ABI, unsigned SpellingListIndex);
8376 void AddNSConsumedAttr(SourceRange AttrRange, Decl *D,
8377 unsigned SpellingListIndex, bool isNSConsumed,
8378 bool isTemplateInstantiation);
8380 bool checkNSReturnsRetainedReturnType(SourceLocation loc, QualType type);
8382 //===--------------------------------------------------------------------===//
8383 // C++ Coroutines TS
8385 bool ActOnCoroutineBodyStart(Scope *S, SourceLocation KwLoc,
8387 ExprResult ActOnCoawaitExpr(Scope *S, SourceLocation KwLoc, Expr *E);
8388 ExprResult ActOnCoyieldExpr(Scope *S, SourceLocation KwLoc, Expr *E);
8389 StmtResult ActOnCoreturnStmt(Scope *S, SourceLocation KwLoc, Expr *E);
8391 ExprResult BuildResolvedCoawaitExpr(SourceLocation KwLoc, Expr *E,
8392 bool IsImplicit = false);
8393 ExprResult BuildUnresolvedCoawaitExpr(SourceLocation KwLoc, Expr *E,
8394 UnresolvedLookupExpr* Lookup);
8395 ExprResult BuildCoyieldExpr(SourceLocation KwLoc, Expr *E);
8396 StmtResult BuildCoreturnStmt(SourceLocation KwLoc, Expr *E,
8397 bool IsImplicit = false);
8398 StmtResult BuildCoroutineBodyStmt(CoroutineBodyStmt::CtorArgs);
8399 VarDecl *buildCoroutinePromise(SourceLocation Loc);
8400 void CheckCompletedCoroutineBody(FunctionDecl *FD, Stmt *&Body);
8402 //===--------------------------------------------------------------------===//
8403 // OpenCL extensions.
8406 std::string CurrOpenCLExtension;
8407 /// Extensions required by an OpenCL type.
8408 llvm::DenseMap<const Type*, std::set<std::string>> OpenCLTypeExtMap;
8409 /// Extensions required by an OpenCL declaration.
8410 llvm::DenseMap<const Decl*, std::set<std::string>> OpenCLDeclExtMap;
8412 llvm::StringRef getCurrentOpenCLExtension() const {
8413 return CurrOpenCLExtension;
8415 void setCurrentOpenCLExtension(llvm::StringRef Ext) {
8416 CurrOpenCLExtension = Ext;
8419 /// \brief Set OpenCL extensions for a type which can only be used when these
8420 /// OpenCL extensions are enabled. If \p Exts is empty, do nothing.
8421 /// \param Exts A space separated list of OpenCL extensions.
8422 void setOpenCLExtensionForType(QualType T, llvm::StringRef Exts);
8424 /// \brief Set OpenCL extensions for a declaration which can only be
8425 /// used when these OpenCL extensions are enabled. If \p Exts is empty, do
8427 /// \param Exts A space separated list of OpenCL extensions.
8428 void setOpenCLExtensionForDecl(Decl *FD, llvm::StringRef Exts);
8430 /// \brief Set current OpenCL extensions for a type which can only be used
8431 /// when these OpenCL extensions are enabled. If current OpenCL extension is
8432 /// empty, do nothing.
8433 void setCurrentOpenCLExtensionForType(QualType T);
8435 /// \brief Set current OpenCL extensions for a declaration which
8436 /// can only be used when these OpenCL extensions are enabled. If current
8437 /// OpenCL extension is empty, do nothing.
8438 void setCurrentOpenCLExtensionForDecl(Decl *FD);
8440 bool isOpenCLDisabledDecl(Decl *FD);
8442 /// \brief Check if type \p T corresponding to declaration specifier \p DS
8443 /// is disabled due to required OpenCL extensions being disabled. If so,
8444 /// emit diagnostics.
8445 /// \return true if type is disabled.
8446 bool checkOpenCLDisabledTypeDeclSpec(const DeclSpec &DS, QualType T);
8448 /// \brief Check if declaration \p D used by expression \p E
8449 /// is disabled due to required OpenCL extensions being disabled. If so,
8450 /// emit diagnostics.
8451 /// \return true if type is disabled.
8452 bool checkOpenCLDisabledDecl(const NamedDecl &D, const Expr &E);
8454 //===--------------------------------------------------------------------===//
8455 // OpenMP directives and clauses.
8458 void *VarDataSharingAttributesStack;
8459 /// Set to true inside '#pragma omp declare target' region.
8460 bool IsInOpenMPDeclareTargetContext = false;
8461 /// \brief Initialization of data-sharing attributes stack.
8462 void InitDataSharingAttributesStack();
8463 void DestroyDataSharingAttributesStack();
8465 VerifyPositiveIntegerConstantInClause(Expr *Op, OpenMPClauseKind CKind,
8466 bool StrictlyPositive = true);
8467 /// Returns OpenMP nesting level for current directive.
8468 unsigned getOpenMPNestingLevel() const;
8470 /// Push new OpenMP function region for non-capturing function.
8471 void pushOpenMPFunctionRegion();
8473 /// Pop OpenMP function region for non-capturing function.
8474 void popOpenMPFunctionRegion(const sema::FunctionScopeInfo *OldFSI);
8476 /// Checks if a type or a declaration is disabled due to the owning extension
8477 /// being disabled, and emits diagnostic messages if it is disabled.
8478 /// \param D type or declaration to be checked.
8479 /// \param DiagLoc source location for the diagnostic message.
8480 /// \param DiagInfo information to be emitted for the diagnostic message.
8481 /// \param SrcRange source range of the declaration.
8482 /// \param Map maps type or declaration to the extensions.
8483 /// \param Selector selects diagnostic message: 0 for type and 1 for
8485 /// \return true if the type or declaration is disabled.
8486 template <typename T, typename DiagLocT, typename DiagInfoT, typename MapT>
8487 bool checkOpenCLDisabledTypeOrDecl(T D, DiagLocT DiagLoc, DiagInfoT DiagInfo,
8488 MapT &Map, unsigned Selector = 0,
8489 SourceRange SrcRange = SourceRange());
8492 /// \brief Return true if the provided declaration \a VD should be captured by
8494 /// \param Level Relative level of nested OpenMP construct for that the check
8496 bool IsOpenMPCapturedByRef(ValueDecl *D, unsigned Level);
8498 /// \brief Check if the specified variable is used in one of the private
8499 /// clauses (private, firstprivate, lastprivate, reduction etc.) in OpenMP
8501 VarDecl *IsOpenMPCapturedDecl(ValueDecl *D);
8502 ExprResult getOpenMPCapturedExpr(VarDecl *Capture, ExprValueKind VK,
8503 ExprObjectKind OK, SourceLocation Loc);
8505 /// \brief Check if the specified variable is used in 'private' clause.
8506 /// \param Level Relative level of nested OpenMP construct for that the check
8508 bool isOpenMPPrivateDecl(ValueDecl *D, unsigned Level);
8510 /// \brief Check if the specified variable is captured by 'target' directive.
8511 /// \param Level Relative level of nested OpenMP construct for that the check
8513 bool isOpenMPTargetCapturedDecl(ValueDecl *D, unsigned Level);
8515 ExprResult PerformOpenMPImplicitIntegerConversion(SourceLocation OpLoc,
8517 /// \brief Called on start of new data sharing attribute block.
8518 void StartOpenMPDSABlock(OpenMPDirectiveKind K,
8519 const DeclarationNameInfo &DirName, Scope *CurScope,
8520 SourceLocation Loc);
8521 /// \brief Start analysis of clauses.
8522 void StartOpenMPClause(OpenMPClauseKind K);
8523 /// \brief End analysis of clauses.
8524 void EndOpenMPClause();
8525 /// \brief Called on end of data sharing attribute block.
8526 void EndOpenMPDSABlock(Stmt *CurDirective);
8528 /// \brief Check if the current region is an OpenMP loop region and if it is,
8529 /// mark loop control variable, used in \p Init for loop initialization, as
8530 /// private by default.
8531 /// \param Init First part of the for loop.
8532 void ActOnOpenMPLoopInitialization(SourceLocation ForLoc, Stmt *Init);
8534 // OpenMP directives and clauses.
8535 /// \brief Called on correct id-expression from the '#pragma omp
8537 ExprResult ActOnOpenMPIdExpression(Scope *CurScope,
8538 CXXScopeSpec &ScopeSpec,
8539 const DeclarationNameInfo &Id);
8540 /// \brief Called on well-formed '#pragma omp threadprivate'.
8541 DeclGroupPtrTy ActOnOpenMPThreadprivateDirective(
8543 ArrayRef<Expr *> VarList);
8544 /// \brief Builds a new OpenMPThreadPrivateDecl and checks its correctness.
8545 OMPThreadPrivateDecl *CheckOMPThreadPrivateDecl(
8547 ArrayRef<Expr *> VarList);
8548 /// \brief Check if the specified type is allowed to be used in 'omp declare
8549 /// reduction' construct.
8550 QualType ActOnOpenMPDeclareReductionType(SourceLocation TyLoc,
8551 TypeResult ParsedType);
8552 /// \brief Called on start of '#pragma omp declare reduction'.
8553 DeclGroupPtrTy ActOnOpenMPDeclareReductionDirectiveStart(
8554 Scope *S, DeclContext *DC, DeclarationName Name,
8555 ArrayRef<std::pair<QualType, SourceLocation>> ReductionTypes,
8556 AccessSpecifier AS, Decl *PrevDeclInScope = nullptr);
8557 /// \brief Initialize declare reduction construct initializer.
8558 void ActOnOpenMPDeclareReductionCombinerStart(Scope *S, Decl *D);
8559 /// \brief Finish current declare reduction construct initializer.
8560 void ActOnOpenMPDeclareReductionCombinerEnd(Decl *D, Expr *Combiner);
8561 /// \brief Initialize declare reduction construct initializer.
8562 void ActOnOpenMPDeclareReductionInitializerStart(Scope *S, Decl *D);
8563 /// \brief Finish current declare reduction construct initializer.
8564 void ActOnOpenMPDeclareReductionInitializerEnd(Decl *D, Expr *Initializer);
8565 /// \brief Called at the end of '#pragma omp declare reduction'.
8566 DeclGroupPtrTy ActOnOpenMPDeclareReductionDirectiveEnd(
8567 Scope *S, DeclGroupPtrTy DeclReductions, bool IsValid);
8569 /// Called on the start of target region i.e. '#pragma omp declare target'.
8570 bool ActOnStartOpenMPDeclareTargetDirective(SourceLocation Loc);
8571 /// Called at the end of target region i.e. '#pragme omp end declare target'.
8572 void ActOnFinishOpenMPDeclareTargetDirective();
8573 /// Called on correct id-expression from the '#pragma omp declare target'.
8574 void ActOnOpenMPDeclareTargetName(Scope *CurScope, CXXScopeSpec &ScopeSpec,
8575 const DeclarationNameInfo &Id,
8576 OMPDeclareTargetDeclAttr::MapTypeTy MT,
8577 NamedDeclSetType &SameDirectiveDecls);
8578 /// Check declaration inside target region.
8579 void checkDeclIsAllowedInOpenMPTarget(Expr *E, Decl *D);
8580 /// Return true inside OpenMP target region.
8581 bool isInOpenMPDeclareTargetContext() const {
8582 return IsInOpenMPDeclareTargetContext;
8585 /// Return the number of captured regions created for an OpenMP directive.
8586 static int getOpenMPCaptureLevels(OpenMPDirectiveKind Kind);
8588 /// \brief Initialization of captured region for OpenMP region.
8589 void ActOnOpenMPRegionStart(OpenMPDirectiveKind DKind, Scope *CurScope);
8590 /// \brief End of OpenMP region.
8592 /// \param S Statement associated with the current OpenMP region.
8593 /// \param Clauses List of clauses for the current OpenMP region.
8595 /// \returns Statement for finished OpenMP region.
8596 StmtResult ActOnOpenMPRegionEnd(StmtResult S, ArrayRef<OMPClause *> Clauses);
8597 StmtResult ActOnOpenMPExecutableDirective(
8598 OpenMPDirectiveKind Kind, const DeclarationNameInfo &DirName,
8599 OpenMPDirectiveKind CancelRegion, ArrayRef<OMPClause *> Clauses,
8600 Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc);
8601 /// \brief Called on well-formed '\#pragma omp parallel' after parsing
8602 /// of the associated statement.
8603 StmtResult ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses,
8605 SourceLocation StartLoc,
8606 SourceLocation EndLoc);
8607 /// \brief Called on well-formed '\#pragma omp simd' after parsing
8608 /// of the associated statement.
8609 StmtResult ActOnOpenMPSimdDirective(
8610 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8611 SourceLocation EndLoc,
8612 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8613 /// \brief Called on well-formed '\#pragma omp for' after parsing
8614 /// of the associated statement.
8615 StmtResult ActOnOpenMPForDirective(
8616 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8617 SourceLocation EndLoc,
8618 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8619 /// \brief Called on well-formed '\#pragma omp for simd' after parsing
8620 /// of the associated statement.
8621 StmtResult ActOnOpenMPForSimdDirective(
8622 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8623 SourceLocation EndLoc,
8624 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8625 /// \brief Called on well-formed '\#pragma omp sections' after parsing
8626 /// of the associated statement.
8627 StmtResult ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses,
8628 Stmt *AStmt, SourceLocation StartLoc,
8629 SourceLocation EndLoc);
8630 /// \brief Called on well-formed '\#pragma omp section' after parsing of the
8631 /// associated statement.
8632 StmtResult ActOnOpenMPSectionDirective(Stmt *AStmt, SourceLocation StartLoc,
8633 SourceLocation EndLoc);
8634 /// \brief Called on well-formed '\#pragma omp single' after parsing of the
8635 /// associated statement.
8636 StmtResult ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses,
8637 Stmt *AStmt, SourceLocation StartLoc,
8638 SourceLocation EndLoc);
8639 /// \brief Called on well-formed '\#pragma omp master' after parsing of the
8640 /// associated statement.
8641 StmtResult ActOnOpenMPMasterDirective(Stmt *AStmt, SourceLocation StartLoc,
8642 SourceLocation EndLoc);
8643 /// \brief Called on well-formed '\#pragma omp critical' after parsing of the
8644 /// associated statement.
8645 StmtResult ActOnOpenMPCriticalDirective(const DeclarationNameInfo &DirName,
8646 ArrayRef<OMPClause *> Clauses,
8647 Stmt *AStmt, SourceLocation StartLoc,
8648 SourceLocation EndLoc);
8649 /// \brief Called on well-formed '\#pragma omp parallel for' after parsing
8650 /// of the associated statement.
8651 StmtResult ActOnOpenMPParallelForDirective(
8652 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8653 SourceLocation EndLoc,
8654 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8655 /// \brief Called on well-formed '\#pragma omp parallel for simd' after
8656 /// parsing of the associated statement.
8657 StmtResult ActOnOpenMPParallelForSimdDirective(
8658 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8659 SourceLocation EndLoc,
8660 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8661 /// \brief Called on well-formed '\#pragma omp parallel sections' after
8662 /// parsing of the associated statement.
8663 StmtResult ActOnOpenMPParallelSectionsDirective(ArrayRef<OMPClause *> Clauses,
8665 SourceLocation StartLoc,
8666 SourceLocation EndLoc);
8667 /// \brief Called on well-formed '\#pragma omp task' after parsing of the
8668 /// associated statement.
8669 StmtResult ActOnOpenMPTaskDirective(ArrayRef<OMPClause *> Clauses,
8670 Stmt *AStmt, SourceLocation StartLoc,
8671 SourceLocation EndLoc);
8672 /// \brief Called on well-formed '\#pragma omp taskyield'.
8673 StmtResult ActOnOpenMPTaskyieldDirective(SourceLocation StartLoc,
8674 SourceLocation EndLoc);
8675 /// \brief Called on well-formed '\#pragma omp barrier'.
8676 StmtResult ActOnOpenMPBarrierDirective(SourceLocation StartLoc,
8677 SourceLocation EndLoc);
8678 /// \brief Called on well-formed '\#pragma omp taskwait'.
8679 StmtResult ActOnOpenMPTaskwaitDirective(SourceLocation StartLoc,
8680 SourceLocation EndLoc);
8681 /// \brief Called on well-formed '\#pragma omp taskgroup'.
8682 StmtResult ActOnOpenMPTaskgroupDirective(ArrayRef<OMPClause *> Clauses,
8683 Stmt *AStmt, SourceLocation StartLoc,
8684 SourceLocation EndLoc);
8685 /// \brief Called on well-formed '\#pragma omp flush'.
8686 StmtResult ActOnOpenMPFlushDirective(ArrayRef<OMPClause *> Clauses,
8687 SourceLocation StartLoc,
8688 SourceLocation EndLoc);
8689 /// \brief Called on well-formed '\#pragma omp ordered' after parsing of the
8690 /// associated statement.
8691 StmtResult ActOnOpenMPOrderedDirective(ArrayRef<OMPClause *> Clauses,
8692 Stmt *AStmt, SourceLocation StartLoc,
8693 SourceLocation EndLoc);
8694 /// \brief Called on well-formed '\#pragma omp atomic' after parsing of the
8695 /// associated statement.
8696 StmtResult ActOnOpenMPAtomicDirective(ArrayRef<OMPClause *> Clauses,
8697 Stmt *AStmt, SourceLocation StartLoc,
8698 SourceLocation EndLoc);
8699 /// \brief Called on well-formed '\#pragma omp target' after parsing of the
8700 /// associated statement.
8701 StmtResult ActOnOpenMPTargetDirective(ArrayRef<OMPClause *> Clauses,
8702 Stmt *AStmt, SourceLocation StartLoc,
8703 SourceLocation EndLoc);
8704 /// \brief Called on well-formed '\#pragma omp target data' after parsing of
8705 /// the associated statement.
8706 StmtResult ActOnOpenMPTargetDataDirective(ArrayRef<OMPClause *> Clauses,
8707 Stmt *AStmt, SourceLocation StartLoc,
8708 SourceLocation EndLoc);
8709 /// \brief Called on well-formed '\#pragma omp target enter data' after
8710 /// parsing of the associated statement.
8711 StmtResult ActOnOpenMPTargetEnterDataDirective(ArrayRef<OMPClause *> Clauses,
8712 SourceLocation StartLoc,
8713 SourceLocation EndLoc);
8714 /// \brief Called on well-formed '\#pragma omp target exit data' after
8715 /// parsing of the associated statement.
8716 StmtResult ActOnOpenMPTargetExitDataDirective(ArrayRef<OMPClause *> Clauses,
8717 SourceLocation StartLoc,
8718 SourceLocation EndLoc);
8719 /// \brief Called on well-formed '\#pragma omp target parallel' after
8720 /// parsing of the associated statement.
8721 StmtResult ActOnOpenMPTargetParallelDirective(ArrayRef<OMPClause *> Clauses,
8723 SourceLocation StartLoc,
8724 SourceLocation EndLoc);
8725 /// \brief Called on well-formed '\#pragma omp target parallel for' after
8726 /// parsing of the associated statement.
8727 StmtResult ActOnOpenMPTargetParallelForDirective(
8728 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8729 SourceLocation EndLoc,
8730 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8731 /// \brief Called on well-formed '\#pragma omp teams' after parsing of the
8732 /// associated statement.
8733 StmtResult ActOnOpenMPTeamsDirective(ArrayRef<OMPClause *> Clauses,
8734 Stmt *AStmt, SourceLocation StartLoc,
8735 SourceLocation EndLoc);
8736 /// \brief Called on well-formed '\#pragma omp cancellation point'.
8738 ActOnOpenMPCancellationPointDirective(SourceLocation StartLoc,
8739 SourceLocation EndLoc,
8740 OpenMPDirectiveKind CancelRegion);
8741 /// \brief Called on well-formed '\#pragma omp cancel'.
8742 StmtResult ActOnOpenMPCancelDirective(ArrayRef<OMPClause *> Clauses,
8743 SourceLocation StartLoc,
8744 SourceLocation EndLoc,
8745 OpenMPDirectiveKind CancelRegion);
8746 /// \brief Called on well-formed '\#pragma omp taskloop' after parsing of the
8747 /// associated statement.
8748 StmtResult ActOnOpenMPTaskLoopDirective(
8749 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8750 SourceLocation EndLoc,
8751 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8752 /// \brief Called on well-formed '\#pragma omp taskloop simd' after parsing of
8753 /// the associated statement.
8754 StmtResult ActOnOpenMPTaskLoopSimdDirective(
8755 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8756 SourceLocation EndLoc,
8757 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8758 /// \brief Called on well-formed '\#pragma omp distribute' after parsing
8759 /// of the associated statement.
8760 StmtResult ActOnOpenMPDistributeDirective(
8761 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8762 SourceLocation EndLoc,
8763 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8764 /// \brief Called on well-formed '\#pragma omp target update'.
8765 StmtResult ActOnOpenMPTargetUpdateDirective(ArrayRef<OMPClause *> Clauses,
8766 SourceLocation StartLoc,
8767 SourceLocation EndLoc);
8768 /// \brief Called on well-formed '\#pragma omp distribute parallel for' after
8769 /// parsing of the associated statement.
8770 StmtResult ActOnOpenMPDistributeParallelForDirective(
8771 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8772 SourceLocation EndLoc,
8773 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8774 /// \brief Called on well-formed '\#pragma omp distribute parallel for simd'
8775 /// after parsing of the associated statement.
8776 StmtResult ActOnOpenMPDistributeParallelForSimdDirective(
8777 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8778 SourceLocation EndLoc,
8779 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8780 /// \brief Called on well-formed '\#pragma omp distribute simd' after
8781 /// parsing of the associated statement.
8782 StmtResult ActOnOpenMPDistributeSimdDirective(
8783 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8784 SourceLocation EndLoc,
8785 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8786 /// \brief Called on well-formed '\#pragma omp target parallel for simd' after
8787 /// parsing of the associated statement.
8788 StmtResult ActOnOpenMPTargetParallelForSimdDirective(
8789 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8790 SourceLocation EndLoc,
8791 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8792 /// \brief Called on well-formed '\#pragma omp target simd' after parsing of
8793 /// the associated statement.
8794 StmtResult ActOnOpenMPTargetSimdDirective(
8795 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8796 SourceLocation EndLoc,
8797 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8798 /// Called on well-formed '\#pragma omp teams distribute' after parsing of
8799 /// the associated statement.
8800 StmtResult ActOnOpenMPTeamsDistributeDirective(
8801 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8802 SourceLocation EndLoc,
8803 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8804 /// Called on well-formed '\#pragma omp teams distribute simd' after parsing
8805 /// of the associated statement.
8806 StmtResult ActOnOpenMPTeamsDistributeSimdDirective(
8807 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8808 SourceLocation EndLoc,
8809 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8810 /// Called on well-formed '\#pragma omp teams distribute parallel for simd'
8811 /// after parsing of the associated statement.
8812 StmtResult ActOnOpenMPTeamsDistributeParallelForSimdDirective(
8813 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8814 SourceLocation EndLoc,
8815 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8816 /// Called on well-formed '\#pragma omp teams distribute parallel for'
8817 /// after parsing of the associated statement.
8818 StmtResult ActOnOpenMPTeamsDistributeParallelForDirective(
8819 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8820 SourceLocation EndLoc,
8821 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8822 /// Called on well-formed '\#pragma omp target teams' after parsing of the
8823 /// associated statement.
8824 StmtResult ActOnOpenMPTargetTeamsDirective(ArrayRef<OMPClause *> Clauses,
8826 SourceLocation StartLoc,
8827 SourceLocation EndLoc);
8828 /// Called on well-formed '\#pragma omp target teams distribute' after parsing
8829 /// of the associated statement.
8830 StmtResult ActOnOpenMPTargetTeamsDistributeDirective(
8831 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8832 SourceLocation EndLoc,
8833 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8834 /// Called on well-formed '\#pragma omp target teams distribute parallel for'
8835 /// after parsing of the associated statement.
8836 StmtResult ActOnOpenMPTargetTeamsDistributeParallelForDirective(
8837 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8838 SourceLocation EndLoc,
8839 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8840 /// Called on well-formed '\#pragma omp target teams distribute parallel for
8841 /// simd' after parsing of the associated statement.
8842 StmtResult ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective(
8843 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8844 SourceLocation EndLoc,
8845 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8846 /// Called on well-formed '\#pragma omp target teams distribute simd' after
8847 /// parsing of the associated statement.
8848 StmtResult ActOnOpenMPTargetTeamsDistributeSimdDirective(
8849 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8850 SourceLocation EndLoc,
8851 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8853 /// Checks correctness of linear modifiers.
8854 bool CheckOpenMPLinearModifier(OpenMPLinearClauseKind LinKind,
8855 SourceLocation LinLoc);
8856 /// Checks that the specified declaration matches requirements for the linear
8858 bool CheckOpenMPLinearDecl(ValueDecl *D, SourceLocation ELoc,
8859 OpenMPLinearClauseKind LinKind, QualType Type);
8861 /// \brief Called on well-formed '\#pragma omp declare simd' after parsing of
8862 /// the associated method/function.
8863 DeclGroupPtrTy ActOnOpenMPDeclareSimdDirective(
8864 DeclGroupPtrTy DG, OMPDeclareSimdDeclAttr::BranchStateTy BS,
8865 Expr *Simdlen, ArrayRef<Expr *> Uniforms, ArrayRef<Expr *> Aligneds,
8866 ArrayRef<Expr *> Alignments, ArrayRef<Expr *> Linears,
8867 ArrayRef<unsigned> LinModifiers, ArrayRef<Expr *> Steps, SourceRange SR);
8869 OMPClause *ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind,
8871 SourceLocation StartLoc,
8872 SourceLocation LParenLoc,
8873 SourceLocation EndLoc);
8874 /// \brief Called on well-formed 'if' clause.
8875 OMPClause *ActOnOpenMPIfClause(OpenMPDirectiveKind NameModifier,
8876 Expr *Condition, SourceLocation StartLoc,
8877 SourceLocation LParenLoc,
8878 SourceLocation NameModifierLoc,
8879 SourceLocation ColonLoc,
8880 SourceLocation EndLoc);
8881 /// \brief Called on well-formed 'final' clause.
8882 OMPClause *ActOnOpenMPFinalClause(Expr *Condition, SourceLocation StartLoc,
8883 SourceLocation LParenLoc,
8884 SourceLocation EndLoc);
8885 /// \brief Called on well-formed 'num_threads' clause.
8886 OMPClause *ActOnOpenMPNumThreadsClause(Expr *NumThreads,
8887 SourceLocation StartLoc,
8888 SourceLocation LParenLoc,
8889 SourceLocation EndLoc);
8890 /// \brief Called on well-formed 'safelen' clause.
8891 OMPClause *ActOnOpenMPSafelenClause(Expr *Length,
8892 SourceLocation StartLoc,
8893 SourceLocation LParenLoc,
8894 SourceLocation EndLoc);
8895 /// \brief Called on well-formed 'simdlen' clause.
8896 OMPClause *ActOnOpenMPSimdlenClause(Expr *Length, SourceLocation StartLoc,
8897 SourceLocation LParenLoc,
8898 SourceLocation EndLoc);
8899 /// \brief Called on well-formed 'collapse' clause.
8900 OMPClause *ActOnOpenMPCollapseClause(Expr *NumForLoops,
8901 SourceLocation StartLoc,
8902 SourceLocation LParenLoc,
8903 SourceLocation EndLoc);
8904 /// \brief Called on well-formed 'ordered' clause.
8906 ActOnOpenMPOrderedClause(SourceLocation StartLoc, SourceLocation EndLoc,
8907 SourceLocation LParenLoc = SourceLocation(),
8908 Expr *NumForLoops = nullptr);
8909 /// \brief Called on well-formed 'grainsize' clause.
8910 OMPClause *ActOnOpenMPGrainsizeClause(Expr *Size, SourceLocation StartLoc,
8911 SourceLocation LParenLoc,
8912 SourceLocation EndLoc);
8913 /// \brief Called on well-formed 'num_tasks' clause.
8914 OMPClause *ActOnOpenMPNumTasksClause(Expr *NumTasks, SourceLocation StartLoc,
8915 SourceLocation LParenLoc,
8916 SourceLocation EndLoc);
8917 /// \brief Called on well-formed 'hint' clause.
8918 OMPClause *ActOnOpenMPHintClause(Expr *Hint, SourceLocation StartLoc,
8919 SourceLocation LParenLoc,
8920 SourceLocation EndLoc);
8922 OMPClause *ActOnOpenMPSimpleClause(OpenMPClauseKind Kind,
8924 SourceLocation ArgumentLoc,
8925 SourceLocation StartLoc,
8926 SourceLocation LParenLoc,
8927 SourceLocation EndLoc);
8928 /// \brief Called on well-formed 'default' clause.
8929 OMPClause *ActOnOpenMPDefaultClause(OpenMPDefaultClauseKind Kind,
8930 SourceLocation KindLoc,
8931 SourceLocation StartLoc,
8932 SourceLocation LParenLoc,
8933 SourceLocation EndLoc);
8934 /// \brief Called on well-formed 'proc_bind' clause.
8935 OMPClause *ActOnOpenMPProcBindClause(OpenMPProcBindClauseKind Kind,
8936 SourceLocation KindLoc,
8937 SourceLocation StartLoc,
8938 SourceLocation LParenLoc,
8939 SourceLocation EndLoc);
8941 OMPClause *ActOnOpenMPSingleExprWithArgClause(
8942 OpenMPClauseKind Kind, ArrayRef<unsigned> Arguments, Expr *Expr,
8943 SourceLocation StartLoc, SourceLocation LParenLoc,
8944 ArrayRef<SourceLocation> ArgumentsLoc, SourceLocation DelimLoc,
8945 SourceLocation EndLoc);
8946 /// \brief Called on well-formed 'schedule' clause.
8947 OMPClause *ActOnOpenMPScheduleClause(
8948 OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2,
8949 OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
8950 SourceLocation LParenLoc, SourceLocation M1Loc, SourceLocation M2Loc,
8951 SourceLocation KindLoc, SourceLocation CommaLoc, SourceLocation EndLoc);
8953 OMPClause *ActOnOpenMPClause(OpenMPClauseKind Kind, SourceLocation StartLoc,
8954 SourceLocation EndLoc);
8955 /// \brief Called on well-formed 'nowait' clause.
8956 OMPClause *ActOnOpenMPNowaitClause(SourceLocation StartLoc,
8957 SourceLocation EndLoc);
8958 /// \brief Called on well-formed 'untied' clause.
8959 OMPClause *ActOnOpenMPUntiedClause(SourceLocation StartLoc,
8960 SourceLocation EndLoc);
8961 /// \brief Called on well-formed 'mergeable' clause.
8962 OMPClause *ActOnOpenMPMergeableClause(SourceLocation StartLoc,
8963 SourceLocation EndLoc);
8964 /// \brief Called on well-formed 'read' clause.
8965 OMPClause *ActOnOpenMPReadClause(SourceLocation StartLoc,
8966 SourceLocation EndLoc);
8967 /// \brief Called on well-formed 'write' clause.
8968 OMPClause *ActOnOpenMPWriteClause(SourceLocation StartLoc,
8969 SourceLocation EndLoc);
8970 /// \brief Called on well-formed 'update' clause.
8971 OMPClause *ActOnOpenMPUpdateClause(SourceLocation StartLoc,
8972 SourceLocation EndLoc);
8973 /// \brief Called on well-formed 'capture' clause.
8974 OMPClause *ActOnOpenMPCaptureClause(SourceLocation StartLoc,
8975 SourceLocation EndLoc);
8976 /// \brief Called on well-formed 'seq_cst' clause.
8977 OMPClause *ActOnOpenMPSeqCstClause(SourceLocation StartLoc,
8978 SourceLocation EndLoc);
8979 /// \brief Called on well-formed 'threads' clause.
8980 OMPClause *ActOnOpenMPThreadsClause(SourceLocation StartLoc,
8981 SourceLocation EndLoc);
8982 /// \brief Called on well-formed 'simd' clause.
8983 OMPClause *ActOnOpenMPSIMDClause(SourceLocation StartLoc,
8984 SourceLocation EndLoc);
8985 /// \brief Called on well-formed 'nogroup' clause.
8986 OMPClause *ActOnOpenMPNogroupClause(SourceLocation StartLoc,
8987 SourceLocation EndLoc);
8989 OMPClause *ActOnOpenMPVarListClause(
8990 OpenMPClauseKind Kind, ArrayRef<Expr *> Vars, Expr *TailExpr,
8991 SourceLocation StartLoc, SourceLocation LParenLoc,
8992 SourceLocation ColonLoc, SourceLocation EndLoc,
8993 CXXScopeSpec &ReductionIdScopeSpec,
8994 const DeclarationNameInfo &ReductionId, OpenMPDependClauseKind DepKind,
8995 OpenMPLinearClauseKind LinKind, OpenMPMapClauseKind MapTypeModifier,
8996 OpenMPMapClauseKind MapType, bool IsMapTypeImplicit,
8997 SourceLocation DepLinMapLoc);
8998 /// \brief Called on well-formed 'private' clause.
8999 OMPClause *ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList,
9000 SourceLocation StartLoc,
9001 SourceLocation LParenLoc,
9002 SourceLocation EndLoc);
9003 /// \brief Called on well-formed 'firstprivate' clause.
9004 OMPClause *ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList,
9005 SourceLocation StartLoc,
9006 SourceLocation LParenLoc,
9007 SourceLocation EndLoc);
9008 /// \brief Called on well-formed 'lastprivate' clause.
9009 OMPClause *ActOnOpenMPLastprivateClause(ArrayRef<Expr *> VarList,
9010 SourceLocation StartLoc,
9011 SourceLocation LParenLoc,
9012 SourceLocation EndLoc);
9013 /// \brief Called on well-formed 'shared' clause.
9014 OMPClause *ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList,
9015 SourceLocation StartLoc,
9016 SourceLocation LParenLoc,
9017 SourceLocation EndLoc);
9018 /// \brief Called on well-formed 'reduction' clause.
9019 OMPClause *ActOnOpenMPReductionClause(
9020 ArrayRef<Expr *> VarList, SourceLocation StartLoc,
9021 SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc,
9022 CXXScopeSpec &ReductionIdScopeSpec,
9023 const DeclarationNameInfo &ReductionId,
9024 ArrayRef<Expr *> UnresolvedReductions = llvm::None);
9025 /// Called on well-formed 'task_reduction' clause.
9026 OMPClause *ActOnOpenMPTaskReductionClause(
9027 ArrayRef<Expr *> VarList, SourceLocation StartLoc,
9028 SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc,
9029 CXXScopeSpec &ReductionIdScopeSpec,
9030 const DeclarationNameInfo &ReductionId,
9031 ArrayRef<Expr *> UnresolvedReductions = llvm::None);
9032 /// \brief Called on well-formed 'linear' clause.
9034 ActOnOpenMPLinearClause(ArrayRef<Expr *> VarList, Expr *Step,
9035 SourceLocation StartLoc, SourceLocation LParenLoc,
9036 OpenMPLinearClauseKind LinKind, SourceLocation LinLoc,
9037 SourceLocation ColonLoc, SourceLocation EndLoc);
9038 /// \brief Called on well-formed 'aligned' clause.
9039 OMPClause *ActOnOpenMPAlignedClause(ArrayRef<Expr *> VarList,
9041 SourceLocation StartLoc,
9042 SourceLocation LParenLoc,
9043 SourceLocation ColonLoc,
9044 SourceLocation EndLoc);
9045 /// \brief Called on well-formed 'copyin' clause.
9046 OMPClause *ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList,
9047 SourceLocation StartLoc,
9048 SourceLocation LParenLoc,
9049 SourceLocation EndLoc);
9050 /// \brief Called on well-formed 'copyprivate' clause.
9051 OMPClause *ActOnOpenMPCopyprivateClause(ArrayRef<Expr *> VarList,
9052 SourceLocation StartLoc,
9053 SourceLocation LParenLoc,
9054 SourceLocation EndLoc);
9055 /// \brief Called on well-formed 'flush' pseudo clause.
9056 OMPClause *ActOnOpenMPFlushClause(ArrayRef<Expr *> VarList,
9057 SourceLocation StartLoc,
9058 SourceLocation LParenLoc,
9059 SourceLocation EndLoc);
9060 /// \brief Called on well-formed 'depend' clause.
9062 ActOnOpenMPDependClause(OpenMPDependClauseKind DepKind, SourceLocation DepLoc,
9063 SourceLocation ColonLoc, ArrayRef<Expr *> VarList,
9064 SourceLocation StartLoc, SourceLocation LParenLoc,
9065 SourceLocation EndLoc);
9066 /// \brief Called on well-formed 'device' clause.
9067 OMPClause *ActOnOpenMPDeviceClause(Expr *Device, SourceLocation StartLoc,
9068 SourceLocation LParenLoc,
9069 SourceLocation EndLoc);
9070 /// \brief Called on well-formed 'map' clause.
9072 ActOnOpenMPMapClause(OpenMPMapClauseKind MapTypeModifier,
9073 OpenMPMapClauseKind MapType, bool IsMapTypeImplicit,
9074 SourceLocation MapLoc, SourceLocation ColonLoc,
9075 ArrayRef<Expr *> VarList, SourceLocation StartLoc,
9076 SourceLocation LParenLoc, SourceLocation EndLoc);
9077 /// \brief Called on well-formed 'num_teams' clause.
9078 OMPClause *ActOnOpenMPNumTeamsClause(Expr *NumTeams, SourceLocation StartLoc,
9079 SourceLocation LParenLoc,
9080 SourceLocation EndLoc);
9081 /// \brief Called on well-formed 'thread_limit' clause.
9082 OMPClause *ActOnOpenMPThreadLimitClause(Expr *ThreadLimit,
9083 SourceLocation StartLoc,
9084 SourceLocation LParenLoc,
9085 SourceLocation EndLoc);
9086 /// \brief Called on well-formed 'priority' clause.
9087 OMPClause *ActOnOpenMPPriorityClause(Expr *Priority, SourceLocation StartLoc,
9088 SourceLocation LParenLoc,
9089 SourceLocation EndLoc);
9090 /// \brief Called on well-formed 'dist_schedule' clause.
9091 OMPClause *ActOnOpenMPDistScheduleClause(
9092 OpenMPDistScheduleClauseKind Kind, Expr *ChunkSize,
9093 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation KindLoc,
9094 SourceLocation CommaLoc, SourceLocation EndLoc);
9095 /// \brief Called on well-formed 'defaultmap' clause.
9096 OMPClause *ActOnOpenMPDefaultmapClause(
9097 OpenMPDefaultmapClauseModifier M, OpenMPDefaultmapClauseKind Kind,
9098 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation MLoc,
9099 SourceLocation KindLoc, SourceLocation EndLoc);
9100 /// \brief Called on well-formed 'to' clause.
9101 OMPClause *ActOnOpenMPToClause(ArrayRef<Expr *> VarList,
9102 SourceLocation StartLoc,
9103 SourceLocation LParenLoc,
9104 SourceLocation EndLoc);
9105 /// \brief Called on well-formed 'from' clause.
9106 OMPClause *ActOnOpenMPFromClause(ArrayRef<Expr *> VarList,
9107 SourceLocation StartLoc,
9108 SourceLocation LParenLoc,
9109 SourceLocation EndLoc);
9110 /// Called on well-formed 'use_device_ptr' clause.
9111 OMPClause *ActOnOpenMPUseDevicePtrClause(ArrayRef<Expr *> VarList,
9112 SourceLocation StartLoc,
9113 SourceLocation LParenLoc,
9114 SourceLocation EndLoc);
9115 /// Called on well-formed 'is_device_ptr' clause.
9116 OMPClause *ActOnOpenMPIsDevicePtrClause(ArrayRef<Expr *> VarList,
9117 SourceLocation StartLoc,
9118 SourceLocation LParenLoc,
9119 SourceLocation EndLoc);
9121 /// \brief The kind of conversion being performed.
9122 enum CheckedConversionKind {
9123 /// \brief An implicit conversion.
9124 CCK_ImplicitConversion,
9125 /// \brief A C-style cast.
9127 /// \brief A functional-style cast.
9129 /// \brief A cast other than a C-style cast.
9133 /// ImpCastExprToType - If Expr is not of type 'Type', insert an implicit
9134 /// cast. If there is already an implicit cast, merge into the existing one.
9135 /// If isLvalue, the result of the cast is an lvalue.
9136 ExprResult ImpCastExprToType(Expr *E, QualType Type, CastKind CK,
9137 ExprValueKind VK = VK_RValue,
9138 const CXXCastPath *BasePath = nullptr,
9139 CheckedConversionKind CCK
9140 = CCK_ImplicitConversion);
9142 /// ScalarTypeToBooleanCastKind - Returns the cast kind corresponding
9143 /// to the conversion from scalar type ScalarTy to the Boolean type.
9144 static CastKind ScalarTypeToBooleanCastKind(QualType ScalarTy);
9146 /// IgnoredValueConversions - Given that an expression's result is
9147 /// syntactically ignored, perform any conversions that are
9149 ExprResult IgnoredValueConversions(Expr *E);
9151 // UsualUnaryConversions - promotes integers (C99 6.3.1.1p2) and converts
9152 // functions and arrays to their respective pointers (C99 6.3.2.1).
9153 ExprResult UsualUnaryConversions(Expr *E);
9155 /// CallExprUnaryConversions - a special case of an unary conversion
9156 /// performed on a function designator of a call expression.
9157 ExprResult CallExprUnaryConversions(Expr *E);
9159 // DefaultFunctionArrayConversion - converts functions and arrays
9160 // to their respective pointers (C99 6.3.2.1).
9161 ExprResult DefaultFunctionArrayConversion(Expr *E, bool Diagnose = true);
9163 // DefaultFunctionArrayLvalueConversion - converts functions and
9164 // arrays to their respective pointers and performs the
9165 // lvalue-to-rvalue conversion.
9166 ExprResult DefaultFunctionArrayLvalueConversion(Expr *E,
9167 bool Diagnose = true);
9169 // DefaultLvalueConversion - performs lvalue-to-rvalue conversion on
9170 // the operand. This is DefaultFunctionArrayLvalueConversion,
9171 // except that it assumes the operand isn't of function or array
9173 ExprResult DefaultLvalueConversion(Expr *E);
9175 // DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
9176 // do not have a prototype. Integer promotions are performed on each
9177 // argument, and arguments that have type float are promoted to double.
9178 ExprResult DefaultArgumentPromotion(Expr *E);
9180 /// If \p E is a prvalue denoting an unmaterialized temporary, materialize
9181 /// it as an xvalue. In C++98, the result will still be a prvalue, because
9182 /// we don't have xvalues there.
9183 ExprResult TemporaryMaterializationConversion(Expr *E);
9185 // Used for emitting the right warning by DefaultVariadicArgumentPromotion
9186 enum VariadicCallType {
9190 VariadicConstructor,
9191 VariadicDoesNotApply
9194 VariadicCallType getVariadicCallType(FunctionDecl *FDecl,
9195 const FunctionProtoType *Proto,
9198 // Used for determining in which context a type is allowed to be passed to a
9208 // Determines which VarArgKind fits an expression.
9209 VarArgKind isValidVarArgType(const QualType &Ty);
9211 /// Check to see if the given expression is a valid argument to a variadic
9212 /// function, issuing a diagnostic if not.
9213 void checkVariadicArgument(const Expr *E, VariadicCallType CT);
9215 /// Check to see if a given expression could have '.c_str()' called on it.
9216 bool hasCStrMethod(const Expr *E);
9218 /// GatherArgumentsForCall - Collector argument expressions for various
9219 /// form of call prototypes.
9220 bool GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl,
9221 const FunctionProtoType *Proto,
9222 unsigned FirstParam, ArrayRef<Expr *> Args,
9223 SmallVectorImpl<Expr *> &AllArgs,
9224 VariadicCallType CallType = VariadicDoesNotApply,
9225 bool AllowExplicit = false,
9226 bool IsListInitialization = false);
9228 // DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
9229 // will create a runtime trap if the resulting type is not a POD type.
9230 ExprResult DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
9231 FunctionDecl *FDecl);
9233 // UsualArithmeticConversions - performs the UsualUnaryConversions on it's
9234 // operands and then handles various conversions that are common to binary
9235 // operators (C99 6.3.1.8). If both operands aren't arithmetic, this
9236 // routine returns the first non-arithmetic type found. The client is
9237 // responsible for emitting appropriate error diagnostics.
9238 QualType UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
9239 bool IsCompAssign = false);
9241 /// AssignConvertType - All of the 'assignment' semantic checks return this
9242 /// enum to indicate whether the assignment was allowed. These checks are
9243 /// done for simple assignments, as well as initialization, return from
9244 /// function, argument passing, etc. The query is phrased in terms of a
9245 /// source and destination type.
9246 enum AssignConvertType {
9247 /// Compatible - the types are compatible according to the standard.
9250 /// PointerToInt - The assignment converts a pointer to an int, which we
9251 /// accept as an extension.
9254 /// IntToPointer - The assignment converts an int to a pointer, which we
9255 /// accept as an extension.
9258 /// FunctionVoidPointer - The assignment is between a function pointer and
9259 /// void*, which the standard doesn't allow, but we accept as an extension.
9260 FunctionVoidPointer,
9262 /// IncompatiblePointer - The assignment is between two pointers types that
9263 /// are not compatible, but we accept them as an extension.
9264 IncompatiblePointer,
9266 /// IncompatiblePointerSign - The assignment is between two pointers types
9267 /// which point to integers which have a different sign, but are otherwise
9268 /// identical. This is a subset of the above, but broken out because it's by
9269 /// far the most common case of incompatible pointers.
9270 IncompatiblePointerSign,
9272 /// CompatiblePointerDiscardsQualifiers - The assignment discards
9273 /// c/v/r qualifiers, which we accept as an extension.
9274 CompatiblePointerDiscardsQualifiers,
9276 /// IncompatiblePointerDiscardsQualifiers - The assignment
9277 /// discards qualifiers that we don't permit to be discarded,
9278 /// like address spaces.
9279 IncompatiblePointerDiscardsQualifiers,
9281 /// IncompatibleNestedPointerQualifiers - The assignment is between two
9282 /// nested pointer types, and the qualifiers other than the first two
9283 /// levels differ e.g. char ** -> const char **, but we accept them as an
9285 IncompatibleNestedPointerQualifiers,
9287 /// IncompatibleVectors - The assignment is between two vector types that
9288 /// have the same size, which we accept as an extension.
9289 IncompatibleVectors,
9291 /// IntToBlockPointer - The assignment converts an int to a block
9292 /// pointer. We disallow this.
9295 /// IncompatibleBlockPointer - The assignment is between two block
9296 /// pointers types that are not compatible.
9297 IncompatibleBlockPointer,
9299 /// IncompatibleObjCQualifiedId - The assignment is between a qualified
9300 /// id type and something else (that is incompatible with it). For example,
9301 /// "id <XXX>" = "Foo *", where "Foo *" doesn't implement the XXX protocol.
9302 IncompatibleObjCQualifiedId,
9304 /// IncompatibleObjCWeakRef - Assigning a weak-unavailable object to an
9305 /// object with __weak qualifier.
9306 IncompatibleObjCWeakRef,
9308 /// Incompatible - We reject this conversion outright, it is invalid to
9309 /// represent it in the AST.
9313 /// DiagnoseAssignmentResult - Emit a diagnostic, if required, for the
9314 /// assignment conversion type specified by ConvTy. This returns true if the
9315 /// conversion was invalid or false if the conversion was accepted.
9316 bool DiagnoseAssignmentResult(AssignConvertType ConvTy,
9318 QualType DstType, QualType SrcType,
9319 Expr *SrcExpr, AssignmentAction Action,
9320 bool *Complained = nullptr);
9322 /// IsValueInFlagEnum - Determine if a value is allowed as part of a flag
9323 /// enum. If AllowMask is true, then we also allow the complement of a valid
9324 /// value, to be used as a mask.
9325 bool IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
9326 bool AllowMask) const;
9328 /// DiagnoseAssignmentEnum - Warn if assignment to enum is a constant
9329 /// integer not in the range of enum values.
9330 void DiagnoseAssignmentEnum(QualType DstType, QualType SrcType,
9333 /// CheckAssignmentConstraints - Perform type checking for assignment,
9334 /// argument passing, variable initialization, and function return values.
9336 AssignConvertType CheckAssignmentConstraints(SourceLocation Loc,
9340 /// Check assignment constraints and optionally prepare for a conversion of
9341 /// the RHS to the LHS type. The conversion is prepared for if ConvertRHS
9343 AssignConvertType CheckAssignmentConstraints(QualType LHSType,
9346 bool ConvertRHS = true);
9348 /// Check assignment constraints for an assignment of RHS to LHSType.
9350 /// \param LHSType The destination type for the assignment.
9351 /// \param RHS The source expression for the assignment.
9352 /// \param Diagnose If \c true, diagnostics may be produced when checking
9353 /// for assignability. If a diagnostic is produced, \p RHS will be
9354 /// set to ExprError(). Note that this function may still return
9355 /// without producing a diagnostic, even for an invalid assignment.
9356 /// \param DiagnoseCFAudited If \c true, the target is a function parameter
9357 /// in an audited Core Foundation API and does not need to be checked
9358 /// for ARC retain issues.
9359 /// \param ConvertRHS If \c true, \p RHS will be updated to model the
9360 /// conversions necessary to perform the assignment. If \c false,
9361 /// \p Diagnose must also be \c false.
9362 AssignConvertType CheckSingleAssignmentConstraints(
9363 QualType LHSType, ExprResult &RHS, bool Diagnose = true,
9364 bool DiagnoseCFAudited = false, bool ConvertRHS = true);
9366 // \brief If the lhs type is a transparent union, check whether we
9367 // can initialize the transparent union with the given expression.
9368 AssignConvertType CheckTransparentUnionArgumentConstraints(QualType ArgType,
9371 bool IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType);
9373 bool CheckExceptionSpecCompatibility(Expr *From, QualType ToType);
9375 ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
9376 AssignmentAction Action,
9377 bool AllowExplicit = false);
9378 ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
9379 AssignmentAction Action,
9381 ImplicitConversionSequence& ICS);
9382 ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
9383 const ImplicitConversionSequence& ICS,
9384 AssignmentAction Action,
9385 CheckedConversionKind CCK
9386 = CCK_ImplicitConversion);
9387 ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
9388 const StandardConversionSequence& SCS,
9389 AssignmentAction Action,
9390 CheckedConversionKind CCK);
9392 /// the following "Check" methods will return a valid/converted QualType
9393 /// or a null QualType (indicating an error diagnostic was issued).
9395 /// type checking binary operators (subroutines of CreateBuiltinBinOp).
9396 QualType InvalidOperands(SourceLocation Loc, ExprResult &LHS,
9398 QualType InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS,
9400 QualType CheckPointerToMemberOperands( // C++ 5.5
9401 ExprResult &LHS, ExprResult &RHS, ExprValueKind &VK,
9402 SourceLocation OpLoc, bool isIndirect);
9403 QualType CheckMultiplyDivideOperands( // C99 6.5.5
9404 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign,
9406 QualType CheckRemainderOperands( // C99 6.5.5
9407 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
9408 bool IsCompAssign = false);
9409 QualType CheckAdditionOperands( // C99 6.5.6
9410 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
9411 BinaryOperatorKind Opc, QualType* CompLHSTy = nullptr);
9412 QualType CheckSubtractionOperands( // C99 6.5.6
9413 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
9414 QualType* CompLHSTy = nullptr);
9415 QualType CheckShiftOperands( // C99 6.5.7
9416 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
9417 BinaryOperatorKind Opc, bool IsCompAssign = false);
9418 QualType CheckCompareOperands( // C99 6.5.8/9
9419 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
9420 BinaryOperatorKind Opc, bool isRelational);
9421 QualType CheckBitwiseOperands( // C99 6.5.[10...12]
9422 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
9423 BinaryOperatorKind Opc);
9424 QualType CheckLogicalOperands( // C99 6.5.[13,14]
9425 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
9426 BinaryOperatorKind Opc);
9427 // CheckAssignmentOperands is used for both simple and compound assignment.
9428 // For simple assignment, pass both expressions and a null converted type.
9429 // For compound assignment, pass both expressions and the converted type.
9430 QualType CheckAssignmentOperands( // C99 6.5.16.[1,2]
9431 Expr *LHSExpr, ExprResult &RHS, SourceLocation Loc, QualType CompoundType);
9433 ExprResult checkPseudoObjectIncDec(Scope *S, SourceLocation OpLoc,
9434 UnaryOperatorKind Opcode, Expr *Op);
9435 ExprResult checkPseudoObjectAssignment(Scope *S, SourceLocation OpLoc,
9436 BinaryOperatorKind Opcode,
9437 Expr *LHS, Expr *RHS);
9438 ExprResult checkPseudoObjectRValue(Expr *E);
9439 Expr *recreateSyntacticForm(PseudoObjectExpr *E);
9441 QualType CheckConditionalOperands( // C99 6.5.15
9442 ExprResult &Cond, ExprResult &LHS, ExprResult &RHS,
9443 ExprValueKind &VK, ExprObjectKind &OK, SourceLocation QuestionLoc);
9444 QualType CXXCheckConditionalOperands( // C++ 5.16
9445 ExprResult &cond, ExprResult &lhs, ExprResult &rhs,
9446 ExprValueKind &VK, ExprObjectKind &OK, SourceLocation questionLoc);
9447 QualType FindCompositePointerType(SourceLocation Loc, Expr *&E1, Expr *&E2,
9448 bool ConvertArgs = true);
9449 QualType FindCompositePointerType(SourceLocation Loc,
9450 ExprResult &E1, ExprResult &E2,
9451 bool ConvertArgs = true) {
9452 Expr *E1Tmp = E1.get(), *E2Tmp = E2.get();
9453 QualType Composite =
9454 FindCompositePointerType(Loc, E1Tmp, E2Tmp, ConvertArgs);
9460 QualType FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
9461 SourceLocation QuestionLoc);
9463 bool DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
9464 SourceLocation QuestionLoc);
9466 void DiagnoseAlwaysNonNullPointer(Expr *E,
9467 Expr::NullPointerConstantKind NullType,
9468 bool IsEqual, SourceRange Range);
9470 /// type checking for vector binary operators.
9471 QualType CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
9472 SourceLocation Loc, bool IsCompAssign,
9473 bool AllowBothBool, bool AllowBoolConversion);
9474 QualType GetSignedVectorType(QualType V);
9475 QualType CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
9476 SourceLocation Loc, bool isRelational);
9477 QualType CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
9478 SourceLocation Loc);
9480 bool areLaxCompatibleVectorTypes(QualType srcType, QualType destType);
9481 bool isLaxVectorConversion(QualType srcType, QualType destType);
9483 /// type checking declaration initializers (C99 6.7.8)
9484 bool CheckForConstantInitializer(Expr *e, QualType t);
9486 // type checking C++ declaration initializers (C++ [dcl.init]).
9488 /// ReferenceCompareResult - Expresses the result of comparing two
9489 /// types (cv1 T1 and cv2 T2) to determine their compatibility for the
9490 /// purposes of initialization by reference (C++ [dcl.init.ref]p4).
9491 enum ReferenceCompareResult {
9492 /// Ref_Incompatible - The two types are incompatible, so direct
9493 /// reference binding is not possible.
9494 Ref_Incompatible = 0,
9495 /// Ref_Related - The two types are reference-related, which means
9496 /// that their unqualified forms (T1 and T2) are either the same
9497 /// or T1 is a base class of T2.
9499 /// Ref_Compatible - The two types are reference-compatible.
9503 ReferenceCompareResult CompareReferenceRelationship(SourceLocation Loc,
9504 QualType T1, QualType T2,
9505 bool &DerivedToBase,
9506 bool &ObjCConversion,
9507 bool &ObjCLifetimeConversion);
9509 ExprResult checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
9510 Expr *CastExpr, CastKind &CastKind,
9511 ExprValueKind &VK, CXXCastPath &Path);
9513 /// \brief Force an expression with unknown-type to an expression of the
9515 ExprResult forceUnknownAnyToType(Expr *E, QualType ToType);
9517 /// \brief Type-check an expression that's being passed to an
9518 /// __unknown_anytype parameter.
9519 ExprResult checkUnknownAnyArg(SourceLocation callLoc,
9520 Expr *result, QualType ¶mType);
9522 // CheckVectorCast - check type constraints for vectors.
9523 // Since vectors are an extension, there are no C standard reference for this.
9524 // We allow casting between vectors and integer datatypes of the same size.
9525 // returns true if the cast is invalid
9526 bool CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
9529 /// \brief Prepare `SplattedExpr` for a vector splat operation, adding
9530 /// implicit casts if necessary.
9531 ExprResult prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr);
9533 // CheckExtVectorCast - check type constraints for extended vectors.
9534 // Since vectors are an extension, there are no C standard reference for this.
9535 // We allow casting between vectors and integer datatypes of the same size,
9536 // or vectors and the element type of that vector.
9537 // returns the cast expr
9538 ExprResult CheckExtVectorCast(SourceRange R, QualType DestTy, Expr *CastExpr,
9541 ExprResult BuildCXXFunctionalCastExpr(TypeSourceInfo *TInfo, QualType Type,
9542 SourceLocation LParenLoc,
9544 SourceLocation RParenLoc);
9546 enum ARCConversionResult { ACR_okay, ACR_unbridged, ACR_error };
9548 /// \brief Checks for invalid conversions and casts between
9549 /// retainable pointers and other pointer kinds for ARC and Weak.
9550 ARCConversionResult CheckObjCConversion(SourceRange castRange,
9551 QualType castType, Expr *&op,
9552 CheckedConversionKind CCK,
9553 bool Diagnose = true,
9554 bool DiagnoseCFAudited = false,
9555 BinaryOperatorKind Opc = BO_PtrMemD
9558 Expr *stripARCUnbridgedCast(Expr *e);
9559 void diagnoseARCUnbridgedCast(Expr *e);
9561 bool CheckObjCARCUnavailableWeakConversion(QualType castType,
9564 /// checkRetainCycles - Check whether an Objective-C message send
9565 /// might create an obvious retain cycle.
9566 void checkRetainCycles(ObjCMessageExpr *msg);
9567 void checkRetainCycles(Expr *receiver, Expr *argument);
9568 void checkRetainCycles(VarDecl *Var, Expr *Init);
9570 /// checkUnsafeAssigns - Check whether +1 expr is being assigned
9571 /// to weak/__unsafe_unretained type.
9572 bool checkUnsafeAssigns(SourceLocation Loc, QualType LHS, Expr *RHS);
9574 /// checkUnsafeExprAssigns - Check whether +1 expr is being assigned
9575 /// to weak/__unsafe_unretained expression.
9576 void checkUnsafeExprAssigns(SourceLocation Loc, Expr *LHS, Expr *RHS);
9578 /// CheckMessageArgumentTypes - Check types in an Obj-C message send.
9579 /// \param Method - May be null.
9580 /// \param [out] ReturnType - The return type of the send.
9581 /// \return true iff there were any incompatible types.
9582 bool CheckMessageArgumentTypes(QualType ReceiverType,
9583 MultiExprArg Args, Selector Sel,
9584 ArrayRef<SourceLocation> SelectorLocs,
9585 ObjCMethodDecl *Method, bool isClassMessage,
9586 bool isSuperMessage,
9587 SourceLocation lbrac, SourceLocation rbrac,
9588 SourceRange RecRange,
9589 QualType &ReturnType, ExprValueKind &VK);
9591 /// \brief Determine the result of a message send expression based on
9592 /// the type of the receiver, the method expected to receive the message,
9593 /// and the form of the message send.
9594 QualType getMessageSendResultType(QualType ReceiverType,
9595 ObjCMethodDecl *Method,
9596 bool isClassMessage, bool isSuperMessage);
9598 /// \brief If the given expression involves a message send to a method
9599 /// with a related result type, emit a note describing what happened.
9600 void EmitRelatedResultTypeNote(const Expr *E);
9602 /// \brief Given that we had incompatible pointer types in a return
9603 /// statement, check whether we're in a method with a related result
9604 /// type, and if so, emit a note describing what happened.
9605 void EmitRelatedResultTypeNoteForReturn(QualType destType);
9607 class ConditionResult {
9609 FullExprArg Condition;
9615 ConditionResult(Sema &S, Decl *ConditionVar, FullExprArg Condition,
9617 : ConditionVar(ConditionVar), Condition(Condition), Invalid(false),
9618 HasKnownValue(IsConstexpr && Condition.get() &&
9619 !Condition.get()->isValueDependent()),
9620 KnownValue(HasKnownValue &&
9621 !!Condition.get()->EvaluateKnownConstInt(S.Context)) {}
9622 explicit ConditionResult(bool Invalid)
9623 : ConditionVar(nullptr), Condition(nullptr), Invalid(Invalid),
9624 HasKnownValue(false), KnownValue(false) {}
9627 ConditionResult() : ConditionResult(false) {}
9628 bool isInvalid() const { return Invalid; }
9629 std::pair<VarDecl *, Expr *> get() const {
9630 return std::make_pair(cast_or_null<VarDecl>(ConditionVar),
9633 llvm::Optional<bool> getKnownValue() const {
9639 static ConditionResult ConditionError() { return ConditionResult(true); }
9641 enum class ConditionKind {
9642 Boolean, ///< A boolean condition, from 'if', 'while', 'for', or 'do'.
9643 ConstexprIf, ///< A constant boolean condition from 'if constexpr'.
9644 Switch ///< An integral condition for a 'switch' statement.
9647 ConditionResult ActOnCondition(Scope *S, SourceLocation Loc,
9648 Expr *SubExpr, ConditionKind CK);
9650 ConditionResult ActOnConditionVariable(Decl *ConditionVar,
9651 SourceLocation StmtLoc,
9654 DeclResult ActOnCXXConditionDeclaration(Scope *S, Declarator &D);
9656 ExprResult CheckConditionVariable(VarDecl *ConditionVar,
9657 SourceLocation StmtLoc,
9659 ExprResult CheckSwitchCondition(SourceLocation SwitchLoc, Expr *Cond);
9661 /// CheckBooleanCondition - Diagnose problems involving the use of
9662 /// the given expression as a boolean condition (e.g. in an if
9663 /// statement). Also performs the standard function and array
9664 /// decays, possibly changing the input variable.
9666 /// \param Loc - A location associated with the condition, e.g. the
9668 /// \return true iff there were any errors
9669 ExprResult CheckBooleanCondition(SourceLocation Loc, Expr *E,
9670 bool IsConstexpr = false);
9672 /// DiagnoseAssignmentAsCondition - Given that an expression is
9673 /// being used as a boolean condition, warn if it's an assignment.
9674 void DiagnoseAssignmentAsCondition(Expr *E);
9676 /// \brief Redundant parentheses over an equality comparison can indicate
9677 /// that the user intended an assignment used as condition.
9678 void DiagnoseEqualityWithExtraParens(ParenExpr *ParenE);
9680 /// CheckCXXBooleanCondition - Returns true if conversion to bool is invalid.
9681 ExprResult CheckCXXBooleanCondition(Expr *CondExpr, bool IsConstexpr = false);
9683 /// ConvertIntegerToTypeWarnOnOverflow - Convert the specified APInt to have
9684 /// the specified width and sign. If an overflow occurs, detect it and emit
9685 /// the specified diagnostic.
9686 void ConvertIntegerToTypeWarnOnOverflow(llvm::APSInt &OldVal,
9687 unsigned NewWidth, bool NewSign,
9688 SourceLocation Loc, unsigned DiagID);
9690 /// Checks that the Objective-C declaration is declared in the global scope.
9691 /// Emits an error and marks the declaration as invalid if it's not declared
9692 /// in the global scope.
9693 bool CheckObjCDeclScope(Decl *D);
9695 /// \brief Abstract base class used for diagnosing integer constant
9696 /// expression violations.
9697 class VerifyICEDiagnoser {
9701 VerifyICEDiagnoser(bool Suppress = false) : Suppress(Suppress) { }
9703 virtual void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) =0;
9704 virtual void diagnoseFold(Sema &S, SourceLocation Loc, SourceRange SR);
9705 virtual ~VerifyICEDiagnoser() { }
9708 /// VerifyIntegerConstantExpression - Verifies that an expression is an ICE,
9709 /// and reports the appropriate diagnostics. Returns false on success.
9710 /// Can optionally return the value of the expression.
9711 ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
9712 VerifyICEDiagnoser &Diagnoser,
9713 bool AllowFold = true);
9714 ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
9716 bool AllowFold = true);
9717 ExprResult VerifyIntegerConstantExpression(Expr *E,
9718 llvm::APSInt *Result = nullptr);
9720 /// VerifyBitField - verifies that a bit field expression is an ICE and has
9721 /// the correct width, and that the field type is valid.
9722 /// Returns false on success.
9723 /// Can optionally return whether the bit-field is of width 0
9724 ExprResult VerifyBitField(SourceLocation FieldLoc, IdentifierInfo *FieldName,
9725 QualType FieldTy, bool IsMsStruct,
9726 Expr *BitWidth, bool *ZeroWidth = nullptr);
9729 unsigned ForceCUDAHostDeviceDepth = 0;
9732 /// Increments our count of the number of times we've seen a pragma forcing
9733 /// functions to be __host__ __device__. So long as this count is greater
9734 /// than zero, all functions encountered will be __host__ __device__.
9735 void PushForceCUDAHostDevice();
9737 /// Decrements our count of the number of times we've seen a pragma forcing
9738 /// functions to be __host__ __device__. Returns false if the count is 0
9739 /// before incrementing, so you can emit an error.
9740 bool PopForceCUDAHostDevice();
9742 /// Diagnostics that are emitted only if we discover that the given function
9743 /// must be codegen'ed. Because handling these correctly adds overhead to
9744 /// compilation, this is currently only enabled for CUDA compilations.
9745 llvm::DenseMap<CanonicalDeclPtr<FunctionDecl>,
9746 std::vector<PartialDiagnosticAt>>
9749 /// A pair of a canonical FunctionDecl and a SourceLocation. When used as the
9750 /// key in a hashtable, both the FD and location are hashed.
9751 struct FunctionDeclAndLoc {
9752 CanonicalDeclPtr<FunctionDecl> FD;
9756 /// FunctionDecls and SourceLocations for which CheckCUDACall has emitted a
9757 /// (maybe deferred) "bad call" diagnostic. We use this to avoid emitting the
9758 /// same deferred diag twice.
9759 llvm::DenseSet<FunctionDeclAndLoc> LocsWithCUDACallDiags;
9761 /// An inverse call graph, mapping known-emitted functions to one of their
9762 /// known-emitted callers (plus the location of the call).
9764 /// Functions that we can tell a priori must be emitted aren't added to this
9766 llvm::DenseMap</* Callee = */ CanonicalDeclPtr<FunctionDecl>,
9767 /* Caller = */ FunctionDeclAndLoc>
9768 CUDAKnownEmittedFns;
9770 /// A partial call graph maintained during CUDA compilation to support
9771 /// deferred diagnostics.
9773 /// Functions are only added here if, at the time they're considered, they are
9774 /// not known-emitted. As soon as we discover that a function is
9775 /// known-emitted, we remove it and everything it transitively calls from this
9776 /// set and add those functions to CUDAKnownEmittedFns.
9777 llvm::DenseMap</* Caller = */ CanonicalDeclPtr<FunctionDecl>,
9778 /* Callees = */ llvm::MapVector<CanonicalDeclPtr<FunctionDecl>,
9782 /// Diagnostic builder for CUDA errors which may or may not be deferred.
9784 /// In CUDA, there exist constructs (e.g. variable-length arrays, try/catch)
9785 /// which are not allowed to appear inside __device__ functions and are
9786 /// allowed to appear in __host__ __device__ functions only if the host+device
9787 /// function is never codegen'ed.
9789 /// To handle this, we use the notion of "deferred diagnostics", where we
9790 /// attach a diagnostic to a FunctionDecl that's emitted iff it's codegen'ed.
9792 /// This class lets you emit either a regular diagnostic, a deferred
9793 /// diagnostic, or no diagnostic at all, according to an argument you pass to
9794 /// its constructor, thus simplifying the process of creating these "maybe
9795 /// deferred" diagnostics.
9796 class CUDADiagBuilder {
9799 /// Emit no diagnostics.
9801 /// Emit the diagnostic immediately (i.e., behave like Sema::Diag()).
9803 /// Emit the diagnostic immediately, and, if it's a warning or error, also
9804 /// emit a call stack showing how this function can be reached by an a
9805 /// priori known-emitted function.
9806 K_ImmediateWithCallStack,
9807 /// Create a deferred diagnostic, which is emitted only if the function
9808 /// it's attached to is codegen'ed. Also emit a call stack as with
9809 /// K_ImmediateWithCallStack.
9813 CUDADiagBuilder(Kind K, SourceLocation Loc, unsigned DiagID,
9814 FunctionDecl *Fn, Sema &S);
9817 /// Convertible to bool: True if we immediately emitted an error, false if
9818 /// we didn't emit an error or we created a deferred error.
9822 /// if (CUDADiagBuilder(...) << foo << bar)
9823 /// return ExprError();
9825 /// But see CUDADiagIfDeviceCode() and CUDADiagIfHostCode() -- you probably
9826 /// want to use these instead of creating a CUDADiagBuilder yourself.
9827 operator bool() const { return ImmediateDiag.hasValue(); }
9829 template <typename T>
9830 friend const CUDADiagBuilder &operator<<(const CUDADiagBuilder &Diag,
9832 if (Diag.ImmediateDiag.hasValue())
9833 *Diag.ImmediateDiag << Value;
9834 else if (Diag.PartialDiag.hasValue())
9835 *Diag.PartialDiag << Value;
9846 // Invariant: At most one of these Optionals has a value.
9847 // FIXME: Switch these to a Variant once that exists.
9848 llvm::Optional<SemaDiagnosticBuilder> ImmediateDiag;
9849 llvm::Optional<PartialDiagnostic> PartialDiag;
9852 /// Creates a CUDADiagBuilder that emits the diagnostic if the current context
9853 /// is "used as device code".
9855 /// - If CurContext is a __host__ function, does not emit any diagnostics.
9856 /// - If CurContext is a __device__ or __global__ function, emits the
9857 /// diagnostics immediately.
9858 /// - If CurContext is a __host__ __device__ function and we are compiling for
9859 /// the device, creates a diagnostic which is emitted if and when we realize
9860 /// that the function will be codegen'ed.
9864 /// // Variable-length arrays are not allowed in CUDA device code.
9865 /// if (CUDADiagIfDeviceCode(Loc, diag::err_cuda_vla) << CurrentCUDATarget())
9866 /// return ExprError();
9867 /// // Otherwise, continue parsing as normal.
9868 CUDADiagBuilder CUDADiagIfDeviceCode(SourceLocation Loc, unsigned DiagID);
9870 /// Creates a CUDADiagBuilder that emits the diagnostic if the current context
9871 /// is "used as host code".
9873 /// Same as CUDADiagIfDeviceCode, with "host" and "device" switched.
9874 CUDADiagBuilder CUDADiagIfHostCode(SourceLocation Loc, unsigned DiagID);
9876 enum CUDAFunctionTarget {
9884 /// Determines whether the given function is a CUDA device/host/kernel/etc.
9887 /// Use this rather than examining the function's attributes yourself -- you
9888 /// will get it wrong. Returns CFT_Host if D is null.
9889 CUDAFunctionTarget IdentifyCUDATarget(const FunctionDecl *D,
9890 bool IgnoreImplicitHDAttr = false);
9891 CUDAFunctionTarget IdentifyCUDATarget(const AttributeList *Attr);
9893 /// Gets the CUDA target for the current context.
9894 CUDAFunctionTarget CurrentCUDATarget() {
9895 return IdentifyCUDATarget(dyn_cast<FunctionDecl>(CurContext));
9898 // CUDA function call preference. Must be ordered numerically from
9900 enum CUDAFunctionPreference {
9901 CFP_Never, // Invalid caller/callee combination.
9902 CFP_WrongSide, // Calls from host-device to host or device
9903 // function that do not match current compilation
9905 CFP_HostDevice, // Any calls to host/device functions.
9906 CFP_SameSide, // Calls from host-device to host or device
9907 // function matching current compilation mode.
9908 CFP_Native, // host-to-host or device-to-device calls.
9911 /// Identifies relative preference of a given Caller/Callee
9912 /// combination, based on their host/device attributes.
9913 /// \param Caller function which needs address of \p Callee.
9914 /// nullptr in case of global context.
9915 /// \param Callee target function
9917 /// \returns preference value for particular Caller/Callee combination.
9918 CUDAFunctionPreference IdentifyCUDAPreference(const FunctionDecl *Caller,
9919 const FunctionDecl *Callee);
9921 /// Determines whether Caller may invoke Callee, based on their CUDA
9922 /// host/device attributes. Returns false if the call is not allowed.
9924 /// Note: Will return true for CFP_WrongSide calls. These may appear in
9925 /// semantically correct CUDA programs, but only if they're never codegen'ed.
9926 bool IsAllowedCUDACall(const FunctionDecl *Caller,
9927 const FunctionDecl *Callee) {
9928 return IdentifyCUDAPreference(Caller, Callee) != CFP_Never;
9931 /// May add implicit CUDAHostAttr and CUDADeviceAttr attributes to FD,
9932 /// depending on FD and the current compilation settings.
9933 void maybeAddCUDAHostDeviceAttrs(FunctionDecl *FD,
9934 const LookupResult &Previous);
9937 /// Check whether we're allowed to call Callee from the current context.
9939 /// - If the call is never allowed in a semantically-correct program
9940 /// (CFP_Never), emits an error and returns false.
9942 /// - If the call is allowed in semantically-correct programs, but only if
9943 /// it's never codegen'ed (CFP_WrongSide), creates a deferred diagnostic to
9944 /// be emitted if and when the caller is codegen'ed, and returns true.
9946 /// Will only create deferred diagnostics for a given SourceLocation once,
9947 /// so you can safely call this multiple times without generating duplicate
9948 /// deferred errors.
9950 /// - Otherwise, returns true without emitting any diagnostics.
9951 bool CheckCUDACall(SourceLocation Loc, FunctionDecl *Callee);
9953 /// Set __device__ or __host__ __device__ attributes on the given lambda
9954 /// operator() method.
9956 /// CUDA lambdas declared inside __device__ or __global__ functions inherit
9957 /// the __device__ attribute. Similarly, lambdas inside __host__ __device__
9958 /// functions become __host__ __device__ themselves.
9959 void CUDASetLambdaAttrs(CXXMethodDecl *Method);
9961 /// Finds a function in \p Matches with highest calling priority
9962 /// from \p Caller context and erases all functions with lower
9963 /// calling priority.
9964 void EraseUnwantedCUDAMatches(
9965 const FunctionDecl *Caller,
9966 SmallVectorImpl<std::pair<DeclAccessPair, FunctionDecl *>> &Matches);
9968 /// Given a implicit special member, infer its CUDA target from the
9969 /// calls it needs to make to underlying base/field special members.
9970 /// \param ClassDecl the class for which the member is being created.
9971 /// \param CSM the kind of special member.
9972 /// \param MemberDecl the special member itself.
9973 /// \param ConstRHS true if this is a copy operation with a const object on
9975 /// \param Diagnose true if this call should emit diagnostics.
9976 /// \return true if there was an error inferring.
9977 /// The result of this call is implicit CUDA target attribute(s) attached to
9978 /// the member declaration.
9979 bool inferCUDATargetForImplicitSpecialMember(CXXRecordDecl *ClassDecl,
9980 CXXSpecialMember CSM,
9981 CXXMethodDecl *MemberDecl,
9985 /// \return true if \p CD can be considered empty according to CUDA
9986 /// (E.2.3.1 in CUDA 7.5 Programming guide).
9987 bool isEmptyCudaConstructor(SourceLocation Loc, CXXConstructorDecl *CD);
9988 bool isEmptyCudaDestructor(SourceLocation Loc, CXXDestructorDecl *CD);
9990 /// Check whether NewFD is a valid overload for CUDA. Emits
9991 /// diagnostics and invalidates NewFD if not.
9992 void checkCUDATargetOverload(FunctionDecl *NewFD,
9993 const LookupResult &Previous);
9994 /// Copies target attributes from the template TD to the function FD.
9995 void inheritCUDATargetAttrs(FunctionDecl *FD, const FunctionTemplateDecl &TD);
9997 /// \name Code completion
9999 /// \brief Describes the context in which code completion occurs.
10000 enum ParserCompletionContext {
10001 /// \brief Code completion occurs at top-level or namespace context.
10003 /// \brief Code completion occurs within a class, struct, or union.
10005 /// \brief Code completion occurs within an Objective-C interface, protocol,
10008 /// \brief Code completion occurs within an Objective-C implementation or
10009 /// category implementation
10010 PCC_ObjCImplementation,
10011 /// \brief Code completion occurs within the list of instance variables
10012 /// in an Objective-C interface, protocol, category, or implementation.
10013 PCC_ObjCInstanceVariableList,
10014 /// \brief Code completion occurs following one or more template
10017 /// \brief Code completion occurs following one or more template
10018 /// headers within a class.
10019 PCC_MemberTemplate,
10020 /// \brief Code completion occurs within an expression.
10022 /// \brief Code completion occurs within a statement, which may
10023 /// also be an expression or a declaration.
10025 /// \brief Code completion occurs at the beginning of the
10026 /// initialization statement (or expression) in a for loop.
10028 /// \brief Code completion occurs within the condition of an if,
10029 /// while, switch, or for statement.
10031 /// \brief Code completion occurs within the body of a function on a
10032 /// recovery path, where we do not have a specific handle on our position
10033 /// in the grammar.
10034 PCC_RecoveryInFunction,
10035 /// \brief Code completion occurs where only a type is permitted.
10037 /// \brief Code completion occurs in a parenthesized expression, which
10038 /// might also be a type cast.
10039 PCC_ParenthesizedExpression,
10040 /// \brief Code completion occurs within a sequence of declaration
10041 /// specifiers within a function, method, or block.
10042 PCC_LocalDeclarationSpecifiers
10045 void CodeCompleteModuleImport(SourceLocation ImportLoc, ModuleIdPath Path);
10046 void CodeCompleteOrdinaryName(Scope *S,
10047 ParserCompletionContext CompletionContext);
10048 void CodeCompleteDeclSpec(Scope *S, DeclSpec &DS,
10049 bool AllowNonIdentifiers,
10050 bool AllowNestedNameSpecifiers);
10052 struct CodeCompleteExpressionData;
10053 void CodeCompleteExpression(Scope *S,
10054 const CodeCompleteExpressionData &Data);
10055 void CodeCompleteMemberReferenceExpr(Scope *S, Expr *Base,
10056 SourceLocation OpLoc, bool IsArrow,
10057 bool IsBaseExprStatement);
10058 void CodeCompletePostfixExpression(Scope *S, ExprResult LHS);
10059 void CodeCompleteTag(Scope *S, unsigned TagSpec);
10060 void CodeCompleteTypeQualifiers(DeclSpec &DS);
10061 void CodeCompleteFunctionQualifiers(DeclSpec &DS, Declarator &D,
10062 const VirtSpecifiers *VS = nullptr);
10063 void CodeCompleteBracketDeclarator(Scope *S);
10064 void CodeCompleteCase(Scope *S);
10065 void CodeCompleteCall(Scope *S, Expr *Fn, ArrayRef<Expr *> Args);
10066 void CodeCompleteConstructor(Scope *S, QualType Type, SourceLocation Loc,
10067 ArrayRef<Expr *> Args);
10068 void CodeCompleteInitializer(Scope *S, Decl *D);
10069 void CodeCompleteReturn(Scope *S);
10070 void CodeCompleteAfterIf(Scope *S);
10071 void CodeCompleteAssignmentRHS(Scope *S, Expr *LHS);
10073 void CodeCompleteQualifiedId(Scope *S, CXXScopeSpec &SS,
10074 bool EnteringContext);
10075 void CodeCompleteUsing(Scope *S);
10076 void CodeCompleteUsingDirective(Scope *S);
10077 void CodeCompleteNamespaceDecl(Scope *S);
10078 void CodeCompleteNamespaceAliasDecl(Scope *S);
10079 void CodeCompleteOperatorName(Scope *S);
10080 void CodeCompleteConstructorInitializer(
10082 ArrayRef<CXXCtorInitializer *> Initializers);
10084 void CodeCompleteLambdaIntroducer(Scope *S, LambdaIntroducer &Intro,
10085 bool AfterAmpersand);
10087 void CodeCompleteObjCAtDirective(Scope *S);
10088 void CodeCompleteObjCAtVisibility(Scope *S);
10089 void CodeCompleteObjCAtStatement(Scope *S);
10090 void CodeCompleteObjCAtExpression(Scope *S);
10091 void CodeCompleteObjCPropertyFlags(Scope *S, ObjCDeclSpec &ODS);
10092 void CodeCompleteObjCPropertyGetter(Scope *S);
10093 void CodeCompleteObjCPropertySetter(Scope *S);
10094 void CodeCompleteObjCPassingType(Scope *S, ObjCDeclSpec &DS,
10096 void CodeCompleteObjCMessageReceiver(Scope *S);
10097 void CodeCompleteObjCSuperMessage(Scope *S, SourceLocation SuperLoc,
10098 ArrayRef<IdentifierInfo *> SelIdents,
10099 bool AtArgumentExpression);
10100 void CodeCompleteObjCClassMessage(Scope *S, ParsedType Receiver,
10101 ArrayRef<IdentifierInfo *> SelIdents,
10102 bool AtArgumentExpression,
10103 bool IsSuper = false);
10104 void CodeCompleteObjCInstanceMessage(Scope *S, Expr *Receiver,
10105 ArrayRef<IdentifierInfo *> SelIdents,
10106 bool AtArgumentExpression,
10107 ObjCInterfaceDecl *Super = nullptr);
10108 void CodeCompleteObjCForCollection(Scope *S,
10109 DeclGroupPtrTy IterationVar);
10110 void CodeCompleteObjCSelector(Scope *S,
10111 ArrayRef<IdentifierInfo *> SelIdents);
10112 void CodeCompleteObjCProtocolReferences(
10113 ArrayRef<IdentifierLocPair> Protocols);
10114 void CodeCompleteObjCProtocolDecl(Scope *S);
10115 void CodeCompleteObjCInterfaceDecl(Scope *S);
10116 void CodeCompleteObjCSuperclass(Scope *S,
10117 IdentifierInfo *ClassName,
10118 SourceLocation ClassNameLoc);
10119 void CodeCompleteObjCImplementationDecl(Scope *S);
10120 void CodeCompleteObjCInterfaceCategory(Scope *S,
10121 IdentifierInfo *ClassName,
10122 SourceLocation ClassNameLoc);
10123 void CodeCompleteObjCImplementationCategory(Scope *S,
10124 IdentifierInfo *ClassName,
10125 SourceLocation ClassNameLoc);
10126 void CodeCompleteObjCPropertyDefinition(Scope *S);
10127 void CodeCompleteObjCPropertySynthesizeIvar(Scope *S,
10128 IdentifierInfo *PropertyName);
10129 void CodeCompleteObjCMethodDecl(Scope *S,
10130 bool IsInstanceMethod,
10131 ParsedType ReturnType);
10132 void CodeCompleteObjCMethodDeclSelector(Scope *S,
10133 bool IsInstanceMethod,
10134 bool AtParameterName,
10135 ParsedType ReturnType,
10136 ArrayRef<IdentifierInfo *> SelIdents);
10137 void CodeCompleteObjCClassPropertyRefExpr(Scope *S, IdentifierInfo &ClassName,
10138 SourceLocation ClassNameLoc,
10139 bool IsBaseExprStatement);
10140 void CodeCompletePreprocessorDirective(bool InConditional);
10141 void CodeCompleteInPreprocessorConditionalExclusion(Scope *S);
10142 void CodeCompletePreprocessorMacroName(bool IsDefinition);
10143 void CodeCompletePreprocessorExpression();
10144 void CodeCompletePreprocessorMacroArgument(Scope *S,
10145 IdentifierInfo *Macro,
10146 MacroInfo *MacroInfo,
10147 unsigned Argument);
10148 void CodeCompleteNaturalLanguage();
10149 void CodeCompleteAvailabilityPlatformName();
10150 void GatherGlobalCodeCompletions(CodeCompletionAllocator &Allocator,
10151 CodeCompletionTUInfo &CCTUInfo,
10152 SmallVectorImpl<CodeCompletionResult> &Results);
10155 //===--------------------------------------------------------------------===//
10156 // Extra semantic analysis beyond the C type system
10159 SourceLocation getLocationOfStringLiteralByte(const StringLiteral *SL,
10160 unsigned ByteNo) const;
10163 void CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
10164 const ArraySubscriptExpr *ASE=nullptr,
10165 bool AllowOnePastEnd=true, bool IndexNegated=false);
10166 void CheckArrayAccess(const Expr *E);
10167 // Used to grab the relevant information from a FormatAttr and a
10168 // FunctionDeclaration.
10169 struct FormatStringInfo {
10170 unsigned FormatIdx;
10171 unsigned FirstDataArg;
10175 static bool getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
10176 FormatStringInfo *FSI);
10177 bool CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
10178 const FunctionProtoType *Proto);
10179 bool CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation loc,
10180 ArrayRef<const Expr *> Args);
10181 bool CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
10182 const FunctionProtoType *Proto);
10183 bool CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto);
10184 void CheckConstructorCall(FunctionDecl *FDecl,
10185 ArrayRef<const Expr *> Args,
10186 const FunctionProtoType *Proto,
10187 SourceLocation Loc);
10189 void checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
10190 const Expr *ThisArg, ArrayRef<const Expr *> Args,
10191 bool IsMemberFunction, SourceLocation Loc, SourceRange Range,
10192 VariadicCallType CallType);
10194 bool CheckObjCString(Expr *Arg);
10195 ExprResult CheckOSLogFormatStringArg(Expr *Arg);
10197 ExprResult CheckBuiltinFunctionCall(FunctionDecl *FDecl,
10198 unsigned BuiltinID, CallExpr *TheCall);
10200 bool CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
10201 unsigned MaxWidth);
10202 bool CheckNeonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
10203 bool CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
10205 bool CheckAArch64BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
10206 bool CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
10207 bool CheckSystemZBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
10208 bool CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall);
10209 bool CheckX86BuiltinGatherScatterScale(unsigned BuiltinID, CallExpr *TheCall);
10210 bool CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
10211 bool CheckPPCBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
10213 bool SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall);
10214 bool SemaBuiltinVAStartARM(CallExpr *Call);
10215 bool SemaBuiltinUnorderedCompare(CallExpr *TheCall);
10216 bool SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs);
10217 bool SemaBuiltinVSX(CallExpr *TheCall);
10218 bool SemaBuiltinOSLogFormat(CallExpr *TheCall);
10221 // Used by C++ template instantiation.
10222 ExprResult SemaBuiltinShuffleVector(CallExpr *TheCall);
10223 ExprResult SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
10224 SourceLocation BuiltinLoc,
10225 SourceLocation RParenLoc);
10228 bool SemaBuiltinPrefetch(CallExpr *TheCall);
10229 bool SemaBuiltinAllocaWithAlign(CallExpr *TheCall);
10230 bool SemaBuiltinAssume(CallExpr *TheCall);
10231 bool SemaBuiltinAssumeAligned(CallExpr *TheCall);
10232 bool SemaBuiltinLongjmp(CallExpr *TheCall);
10233 bool SemaBuiltinSetjmp(CallExpr *TheCall);
10234 ExprResult SemaBuiltinAtomicOverloaded(ExprResult TheCallResult);
10235 ExprResult SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult);
10236 ExprResult SemaAtomicOpsOverloaded(ExprResult TheCallResult,
10237 AtomicExpr::AtomicOp Op);
10238 bool SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
10239 llvm::APSInt &Result);
10240 bool SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
10241 int Low, int High);
10242 bool SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum,
10243 unsigned Multiple);
10244 bool SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall,
10245 int ArgNum, unsigned ExpectedFieldNum,
10248 enum FormatStringType {
10255 FST_FreeBSDKPrintf,
10260 static FormatStringType GetFormatStringType(const FormatAttr *Format);
10262 bool FormatStringHasSArg(const StringLiteral *FExpr);
10264 static bool GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx);
10267 bool CheckFormatArguments(const FormatAttr *Format,
10268 ArrayRef<const Expr *> Args,
10270 VariadicCallType CallType,
10271 SourceLocation Loc, SourceRange Range,
10272 llvm::SmallBitVector &CheckedVarArgs);
10273 bool CheckFormatArguments(ArrayRef<const Expr *> Args,
10274 bool HasVAListArg, unsigned format_idx,
10275 unsigned firstDataArg, FormatStringType Type,
10276 VariadicCallType CallType,
10277 SourceLocation Loc, SourceRange range,
10278 llvm::SmallBitVector &CheckedVarArgs);
10280 void CheckAbsoluteValueFunction(const CallExpr *Call,
10281 const FunctionDecl *FDecl);
10283 void CheckMaxUnsignedZero(const CallExpr *Call, const FunctionDecl *FDecl);
10285 void CheckMemaccessArguments(const CallExpr *Call,
10287 IdentifierInfo *FnName);
10289 void CheckStrlcpycatArguments(const CallExpr *Call,
10290 IdentifierInfo *FnName);
10292 void CheckStrncatArguments(const CallExpr *Call,
10293 IdentifierInfo *FnName);
10295 void CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
10296 SourceLocation ReturnLoc,
10297 bool isObjCMethod = false,
10298 const AttrVec *Attrs = nullptr,
10299 const FunctionDecl *FD = nullptr);
10301 void CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr* RHS);
10302 void CheckImplicitConversions(Expr *E, SourceLocation CC = SourceLocation());
10303 void CheckBoolLikeConversion(Expr *E, SourceLocation CC);
10304 void CheckForIntOverflow(Expr *E);
10305 void CheckUnsequencedOperations(Expr *E);
10307 /// \brief Perform semantic checks on a completed expression. This will either
10308 /// be a full-expression or a default argument expression.
10309 void CheckCompletedExpr(Expr *E, SourceLocation CheckLoc = SourceLocation(),
10310 bool IsConstexpr = false);
10312 void CheckBitFieldInitialization(SourceLocation InitLoc, FieldDecl *Field,
10315 /// Check if there is a field shadowing.
10316 void CheckShadowInheritedFields(const SourceLocation &Loc,
10317 DeclarationName FieldName,
10318 const CXXRecordDecl *RD);
10320 /// \brief Check if the given expression contains 'break' or 'continue'
10321 /// statement that produces control flow different from GCC.
10322 void CheckBreakContinueBinding(Expr *E);
10324 /// \brief Check whether receiver is mutable ObjC container which
10325 /// attempts to add itself into the container
10326 void CheckObjCCircularContainer(ObjCMessageExpr *Message);
10328 void AnalyzeDeleteExprMismatch(const CXXDeleteExpr *DE);
10329 void AnalyzeDeleteExprMismatch(FieldDecl *Field, SourceLocation DeleteLoc,
10330 bool DeleteWasArrayForm);
10332 /// \brief Register a magic integral constant to be used as a type tag.
10333 void RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
10334 uint64_t MagicValue, QualType Type,
10335 bool LayoutCompatible, bool MustBeNull);
10337 struct TypeTagData {
10340 TypeTagData(QualType Type, bool LayoutCompatible, bool MustBeNull) :
10341 Type(Type), LayoutCompatible(LayoutCompatible),
10342 MustBeNull(MustBeNull)
10347 /// If true, \c Type should be compared with other expression's types for
10348 /// layout-compatibility.
10349 unsigned LayoutCompatible : 1;
10350 unsigned MustBeNull : 1;
10353 /// A pair of ArgumentKind identifier and magic value. This uniquely
10354 /// identifies the magic value.
10355 typedef std::pair<const IdentifierInfo *, uint64_t> TypeTagMagicValue;
10358 /// \brief A map from magic value to type information.
10359 std::unique_ptr<llvm::DenseMap<TypeTagMagicValue, TypeTagData>>
10360 TypeTagForDatatypeMagicValues;
10362 /// \brief Peform checks on a call of a function with argument_with_type_tag
10363 /// or pointer_with_type_tag attributes.
10364 void CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
10365 const Expr * const *ExprArgs);
10367 /// \brief Check if we are taking the address of a packed field
10368 /// as this may be a problem if the pointer value is dereferenced.
10369 void CheckAddressOfPackedMember(Expr *rhs);
10371 /// \brief The parser's current scope.
10373 /// The parser maintains this state here.
10376 mutable IdentifierInfo *Ident_super;
10377 mutable IdentifierInfo *Ident___float128;
10379 /// Nullability type specifiers.
10380 IdentifierInfo *Ident__Nonnull = nullptr;
10381 IdentifierInfo *Ident__Nullable = nullptr;
10382 IdentifierInfo *Ident__Null_unspecified = nullptr;
10384 IdentifierInfo *Ident_NSError = nullptr;
10387 friend class Parser;
10388 friend class InitializationSequence;
10389 friend class ASTReader;
10390 friend class ASTDeclReader;
10391 friend class ASTWriter;
10394 /// Retrieve the keyword associated
10395 IdentifierInfo *getNullabilityKeyword(NullabilityKind nullability);
10397 /// The struct behind the CFErrorRef pointer.
10398 RecordDecl *CFError = nullptr;
10400 /// Retrieve the identifier "NSError".
10401 IdentifierInfo *getNSErrorIdent();
10403 /// \brief Retrieve the parser's current scope.
10405 /// This routine must only be used when it is certain that semantic analysis
10406 /// and the parser are in precisely the same context, which is not the case
10407 /// when, e.g., we are performing any kind of template instantiation.
10408 /// Therefore, the only safe places to use this scope are in the parser
10409 /// itself and in routines directly invoked from the parser and *never* from
10410 /// template substitution or instantiation.
10411 Scope *getCurScope() const { return CurScope; }
10413 void incrementMSManglingNumber() const {
10414 return CurScope->incrementMSManglingNumber();
10417 IdentifierInfo *getSuperIdentifier() const;
10418 IdentifierInfo *getFloat128Identifier() const;
10420 Decl *getObjCDeclContext() const;
10422 DeclContext *getCurLexicalContext() const {
10423 return OriginalLexicalContext ? OriginalLexicalContext : CurContext;
10426 const DeclContext *getCurObjCLexicalContext() const {
10427 const DeclContext *DC = getCurLexicalContext();
10428 // A category implicitly has the attribute of the interface.
10429 if (const ObjCCategoryDecl *CatD = dyn_cast<ObjCCategoryDecl>(DC))
10430 DC = CatD->getClassInterface();
10434 /// \brief To be used for checking whether the arguments being passed to
10435 /// function exceeds the number of parameters expected for it.
10436 static bool TooManyArguments(size_t NumParams, size_t NumArgs,
10437 bool PartialOverloading = false) {
10438 // We check whether we're just after a comma in code-completion.
10439 if (NumArgs > 0 && PartialOverloading)
10440 return NumArgs + 1 > NumParams; // If so, we view as an extra argument.
10441 return NumArgs > NumParams;
10444 // Emitting members of dllexported classes is delayed until the class
10445 // (including field initializers) is fully parsed.
10446 SmallVector<CXXRecordDecl*, 4> DelayedDllExportClasses;
10449 /// \brief Helper class that collects misaligned member designations and
10450 /// their location info for delayed diagnostics.
10451 struct MisalignedMember {
10455 CharUnits Alignment;
10457 MisalignedMember() : E(), RD(), MD(), Alignment() {}
10458 MisalignedMember(Expr *E, RecordDecl *RD, ValueDecl *MD,
10459 CharUnits Alignment)
10460 : E(E), RD(RD), MD(MD), Alignment(Alignment) {}
10461 explicit MisalignedMember(Expr *E)
10462 : MisalignedMember(E, nullptr, nullptr, CharUnits()) {}
10464 bool operator==(const MisalignedMember &m) { return this->E == m.E; }
10466 /// \brief Small set of gathered accesses to potentially misaligned members
10467 /// due to the packed attribute.
10468 SmallVector<MisalignedMember, 4> MisalignedMembers;
10470 /// \brief Adds an expression to the set of gathered misaligned members.
10471 void AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD,
10472 CharUnits Alignment);
10475 /// \brief Diagnoses the current set of gathered accesses. This typically
10476 /// happens at full expression level. The set is cleared after emitting the
10478 void DiagnoseMisalignedMembers();
10480 /// \brief This function checks if the expression is in the sef of potentially
10481 /// misaligned members and it is converted to some pointer type T with lower
10482 /// or equal alignment requirements. If so it removes it. This is used when
10483 /// we do not want to diagnose such misaligned access (e.g. in conversions to
10485 void DiscardMisalignedMemberAddress(const Type *T, Expr *E);
10487 /// \brief This function calls Action when it determines that E designates a
10488 /// misaligned member due to the packed attribute. This is used to emit
10489 /// local diagnostics like in reference binding.
10490 void RefersToMemberWithReducedAlignment(
10492 llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)>
10496 /// \brief RAII object that enters a new expression evaluation context.
10497 class EnterExpressionEvaluationContext {
10499 bool Entered = true;
10503 EnterExpressionEvaluationContext(Sema &Actions,
10504 Sema::ExpressionEvaluationContext NewContext,
10505 Decl *LambdaContextDecl = nullptr,
10506 bool IsDecltype = false,
10507 bool ShouldEnter = true)
10508 : Actions(Actions), Entered(ShouldEnter) {
10510 Actions.PushExpressionEvaluationContext(NewContext, LambdaContextDecl,
10513 EnterExpressionEvaluationContext(Sema &Actions,
10514 Sema::ExpressionEvaluationContext NewContext,
10515 Sema::ReuseLambdaContextDecl_t,
10516 bool IsDecltype = false)
10517 : Actions(Actions) {
10518 Actions.PushExpressionEvaluationContext(NewContext,
10519 Sema::ReuseLambdaContextDecl,
10523 enum InitListTag { InitList };
10524 EnterExpressionEvaluationContext(Sema &Actions, InitListTag,
10525 bool ShouldEnter = true)
10526 : Actions(Actions), Entered(false) {
10527 // In C++11 onwards, narrowing checks are performed on the contents of
10528 // braced-init-lists, even when they occur within unevaluated operands.
10529 // Therefore we still need to instantiate constexpr functions used in such
10531 if (ShouldEnter && Actions.isUnevaluatedContext() &&
10532 Actions.getLangOpts().CPlusPlus11) {
10533 Actions.PushExpressionEvaluationContext(
10534 Sema::ExpressionEvaluationContext::UnevaluatedList, nullptr, false);
10539 ~EnterExpressionEvaluationContext() {
10541 Actions.PopExpressionEvaluationContext();
10545 DeductionFailureInfo
10546 MakeDeductionFailureInfo(ASTContext &Context, Sema::TemplateDeductionResult TDK,
10547 sema::TemplateDeductionInfo &Info);
10549 /// \brief Contains a late templated function.
10550 /// Will be parsed at the end of the translation unit, used by Sema & Parser.
10551 struct LateParsedTemplate {
10553 /// \brief The template function declaration to be late parsed.
10557 } // end namespace clang
10560 // Hash a FunctionDeclAndLoc by looking at both its FunctionDecl and its
10562 template <> struct DenseMapInfo<clang::Sema::FunctionDeclAndLoc> {
10563 using FunctionDeclAndLoc = clang::Sema::FunctionDeclAndLoc;
10564 using FDBaseInfo = DenseMapInfo<clang::CanonicalDeclPtr<clang::FunctionDecl>>;
10566 static FunctionDeclAndLoc getEmptyKey() {
10567 return {FDBaseInfo::getEmptyKey(), clang::SourceLocation()};
10570 static FunctionDeclAndLoc getTombstoneKey() {
10571 return {FDBaseInfo::getTombstoneKey(), clang::SourceLocation()};
10574 static unsigned getHashValue(const FunctionDeclAndLoc &FDL) {
10575 return hash_combine(FDBaseInfo::getHashValue(FDL.FD),
10576 FDL.Loc.getRawEncoding());
10579 static bool isEqual(const FunctionDeclAndLoc &LHS,
10580 const FunctionDeclAndLoc &RHS) {
10581 return LHS.FD == RHS.FD && LHS.Loc == RHS.Loc;
10584 } // namespace llvm