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/DeclarationName.h"
20 #include "clang/AST/Expr.h"
21 #include "clang/AST/ExprObjC.h"
22 #include "clang/AST/ExternalASTSource.h"
23 #include "clang/AST/MangleNumberingContext.h"
24 #include "clang/AST/NSAPI.h"
25 #include "clang/AST/PrettyPrinter.h"
26 #include "clang/AST/TypeLoc.h"
27 #include "clang/Basic/ExpressionTraits.h"
28 #include "clang/Basic/LangOptions.h"
29 #include "clang/Basic/Module.h"
30 #include "clang/Basic/OpenMPKinds.h"
31 #include "clang/Basic/Specifiers.h"
32 #include "clang/Basic/TemplateKinds.h"
33 #include "clang/Basic/TypeTraits.h"
34 #include "clang/Sema/AnalysisBasedWarnings.h"
35 #include "clang/Sema/DeclSpec.h"
36 #include "clang/Sema/ExternalSemaSource.h"
37 #include "clang/Sema/IdentifierResolver.h"
38 #include "clang/Sema/LocInfoType.h"
39 #include "clang/Sema/ObjCMethodList.h"
40 #include "clang/Sema/Ownership.h"
41 #include "clang/Sema/Scope.h"
42 #include "clang/Sema/ScopeInfo.h"
43 #include "clang/Sema/TypoCorrection.h"
44 #include "clang/Sema/Weak.h"
45 #include "llvm/ADT/ArrayRef.h"
46 #include "llvm/ADT/Optional.h"
47 #include "llvm/ADT/SetVector.h"
48 #include "llvm/ADT/SmallPtrSet.h"
49 #include "llvm/ADT/SmallVector.h"
50 #include "llvm/ADT/TinyPtrVector.h"
58 template <typename ValueT> struct DenseMapInfo;
59 template <typename ValueT, typename ValueInfoT> class DenseSet;
61 class InlineAsmIdentifierInfo;
68 class ASTMutationListener;
77 class CXXBindTemporaryExpr;
78 typedef SmallVector<CXXBaseSpecifier*, 4> CXXCastPath;
79 class CXXConstructorDecl;
80 class CXXConversionDecl;
82 class CXXDestructorDecl;
83 class CXXFieldCollector;
84 class CXXMemberCallExpr;
90 class ClassTemplateDecl;
91 class ClassTemplatePartialSpecializationDecl;
92 class ClassTemplateSpecializationDecl;
93 class VarTemplatePartialSpecializationDecl;
94 class CodeCompleteConsumer;
95 class CodeCompletionAllocator;
96 class CodeCompletionTUInfo;
97 class CodeCompletionResult;
102 class DeclaratorDecl;
103 class DeducedTemplateArgument;
104 class DependentDiagnostic;
105 class DesignatedInitExpr;
108 class EnumConstantDecl;
111 class ExternalSemaSource;
115 class FunctionProtoType;
116 class FunctionTemplateDecl;
117 class ImplicitConversionSequence;
119 class InitializationKind;
120 class InitializationSequence;
121 class InitializedEntity;
122 class IntegerLiteral;
126 class LocalInstantiationScope;
129 typedef ArrayRef<std::pair<IdentifierInfo *, SourceLocation>> ModuleIdPath;
131 class MultiLevelTemplateArgumentList;
133 class ObjCCategoryDecl;
134 class ObjCCategoryImplDecl;
135 class ObjCCompatibleAliasDecl;
136 class ObjCContainerDecl;
138 class ObjCImplementationDecl;
139 class ObjCInterfaceDecl;
141 template <class T> class ObjCList;
142 class ObjCMessageExpr;
143 class ObjCMethodDecl;
144 class ObjCPropertyDecl;
145 class ObjCProtocolDecl;
146 class OMPThreadPrivateDecl;
148 class OverloadCandidateSet;
153 class PseudoDestructorTypeStorage;
154 class PseudoObjectExpr;
156 class StandardConversionSequence;
160 class TemplateArgument;
161 class TemplateArgumentList;
162 class TemplateArgumentLoc;
164 class TemplateParameterList;
165 class TemplatePartialOrderingContext;
166 class TemplateTemplateParmDecl;
170 class TypedefNameDecl;
172 class TypoCorrectionConsumer;
174 class UnresolvedLookupExpr;
175 class UnresolvedMemberExpr;
176 class UnresolvedSetImpl;
177 class UnresolvedSetIterator;
179 class UsingShadowDecl;
182 class VarTemplateSpecializationDecl;
183 class VisibilityAttr;
184 class VisibleDeclConsumer;
185 class IndirectFieldDecl;
186 struct DeductionFailureInfo;
187 class TemplateSpecCandidateSet;
190 class AccessedEntity;
191 class BlockScopeInfo;
192 class CapturedRegionScopeInfo;
193 class CapturingScopeInfo;
194 class CompoundScopeInfo;
195 class DelayedDiagnostic;
196 class DelayedDiagnosticPool;
197 class FunctionScopeInfo;
198 class LambdaScopeInfo;
199 class PossiblyUnreachableDiag;
200 class TemplateDeductionInfo;
203 namespace threadSafety {
205 void threadSafetyCleanup(BeforeSet* Cache);
208 // FIXME: No way to easily map from TemplateTypeParmTypes to
209 // TemplateTypeParmDecls, so we have this horrible PointerUnion.
210 typedef std::pair<llvm::PointerUnion<const TemplateTypeParmType*, NamedDecl*>,
211 SourceLocation> UnexpandedParameterPack;
213 /// Describes whether we've seen any nullability information for the given
215 struct FileNullability {
216 /// The first pointer declarator (of any pointer kind) in the file that does
217 /// not have a corresponding nullability annotation.
218 SourceLocation PointerLoc;
220 /// Which kind of pointer declarator we saw.
223 /// Whether we saw any type nullability annotations in the given file.
224 bool SawTypeNullability = false;
227 /// A mapping from file IDs to a record of whether we've seen nullability
228 /// information in that file.
229 class FileNullabilityMap {
230 /// A mapping from file IDs to the nullability information for each file ID.
231 llvm::DenseMap<FileID, FileNullability> Map;
233 /// A single-element cache based on the file ID.
236 FileNullability Nullability;
240 FileNullability &operator[](FileID file) {
241 // Check the single-element cache.
242 if (file == Cache.File)
243 return Cache.Nullability;
245 // It's not in the single-element cache; flush the cache if we have one.
246 if (!Cache.File.isInvalid()) {
247 Map[Cache.File] = Cache.Nullability;
250 // Pull this entry into the cache.
252 Cache.Nullability = Map[file];
253 return Cache.Nullability;
257 /// Sema - This implements semantic analysis and AST building for C.
259 Sema(const Sema &) = delete;
260 void operator=(const Sema &) = delete;
262 ///\brief Source of additional semantic information.
263 ExternalSemaSource *ExternalSource;
265 ///\brief Whether Sema has generated a multiplexer and has to delete it.
266 bool isMultiplexExternalSource;
268 static bool mightHaveNonExternalLinkage(const DeclaratorDecl *FD);
270 bool isVisibleSlow(const NamedDecl *D);
272 bool shouldLinkPossiblyHiddenDecl(const NamedDecl *Old,
273 const NamedDecl *New) {
274 // We are about to link these. It is now safe to compute the linkage of
275 // the new decl. If the new decl has external linkage, we will
276 // link it with the hidden decl (which also has external linkage) and
277 // it will keep having external linkage. If it has internal linkage, we
278 // will not link it. Since it has no previous decls, it will remain
279 // with internal linkage.
280 if (getLangOpts().ModulesHideInternalLinkage)
281 return isVisible(Old) || New->isExternallyVisible();
286 typedef OpaquePtr<DeclGroupRef> DeclGroupPtrTy;
287 typedef OpaquePtr<TemplateName> TemplateTy;
288 typedef OpaquePtr<QualType> TypeTy;
290 OpenCLOptions OpenCLFeatures;
291 FPOptions FPFeatures;
293 const LangOptions &LangOpts;
296 ASTConsumer &Consumer;
297 DiagnosticsEngine &Diags;
298 SourceManager &SourceMgr;
300 /// \brief Flag indicating whether or not to collect detailed statistics.
303 /// \brief Code-completion consumer.
304 CodeCompleteConsumer *CodeCompleter;
306 /// CurContext - This is the current declaration context of parsing.
307 DeclContext *CurContext;
309 /// \brief Generally null except when we temporarily switch decl contexts,
310 /// like in \see ActOnObjCTemporaryExitContainerContext.
311 DeclContext *OriginalLexicalContext;
313 /// VAListTagName - The declaration name corresponding to __va_list_tag.
314 /// This is used as part of a hack to omit that class from ADL results.
315 DeclarationName VAListTagName;
317 /// PackContext - Manages the stack for \#pragma pack. An alignment
318 /// of 0 indicates default alignment.
319 void *PackContext; // Really a "PragmaPackStack*"
321 bool MSStructPragmaOn; // True when \#pragma ms_struct on
323 /// \brief Controls member pointer representation format under the MS ABI.
324 LangOptions::PragmaMSPointersToMembersKind
325 MSPointerToMemberRepresentationMethod;
327 enum PragmaVtorDispKind {
328 PVDK_Push, ///< #pragma vtordisp(push, mode)
329 PVDK_Set, ///< #pragma vtordisp(mode)
330 PVDK_Pop, ///< #pragma vtordisp(pop)
331 PVDK_Reset ///< #pragma vtordisp()
334 enum PragmaMsStackAction {
335 PSK_Reset, // #pragma ()
336 PSK_Set, // #pragma ("name")
337 PSK_Push, // #pragma (push[, id])
338 PSK_Push_Set, // #pragma (push[, id], "name")
339 PSK_Pop, // #pragma (pop[, id])
340 PSK_Pop_Set, // #pragma (pop[, id], "name")
343 /// \brief Whether to insert vtordisps prior to virtual bases in the Microsoft
344 /// C++ ABI. Possible values are 0, 1, and 2, which mean:
346 /// 0: Suppress all vtordisps
347 /// 1: Insert vtordisps in the presence of vbase overrides and non-trivial
349 /// 2: Always insert vtordisps to support RTTI on partially constructed
352 /// The stack always has at least one element in it.
353 SmallVector<MSVtorDispAttr::Mode, 2> VtorDispModeStack;
355 /// Stack of active SEH __finally scopes. Can be empty.
356 SmallVector<Scope*, 2> CurrentSEHFinally;
358 /// \brief Source location for newly created implicit MSInheritanceAttrs
359 SourceLocation ImplicitMSInheritanceAttrLoc;
361 template<typename ValueType>
364 llvm::StringRef StackSlotLabel;
366 SourceLocation PragmaLocation;
367 Slot(llvm::StringRef StackSlotLabel,
369 SourceLocation PragmaLocation)
370 : StackSlotLabel(StackSlotLabel), Value(Value),
371 PragmaLocation(PragmaLocation) {}
373 void Act(SourceLocation PragmaLocation,
374 PragmaMsStackAction Action,
375 llvm::StringRef StackSlotLabel,
377 explicit PragmaStack(const ValueType &Value)
378 : CurrentValue(Value) {}
379 SmallVector<Slot, 2> Stack;
380 ValueType CurrentValue;
381 SourceLocation CurrentPragmaLocation;
383 // FIXME: We should serialize / deserialize these if they occur in a PCH (but
384 // we shouldn't do so if they're in a module).
385 PragmaStack<StringLiteral *> DataSegStack;
386 PragmaStack<StringLiteral *> BSSSegStack;
387 PragmaStack<StringLiteral *> ConstSegStack;
388 PragmaStack<StringLiteral *> CodeSegStack;
390 /// A mapping that describes the nullability we've seen in each header file.
391 FileNullabilityMap NullabilityMap;
393 /// Last section used with #pragma init_seg.
394 StringLiteral *CurInitSeg;
395 SourceLocation CurInitSegLoc;
397 /// VisContext - Manages the stack for \#pragma GCC visibility.
398 void *VisContext; // Really a "PragmaVisStack*"
400 /// \brief This represents the last location of a "#pragma clang optimize off"
401 /// directive if such a directive has not been closed by an "on" yet. If
402 /// optimizations are currently "on", this is set to an invalid location.
403 SourceLocation OptimizeOffPragmaLocation;
405 /// \brief Flag indicating if Sema is building a recovery call expression.
407 /// This flag is used to avoid building recovery call expressions
408 /// if Sema is already doing so, which would cause infinite recursions.
409 bool IsBuildingRecoveryCallExpr;
411 /// ExprNeedsCleanups - True if the current evaluation context
412 /// requires cleanups to be run at its conclusion.
413 bool ExprNeedsCleanups;
415 /// ExprCleanupObjects - This is the stack of objects requiring
416 /// cleanup that are created by the current full expression. The
417 /// element type here is ExprWithCleanups::Object.
418 SmallVector<BlockDecl*, 8> ExprCleanupObjects;
420 /// \brief Store a list of either DeclRefExprs or MemberExprs
421 /// that contain a reference to a variable (constant) that may or may not
422 /// be odr-used in this Expr, and we won't know until all lvalue-to-rvalue
423 /// and discarded value conversions have been applied to all subexpressions
424 /// of the enclosing full expression. This is cleared at the end of each
426 llvm::SmallPtrSet<Expr*, 2> MaybeODRUseExprs;
428 /// \brief Stack containing information about each of the nested
429 /// function, block, and method scopes that are currently active.
431 /// This array is never empty. Clients should ignore the first
432 /// element, which is used to cache a single FunctionScopeInfo
433 /// that's used to parse every top-level function.
434 SmallVector<sema::FunctionScopeInfo *, 4> FunctionScopes;
436 typedef LazyVector<TypedefNameDecl *, ExternalSemaSource,
437 &ExternalSemaSource::ReadExtVectorDecls, 2, 2>
440 /// ExtVectorDecls - This is a list all the extended vector types. This allows
441 /// us to associate a raw vector type with one of the ext_vector type names.
442 /// This is only necessary for issuing pretty diagnostics.
443 ExtVectorDeclsType ExtVectorDecls;
445 /// FieldCollector - Collects CXXFieldDecls during parsing of C++ classes.
446 std::unique_ptr<CXXFieldCollector> FieldCollector;
448 typedef llvm::SmallSetVector<const NamedDecl*, 16> NamedDeclSetType;
450 /// \brief Set containing all declared private fields that are not used.
451 NamedDeclSetType UnusedPrivateFields;
453 /// \brief Set containing all typedefs that are likely unused.
454 llvm::SmallSetVector<const TypedefNameDecl *, 4>
455 UnusedLocalTypedefNameCandidates;
457 /// \brief Delete-expressions to be analyzed at the end of translation unit
459 /// This list contains class members, and locations of delete-expressions
460 /// that could not be proven as to whether they mismatch with new-expression
461 /// used in initializer of the field.
462 typedef std::pair<SourceLocation, bool> DeleteExprLoc;
463 typedef llvm::SmallVector<DeleteExprLoc, 4> DeleteLocs;
464 llvm::MapVector<FieldDecl *, DeleteLocs> DeleteExprs;
466 typedef llvm::SmallPtrSet<const CXXRecordDecl*, 8> RecordDeclSetTy;
468 /// PureVirtualClassDiagSet - a set of class declarations which we have
469 /// emitted a list of pure virtual functions. Used to prevent emitting the
470 /// same list more than once.
471 std::unique_ptr<RecordDeclSetTy> PureVirtualClassDiagSet;
473 /// ParsingInitForAutoVars - a set of declarations with auto types for which
474 /// we are currently parsing the initializer.
475 llvm::SmallPtrSet<const Decl*, 4> ParsingInitForAutoVars;
477 /// \brief Look for a locally scoped extern "C" declaration by the given name.
478 NamedDecl *findLocallyScopedExternCDecl(DeclarationName Name);
480 typedef LazyVector<VarDecl *, ExternalSemaSource,
481 &ExternalSemaSource::ReadTentativeDefinitions, 2, 2>
482 TentativeDefinitionsType;
484 /// \brief All the tentative definitions encountered in the TU.
485 TentativeDefinitionsType TentativeDefinitions;
487 typedef LazyVector<const DeclaratorDecl *, ExternalSemaSource,
488 &ExternalSemaSource::ReadUnusedFileScopedDecls, 2, 2>
489 UnusedFileScopedDeclsType;
491 /// \brief The set of file scoped decls seen so far that have not been used
492 /// and must warn if not used. Only contains the first declaration.
493 UnusedFileScopedDeclsType UnusedFileScopedDecls;
495 typedef LazyVector<CXXConstructorDecl *, ExternalSemaSource,
496 &ExternalSemaSource::ReadDelegatingConstructors, 2, 2>
497 DelegatingCtorDeclsType;
499 /// \brief All the delegating constructors seen so far in the file, used for
500 /// cycle detection at the end of the TU.
501 DelegatingCtorDeclsType DelegatingCtorDecls;
503 /// \brief All the overriding functions seen during a class definition
504 /// that had their exception spec checks delayed, plus the overridden
506 SmallVector<std::pair<const CXXMethodDecl*, const CXXMethodDecl*>, 2>
507 DelayedExceptionSpecChecks;
509 /// \brief All the members seen during a class definition which were both
510 /// explicitly defaulted and had explicitly-specified exception
511 /// specifications, along with the function type containing their
512 /// user-specified exception specification. Those exception specifications
513 /// were overridden with the default specifications, but we still need to
514 /// check whether they are compatible with the default specification, and
515 /// we can't do that until the nesting set of class definitions is complete.
516 SmallVector<std::pair<CXXMethodDecl*, const FunctionProtoType*>, 2>
517 DelayedDefaultedMemberExceptionSpecs;
519 typedef llvm::MapVector<const FunctionDecl *, LateParsedTemplate *>
520 LateParsedTemplateMapT;
521 LateParsedTemplateMapT LateParsedTemplateMap;
523 /// \brief Callback to the parser to parse templated functions when needed.
524 typedef void LateTemplateParserCB(void *P, LateParsedTemplate &LPT);
525 typedef void LateTemplateParserCleanupCB(void *P);
526 LateTemplateParserCB *LateTemplateParser;
527 LateTemplateParserCleanupCB *LateTemplateParserCleanup;
530 void SetLateTemplateParser(LateTemplateParserCB *LTP,
531 LateTemplateParserCleanupCB *LTPCleanup,
533 LateTemplateParser = LTP;
534 LateTemplateParserCleanup = LTPCleanup;
538 class DelayedDiagnostics;
540 class DelayedDiagnosticsState {
541 sema::DelayedDiagnosticPool *SavedPool;
542 friend class Sema::DelayedDiagnostics;
544 typedef DelayedDiagnosticsState ParsingDeclState;
545 typedef DelayedDiagnosticsState ProcessingContextState;
547 /// A class which encapsulates the logic for delaying diagnostics
548 /// during parsing and other processing.
549 class DelayedDiagnostics {
550 /// \brief The current pool of diagnostics into which delayed
551 /// diagnostics should go.
552 sema::DelayedDiagnosticPool *CurPool;
555 DelayedDiagnostics() : CurPool(nullptr) {}
557 /// Adds a delayed diagnostic.
558 void add(const sema::DelayedDiagnostic &diag); // in DelayedDiagnostic.h
560 /// Determines whether diagnostics should be delayed.
561 bool shouldDelayDiagnostics() { return CurPool != nullptr; }
563 /// Returns the current delayed-diagnostics pool.
564 sema::DelayedDiagnosticPool *getCurrentPool() const {
568 /// Enter a new scope. Access and deprecation diagnostics will be
569 /// collected in this pool.
570 DelayedDiagnosticsState push(sema::DelayedDiagnosticPool &pool) {
571 DelayedDiagnosticsState state;
572 state.SavedPool = CurPool;
577 /// Leave a delayed-diagnostic state that was previously pushed.
578 /// Do not emit any of the diagnostics. This is performed as part
579 /// of the bookkeeping of popping a pool "properly".
580 void popWithoutEmitting(DelayedDiagnosticsState state) {
581 CurPool = state.SavedPool;
584 /// Enter a new scope where access and deprecation diagnostics are
586 DelayedDiagnosticsState pushUndelayed() {
587 DelayedDiagnosticsState state;
588 state.SavedPool = CurPool;
593 /// Undo a previous pushUndelayed().
594 void popUndelayed(DelayedDiagnosticsState state) {
595 assert(CurPool == nullptr);
596 CurPool = state.SavedPool;
598 } DelayedDiagnostics;
600 /// A RAII object to temporarily push a declaration context.
604 DeclContext *SavedContext;
605 ProcessingContextState SavedContextState;
606 QualType SavedCXXThisTypeOverride;
609 ContextRAII(Sema &S, DeclContext *ContextToPush, bool NewThisContext = true)
610 : S(S), SavedContext(S.CurContext),
611 SavedContextState(S.DelayedDiagnostics.pushUndelayed()),
612 SavedCXXThisTypeOverride(S.CXXThisTypeOverride)
614 assert(ContextToPush && "pushing null context");
615 S.CurContext = ContextToPush;
617 S.CXXThisTypeOverride = QualType();
621 if (!SavedContext) return;
622 S.CurContext = SavedContext;
623 S.DelayedDiagnostics.popUndelayed(SavedContextState);
624 S.CXXThisTypeOverride = SavedCXXThisTypeOverride;
625 SavedContext = nullptr;
633 /// \brief RAII object to handle the state changes required to synthesize
635 class SynthesizedFunctionScope {
637 Sema::ContextRAII SavedContext;
640 SynthesizedFunctionScope(Sema &S, DeclContext *DC)
641 : S(S), SavedContext(S, DC)
643 S.PushFunctionScope();
644 S.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated);
647 ~SynthesizedFunctionScope() {
648 S.PopExpressionEvaluationContext();
649 S.PopFunctionScopeInfo();
653 /// WeakUndeclaredIdentifiers - Identifiers contained in
654 /// \#pragma weak before declared. rare. may alias another
655 /// identifier, declared or undeclared
656 llvm::MapVector<IdentifierInfo *, WeakInfo> WeakUndeclaredIdentifiers;
658 /// ExtnameUndeclaredIdentifiers - Identifiers contained in
659 /// \#pragma redefine_extname before declared. Used in Solaris system headers
660 /// to define functions that occur in multiple standards to call the version
661 /// in the currently selected standard.
662 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*> ExtnameUndeclaredIdentifiers;
665 /// \brief Load weak undeclared identifiers from the external source.
666 void LoadExternalWeakUndeclaredIdentifiers();
668 /// WeakTopLevelDecl - Translation-unit scoped declarations generated by
669 /// \#pragma weak during processing of other Decls.
670 /// I couldn't figure out a clean way to generate these in-line, so
671 /// we store them here and handle separately -- which is a hack.
672 /// It would be best to refactor this.
673 SmallVector<Decl*,2> WeakTopLevelDecl;
675 IdentifierResolver IdResolver;
677 /// Translation Unit Scope - useful to Objective-C actions that need
678 /// to lookup file scope declarations in the "ordinary" C decl namespace.
679 /// For example, user-defined classes, built-in "id" type, etc.
682 /// \brief The C++ "std" namespace, where the standard library resides.
683 LazyDeclPtr StdNamespace;
685 /// \brief The C++ "std::bad_alloc" class, which is defined by the C++
686 /// standard library.
687 LazyDeclPtr StdBadAlloc;
689 /// \brief The C++ "std::initializer_list" template, which is defined in
690 /// \<initializer_list>.
691 ClassTemplateDecl *StdInitializerList;
693 /// \brief The C++ "type_info" declaration, which is defined in \<typeinfo>.
694 RecordDecl *CXXTypeInfoDecl;
696 /// \brief The MSVC "_GUID" struct, which is defined in MSVC header files.
697 RecordDecl *MSVCGuidDecl;
699 /// \brief Caches identifiers/selectors for NSFoundation APIs.
700 std::unique_ptr<NSAPI> NSAPIObj;
702 /// \brief The declaration of the Objective-C NSNumber class.
703 ObjCInterfaceDecl *NSNumberDecl;
705 /// \brief The declaration of the Objective-C NSValue class.
706 ObjCInterfaceDecl *NSValueDecl;
708 /// \brief Pointer to NSNumber type (NSNumber *).
709 QualType NSNumberPointer;
711 /// \brief Pointer to NSValue type (NSValue *).
712 QualType NSValuePointer;
714 /// \brief The Objective-C NSNumber methods used to create NSNumber literals.
715 ObjCMethodDecl *NSNumberLiteralMethods[NSAPI::NumNSNumberLiteralMethods];
717 /// \brief The declaration of the Objective-C NSString class.
718 ObjCInterfaceDecl *NSStringDecl;
720 /// \brief Pointer to NSString type (NSString *).
721 QualType NSStringPointer;
723 /// \brief The declaration of the stringWithUTF8String: method.
724 ObjCMethodDecl *StringWithUTF8StringMethod;
726 /// \brief The declaration of the valueWithBytes:objCType: method.
727 ObjCMethodDecl *ValueWithBytesObjCTypeMethod;
729 /// \brief The declaration of the Objective-C NSArray class.
730 ObjCInterfaceDecl *NSArrayDecl;
732 /// \brief Pointer to NSMutableArray type (NSMutableArray *).
733 QualType NSMutableArrayPointer;
735 /// \brief The declaration of the arrayWithObjects:count: method.
736 ObjCMethodDecl *ArrayWithObjectsMethod;
738 /// \brief The declaration of the Objective-C NSDictionary class.
739 ObjCInterfaceDecl *NSDictionaryDecl;
741 /// \brief Pointer to NSMutableDictionary type (NSMutableDictionary *).
742 QualType NSMutableDictionaryPointer;
744 /// \brief Pointer to NSMutableSet type (NSMutableSet *).
745 QualType NSMutableSetPointer;
747 /// \brief Pointer to NSCountedSet type (NSCountedSet *).
748 QualType NSCountedSetPointer;
750 /// \brief Pointer to NSMutableOrderedSet type (NSMutableOrderedSet *).
751 QualType NSMutableOrderedSetPointer;
753 /// \brief The declaration of the dictionaryWithObjects:forKeys:count: method.
754 ObjCMethodDecl *DictionaryWithObjectsMethod;
756 /// \brief id<NSCopying> type.
757 QualType QIDNSCopying;
759 /// \brief will hold 'respondsToSelector:'
760 Selector RespondsToSelectorSel;
762 /// \brief counter for internal MS Asm label names.
763 unsigned MSAsmLabelNameCounter;
765 /// A flag to remember whether the implicit forms of operator new and delete
766 /// have been declared.
767 bool GlobalNewDeleteDeclared;
769 /// A flag to indicate that we're in a context that permits abstract
770 /// references to fields. This is really a
771 bool AllowAbstractFieldReference;
773 /// \brief Describes how the expressions currently being parsed are
774 /// evaluated at run-time, if at all.
775 enum ExpressionEvaluationContext {
776 /// \brief The current expression and its subexpressions occur within an
777 /// unevaluated operand (C++11 [expr]p7), such as the subexpression of
778 /// \c sizeof, where the type of the expression may be significant but
779 /// no code will be generated to evaluate the value of the expression at
783 /// \brief The current expression occurs within an unevaluated
784 /// operand that unconditionally permits abstract references to
785 /// fields, such as a SIZE operator in MS-style inline assembly.
788 /// \brief The current context is "potentially evaluated" in C++11 terms,
789 /// but the expression is evaluated at compile-time (like the values of
790 /// cases in a switch statement).
793 /// \brief The current expression is potentially evaluated at run time,
794 /// which means that code may be generated to evaluate the value of the
795 /// expression at run time.
796 PotentiallyEvaluated,
798 /// \brief The current expression is potentially evaluated, but any
799 /// declarations referenced inside that expression are only used if
800 /// in fact the current expression is used.
802 /// This value is used when parsing default function arguments, for which
803 /// we would like to provide diagnostics (e.g., passing non-POD arguments
804 /// through varargs) but do not want to mark declarations as "referenced"
805 /// until the default argument is used.
806 PotentiallyEvaluatedIfUsed
809 /// \brief Data structure used to record current or nested
810 /// expression evaluation contexts.
811 struct ExpressionEvaluationContextRecord {
812 /// \brief The expression evaluation context.
813 ExpressionEvaluationContext Context;
815 /// \brief Whether the enclosing context needed a cleanup.
816 bool ParentNeedsCleanups;
818 /// \brief Whether we are in a decltype expression.
821 /// \brief The number of active cleanup objects when we entered
822 /// this expression evaluation context.
823 unsigned NumCleanupObjects;
825 /// \brief The number of typos encountered during this expression evaluation
826 /// context (i.e. the number of TypoExprs created).
829 llvm::SmallPtrSet<Expr*, 2> SavedMaybeODRUseExprs;
831 /// \brief The lambdas that are present within this context, if it
832 /// is indeed an unevaluated context.
833 SmallVector<LambdaExpr *, 2> Lambdas;
835 /// \brief The declaration that provides context for lambda expressions
836 /// and block literals if the normal declaration context does not
837 /// suffice, e.g., in a default function argument.
838 Decl *ManglingContextDecl;
840 /// \brief The context information used to mangle lambda expressions
841 /// and block literals within this context.
843 /// This mangling information is allocated lazily, since most contexts
844 /// do not have lambda expressions or block literals.
845 IntrusiveRefCntPtr<MangleNumberingContext> MangleNumbering;
847 /// \brief If we are processing a decltype type, a set of call expressions
848 /// for which we have deferred checking the completeness of the return type.
849 SmallVector<CallExpr *, 8> DelayedDecltypeCalls;
851 /// \brief If we are processing a decltype type, a set of temporary binding
852 /// expressions for which we have deferred checking the destructor.
853 SmallVector<CXXBindTemporaryExpr *, 8> DelayedDecltypeBinds;
855 ExpressionEvaluationContextRecord(ExpressionEvaluationContext Context,
856 unsigned NumCleanupObjects,
857 bool ParentNeedsCleanups,
858 Decl *ManglingContextDecl,
860 : Context(Context), ParentNeedsCleanups(ParentNeedsCleanups),
861 IsDecltype(IsDecltype), NumCleanupObjects(NumCleanupObjects),
863 ManglingContextDecl(ManglingContextDecl), MangleNumbering() { }
865 /// \brief Retrieve the mangling numbering context, used to consistently
866 /// number constructs like lambdas for mangling.
867 MangleNumberingContext &getMangleNumberingContext(ASTContext &Ctx);
869 bool isUnevaluated() const {
870 return Context == Unevaluated || Context == UnevaluatedAbstract;
874 /// A stack of expression evaluation contexts.
875 SmallVector<ExpressionEvaluationContextRecord, 8> ExprEvalContexts;
877 /// \brief Compute the mangling number context for a lambda expression or
880 /// \param DC - The DeclContext containing the lambda expression or
882 /// \param[out] ManglingContextDecl - Returns the ManglingContextDecl
883 /// associated with the context, if relevant.
884 MangleNumberingContext *getCurrentMangleNumberContext(
885 const DeclContext *DC,
886 Decl *&ManglingContextDecl);
889 /// SpecialMemberOverloadResult - The overloading result for a special member
892 /// This is basically a wrapper around PointerIntPair. The lowest bits of the
893 /// integer are used to determine whether overload resolution succeeded.
894 class SpecialMemberOverloadResult : public llvm::FastFoldingSetNode {
903 llvm::PointerIntPair<CXXMethodDecl*, 2> Pair;
906 SpecialMemberOverloadResult(const llvm::FoldingSetNodeID &ID)
907 : FastFoldingSetNode(ID)
910 CXXMethodDecl *getMethod() const { return Pair.getPointer(); }
911 void setMethod(CXXMethodDecl *MD) { Pair.setPointer(MD); }
913 Kind getKind() const { return static_cast<Kind>(Pair.getInt()); }
914 void setKind(Kind K) { Pair.setInt(K); }
917 /// \brief A cache of special member function overload resolution results
919 llvm::FoldingSet<SpecialMemberOverloadResult> SpecialMemberCache;
921 /// \brief The kind of translation unit we are processing.
923 /// When we're processing a complete translation unit, Sema will perform
924 /// end-of-translation-unit semantic tasks (such as creating
925 /// initializers for tentative definitions in C) once parsing has
926 /// completed. Modules and precompiled headers perform different kinds of
928 TranslationUnitKind TUKind;
930 llvm::BumpPtrAllocator BumpAlloc;
932 /// \brief The number of SFINAE diagnostics that have been trapped.
933 unsigned NumSFINAEErrors;
935 typedef llvm::DenseMap<ParmVarDecl *, llvm::TinyPtrVector<ParmVarDecl *>>
936 UnparsedDefaultArgInstantiationsMap;
938 /// \brief A mapping from parameters with unparsed default arguments to the
939 /// set of instantiations of each parameter.
941 /// This mapping is a temporary data structure used when parsing
942 /// nested class templates or nested classes of class templates,
943 /// where we might end up instantiating an inner class before the
944 /// default arguments of its methods have been parsed.
945 UnparsedDefaultArgInstantiationsMap UnparsedDefaultArgInstantiations;
947 // Contains the locations of the beginning of unparsed default
948 // argument locations.
949 llvm::DenseMap<ParmVarDecl *, SourceLocation> UnparsedDefaultArgLocs;
951 /// UndefinedInternals - all the used, undefined objects which require a
952 /// definition in this translation unit.
953 llvm::DenseMap<NamedDecl *, SourceLocation> UndefinedButUsed;
955 /// Obtain a sorted list of functions that are undefined but ODR-used.
956 void getUndefinedButUsed(
957 SmallVectorImpl<std::pair<NamedDecl *, SourceLocation> > &Undefined);
959 /// Retrieves list of suspicious delete-expressions that will be checked at
960 /// the end of translation unit.
961 const llvm::MapVector<FieldDecl *, DeleteLocs> &
962 getMismatchingDeleteExpressions() const;
964 typedef std::pair<ObjCMethodList, ObjCMethodList> GlobalMethods;
965 typedef llvm::DenseMap<Selector, GlobalMethods> GlobalMethodPool;
967 /// Method Pool - allows efficient lookup when typechecking messages to "id".
968 /// We need to maintain a list, since selectors can have differing signatures
969 /// across classes. In Cocoa, this happens to be extremely uncommon (only 1%
970 /// of selectors are "overloaded").
971 /// At the head of the list it is recorded whether there were 0, 1, or >= 2
972 /// methods inside categories with a particular selector.
973 GlobalMethodPool MethodPool;
975 /// Method selectors used in a \@selector expression. Used for implementation
977 llvm::MapVector<Selector, SourceLocation> ReferencedSelectors;
979 /// Kinds of C++ special members.
980 enum CXXSpecialMember {
981 CXXDefaultConstructor,
990 typedef std::pair<CXXRecordDecl*, CXXSpecialMember> SpecialMemberDecl;
992 /// The C++ special members which we are currently in the process of
993 /// declaring. If this process recursively triggers the declaration of the
994 /// same special member, we should act as if it is not yet declared.
995 llvm::SmallSet<SpecialMemberDecl, 4> SpecialMembersBeingDeclared;
997 void ReadMethodPool(Selector Sel);
999 /// Private Helper predicate to check for 'self'.
1000 bool isSelfExpr(Expr *RExpr);
1001 bool isSelfExpr(Expr *RExpr, const ObjCMethodDecl *Method);
1003 /// \brief Cause the active diagnostic on the DiagosticsEngine to be
1004 /// emitted. This is closely coupled to the SemaDiagnosticBuilder class and
1005 /// should not be used elsewhere.
1006 void EmitCurrentDiagnostic(unsigned DiagID);
1008 /// Records and restores the FP_CONTRACT state on entry/exit of compound
1010 class FPContractStateRAII {
1012 FPContractStateRAII(Sema& S)
1013 : S(S), OldFPContractState(S.FPFeatures.fp_contract) {}
1014 ~FPContractStateRAII() {
1015 S.FPFeatures.fp_contract = OldFPContractState;
1019 bool OldFPContractState : 1;
1022 void addImplicitTypedef(StringRef Name, QualType T);
1025 Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer,
1026 TranslationUnitKind TUKind = TU_Complete,
1027 CodeCompleteConsumer *CompletionConsumer = nullptr);
1030 /// \brief Perform initialization that occurs after the parser has been
1031 /// initialized but before it parses anything.
1034 const LangOptions &getLangOpts() const { return LangOpts; }
1035 OpenCLOptions &getOpenCLOptions() { return OpenCLFeatures; }
1036 FPOptions &getFPOptions() { return FPFeatures; }
1038 DiagnosticsEngine &getDiagnostics() const { return Diags; }
1039 SourceManager &getSourceManager() const { return SourceMgr; }
1040 Preprocessor &getPreprocessor() const { return PP; }
1041 ASTContext &getASTContext() const { return Context; }
1042 ASTConsumer &getASTConsumer() const { return Consumer; }
1043 ASTMutationListener *getASTMutationListener() const;
1044 ExternalSemaSource* getExternalSource() const { return ExternalSource; }
1046 ///\brief Registers an external source. If an external source already exists,
1047 /// creates a multiplex external source and appends to it.
1049 ///\param[in] E - A non-null external sema source.
1051 void addExternalSource(ExternalSemaSource *E);
1053 void PrintStats() const;
1055 /// \brief Helper class that creates diagnostics with optional
1056 /// template instantiation stacks.
1058 /// This class provides a wrapper around the basic DiagnosticBuilder
1059 /// class that emits diagnostics. SemaDiagnosticBuilder is
1060 /// responsible for emitting the diagnostic (as DiagnosticBuilder
1061 /// does) and, if the diagnostic comes from inside a template
1062 /// instantiation, printing the template instantiation stack as
1064 class SemaDiagnosticBuilder : public DiagnosticBuilder {
1069 SemaDiagnosticBuilder(DiagnosticBuilder &DB, Sema &SemaRef, unsigned DiagID)
1070 : DiagnosticBuilder(DB), SemaRef(SemaRef), DiagID(DiagID) { }
1072 ~SemaDiagnosticBuilder() {
1073 // If we aren't active, there is nothing to do.
1074 if (!isActive()) return;
1076 // Otherwise, we need to emit the diagnostic. First flush the underlying
1077 // DiagnosticBuilder data, and clear the diagnostic builder itself so it
1078 // won't emit the diagnostic in its own destructor.
1080 // This seems wasteful, in that as written the DiagnosticBuilder dtor will
1081 // do its own needless checks to see if the diagnostic needs to be
1082 // emitted. However, because we take care to ensure that the builder
1083 // objects never escape, a sufficiently smart compiler will be able to
1084 // eliminate that code.
1088 // Dispatch to Sema to emit the diagnostic.
1089 SemaRef.EmitCurrentDiagnostic(DiagID);
1092 /// Teach operator<< to produce an object of the correct type.
1093 template<typename T>
1094 friend const SemaDiagnosticBuilder &operator<<(
1095 const SemaDiagnosticBuilder &Diag, const T &Value) {
1096 const DiagnosticBuilder &BaseDiag = Diag;
1102 /// \brief Emit a diagnostic.
1103 SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID) {
1104 DiagnosticBuilder DB = Diags.Report(Loc, DiagID);
1105 return SemaDiagnosticBuilder(DB, *this, DiagID);
1108 /// \brief Emit a partial diagnostic.
1109 SemaDiagnosticBuilder Diag(SourceLocation Loc, const PartialDiagnostic& PD);
1111 /// \brief Build a partial diagnostic.
1112 PartialDiagnostic PDiag(unsigned DiagID = 0); // in SemaInternal.h
1114 bool findMacroSpelling(SourceLocation &loc, StringRef name);
1116 /// \brief Get a string to suggest for zero-initialization of a type.
1118 getFixItZeroInitializerForType(QualType T, SourceLocation Loc) const;
1119 std::string getFixItZeroLiteralForType(QualType T, SourceLocation Loc) const;
1121 /// \brief Calls \c Lexer::getLocForEndOfToken()
1122 SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset = 0);
1124 /// \brief Retrieve the module loader associated with the preprocessor.
1125 ModuleLoader &getModuleLoader() const;
1127 void emitAndClearUnusedLocalTypedefWarnings();
1129 void ActOnEndOfTranslationUnit();
1131 void CheckDelegatingCtorCycles();
1133 Scope *getScopeForContext(DeclContext *Ctx);
1135 void PushFunctionScope();
1136 void PushBlockScope(Scope *BlockScope, BlockDecl *Block);
1137 sema::LambdaScopeInfo *PushLambdaScope();
1139 /// \brief This is used to inform Sema what the current TemplateParameterDepth
1140 /// is during Parsing. Currently it is used to pass on the depth
1141 /// when parsing generic lambda 'auto' parameters.
1142 void RecordParsingTemplateParameterDepth(unsigned Depth);
1144 void PushCapturedRegionScope(Scope *RegionScope, CapturedDecl *CD,
1146 CapturedRegionKind K);
1148 PopFunctionScopeInfo(const sema::AnalysisBasedWarnings::Policy *WP = nullptr,
1149 const Decl *D = nullptr,
1150 const BlockExpr *blkExpr = nullptr);
1152 sema::FunctionScopeInfo *getCurFunction() const {
1153 return FunctionScopes.back();
1156 sema::FunctionScopeInfo *getEnclosingFunction() const {
1157 if (FunctionScopes.empty())
1160 for (int e = FunctionScopes.size()-1; e >= 0; --e) {
1161 if (isa<sema::BlockScopeInfo>(FunctionScopes[e]))
1163 return FunctionScopes[e];
1168 template <typename ExprT>
1169 void recordUseOfEvaluatedWeak(const ExprT *E, bool IsRead=true) {
1170 if (!isUnevaluatedContext())
1171 getCurFunction()->recordUseOfWeak(E, IsRead);
1174 void PushCompoundScope();
1175 void PopCompoundScope();
1177 sema::CompoundScopeInfo &getCurCompoundScope() const;
1179 bool hasAnyUnrecoverableErrorsInThisFunction() const;
1181 /// \brief Retrieve the current block, if any.
1182 sema::BlockScopeInfo *getCurBlock();
1184 /// \brief Retrieve the current lambda scope info, if any.
1185 sema::LambdaScopeInfo *getCurLambda();
1187 /// \brief Retrieve the current generic lambda info, if any.
1188 sema::LambdaScopeInfo *getCurGenericLambda();
1190 /// \brief Retrieve the current captured region, if any.
1191 sema::CapturedRegionScopeInfo *getCurCapturedRegion();
1193 /// WeakTopLevelDeclDecls - access to \#pragma weak-generated Decls
1194 SmallVectorImpl<Decl *> &WeakTopLevelDecls() { return WeakTopLevelDecl; }
1196 void ActOnComment(SourceRange Comment);
1198 //===--------------------------------------------------------------------===//
1199 // Type Analysis / Processing: SemaType.cpp.
1202 QualType BuildQualifiedType(QualType T, SourceLocation Loc, Qualifiers Qs,
1203 const DeclSpec *DS = nullptr);
1204 QualType BuildQualifiedType(QualType T, SourceLocation Loc, unsigned CVRA,
1205 const DeclSpec *DS = nullptr);
1206 QualType BuildPointerType(QualType T,
1207 SourceLocation Loc, DeclarationName Entity);
1208 QualType BuildReferenceType(QualType T, bool LValueRef,
1209 SourceLocation Loc, DeclarationName Entity);
1210 QualType BuildArrayType(QualType T, ArrayType::ArraySizeModifier ASM,
1211 Expr *ArraySize, unsigned Quals,
1212 SourceRange Brackets, DeclarationName Entity);
1213 QualType BuildExtVectorType(QualType T, Expr *ArraySize,
1214 SourceLocation AttrLoc);
1216 bool CheckFunctionReturnType(QualType T, SourceLocation Loc);
1218 unsigned deduceWeakPropertyFromType(QualType T) {
1219 if ((getLangOpts().getGC() != LangOptions::NonGC &&
1220 T.isObjCGCWeak()) ||
1221 (getLangOpts().ObjCAutoRefCount &&
1222 T.getObjCLifetime() == Qualifiers::OCL_Weak))
1223 return ObjCDeclSpec::DQ_PR_weak;
1228 /// \brief Build a function type.
1230 /// This routine checks the function type according to C++ rules and
1231 /// under the assumption that the result type and parameter types have
1232 /// just been instantiated from a template. It therefore duplicates
1233 /// some of the behavior of GetTypeForDeclarator, but in a much
1234 /// simpler form that is only suitable for this narrow use case.
1236 /// \param T The return type of the function.
1238 /// \param ParamTypes The parameter types of the function. This array
1239 /// will be modified to account for adjustments to the types of the
1240 /// function parameters.
1242 /// \param Loc The location of the entity whose type involves this
1243 /// function type or, if there is no such entity, the location of the
1244 /// type that will have function type.
1246 /// \param Entity The name of the entity that involves the function
1249 /// \param EPI Extra information about the function type. Usually this will
1250 /// be taken from an existing function with the same prototype.
1252 /// \returns A suitable function type, if there are no errors. The
1253 /// unqualified type will always be a FunctionProtoType.
1254 /// Otherwise, returns a NULL type.
1255 QualType BuildFunctionType(QualType T,
1256 MutableArrayRef<QualType> ParamTypes,
1257 SourceLocation Loc, DeclarationName Entity,
1258 const FunctionProtoType::ExtProtoInfo &EPI);
1260 QualType BuildMemberPointerType(QualType T, QualType Class,
1262 DeclarationName Entity);
1263 QualType BuildBlockPointerType(QualType T,
1264 SourceLocation Loc, DeclarationName Entity);
1265 QualType BuildParenType(QualType T);
1266 QualType BuildAtomicType(QualType T, SourceLocation Loc);
1268 TypeSourceInfo *GetTypeForDeclarator(Declarator &D, Scope *S);
1269 TypeSourceInfo *GetTypeForDeclaratorCast(Declarator &D, QualType FromTy);
1270 TypeSourceInfo *GetTypeSourceInfoForDeclarator(Declarator &D, QualType T,
1271 TypeSourceInfo *ReturnTypeInfo);
1273 /// \brief Package the given type and TSI into a ParsedType.
1274 ParsedType CreateParsedType(QualType T, TypeSourceInfo *TInfo);
1275 DeclarationNameInfo GetNameForDeclarator(Declarator &D);
1276 DeclarationNameInfo GetNameFromUnqualifiedId(const UnqualifiedId &Name);
1277 static QualType GetTypeFromParser(ParsedType Ty,
1278 TypeSourceInfo **TInfo = nullptr);
1279 CanThrowResult canThrow(const Expr *E);
1280 const FunctionProtoType *ResolveExceptionSpec(SourceLocation Loc,
1281 const FunctionProtoType *FPT);
1282 void UpdateExceptionSpec(FunctionDecl *FD,
1283 const FunctionProtoType::ExceptionSpecInfo &ESI);
1284 bool CheckSpecifiedExceptionType(QualType &T, const SourceRange &Range);
1285 bool CheckDistantExceptionSpec(QualType T);
1286 bool CheckEquivalentExceptionSpec(FunctionDecl *Old, FunctionDecl *New);
1287 bool CheckEquivalentExceptionSpec(
1288 const FunctionProtoType *Old, SourceLocation OldLoc,
1289 const FunctionProtoType *New, SourceLocation NewLoc);
1290 bool CheckEquivalentExceptionSpec(
1291 const PartialDiagnostic &DiagID, const PartialDiagnostic & NoteID,
1292 const FunctionProtoType *Old, SourceLocation OldLoc,
1293 const FunctionProtoType *New, SourceLocation NewLoc,
1294 bool *MissingExceptionSpecification = nullptr,
1295 bool *MissingEmptyExceptionSpecification = nullptr,
1296 bool AllowNoexceptAllMatchWithNoSpec = false,
1297 bool IsOperatorNew = false);
1298 bool CheckExceptionSpecSubset(
1299 const PartialDiagnostic &DiagID, const PartialDiagnostic & NoteID,
1300 const FunctionProtoType *Superset, SourceLocation SuperLoc,
1301 const FunctionProtoType *Subset, SourceLocation SubLoc);
1302 bool CheckParamExceptionSpec(const PartialDiagnostic & NoteID,
1303 const FunctionProtoType *Target, SourceLocation TargetLoc,
1304 const FunctionProtoType *Source, SourceLocation SourceLoc);
1306 TypeResult ActOnTypeName(Scope *S, Declarator &D);
1308 /// \brief The parser has parsed the context-sensitive type 'instancetype'
1309 /// in an Objective-C message declaration. Return the appropriate type.
1310 ParsedType ActOnObjCInstanceType(SourceLocation Loc);
1312 /// \brief Abstract class used to diagnose incomplete types.
1313 struct TypeDiagnoser {
1316 TypeDiagnoser(bool Suppressed = false) : Suppressed(Suppressed) { }
1318 virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) = 0;
1319 virtual ~TypeDiagnoser() {}
1322 static int getPrintable(int I) { return I; }
1323 static unsigned getPrintable(unsigned I) { return I; }
1324 static bool getPrintable(bool B) { return B; }
1325 static const char * getPrintable(const char *S) { return S; }
1326 static StringRef getPrintable(StringRef S) { return S; }
1327 static const std::string &getPrintable(const std::string &S) { return S; }
1328 static const IdentifierInfo *getPrintable(const IdentifierInfo *II) {
1331 static DeclarationName getPrintable(DeclarationName N) { return N; }
1332 static QualType getPrintable(QualType T) { return T; }
1333 static SourceRange getPrintable(SourceRange R) { return R; }
1334 static SourceRange getPrintable(SourceLocation L) { return L; }
1335 static SourceRange getPrintable(const Expr *E) { return E->getSourceRange(); }
1336 static SourceRange getPrintable(TypeLoc TL) { return TL.getSourceRange();}
1338 template <typename... Ts> class BoundTypeDiagnoser : public TypeDiagnoser {
1340 std::tuple<const Ts &...> Args;
1342 template <std::size_t... Is>
1343 void emit(const SemaDiagnosticBuilder &DB,
1344 llvm::index_sequence<Is...>) const {
1345 // Apply all tuple elements to the builder in order.
1346 bool Dummy[] = {(DB << getPrintable(std::get<Is>(Args)))...};
1351 BoundTypeDiagnoser(unsigned DiagID, const Ts &...Args)
1352 : TypeDiagnoser(DiagID == 0), DiagID(DiagID), Args(Args...) {}
1354 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
1357 const SemaDiagnosticBuilder &DB = S.Diag(Loc, DiagID);
1358 emit(DB, llvm::index_sequence_for<Ts...>());
1364 bool RequireCompleteTypeImpl(SourceLocation Loc, QualType T,
1365 TypeDiagnoser &Diagnoser);
1367 VisibleModuleSet VisibleModules;
1368 llvm::SmallVector<VisibleModuleSet, 16> VisibleModulesStack;
1370 Module *CachedFakeTopLevelModule;
1373 /// \brief Get the module owning an entity.
1374 Module *getOwningModule(Decl *Entity);
1376 /// \brief Make a merged definition of an existing hidden definition \p ND
1377 /// visible at the specified location.
1378 void makeMergedDefinitionVisible(NamedDecl *ND, SourceLocation Loc);
1380 bool isModuleVisible(Module *M) { return VisibleModules.isVisible(M); }
1382 /// Determine whether a declaration is visible to name lookup.
1383 bool isVisible(const NamedDecl *D) {
1384 return !D->isHidden() || isVisibleSlow(D);
1386 bool hasVisibleMergedDefinition(NamedDecl *Def);
1388 /// Determine if \p D has a visible definition. If not, suggest a declaration
1389 /// that should be made visible to expose the definition.
1390 bool hasVisibleDefinition(NamedDecl *D, NamedDecl **Suggested,
1391 bool OnlyNeedComplete = false);
1392 bool hasVisibleDefinition(const NamedDecl *D) {
1394 return hasVisibleDefinition(const_cast<NamedDecl*>(D), &Hidden);
1397 /// Determine if the template parameter \p D has a visible default argument.
1399 hasVisibleDefaultArgument(const NamedDecl *D,
1400 llvm::SmallVectorImpl<Module *> *Modules = nullptr);
1402 bool RequireCompleteType(SourceLocation Loc, QualType T,
1403 TypeDiagnoser &Diagnoser);
1404 bool RequireCompleteType(SourceLocation Loc, QualType T,
1407 template <typename... Ts>
1408 bool RequireCompleteType(SourceLocation Loc, QualType T, unsigned DiagID,
1409 const Ts &...Args) {
1410 BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
1411 return RequireCompleteType(Loc, T, Diagnoser);
1414 bool RequireCompleteExprType(Expr *E, TypeDiagnoser &Diagnoser);
1415 bool RequireCompleteExprType(Expr *E, unsigned DiagID);
1417 template <typename... Ts>
1418 bool RequireCompleteExprType(Expr *E, unsigned DiagID, const Ts &...Args) {
1419 BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
1420 return RequireCompleteExprType(E, Diagnoser);
1423 bool RequireLiteralType(SourceLocation Loc, QualType T,
1424 TypeDiagnoser &Diagnoser);
1425 bool RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID);
1427 template <typename... Ts>
1428 bool RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID,
1429 const Ts &...Args) {
1430 BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
1431 return RequireLiteralType(Loc, T, Diagnoser);
1434 QualType getElaboratedType(ElaboratedTypeKeyword Keyword,
1435 const CXXScopeSpec &SS, QualType T);
1437 QualType BuildTypeofExprType(Expr *E, SourceLocation Loc);
1438 /// If AsUnevaluated is false, E is treated as though it were an evaluated
1439 /// context, such as when building a type for decltype(auto).
1440 QualType BuildDecltypeType(Expr *E, SourceLocation Loc,
1441 bool AsUnevaluated = true);
1442 QualType BuildUnaryTransformType(QualType BaseType,
1443 UnaryTransformType::UTTKind UKind,
1444 SourceLocation Loc);
1446 //===--------------------------------------------------------------------===//
1447 // Symbol table / Decl tracking callbacks: SemaDecl.cpp.
1450 /// List of decls defined in a function prototype. This contains EnumConstants
1451 /// that incorrectly end up in translation unit scope because there is no
1452 /// function to pin them on. ActOnFunctionDeclarator reads this list and patches
1453 /// them into the FunctionDecl.
1454 std::vector<NamedDecl*> DeclsInPrototypeScope;
1456 DeclGroupPtrTy ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType = nullptr);
1458 void DiagnoseUseOfUnimplementedSelectors();
1460 bool isSimpleTypeSpecifier(tok::TokenKind Kind) const;
1462 ParsedType getTypeName(const IdentifierInfo &II, SourceLocation NameLoc,
1463 Scope *S, CXXScopeSpec *SS = nullptr,
1464 bool isClassName = false,
1465 bool HasTrailingDot = false,
1466 ParsedType ObjectType = ParsedType(),
1467 bool IsCtorOrDtorName = false,
1468 bool WantNontrivialTypeSourceInfo = false,
1469 IdentifierInfo **CorrectedII = nullptr);
1470 TypeSpecifierType isTagName(IdentifierInfo &II, Scope *S);
1471 bool isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S);
1472 void DiagnoseUnknownTypeName(IdentifierInfo *&II,
1473 SourceLocation IILoc,
1476 ParsedType &SuggestedType,
1477 bool AllowClassTemplates = false);
1479 /// \brief For compatibility with MSVC, we delay parsing of some default
1480 /// template type arguments until instantiation time. Emits a warning and
1481 /// returns a synthesized DependentNameType that isn't really dependent on any
1482 /// other template arguments.
1483 ParsedType ActOnDelayedDefaultTemplateArg(const IdentifierInfo &II,
1484 SourceLocation NameLoc);
1486 /// \brief Describes the result of the name lookup and resolution performed
1487 /// by \c ClassifyName().
1488 enum NameClassificationKind {
1494 NC_NestedNameSpecifier,
1500 class NameClassification {
1501 NameClassificationKind Kind;
1503 TemplateName Template;
1505 const IdentifierInfo *Keyword;
1507 explicit NameClassification(NameClassificationKind Kind) : Kind(Kind) {}
1510 NameClassification(ExprResult Expr) : Kind(NC_Expression), Expr(Expr) {}
1512 NameClassification(ParsedType Type) : Kind(NC_Type), Type(Type) {}
1514 NameClassification(const IdentifierInfo *Keyword)
1515 : Kind(NC_Keyword), Keyword(Keyword) { }
1517 static NameClassification Error() {
1518 return NameClassification(NC_Error);
1521 static NameClassification Unknown() {
1522 return NameClassification(NC_Unknown);
1525 static NameClassification NestedNameSpecifier() {
1526 return NameClassification(NC_NestedNameSpecifier);
1529 static NameClassification TypeTemplate(TemplateName Name) {
1530 NameClassification Result(NC_TypeTemplate);
1531 Result.Template = Name;
1535 static NameClassification VarTemplate(TemplateName Name) {
1536 NameClassification Result(NC_VarTemplate);
1537 Result.Template = Name;
1541 static NameClassification FunctionTemplate(TemplateName Name) {
1542 NameClassification Result(NC_FunctionTemplate);
1543 Result.Template = Name;
1547 NameClassificationKind getKind() const { return Kind; }
1549 ParsedType getType() const {
1550 assert(Kind == NC_Type);
1554 ExprResult getExpression() const {
1555 assert(Kind == NC_Expression);
1559 TemplateName getTemplateName() const {
1560 assert(Kind == NC_TypeTemplate || Kind == NC_FunctionTemplate ||
1561 Kind == NC_VarTemplate);
1565 TemplateNameKind getTemplateNameKind() const {
1567 case NC_TypeTemplate:
1568 return TNK_Type_template;
1569 case NC_FunctionTemplate:
1570 return TNK_Function_template;
1571 case NC_VarTemplate:
1572 return TNK_Var_template;
1574 llvm_unreachable("unsupported name classification.");
1579 /// \brief Perform name lookup on the given name, classifying it based on
1580 /// the results of name lookup and the following token.
1582 /// This routine is used by the parser to resolve identifiers and help direct
1583 /// parsing. When the identifier cannot be found, this routine will attempt
1584 /// to correct the typo and classify based on the resulting name.
1586 /// \param S The scope in which we're performing name lookup.
1588 /// \param SS The nested-name-specifier that precedes the name.
1590 /// \param Name The identifier. If typo correction finds an alternative name,
1591 /// this pointer parameter will be updated accordingly.
1593 /// \param NameLoc The location of the identifier.
1595 /// \param NextToken The token following the identifier. Used to help
1596 /// disambiguate the name.
1598 /// \param IsAddressOfOperand True if this name is the operand of a unary
1599 /// address of ('&') expression, assuming it is classified as an
1602 /// \param CCC The correction callback, if typo correction is desired.
1604 ClassifyName(Scope *S, CXXScopeSpec &SS, IdentifierInfo *&Name,
1605 SourceLocation NameLoc, const Token &NextToken,
1606 bool IsAddressOfOperand,
1607 std::unique_ptr<CorrectionCandidateCallback> CCC = nullptr);
1609 Decl *ActOnDeclarator(Scope *S, Declarator &D);
1611 NamedDecl *HandleDeclarator(Scope *S, Declarator &D,
1612 MultiTemplateParamsArg TemplateParameterLists);
1613 void RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S);
1614 bool DiagnoseClassNameShadow(DeclContext *DC, DeclarationNameInfo Info);
1615 bool diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
1616 DeclarationName Name,
1617 SourceLocation Loc);
1619 diagnoseIgnoredQualifiers(unsigned DiagID, unsigned Quals,
1620 SourceLocation FallbackLoc,
1621 SourceLocation ConstQualLoc = SourceLocation(),
1622 SourceLocation VolatileQualLoc = SourceLocation(),
1623 SourceLocation RestrictQualLoc = SourceLocation(),
1624 SourceLocation AtomicQualLoc = SourceLocation());
1626 static bool adjustContextForLocalExternDecl(DeclContext *&DC);
1627 void DiagnoseFunctionSpecifiers(const DeclSpec &DS);
1628 void CheckShadow(Scope *S, VarDecl *D, const LookupResult& R);
1629 void CheckShadow(Scope *S, VarDecl *D);
1630 void CheckCastAlign(Expr *Op, QualType T, SourceRange TRange);
1631 void handleTagNumbering(const TagDecl *Tag, Scope *TagScope);
1632 void setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
1633 TypedefNameDecl *NewTD);
1634 void CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *D);
1635 NamedDecl* ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
1636 TypeSourceInfo *TInfo,
1637 LookupResult &Previous);
1638 NamedDecl* ActOnTypedefNameDecl(Scope* S, DeclContext* DC, TypedefNameDecl *D,
1639 LookupResult &Previous, bool &Redeclaration);
1640 NamedDecl *ActOnVariableDeclarator(Scope *S, Declarator &D, DeclContext *DC,
1641 TypeSourceInfo *TInfo,
1642 LookupResult &Previous,
1643 MultiTemplateParamsArg TemplateParamLists,
1645 // Returns true if the variable declaration is a redeclaration
1646 bool CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous);
1647 void CheckVariableDeclarationType(VarDecl *NewVD);
1648 void CheckCompleteVariableDeclaration(VarDecl *var);
1649 void MaybeSuggestAddingStaticToDecl(const FunctionDecl *D);
1651 NamedDecl* ActOnFunctionDeclarator(Scope* S, Declarator& D, DeclContext* DC,
1652 TypeSourceInfo *TInfo,
1653 LookupResult &Previous,
1654 MultiTemplateParamsArg TemplateParamLists,
1656 bool AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD);
1658 bool CheckConstexprFunctionDecl(const FunctionDecl *FD);
1659 bool CheckConstexprFunctionBody(const FunctionDecl *FD, Stmt *Body);
1661 void DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD);
1662 void FindHiddenVirtualMethods(CXXMethodDecl *MD,
1663 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods);
1664 void NoteHiddenVirtualMethods(CXXMethodDecl *MD,
1665 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods);
1666 // Returns true if the function declaration is a redeclaration
1667 bool CheckFunctionDeclaration(Scope *S,
1668 FunctionDecl *NewFD, LookupResult &Previous,
1669 bool IsExplicitSpecialization);
1670 void CheckMain(FunctionDecl *FD, const DeclSpec &D);
1671 void CheckMSVCRTEntryPoint(FunctionDecl *FD);
1672 Decl *ActOnParamDeclarator(Scope *S, Declarator &D);
1673 ParmVarDecl *BuildParmVarDeclForTypedef(DeclContext *DC,
1676 ParmVarDecl *CheckParameter(DeclContext *DC, SourceLocation StartLoc,
1677 SourceLocation NameLoc, IdentifierInfo *Name,
1678 QualType T, TypeSourceInfo *TSInfo,
1680 void ActOnParamDefaultArgument(Decl *param,
1681 SourceLocation EqualLoc,
1683 void ActOnParamUnparsedDefaultArgument(Decl *param,
1684 SourceLocation EqualLoc,
1685 SourceLocation ArgLoc);
1686 void ActOnParamDefaultArgumentError(Decl *param, SourceLocation EqualLoc);
1687 bool SetParamDefaultArgument(ParmVarDecl *Param, Expr *DefaultArg,
1688 SourceLocation EqualLoc);
1690 void AddInitializerToDecl(Decl *dcl, Expr *init, bool DirectInit,
1691 bool TypeMayContainAuto);
1692 void ActOnUninitializedDecl(Decl *dcl, bool TypeMayContainAuto);
1693 void ActOnInitializerError(Decl *Dcl);
1694 void ActOnPureSpecifier(Decl *D, SourceLocation PureSpecLoc);
1695 void ActOnCXXForRangeDecl(Decl *D);
1696 StmtResult ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc,
1697 IdentifierInfo *Ident,
1698 ParsedAttributes &Attrs,
1699 SourceLocation AttrEnd);
1700 void SetDeclDeleted(Decl *dcl, SourceLocation DelLoc);
1701 void SetDeclDefaulted(Decl *dcl, SourceLocation DefaultLoc);
1702 void FinalizeDeclaration(Decl *D);
1703 DeclGroupPtrTy FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
1704 ArrayRef<Decl *> Group);
1705 DeclGroupPtrTy BuildDeclaratorGroup(MutableArrayRef<Decl *> Group,
1706 bool TypeMayContainAuto = true);
1708 /// Should be called on all declarations that might have attached
1709 /// documentation comments.
1710 void ActOnDocumentableDecl(Decl *D);
1711 void ActOnDocumentableDecls(ArrayRef<Decl *> Group);
1713 void ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
1714 SourceLocation LocAfterDecls);
1715 void CheckForFunctionRedefinition(FunctionDecl *FD,
1716 const FunctionDecl *EffectiveDefinition =
1718 Decl *ActOnStartOfFunctionDef(Scope *S, Declarator &D);
1719 Decl *ActOnStartOfFunctionDef(Scope *S, Decl *D);
1720 void ActOnStartOfObjCMethodDef(Scope *S, Decl *D);
1721 bool isObjCMethodDecl(Decl *D) {
1722 return D && isa<ObjCMethodDecl>(D);
1725 /// \brief Determine whether we can delay parsing the body of a function or
1726 /// function template until it is used, assuming we don't care about emitting
1727 /// code for that function.
1729 /// This will be \c false if we may need the body of the function in the
1730 /// middle of parsing an expression (where it's impractical to switch to
1731 /// parsing a different function), for instance, if it's constexpr in C++11
1732 /// or has an 'auto' return type in C++14. These cases are essentially bugs.
1733 bool canDelayFunctionBody(const Declarator &D);
1735 /// \brief Determine whether we can skip parsing the body of a function
1736 /// definition, assuming we don't care about analyzing its body or emitting
1737 /// code for that function.
1739 /// This will be \c false only if we may need the body of the function in
1740 /// order to parse the rest of the program (for instance, if it is
1741 /// \c constexpr in C++11 or has an 'auto' return type in C++14).
1742 bool canSkipFunctionBody(Decl *D);
1744 void computeNRVO(Stmt *Body, sema::FunctionScopeInfo *Scope);
1745 Decl *ActOnFinishFunctionBody(Decl *Decl, Stmt *Body);
1746 Decl *ActOnFinishFunctionBody(Decl *Decl, Stmt *Body, bool IsInstantiation);
1747 Decl *ActOnSkippedFunctionBody(Decl *Decl);
1748 void ActOnFinishInlineMethodDef(CXXMethodDecl *D);
1750 /// ActOnFinishDelayedAttribute - Invoked when we have finished parsing an
1751 /// attribute for which parsing is delayed.
1752 void ActOnFinishDelayedAttribute(Scope *S, Decl *D, ParsedAttributes &Attrs);
1754 /// \brief Diagnose any unused parameters in the given sequence of
1755 /// ParmVarDecl pointers.
1756 void DiagnoseUnusedParameters(ParmVarDecl * const *Begin,
1757 ParmVarDecl * const *End);
1759 /// \brief Diagnose whether the size of parameters or return value of a
1760 /// function or obj-c method definition is pass-by-value and larger than a
1761 /// specified threshold.
1762 void DiagnoseSizeOfParametersAndReturnValue(ParmVarDecl * const *Begin,
1763 ParmVarDecl * const *End,
1767 void DiagnoseInvalidJumps(Stmt *Body);
1768 Decl *ActOnFileScopeAsmDecl(Expr *expr,
1769 SourceLocation AsmLoc,
1770 SourceLocation RParenLoc);
1772 /// \brief Handle a C++11 empty-declaration and attribute-declaration.
1773 Decl *ActOnEmptyDeclaration(Scope *S,
1774 AttributeList *AttrList,
1775 SourceLocation SemiLoc);
1777 /// \brief The parser has processed a module import declaration.
1779 /// \param AtLoc The location of the '@' symbol, if any.
1781 /// \param ImportLoc The location of the 'import' keyword.
1783 /// \param Path The module access path.
1784 DeclResult ActOnModuleImport(SourceLocation AtLoc, SourceLocation ImportLoc,
1787 /// \brief The parser has processed a module import translated from a
1788 /// #include or similar preprocessing directive.
1789 void ActOnModuleInclude(SourceLocation DirectiveLoc, Module *Mod);
1791 /// \brief The parsed has entered a submodule.
1792 void ActOnModuleBegin(SourceLocation DirectiveLoc, Module *Mod);
1793 /// \brief The parser has left a submodule.
1794 void ActOnModuleEnd(SourceLocation DirectiveLoc, Module *Mod);
1796 /// \brief Create an implicit import of the given module at the given
1797 /// source location, for error recovery, if possible.
1799 /// This routine is typically used when an entity found by name lookup
1800 /// is actually hidden within a module that we know about but the user
1801 /// has forgotten to import.
1802 void createImplicitModuleImportForErrorRecovery(SourceLocation Loc,
1805 /// Kinds of missing import. Note, the values of these enumerators correspond
1806 /// to %select values in diagnostics.
1807 enum class MissingImportKind {
1813 /// \brief Diagnose that the specified declaration needs to be visible but
1814 /// isn't, and suggest a module import that would resolve the problem.
1815 void diagnoseMissingImport(SourceLocation Loc, NamedDecl *Decl,
1816 bool NeedDefinition, bool Recover = true);
1817 void diagnoseMissingImport(SourceLocation Loc, NamedDecl *Decl,
1818 SourceLocation DeclLoc, ArrayRef<Module *> Modules,
1819 MissingImportKind MIK, bool Recover);
1821 /// \brief Retrieve a suitable printing policy.
1822 PrintingPolicy getPrintingPolicy() const {
1823 return getPrintingPolicy(Context, PP);
1826 /// \brief Retrieve a suitable printing policy.
1827 static PrintingPolicy getPrintingPolicy(const ASTContext &Ctx,
1828 const Preprocessor &PP);
1831 void ActOnPopScope(SourceLocation Loc, Scope *S);
1832 void ActOnTranslationUnitScope(Scope *S);
1834 Decl *ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS,
1836 Decl *ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS,
1838 MultiTemplateParamsArg TemplateParams,
1839 bool IsExplicitInstantiation = false);
1841 Decl *BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
1844 const PrintingPolicy &Policy);
1846 Decl *BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
1847 RecordDecl *Record);
1849 bool isAcceptableTagRedeclaration(const TagDecl *Previous,
1850 TagTypeKind NewTag, bool isDefinition,
1851 SourceLocation NewTagLoc,
1852 const IdentifierInfo *Name);
1855 TUK_Reference, // Reference to a tag: 'struct foo *X;'
1856 TUK_Declaration, // Fwd decl of a tag: 'struct foo;'
1857 TUK_Definition, // Definition of a tag: 'struct foo { int X; } Y;'
1858 TUK_Friend // Friend declaration: 'friend struct foo;'
1861 struct SkipBodyInfo {
1862 SkipBodyInfo() : ShouldSkip(false), Previous(nullptr) {}
1864 NamedDecl *Previous;
1867 Decl *ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
1868 SourceLocation KWLoc, CXXScopeSpec &SS,
1869 IdentifierInfo *Name, SourceLocation NameLoc,
1870 AttributeList *Attr, AccessSpecifier AS,
1871 SourceLocation ModulePrivateLoc,
1872 MultiTemplateParamsArg TemplateParameterLists,
1873 bool &OwnedDecl, bool &IsDependent,
1874 SourceLocation ScopedEnumKWLoc,
1875 bool ScopedEnumUsesClassTag, TypeResult UnderlyingType,
1876 bool IsTypeSpecifier, SkipBodyInfo *SkipBody = nullptr);
1878 Decl *ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
1879 unsigned TagSpec, SourceLocation TagLoc,
1881 IdentifierInfo *Name, SourceLocation NameLoc,
1882 AttributeList *Attr,
1883 MultiTemplateParamsArg TempParamLists);
1885 TypeResult ActOnDependentTag(Scope *S,
1888 const CXXScopeSpec &SS,
1889 IdentifierInfo *Name,
1890 SourceLocation TagLoc,
1891 SourceLocation NameLoc);
1893 void ActOnDefs(Scope *S, Decl *TagD, SourceLocation DeclStart,
1894 IdentifierInfo *ClassName,
1895 SmallVectorImpl<Decl *> &Decls);
1896 Decl *ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
1897 Declarator &D, Expr *BitfieldWidth);
1899 FieldDecl *HandleField(Scope *S, RecordDecl *TagD, SourceLocation DeclStart,
1900 Declarator &D, Expr *BitfieldWidth,
1901 InClassInitStyle InitStyle,
1902 AccessSpecifier AS);
1903 MSPropertyDecl *HandleMSProperty(Scope *S, RecordDecl *TagD,
1904 SourceLocation DeclStart,
1905 Declarator &D, Expr *BitfieldWidth,
1906 InClassInitStyle InitStyle,
1908 AttributeList *MSPropertyAttr);
1910 FieldDecl *CheckFieldDecl(DeclarationName Name, QualType T,
1911 TypeSourceInfo *TInfo,
1912 RecordDecl *Record, SourceLocation Loc,
1913 bool Mutable, Expr *BitfieldWidth,
1914 InClassInitStyle InitStyle,
1915 SourceLocation TSSL,
1916 AccessSpecifier AS, NamedDecl *PrevDecl,
1917 Declarator *D = nullptr);
1919 bool CheckNontrivialField(FieldDecl *FD);
1920 void DiagnoseNontrivial(const CXXRecordDecl *Record, CXXSpecialMember CSM);
1921 bool SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
1922 bool Diagnose = false);
1923 CXXSpecialMember getSpecialMember(const CXXMethodDecl *MD);
1924 void ActOnLastBitfield(SourceLocation DeclStart,
1925 SmallVectorImpl<Decl *> &AllIvarDecls);
1926 Decl *ActOnIvar(Scope *S, SourceLocation DeclStart,
1927 Declarator &D, Expr *BitfieldWidth,
1928 tok::ObjCKeywordKind visibility);
1930 // This is used for both record definitions and ObjC interface declarations.
1931 void ActOnFields(Scope* S, SourceLocation RecLoc, Decl *TagDecl,
1932 ArrayRef<Decl *> Fields,
1933 SourceLocation LBrac, SourceLocation RBrac,
1934 AttributeList *AttrList);
1936 /// ActOnTagStartDefinition - Invoked when we have entered the
1937 /// scope of a tag's definition (e.g., for an enumeration, class,
1938 /// struct, or union).
1939 void ActOnTagStartDefinition(Scope *S, Decl *TagDecl);
1941 typedef void *SkippedDefinitionContext;
1943 /// \brief Invoked when we enter a tag definition that we're skipping.
1944 SkippedDefinitionContext ActOnTagStartSkippedDefinition(Scope *S, Decl *TD);
1946 Decl *ActOnObjCContainerStartDefinition(Decl *IDecl);
1948 /// ActOnStartCXXMemberDeclarations - Invoked when we have parsed a
1949 /// C++ record definition's base-specifiers clause and are starting its
1950 /// member declarations.
1951 void ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagDecl,
1952 SourceLocation FinalLoc,
1953 bool IsFinalSpelledSealed,
1954 SourceLocation LBraceLoc);
1956 /// ActOnTagFinishDefinition - Invoked once we have finished parsing
1957 /// the definition of a tag (enumeration, class, struct, or union).
1958 void ActOnTagFinishDefinition(Scope *S, Decl *TagDecl,
1959 SourceLocation RBraceLoc);
1961 void ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context);
1963 void ActOnObjCContainerFinishDefinition();
1965 /// \brief Invoked when we must temporarily exit the objective-c container
1966 /// scope for parsing/looking-up C constructs.
1968 /// Must be followed by a call to \see ActOnObjCReenterContainerContext
1969 void ActOnObjCTemporaryExitContainerContext(DeclContext *DC);
1970 void ActOnObjCReenterContainerContext(DeclContext *DC);
1972 /// ActOnTagDefinitionError - Invoked when there was an unrecoverable
1973 /// error parsing the definition of a tag.
1974 void ActOnTagDefinitionError(Scope *S, Decl *TagDecl);
1976 EnumConstantDecl *CheckEnumConstant(EnumDecl *Enum,
1977 EnumConstantDecl *LastEnumConst,
1978 SourceLocation IdLoc,
1981 bool CheckEnumUnderlyingType(TypeSourceInfo *TI);
1982 bool CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
1983 QualType EnumUnderlyingTy, const EnumDecl *Prev);
1985 /// Determine whether the body of an anonymous enumeration should be skipped.
1986 /// \param II The name of the first enumerator.
1987 SkipBodyInfo shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II,
1988 SourceLocation IILoc);
1990 Decl *ActOnEnumConstant(Scope *S, Decl *EnumDecl, Decl *LastEnumConstant,
1991 SourceLocation IdLoc, IdentifierInfo *Id,
1992 AttributeList *Attrs,
1993 SourceLocation EqualLoc, Expr *Val);
1994 void ActOnEnumBody(SourceLocation EnumLoc, SourceLocation LBraceLoc,
1995 SourceLocation RBraceLoc, Decl *EnumDecl,
1996 ArrayRef<Decl *> Elements,
1997 Scope *S, AttributeList *Attr);
1999 DeclContext *getContainingDC(DeclContext *DC);
2001 /// Set the current declaration context until it gets popped.
2002 void PushDeclContext(Scope *S, DeclContext *DC);
2003 void PopDeclContext();
2005 /// EnterDeclaratorContext - Used when we must lookup names in the context
2006 /// of a declarator's nested name specifier.
2007 void EnterDeclaratorContext(Scope *S, DeclContext *DC);
2008 void ExitDeclaratorContext(Scope *S);
2010 /// Push the parameters of D, which must be a function, into scope.
2011 void ActOnReenterFunctionContext(Scope* S, Decl* D);
2012 void ActOnExitFunctionContext();
2014 DeclContext *getFunctionLevelDeclContext();
2016 /// getCurFunctionDecl - If inside of a function body, this returns a pointer
2017 /// to the function decl for the function being parsed. If we're currently
2018 /// in a 'block', this returns the containing context.
2019 FunctionDecl *getCurFunctionDecl();
2021 /// getCurMethodDecl - If inside of a method body, this returns a pointer to
2022 /// the method decl for the method being parsed. If we're currently
2023 /// in a 'block', this returns the containing context.
2024 ObjCMethodDecl *getCurMethodDecl();
2026 /// getCurFunctionOrMethodDecl - Return the Decl for the current ObjC method
2027 /// or C function we're in, otherwise return null. If we're currently
2028 /// in a 'block', this returns the containing context.
2029 NamedDecl *getCurFunctionOrMethodDecl();
2031 /// Add this decl to the scope shadowed decl chains.
2032 void PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext = true);
2034 /// \brief Make the given externally-produced declaration visible at the
2035 /// top level scope.
2037 /// \param D The externally-produced declaration to push.
2039 /// \param Name The name of the externally-produced declaration.
2040 void pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name);
2042 /// isDeclInScope - If 'Ctx' is a function/method, isDeclInScope returns true
2043 /// if 'D' is in Scope 'S', otherwise 'S' is ignored and isDeclInScope returns
2044 /// true if 'D' belongs to the given declaration context.
2046 /// \param AllowInlineNamespace If \c true, allow the declaration to be in the
2047 /// enclosing namespace set of the context, rather than contained
2048 /// directly within it.
2049 bool isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S = nullptr,
2050 bool AllowInlineNamespace = false);
2052 /// Finds the scope corresponding to the given decl context, if it
2053 /// happens to be an enclosing scope. Otherwise return NULL.
2054 static Scope *getScopeForDeclContext(Scope *S, DeclContext *DC);
2056 /// Subroutines of ActOnDeclarator().
2057 TypedefDecl *ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
2058 TypeSourceInfo *TInfo);
2059 bool isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New);
2061 /// Attribute merging methods. Return true if a new attribute was added.
2062 AvailabilityAttr *mergeAvailabilityAttr(NamedDecl *D, SourceRange Range,
2063 IdentifierInfo *Platform,
2064 VersionTuple Introduced,
2065 VersionTuple Deprecated,
2066 VersionTuple Obsoleted,
2070 unsigned AttrSpellingListIndex);
2071 TypeVisibilityAttr *mergeTypeVisibilityAttr(Decl *D, SourceRange Range,
2072 TypeVisibilityAttr::VisibilityType Vis,
2073 unsigned AttrSpellingListIndex);
2074 VisibilityAttr *mergeVisibilityAttr(Decl *D, SourceRange Range,
2075 VisibilityAttr::VisibilityType Vis,
2076 unsigned AttrSpellingListIndex);
2077 DLLImportAttr *mergeDLLImportAttr(Decl *D, SourceRange Range,
2078 unsigned AttrSpellingListIndex);
2079 DLLExportAttr *mergeDLLExportAttr(Decl *D, SourceRange Range,
2080 unsigned AttrSpellingListIndex);
2082 mergeMSInheritanceAttr(Decl *D, SourceRange Range, bool BestCase,
2083 unsigned AttrSpellingListIndex,
2084 MSInheritanceAttr::Spelling SemanticSpelling);
2085 FormatAttr *mergeFormatAttr(Decl *D, SourceRange Range,
2086 IdentifierInfo *Format, int FormatIdx,
2087 int FirstArg, unsigned AttrSpellingListIndex);
2088 SectionAttr *mergeSectionAttr(Decl *D, SourceRange Range, StringRef Name,
2089 unsigned AttrSpellingListIndex);
2090 AlwaysInlineAttr *mergeAlwaysInlineAttr(Decl *D, SourceRange Range,
2091 IdentifierInfo *Ident,
2092 unsigned AttrSpellingListIndex);
2093 MinSizeAttr *mergeMinSizeAttr(Decl *D, SourceRange Range,
2094 unsigned AttrSpellingListIndex);
2095 OptimizeNoneAttr *mergeOptimizeNoneAttr(Decl *D, SourceRange Range,
2096 unsigned AttrSpellingListIndex);
2098 /// \brief Describes the kind of merge to perform for availability
2099 /// attributes (including "deprecated", "unavailable", and "availability").
2100 enum AvailabilityMergeKind {
2101 /// \brief Don't merge availability attributes at all.
2103 /// \brief Merge availability attributes for a redeclaration, which requires
2106 /// \brief Merge availability attributes for an override, which requires
2107 /// an exact match or a weakening of constraints.
2111 void mergeDeclAttributes(NamedDecl *New, Decl *Old,
2112 AvailabilityMergeKind AMK = AMK_Redeclaration);
2113 void MergeTypedefNameDecl(TypedefNameDecl *New, LookupResult &OldDecls);
2114 bool MergeFunctionDecl(FunctionDecl *New, NamedDecl *&Old, Scope *S,
2115 bool MergeTypeWithOld);
2116 bool MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
2117 Scope *S, bool MergeTypeWithOld);
2118 void mergeObjCMethodDecls(ObjCMethodDecl *New, ObjCMethodDecl *Old);
2119 void MergeVarDecl(VarDecl *New, LookupResult &Previous);
2120 void MergeVarDeclTypes(VarDecl *New, VarDecl *Old, bool MergeTypeWithOld);
2121 void MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old);
2122 bool MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old, Scope *S);
2124 // AssignmentAction - This is used by all the assignment diagnostic functions
2125 // to represent what is actually causing the operation
2126 enum AssignmentAction {
2134 AA_Passing_CFAudited
2137 /// C++ Overloading.
2139 /// This is a legitimate overload: the existing declarations are
2140 /// functions or function templates with different signatures.
2143 /// This is not an overload because the signature exactly matches
2144 /// an existing declaration.
2147 /// This is not an overload because the lookup results contain a
2151 OverloadKind CheckOverload(Scope *S,
2153 const LookupResult &OldDecls,
2154 NamedDecl *&OldDecl,
2155 bool IsForUsingDecl);
2156 bool IsOverload(FunctionDecl *New, FunctionDecl *Old, bool IsForUsingDecl);
2158 /// \brief Checks availability of the function depending on the current
2159 /// function context.Inside an unavailable function,unavailability is ignored.
2161 /// \returns true if \p FD is unavailable and current context is inside
2162 /// an available function, false otherwise.
2163 bool isFunctionConsideredUnavailable(FunctionDecl *FD);
2165 ImplicitConversionSequence
2166 TryImplicitConversion(Expr *From, QualType ToType,
2167 bool SuppressUserConversions,
2169 bool InOverloadResolution,
2171 bool AllowObjCWritebackConversion);
2173 bool IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType);
2174 bool IsFloatingPointPromotion(QualType FromType, QualType ToType);
2175 bool IsComplexPromotion(QualType FromType, QualType ToType);
2176 bool IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
2177 bool InOverloadResolution,
2178 QualType& ConvertedType, bool &IncompatibleObjC);
2179 bool isObjCPointerConversion(QualType FromType, QualType ToType,
2180 QualType& ConvertedType, bool &IncompatibleObjC);
2181 bool isObjCWritebackConversion(QualType FromType, QualType ToType,
2182 QualType &ConvertedType);
2183 bool IsBlockPointerConversion(QualType FromType, QualType ToType,
2184 QualType& ConvertedType);
2185 bool FunctionParamTypesAreEqual(const FunctionProtoType *OldType,
2186 const FunctionProtoType *NewType,
2187 unsigned *ArgPos = nullptr);
2188 void HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
2189 QualType FromType, QualType ToType);
2191 void maybeExtendBlockObject(ExprResult &E);
2192 CastKind PrepareCastToObjCObjectPointer(ExprResult &E);
2193 bool CheckPointerConversion(Expr *From, QualType ToType,
2195 CXXCastPath& BasePath,
2196 bool IgnoreBaseAccess);
2197 bool IsMemberPointerConversion(Expr *From, QualType FromType, QualType ToType,
2198 bool InOverloadResolution,
2199 QualType &ConvertedType);
2200 bool CheckMemberPointerConversion(Expr *From, QualType ToType,
2202 CXXCastPath &BasePath,
2203 bool IgnoreBaseAccess);
2204 bool IsQualificationConversion(QualType FromType, QualType ToType,
2205 bool CStyle, bool &ObjCLifetimeConversion);
2206 bool IsNoReturnConversion(QualType FromType, QualType ToType,
2207 QualType &ResultTy);
2208 bool DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType);
2209 bool isSameOrCompatibleFunctionType(CanQualType Param, CanQualType Arg);
2211 ExprResult PerformMoveOrCopyInitialization(const InitializedEntity &Entity,
2212 const VarDecl *NRVOCandidate,
2213 QualType ResultType,
2215 bool AllowNRVO = true);
2217 bool CanPerformCopyInitialization(const InitializedEntity &Entity,
2219 ExprResult PerformCopyInitialization(const InitializedEntity &Entity,
2220 SourceLocation EqualLoc,
2222 bool TopLevelOfInitList = false,
2223 bool AllowExplicit = false);
2224 ExprResult PerformObjectArgumentInitialization(Expr *From,
2225 NestedNameSpecifier *Qualifier,
2226 NamedDecl *FoundDecl,
2227 CXXMethodDecl *Method);
2229 ExprResult PerformContextuallyConvertToBool(Expr *From);
2230 ExprResult PerformContextuallyConvertToObjCPointer(Expr *From);
2232 /// Contexts in which a converted constant expression is required.
2234 CCEK_CaseValue, ///< Expression in a case label.
2235 CCEK_Enumerator, ///< Enumerator value with fixed underlying type.
2236 CCEK_TemplateArg, ///< Value of a non-type template parameter.
2237 CCEK_NewExpr ///< Constant expression in a noptr-new-declarator.
2239 ExprResult CheckConvertedConstantExpression(Expr *From, QualType T,
2240 llvm::APSInt &Value, CCEKind CCE);
2241 ExprResult CheckConvertedConstantExpression(Expr *From, QualType T,
2242 APValue &Value, CCEKind CCE);
2244 /// \brief Abstract base class used to perform a contextual implicit
2245 /// conversion from an expression to any type passing a filter.
2246 class ContextualImplicitConverter {
2249 bool SuppressConversion;
2251 ContextualImplicitConverter(bool Suppress = false,
2252 bool SuppressConversion = false)
2253 : Suppress(Suppress), SuppressConversion(SuppressConversion) {}
2255 /// \brief Determine whether the specified type is a valid destination type
2256 /// for this conversion.
2257 virtual bool match(QualType T) = 0;
2259 /// \brief Emits a diagnostic complaining that the expression does not have
2260 /// integral or enumeration type.
2261 virtual SemaDiagnosticBuilder
2262 diagnoseNoMatch(Sema &S, SourceLocation Loc, QualType T) = 0;
2264 /// \brief Emits a diagnostic when the expression has incomplete class type.
2265 virtual SemaDiagnosticBuilder
2266 diagnoseIncomplete(Sema &S, SourceLocation Loc, QualType T) = 0;
2268 /// \brief Emits a diagnostic when the only matching conversion function
2270 virtual SemaDiagnosticBuilder diagnoseExplicitConv(
2271 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) = 0;
2273 /// \brief Emits a note for the explicit conversion function.
2274 virtual SemaDiagnosticBuilder
2275 noteExplicitConv(Sema &S, CXXConversionDecl *Conv, QualType ConvTy) = 0;
2277 /// \brief Emits a diagnostic when there are multiple possible conversion
2279 virtual SemaDiagnosticBuilder
2280 diagnoseAmbiguous(Sema &S, SourceLocation Loc, QualType T) = 0;
2282 /// \brief Emits a note for one of the candidate conversions.
2283 virtual SemaDiagnosticBuilder
2284 noteAmbiguous(Sema &S, CXXConversionDecl *Conv, QualType ConvTy) = 0;
2286 /// \brief Emits a diagnostic when we picked a conversion function
2287 /// (for cases when we are not allowed to pick a conversion function).
2288 virtual SemaDiagnosticBuilder diagnoseConversion(
2289 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) = 0;
2291 virtual ~ContextualImplicitConverter() {}
2294 class ICEConvertDiagnoser : public ContextualImplicitConverter {
2295 bool AllowScopedEnumerations;
2298 ICEConvertDiagnoser(bool AllowScopedEnumerations,
2299 bool Suppress, bool SuppressConversion)
2300 : ContextualImplicitConverter(Suppress, SuppressConversion),
2301 AllowScopedEnumerations(AllowScopedEnumerations) {}
2303 /// Match an integral or (possibly scoped) enumeration type.
2304 bool match(QualType T) override;
2306 SemaDiagnosticBuilder
2307 diagnoseNoMatch(Sema &S, SourceLocation Loc, QualType T) override {
2308 return diagnoseNotInt(S, Loc, T);
2311 /// \brief Emits a diagnostic complaining that the expression does not have
2312 /// integral or enumeration type.
2313 virtual SemaDiagnosticBuilder
2314 diagnoseNotInt(Sema &S, SourceLocation Loc, QualType T) = 0;
2317 /// Perform a contextual implicit conversion.
2318 ExprResult PerformContextualImplicitConversion(
2319 SourceLocation Loc, Expr *FromE, ContextualImplicitConverter &Converter);
2322 enum ObjCSubscriptKind {
2327 ObjCSubscriptKind CheckSubscriptingKind(Expr *FromE);
2329 // Note that LK_String is intentionally after the other literals, as
2330 // this is used for diagnostics logic.
2331 enum ObjCLiteralKind {
2340 ObjCLiteralKind CheckLiteralKind(Expr *FromE);
2342 ExprResult PerformObjectMemberConversion(Expr *From,
2343 NestedNameSpecifier *Qualifier,
2344 NamedDecl *FoundDecl,
2347 // Members have to be NamespaceDecl* or TranslationUnitDecl*.
2348 // TODO: make this is a typesafe union.
2349 typedef llvm::SmallPtrSet<DeclContext *, 16> AssociatedNamespaceSet;
2350 typedef llvm::SmallPtrSet<CXXRecordDecl *, 16> AssociatedClassSet;
2352 void AddOverloadCandidate(FunctionDecl *Function,
2353 DeclAccessPair FoundDecl,
2354 ArrayRef<Expr *> Args,
2355 OverloadCandidateSet& CandidateSet,
2356 bool SuppressUserConversions = false,
2357 bool PartialOverloading = false,
2358 bool AllowExplicit = false);
2359 void AddFunctionCandidates(const UnresolvedSetImpl &Functions,
2360 ArrayRef<Expr *> Args,
2361 OverloadCandidateSet &CandidateSet,
2362 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr,
2363 bool SuppressUserConversions = false,
2364 bool PartialOverloading = false);
2365 void AddMethodCandidate(DeclAccessPair FoundDecl,
2366 QualType ObjectType,
2367 Expr::Classification ObjectClassification,
2368 ArrayRef<Expr *> Args,
2369 OverloadCandidateSet& CandidateSet,
2370 bool SuppressUserConversion = false);
2371 void AddMethodCandidate(CXXMethodDecl *Method,
2372 DeclAccessPair FoundDecl,
2373 CXXRecordDecl *ActingContext, QualType ObjectType,
2374 Expr::Classification ObjectClassification,
2375 ArrayRef<Expr *> Args,
2376 OverloadCandidateSet& CandidateSet,
2377 bool SuppressUserConversions = false,
2378 bool PartialOverloading = false);
2379 void AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
2380 DeclAccessPair FoundDecl,
2381 CXXRecordDecl *ActingContext,
2382 TemplateArgumentListInfo *ExplicitTemplateArgs,
2383 QualType ObjectType,
2384 Expr::Classification ObjectClassification,
2385 ArrayRef<Expr *> Args,
2386 OverloadCandidateSet& CandidateSet,
2387 bool SuppressUserConversions = false,
2388 bool PartialOverloading = false);
2389 void AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
2390 DeclAccessPair FoundDecl,
2391 TemplateArgumentListInfo *ExplicitTemplateArgs,
2392 ArrayRef<Expr *> Args,
2393 OverloadCandidateSet& CandidateSet,
2394 bool SuppressUserConversions = false,
2395 bool PartialOverloading = false);
2396 void AddConversionCandidate(CXXConversionDecl *Conversion,
2397 DeclAccessPair FoundDecl,
2398 CXXRecordDecl *ActingContext,
2399 Expr *From, QualType ToType,
2400 OverloadCandidateSet& CandidateSet,
2401 bool AllowObjCConversionOnExplicit);
2402 void AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
2403 DeclAccessPair FoundDecl,
2404 CXXRecordDecl *ActingContext,
2405 Expr *From, QualType ToType,
2406 OverloadCandidateSet &CandidateSet,
2407 bool AllowObjCConversionOnExplicit);
2408 void AddSurrogateCandidate(CXXConversionDecl *Conversion,
2409 DeclAccessPair FoundDecl,
2410 CXXRecordDecl *ActingContext,
2411 const FunctionProtoType *Proto,
2412 Expr *Object, ArrayRef<Expr *> Args,
2413 OverloadCandidateSet& CandidateSet);
2414 void AddMemberOperatorCandidates(OverloadedOperatorKind Op,
2415 SourceLocation OpLoc, ArrayRef<Expr *> Args,
2416 OverloadCandidateSet& CandidateSet,
2417 SourceRange OpRange = SourceRange());
2418 void AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
2419 ArrayRef<Expr *> Args,
2420 OverloadCandidateSet& CandidateSet,
2421 bool IsAssignmentOperator = false,
2422 unsigned NumContextualBoolArguments = 0);
2423 void AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
2424 SourceLocation OpLoc, ArrayRef<Expr *> Args,
2425 OverloadCandidateSet& CandidateSet);
2426 void AddArgumentDependentLookupCandidates(DeclarationName Name,
2428 ArrayRef<Expr *> Args,
2429 TemplateArgumentListInfo *ExplicitTemplateArgs,
2430 OverloadCandidateSet& CandidateSet,
2431 bool PartialOverloading = false);
2433 // Emit as a 'note' the specific overload candidate
2434 void NoteOverloadCandidate(FunctionDecl *Fn, QualType DestType = QualType());
2436 // Emit as a series of 'note's all template and non-templates
2437 // identified by the expression Expr
2438 void NoteAllOverloadCandidates(Expr* E, QualType DestType = QualType());
2440 /// Check the enable_if expressions on the given function. Returns the first
2441 /// failing attribute, or NULL if they were all successful.
2442 EnableIfAttr *CheckEnableIf(FunctionDecl *Function, ArrayRef<Expr *> Args,
2443 bool MissingImplicitThis = false);
2445 // [PossiblyAFunctionType] --> [Return]
2446 // NonFunctionType --> NonFunctionType
2448 // R (*)(A) --> R (A)
2449 // R (&)(A) --> R (A)
2450 // R (S::*)(A) --> R (A)
2451 QualType ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType);
2454 ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
2455 QualType TargetType,
2457 DeclAccessPair &Found,
2458 bool *pHadMultipleCandidates = nullptr);
2461 ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
2462 bool Complain = false,
2463 DeclAccessPair *Found = nullptr);
2465 bool ResolveAndFixSingleFunctionTemplateSpecialization(
2466 ExprResult &SrcExpr,
2467 bool DoFunctionPointerConverion = false,
2468 bool Complain = false,
2469 const SourceRange& OpRangeForComplaining = SourceRange(),
2470 QualType DestTypeForComplaining = QualType(),
2471 unsigned DiagIDForComplaining = 0);
2474 Expr *FixOverloadedFunctionReference(Expr *E,
2475 DeclAccessPair FoundDecl,
2477 ExprResult FixOverloadedFunctionReference(ExprResult,
2478 DeclAccessPair FoundDecl,
2481 void AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
2482 ArrayRef<Expr *> Args,
2483 OverloadCandidateSet &CandidateSet,
2484 bool PartialOverloading = false);
2486 // An enum used to represent the different possible results of building a
2487 // range-based for loop.
2488 enum ForRangeStatus {
2490 FRS_NoViableFunction,
2491 FRS_DiagnosticIssued
2494 // An enum to represent whether something is dealing with a call to begin()
2495 // or a call to end() in a range-based for loop.
2496 enum BeginEndFunction {
2501 ForRangeStatus BuildForRangeBeginEndCall(Scope *S, SourceLocation Loc,
2502 SourceLocation RangeLoc,
2504 BeginEndFunction BEF,
2505 const DeclarationNameInfo &NameInfo,
2506 LookupResult &MemberLookup,
2507 OverloadCandidateSet *CandidateSet,
2508 Expr *Range, ExprResult *CallExpr);
2510 ExprResult BuildOverloadedCallExpr(Scope *S, Expr *Fn,
2511 UnresolvedLookupExpr *ULE,
2512 SourceLocation LParenLoc,
2514 SourceLocation RParenLoc,
2516 bool AllowTypoCorrection=true);
2518 bool buildOverloadedCallSet(Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE,
2519 MultiExprArg Args, SourceLocation RParenLoc,
2520 OverloadCandidateSet *CandidateSet,
2521 ExprResult *Result);
2523 ExprResult CreateOverloadedUnaryOp(SourceLocation OpLoc,
2525 const UnresolvedSetImpl &Fns,
2528 ExprResult CreateOverloadedBinOp(SourceLocation OpLoc,
2530 const UnresolvedSetImpl &Fns,
2531 Expr *LHS, Expr *RHS);
2533 ExprResult CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
2534 SourceLocation RLoc,
2535 Expr *Base,Expr *Idx);
2538 BuildCallToMemberFunction(Scope *S, Expr *MemExpr,
2539 SourceLocation LParenLoc,
2541 SourceLocation RParenLoc);
2543 BuildCallToObjectOfClassType(Scope *S, Expr *Object, SourceLocation LParenLoc,
2545 SourceLocation RParenLoc);
2547 ExprResult BuildOverloadedArrowExpr(Scope *S, Expr *Base,
2548 SourceLocation OpLoc,
2549 bool *NoArrowOperatorFound = nullptr);
2551 /// CheckCallReturnType - Checks that a call expression's return type is
2552 /// complete. Returns true on failure. The location passed in is the location
2553 /// that best represents the call.
2554 bool CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
2555 CallExpr *CE, FunctionDecl *FD);
2557 /// Helpers for dealing with blocks and functions.
2558 bool CheckParmsForFunctionDef(ParmVarDecl *const *Param,
2559 ParmVarDecl *const *ParamEnd,
2560 bool CheckParameterNames);
2561 void CheckCXXDefaultArguments(FunctionDecl *FD);
2562 void CheckExtraCXXDefaultArguments(Declarator &D);
2563 Scope *getNonFieldDeclScope(Scope *S);
2565 /// \name Name lookup
2567 /// These routines provide name lookup that is used during semantic
2568 /// analysis to resolve the various kinds of names (identifiers,
2569 /// overloaded operator names, constructor names, etc.) into zero or
2570 /// more declarations within a particular scope. The major entry
2571 /// points are LookupName, which performs unqualified name lookup,
2572 /// and LookupQualifiedName, which performs qualified name lookup.
2574 /// All name lookup is performed based on some specific criteria,
2575 /// which specify what names will be visible to name lookup and how
2576 /// far name lookup should work. These criteria are important both
2577 /// for capturing language semantics (certain lookups will ignore
2578 /// certain names, for example) and for performance, since name
2579 /// lookup is often a bottleneck in the compilation of C++. Name
2580 /// lookup criteria is specified via the LookupCriteria enumeration.
2582 /// The results of name lookup can vary based on the kind of name
2583 /// lookup performed, the current language, and the translation
2584 /// unit. In C, for example, name lookup will either return nothing
2585 /// (no entity found) or a single declaration. In C++, name lookup
2586 /// can additionally refer to a set of overloaded functions or
2587 /// result in an ambiguity. All of the possible results of name
2588 /// lookup are captured by the LookupResult class, which provides
2589 /// the ability to distinguish among them.
2592 /// @brief Describes the kind of name lookup to perform.
2593 enum LookupNameKind {
2594 /// Ordinary name lookup, which finds ordinary names (functions,
2595 /// variables, typedefs, etc.) in C and most kinds of names
2596 /// (functions, variables, members, types, etc.) in C++.
2597 LookupOrdinaryName = 0,
2598 /// Tag name lookup, which finds the names of enums, classes,
2599 /// structs, and unions.
2601 /// Label name lookup.
2603 /// Member name lookup, which finds the names of
2604 /// class/struct/union members.
2606 /// Look up of an operator name (e.g., operator+) for use with
2607 /// operator overloading. This lookup is similar to ordinary name
2608 /// lookup, but will ignore any declarations that are class members.
2610 /// Look up of a name that precedes the '::' scope resolution
2611 /// operator in C++. This lookup completely ignores operator, object,
2612 /// function, and enumerator names (C++ [basic.lookup.qual]p1).
2613 LookupNestedNameSpecifierName,
2614 /// Look up a namespace name within a C++ using directive or
2615 /// namespace alias definition, ignoring non-namespace names (C++
2616 /// [basic.lookup.udir]p1).
2617 LookupNamespaceName,
2618 /// Look up all declarations in a scope with the given name,
2619 /// including resolved using declarations. This is appropriate
2620 /// for checking redeclarations for a using declaration.
2621 LookupUsingDeclName,
2622 /// Look up an ordinary name that is going to be redeclared as a
2623 /// name with linkage. This lookup ignores any declarations that
2624 /// are outside of the current scope unless they have linkage. See
2625 /// C99 6.2.2p4-5 and C++ [basic.link]p6.
2626 LookupRedeclarationWithLinkage,
2627 /// Look up a friend of a local class. This lookup does not look
2628 /// outside the innermost non-class scope. See C++11 [class.friend]p11.
2629 LookupLocalFriendName,
2630 /// Look up the name of an Objective-C protocol.
2631 LookupObjCProtocolName,
2632 /// Look up implicit 'self' parameter of an objective-c method.
2633 LookupObjCImplicitSelfParam,
2634 /// \brief Look up any declaration with any name.
2638 /// \brief Specifies whether (or how) name lookup is being performed for a
2639 /// redeclaration (vs. a reference).
2640 enum RedeclarationKind {
2641 /// \brief The lookup is a reference to this name that is not for the
2642 /// purpose of redeclaring the name.
2643 NotForRedeclaration = 0,
2644 /// \brief The lookup results will be used for redeclaration of a name,
2645 /// if an entity by that name already exists.
2649 /// \brief The possible outcomes of name lookup for a literal operator.
2650 enum LiteralOperatorLookupResult {
2651 /// \brief The lookup resulted in an error.
2653 /// \brief The lookup found a single 'cooked' literal operator, which
2654 /// expects a normal literal to be built and passed to it.
2656 /// \brief The lookup found a single 'raw' literal operator, which expects
2657 /// a string literal containing the spelling of the literal token.
2659 /// \brief The lookup found an overload set of literal operator templates,
2660 /// which expect the characters of the spelling of the literal token to be
2661 /// passed as a non-type template argument pack.
2663 /// \brief The lookup found an overload set of literal operator templates,
2664 /// which expect the character type and characters of the spelling of the
2665 /// string literal token to be passed as template arguments.
2669 SpecialMemberOverloadResult *LookupSpecialMember(CXXRecordDecl *D,
2670 CXXSpecialMember SM,
2677 typedef std::function<void(const TypoCorrection &)> TypoDiagnosticGenerator;
2678 typedef std::function<ExprResult(Sema &, TypoExpr *, TypoCorrection)>
2679 TypoRecoveryCallback;
2682 bool CppLookupName(LookupResult &R, Scope *S);
2684 struct TypoExprState {
2685 std::unique_ptr<TypoCorrectionConsumer> Consumer;
2686 TypoDiagnosticGenerator DiagHandler;
2687 TypoRecoveryCallback RecoveryHandler;
2689 TypoExprState(TypoExprState&& other) LLVM_NOEXCEPT;
2690 TypoExprState& operator=(TypoExprState&& other) LLVM_NOEXCEPT;
2693 /// \brief The set of unhandled TypoExprs and their associated state.
2694 llvm::MapVector<TypoExpr *, TypoExprState> DelayedTypos;
2696 /// \brief Creates a new TypoExpr AST node.
2697 TypoExpr *createDelayedTypo(std::unique_ptr<TypoCorrectionConsumer> TCC,
2698 TypoDiagnosticGenerator TDG,
2699 TypoRecoveryCallback TRC);
2701 // \brief The set of known/encountered (unique, canonicalized) NamespaceDecls.
2703 // The boolean value will be true to indicate that the namespace was loaded
2704 // from an AST/PCH file, or false otherwise.
2705 llvm::MapVector<NamespaceDecl*, bool> KnownNamespaces;
2707 /// \brief Whether we have already loaded known namespaces from an extenal
2709 bool LoadedExternalKnownNamespaces;
2711 /// \brief Helper for CorrectTypo and CorrectTypoDelayed used to create and
2712 /// populate a new TypoCorrectionConsumer. Returns nullptr if typo correction
2713 /// should be skipped entirely.
2714 std::unique_ptr<TypoCorrectionConsumer>
2715 makeTypoCorrectionConsumer(const DeclarationNameInfo &Typo,
2716 Sema::LookupNameKind LookupKind, Scope *S,
2718 std::unique_ptr<CorrectionCandidateCallback> CCC,
2719 DeclContext *MemberContext, bool EnteringContext,
2720 const ObjCObjectPointerType *OPT,
2721 bool ErrorRecovery);
2724 const TypoExprState &getTypoExprState(TypoExpr *TE) const;
2726 /// \brief Clears the state of the given TypoExpr.
2727 void clearDelayedTypo(TypoExpr *TE);
2729 /// \brief Look up a name, looking for a single declaration. Return
2730 /// null if the results were absent, ambiguous, or overloaded.
2732 /// It is preferable to use the elaborated form and explicitly handle
2733 /// ambiguity and overloaded.
2734 NamedDecl *LookupSingleName(Scope *S, DeclarationName Name,
2736 LookupNameKind NameKind,
2737 RedeclarationKind Redecl
2738 = NotForRedeclaration);
2739 bool LookupName(LookupResult &R, Scope *S,
2740 bool AllowBuiltinCreation = false);
2741 bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
2742 bool InUnqualifiedLookup = false);
2743 bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
2745 bool LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS,
2746 bool AllowBuiltinCreation = false,
2747 bool EnteringContext = false);
2748 ObjCProtocolDecl *LookupProtocol(IdentifierInfo *II, SourceLocation IdLoc,
2749 RedeclarationKind Redecl
2750 = NotForRedeclaration);
2751 bool LookupInSuper(LookupResult &R, CXXRecordDecl *Class);
2753 void LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S,
2754 QualType T1, QualType T2,
2755 UnresolvedSetImpl &Functions);
2756 void addOverloadedOperatorToUnresolvedSet(UnresolvedSetImpl &Functions,
2757 DeclAccessPair Operator,
2758 QualType T1, QualType T2);
2760 LabelDecl *LookupOrCreateLabel(IdentifierInfo *II, SourceLocation IdentLoc,
2761 SourceLocation GnuLabelLoc = SourceLocation());
2763 DeclContextLookupResult LookupConstructors(CXXRecordDecl *Class);
2764 CXXConstructorDecl *LookupDefaultConstructor(CXXRecordDecl *Class);
2765 CXXConstructorDecl *LookupCopyingConstructor(CXXRecordDecl *Class,
2767 CXXMethodDecl *LookupCopyingAssignment(CXXRecordDecl *Class, unsigned Quals,
2768 bool RValueThis, unsigned ThisQuals);
2769 CXXConstructorDecl *LookupMovingConstructor(CXXRecordDecl *Class,
2771 CXXMethodDecl *LookupMovingAssignment(CXXRecordDecl *Class, unsigned Quals,
2772 bool RValueThis, unsigned ThisQuals);
2773 CXXDestructorDecl *LookupDestructor(CXXRecordDecl *Class);
2775 bool checkLiteralOperatorId(const CXXScopeSpec &SS, const UnqualifiedId &Id);
2776 LiteralOperatorLookupResult LookupLiteralOperator(Scope *S, LookupResult &R,
2777 ArrayRef<QualType> ArgTys,
2780 bool AllowStringTemplate);
2781 bool isKnownName(StringRef name);
2783 void ArgumentDependentLookup(DeclarationName Name, SourceLocation Loc,
2784 ArrayRef<Expr *> Args, ADLResult &Functions);
2786 void LookupVisibleDecls(Scope *S, LookupNameKind Kind,
2787 VisibleDeclConsumer &Consumer,
2788 bool IncludeGlobalScope = true);
2789 void LookupVisibleDecls(DeclContext *Ctx, LookupNameKind Kind,
2790 VisibleDeclConsumer &Consumer,
2791 bool IncludeGlobalScope = true);
2793 enum CorrectTypoKind {
2794 CTK_NonError, // CorrectTypo used in a non error recovery situation.
2795 CTK_ErrorRecovery // CorrectTypo used in normal error recovery.
2798 TypoCorrection CorrectTypo(const DeclarationNameInfo &Typo,
2799 Sema::LookupNameKind LookupKind,
2800 Scope *S, CXXScopeSpec *SS,
2801 std::unique_ptr<CorrectionCandidateCallback> CCC,
2802 CorrectTypoKind Mode,
2803 DeclContext *MemberContext = nullptr,
2804 bool EnteringContext = false,
2805 const ObjCObjectPointerType *OPT = nullptr,
2806 bool RecordFailure = true);
2808 TypoExpr *CorrectTypoDelayed(const DeclarationNameInfo &Typo,
2809 Sema::LookupNameKind LookupKind, Scope *S,
2811 std::unique_ptr<CorrectionCandidateCallback> CCC,
2812 TypoDiagnosticGenerator TDG,
2813 TypoRecoveryCallback TRC, CorrectTypoKind Mode,
2814 DeclContext *MemberContext = nullptr,
2815 bool EnteringContext = false,
2816 const ObjCObjectPointerType *OPT = nullptr);
2818 /// \brief Process any TypoExprs in the given Expr and its children,
2819 /// generating diagnostics as appropriate and returning a new Expr if there
2820 /// were typos that were all successfully corrected and ExprError if one or
2821 /// more typos could not be corrected.
2823 /// \param E The Expr to check for TypoExprs.
2825 /// \param InitDecl A VarDecl to avoid because the Expr being corrected is its
2828 /// \param Filter A function applied to a newly rebuilt Expr to determine if
2829 /// it is an acceptable/usable result from a single combination of typo
2830 /// corrections. As long as the filter returns ExprError, different
2831 /// combinations of corrections will be tried until all are exhausted.
2833 CorrectDelayedTyposInExpr(Expr *E, VarDecl *InitDecl = nullptr,
2834 llvm::function_ref<ExprResult(Expr *)> Filter =
2835 [](Expr *E) -> ExprResult { return E; });
2838 CorrectDelayedTyposInExpr(Expr *E,
2839 llvm::function_ref<ExprResult(Expr *)> Filter) {
2840 return CorrectDelayedTyposInExpr(E, nullptr, Filter);
2844 CorrectDelayedTyposInExpr(ExprResult ER, VarDecl *InitDecl = nullptr,
2845 llvm::function_ref<ExprResult(Expr *)> Filter =
2846 [](Expr *E) -> ExprResult { return E; }) {
2847 return ER.isInvalid() ? ER : CorrectDelayedTyposInExpr(ER.get(), Filter);
2851 CorrectDelayedTyposInExpr(ExprResult ER,
2852 llvm::function_ref<ExprResult(Expr *)> Filter) {
2853 return CorrectDelayedTyposInExpr(ER, nullptr, Filter);
2856 void diagnoseTypo(const TypoCorrection &Correction,
2857 const PartialDiagnostic &TypoDiag,
2858 bool ErrorRecovery = true);
2860 void diagnoseTypo(const TypoCorrection &Correction,
2861 const PartialDiagnostic &TypoDiag,
2862 const PartialDiagnostic &PrevNote,
2863 bool ErrorRecovery = true);
2865 void FindAssociatedClassesAndNamespaces(SourceLocation InstantiationLoc,
2866 ArrayRef<Expr *> Args,
2867 AssociatedNamespaceSet &AssociatedNamespaces,
2868 AssociatedClassSet &AssociatedClasses);
2870 void FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S,
2871 bool ConsiderLinkage, bool AllowInlineNamespace);
2873 void DiagnoseAmbiguousLookup(LookupResult &Result);
2876 ObjCInterfaceDecl *getObjCInterfaceDecl(IdentifierInfo *&Id,
2877 SourceLocation IdLoc,
2878 bool TypoCorrection = false);
2879 NamedDecl *LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID,
2880 Scope *S, bool ForRedeclaration,
2881 SourceLocation Loc);
2882 NamedDecl *ImplicitlyDefineFunction(SourceLocation Loc, IdentifierInfo &II,
2884 void AddKnownFunctionAttributes(FunctionDecl *FD);
2886 // More parsing and symbol table subroutines.
2888 void ProcessPragmaWeak(Scope *S, Decl *D);
2889 // Decl attributes - this routine is the top level dispatcher.
2890 void ProcessDeclAttributes(Scope *S, Decl *D, const Declarator &PD);
2891 void ProcessDeclAttributeList(Scope *S, Decl *D, const AttributeList *AL,
2892 bool IncludeCXX11Attributes = true);
2893 bool ProcessAccessDeclAttributeList(AccessSpecDecl *ASDecl,
2894 const AttributeList *AttrList);
2896 void checkUnusedDeclAttributes(Declarator &D);
2898 /// Determine if type T is a valid subject for a nonnull and similar
2899 /// attributes. By default, we look through references (the behavior used by
2900 /// nonnull), but if the second parameter is true, then we treat a reference
2902 bool isValidPointerAttrType(QualType T, bool RefOkay = false);
2904 bool CheckRegparmAttr(const AttributeList &attr, unsigned &value);
2905 bool CheckCallingConvAttr(const AttributeList &attr, CallingConv &CC,
2906 const FunctionDecl *FD = nullptr);
2907 bool CheckNoReturnAttr(const AttributeList &attr);
2908 bool checkStringLiteralArgumentAttr(const AttributeList &Attr,
2909 unsigned ArgNum, StringRef &Str,
2910 SourceLocation *ArgLocation = nullptr);
2911 bool checkSectionName(SourceLocation LiteralLoc, StringRef Str);
2912 void checkTargetAttr(SourceLocation LiteralLoc, StringRef Str);
2913 bool checkMSInheritanceAttrOnDefinition(
2914 CXXRecordDecl *RD, SourceRange Range, bool BestCase,
2915 MSInheritanceAttr::Spelling SemanticSpelling);
2917 void CheckAlignasUnderalignment(Decl *D);
2919 /// Adjust the calling convention of a method to be the ABI default if it
2920 /// wasn't specified explicitly. This handles method types formed from
2921 /// function type typedefs and typename template arguments.
2922 void adjustMemberFunctionCC(QualType &T, bool IsStatic);
2924 // Check if there is an explicit attribute, but only look through parens.
2925 // The intent is to look for an attribute on the current declarator, but not
2926 // one that came from a typedef.
2927 bool hasExplicitCallingConv(QualType &T);
2929 /// Get the outermost AttributedType node that sets a calling convention.
2930 /// Valid types should not have multiple attributes with different CCs.
2931 const AttributedType *getCallingConvAttributedType(QualType T) const;
2933 /// Check whether a nullability type specifier can be added to the given
2936 /// \param type The type to which the nullability specifier will be
2937 /// added. On success, this type will be updated appropriately.
2939 /// \param nullability The nullability specifier to add.
2941 /// \param nullabilityLoc The location of the nullability specifier.
2943 /// \param isContextSensitive Whether this nullability specifier was
2944 /// written as a context-sensitive keyword (in an Objective-C
2945 /// method) or an Objective-C property attribute, rather than as an
2946 /// underscored type specifier.
2948 /// \returns true if nullability cannot be applied, false otherwise.
2949 bool checkNullabilityTypeSpecifier(QualType &type, NullabilityKind nullability,
2950 SourceLocation nullabilityLoc,
2951 bool isContextSensitive);
2953 /// \brief Stmt attributes - this routine is the top level dispatcher.
2954 StmtResult ProcessStmtAttributes(Stmt *Stmt, AttributeList *Attrs,
2957 void WarnConflictingTypedMethods(ObjCMethodDecl *Method,
2958 ObjCMethodDecl *MethodDecl,
2959 bool IsProtocolMethodDecl);
2961 void CheckConflictingOverridingMethod(ObjCMethodDecl *Method,
2962 ObjCMethodDecl *Overridden,
2963 bool IsProtocolMethodDecl);
2965 /// WarnExactTypedMethods - This routine issues a warning if method
2966 /// implementation declaration matches exactly that of its declaration.
2967 void WarnExactTypedMethods(ObjCMethodDecl *Method,
2968 ObjCMethodDecl *MethodDecl,
2969 bool IsProtocolMethodDecl);
2971 typedef llvm::SmallPtrSet<Selector, 8> SelectorSet;
2972 typedef llvm::DenseMap<Selector, ObjCMethodDecl*> ProtocolsMethodsMap;
2974 /// CheckImplementationIvars - This routine checks if the instance variables
2975 /// listed in the implelementation match those listed in the interface.
2976 void CheckImplementationIvars(ObjCImplementationDecl *ImpDecl,
2977 ObjCIvarDecl **Fields, unsigned nIvars,
2978 SourceLocation Loc);
2980 /// ImplMethodsVsClassMethods - This is main routine to warn if any method
2981 /// remains unimplemented in the class or category \@implementation.
2982 void ImplMethodsVsClassMethods(Scope *S, ObjCImplDecl* IMPDecl,
2983 ObjCContainerDecl* IDecl,
2984 bool IncompleteImpl = false);
2986 /// DiagnoseUnimplementedProperties - This routine warns on those properties
2987 /// which must be implemented by this implementation.
2988 void DiagnoseUnimplementedProperties(Scope *S, ObjCImplDecl* IMPDecl,
2989 ObjCContainerDecl *CDecl,
2990 bool SynthesizeProperties);
2992 /// Diagnose any null-resettable synthesized setters.
2993 void diagnoseNullResettableSynthesizedSetters(const ObjCImplDecl *impDecl);
2995 /// DefaultSynthesizeProperties - This routine default synthesizes all
2996 /// properties which must be synthesized in the class's \@implementation.
2997 void DefaultSynthesizeProperties (Scope *S, ObjCImplDecl* IMPDecl,
2998 ObjCInterfaceDecl *IDecl);
2999 void DefaultSynthesizeProperties(Scope *S, Decl *D);
3001 /// IvarBacksCurrentMethodAccessor - This routine returns 'true' if 'IV' is
3002 /// an ivar synthesized for 'Method' and 'Method' is a property accessor
3003 /// declared in class 'IFace'.
3004 bool IvarBacksCurrentMethodAccessor(ObjCInterfaceDecl *IFace,
3005 ObjCMethodDecl *Method, ObjCIvarDecl *IV);
3007 /// DiagnoseUnusedBackingIvarInAccessor - Issue an 'unused' warning if ivar which
3008 /// backs the property is not used in the property's accessor.
3009 void DiagnoseUnusedBackingIvarInAccessor(Scope *S,
3010 const ObjCImplementationDecl *ImplD);
3012 /// GetIvarBackingPropertyAccessor - If method is a property setter/getter and
3013 /// it property has a backing ivar, returns this ivar; otherwise, returns NULL.
3014 /// It also returns ivar's property on success.
3015 ObjCIvarDecl *GetIvarBackingPropertyAccessor(const ObjCMethodDecl *Method,
3016 const ObjCPropertyDecl *&PDecl) const;
3018 /// Called by ActOnProperty to handle \@property declarations in
3019 /// class extensions.
3020 ObjCPropertyDecl *HandlePropertyInClassExtension(Scope *S,
3021 SourceLocation AtLoc,
3022 SourceLocation LParenLoc,
3023 FieldDeclarator &FD,
3026 const bool isAssign,
3027 const bool isReadWrite,
3028 const unsigned Attributes,
3029 const unsigned AttributesAsWritten,
3030 bool *isOverridingProperty,
3032 TypeSourceInfo *TSI,
3033 tok::ObjCKeywordKind MethodImplKind);
3035 /// Called by ActOnProperty and HandlePropertyInClassExtension to
3036 /// handle creating the ObjcPropertyDecl for a category or \@interface.
3037 ObjCPropertyDecl *CreatePropertyDecl(Scope *S,
3038 ObjCContainerDecl *CDecl,
3039 SourceLocation AtLoc,
3040 SourceLocation LParenLoc,
3041 FieldDeclarator &FD,
3044 const bool isAssign,
3045 const bool isReadWrite,
3046 const unsigned Attributes,
3047 const unsigned AttributesAsWritten,
3049 TypeSourceInfo *TSI,
3050 tok::ObjCKeywordKind MethodImplKind,
3051 DeclContext *lexicalDC = nullptr);
3053 /// AtomicPropertySetterGetterRules - This routine enforces the rule (via
3054 /// warning) when atomic property has one but not the other user-declared
3055 /// setter or getter.
3056 void AtomicPropertySetterGetterRules(ObjCImplDecl* IMPDecl,
3057 ObjCContainerDecl* IDecl);
3059 void DiagnoseOwningPropertyGetterSynthesis(const ObjCImplementationDecl *D);
3061 void DiagnoseMissingDesignatedInitOverrides(
3062 const ObjCImplementationDecl *ImplD,
3063 const ObjCInterfaceDecl *IFD);
3065 void DiagnoseDuplicateIvars(ObjCInterfaceDecl *ID, ObjCInterfaceDecl *SID);
3067 enum MethodMatchStrategy {
3072 /// MatchTwoMethodDeclarations - Checks if two methods' type match and returns
3073 /// true, or false, accordingly.
3074 bool MatchTwoMethodDeclarations(const ObjCMethodDecl *Method,
3075 const ObjCMethodDecl *PrevMethod,
3076 MethodMatchStrategy strategy = MMS_strict);
3078 /// MatchAllMethodDeclarations - Check methods declaraed in interface or
3079 /// or protocol against those declared in their implementations.
3080 void MatchAllMethodDeclarations(const SelectorSet &InsMap,
3081 const SelectorSet &ClsMap,
3082 SelectorSet &InsMapSeen,
3083 SelectorSet &ClsMapSeen,
3084 ObjCImplDecl* IMPDecl,
3085 ObjCContainerDecl* IDecl,
3086 bool &IncompleteImpl,
3087 bool ImmediateClass,
3088 bool WarnCategoryMethodImpl=false);
3090 /// CheckCategoryVsClassMethodMatches - Checks that methods implemented in
3091 /// category matches with those implemented in its primary class and
3092 /// warns each time an exact match is found.
3093 void CheckCategoryVsClassMethodMatches(ObjCCategoryImplDecl *CatIMP);
3095 /// \brief Add the given method to the list of globally-known methods.
3096 void addMethodToGlobalList(ObjCMethodList *List, ObjCMethodDecl *Method);
3099 /// AddMethodToGlobalPool - Add an instance or factory method to the global
3100 /// pool. See descriptoin of AddInstanceMethodToGlobalPool.
3101 void AddMethodToGlobalPool(ObjCMethodDecl *Method, bool impl, bool instance);
3103 /// LookupMethodInGlobalPool - Returns the instance or factory method and
3104 /// optionally warns if there are multiple signatures.
3105 ObjCMethodDecl *LookupMethodInGlobalPool(Selector Sel, SourceRange R,
3106 bool receiverIdOrClass,
3110 /// \brief - Returns instance or factory methods in global method pool for
3111 /// given selector. If no such method or only one method found, function returns
3112 /// false; otherwise, it returns true
3113 bool CollectMultipleMethodsInGlobalPool(Selector Sel,
3114 SmallVectorImpl<ObjCMethodDecl*>& Methods,
3117 bool AreMultipleMethodsInGlobalPool(Selector Sel, ObjCMethodDecl *BestMethod,
3119 bool receiverIdOrClass);
3121 void DiagnoseMultipleMethodInGlobalPool(SmallVectorImpl<ObjCMethodDecl*> &Methods,
3122 Selector Sel, SourceRange R,
3123 bool receiverIdOrClass);
3126 /// \brief - Returns a selector which best matches given argument list or
3127 /// nullptr if none could be found
3128 ObjCMethodDecl *SelectBestMethod(Selector Sel, MultiExprArg Args,
3132 /// \brief Record the typo correction failure and return an empty correction.
3133 TypoCorrection FailedCorrection(IdentifierInfo *Typo, SourceLocation TypoLoc,
3134 bool RecordFailure = true) {
3136 TypoCorrectionFailures[Typo].insert(TypoLoc);
3137 return TypoCorrection();
3141 /// AddInstanceMethodToGlobalPool - All instance methods in a translation
3142 /// unit are added to a global pool. This allows us to efficiently associate
3143 /// a selector with a method declaraation for purposes of typechecking
3144 /// messages sent to "id" (where the class of the object is unknown).
3145 void AddInstanceMethodToGlobalPool(ObjCMethodDecl *Method, bool impl=false) {
3146 AddMethodToGlobalPool(Method, impl, /*instance*/true);
3149 /// AddFactoryMethodToGlobalPool - Same as above, but for factory methods.
3150 void AddFactoryMethodToGlobalPool(ObjCMethodDecl *Method, bool impl=false) {
3151 AddMethodToGlobalPool(Method, impl, /*instance*/false);
3154 /// AddAnyMethodToGlobalPool - Add any method, instance or factory to global
3156 void AddAnyMethodToGlobalPool(Decl *D);
3158 /// LookupInstanceMethodInGlobalPool - Returns the method and warns if
3159 /// there are multiple signatures.
3160 ObjCMethodDecl *LookupInstanceMethodInGlobalPool(Selector Sel, SourceRange R,
3161 bool receiverIdOrClass=false) {
3162 return LookupMethodInGlobalPool(Sel, R, receiverIdOrClass,
3166 /// LookupFactoryMethodInGlobalPool - Returns the method and warns if
3167 /// there are multiple signatures.
3168 ObjCMethodDecl *LookupFactoryMethodInGlobalPool(Selector Sel, SourceRange R,
3169 bool receiverIdOrClass=false) {
3170 return LookupMethodInGlobalPool(Sel, R, receiverIdOrClass,
3174 const ObjCMethodDecl *SelectorsForTypoCorrection(Selector Sel,
3175 QualType ObjectType=QualType());
3176 /// LookupImplementedMethodInGlobalPool - Returns the method which has an
3178 ObjCMethodDecl *LookupImplementedMethodInGlobalPool(Selector Sel);
3180 /// CollectIvarsToConstructOrDestruct - Collect those ivars which require
3182 void CollectIvarsToConstructOrDestruct(ObjCInterfaceDecl *OI,
3183 SmallVectorImpl<ObjCIvarDecl*> &Ivars);
3185 //===--------------------------------------------------------------------===//
3186 // Statement Parsing Callbacks: SemaStmt.cpp.
3190 FullExprArg(Sema &actions) : E(nullptr) { }
3192 ExprResult release() {
3196 Expr *get() const { return E; }
3198 Expr *operator->() {
3203 // FIXME: No need to make the entire Sema class a friend when it's just
3204 // Sema::MakeFullExpr that needs access to the constructor below.
3207 explicit FullExprArg(Expr *expr) : E(expr) {}
3212 FullExprArg MakeFullExpr(Expr *Arg) {
3213 return MakeFullExpr(Arg, Arg ? Arg->getExprLoc() : SourceLocation());
3215 FullExprArg MakeFullExpr(Expr *Arg, SourceLocation CC) {
3216 return FullExprArg(ActOnFinishFullExpr(Arg, CC).get());
3218 FullExprArg MakeFullDiscardedValueExpr(Expr *Arg) {
3220 ActOnFinishFullExpr(Arg, Arg ? Arg->getExprLoc() : SourceLocation(),
3221 /*DiscardedValue*/ true);
3222 return FullExprArg(FE.get());
3225 StmtResult ActOnExprStmt(ExprResult Arg);
3226 StmtResult ActOnExprStmtError();
3228 StmtResult ActOnNullStmt(SourceLocation SemiLoc,
3229 bool HasLeadingEmptyMacro = false);
3231 void ActOnStartOfCompoundStmt();
3232 void ActOnFinishOfCompoundStmt();
3233 StmtResult ActOnCompoundStmt(SourceLocation L, SourceLocation R,
3234 ArrayRef<Stmt *> Elts, bool isStmtExpr);
3236 /// \brief A RAII object to enter scope of a compound statement.
3237 class CompoundScopeRAII {
3239 CompoundScopeRAII(Sema &S): S(S) {
3240 S.ActOnStartOfCompoundStmt();
3243 ~CompoundScopeRAII() {
3244 S.ActOnFinishOfCompoundStmt();
3251 /// An RAII helper that pops function a function scope on exit.
3252 struct FunctionScopeRAII {
3255 FunctionScopeRAII(Sema &S) : S(S), Active(true) {}
3256 ~FunctionScopeRAII() {
3258 S.PopFunctionScopeInfo();
3260 void disable() { Active = false; }
3263 StmtResult ActOnDeclStmt(DeclGroupPtrTy Decl,
3264 SourceLocation StartLoc,
3265 SourceLocation EndLoc);
3266 void ActOnForEachDeclStmt(DeclGroupPtrTy Decl);
3267 StmtResult ActOnForEachLValueExpr(Expr *E);
3268 StmtResult ActOnCaseStmt(SourceLocation CaseLoc, Expr *LHSVal,
3269 SourceLocation DotDotDotLoc, Expr *RHSVal,
3270 SourceLocation ColonLoc);
3271 void ActOnCaseStmtBody(Stmt *CaseStmt, Stmt *SubStmt);
3273 StmtResult ActOnDefaultStmt(SourceLocation DefaultLoc,
3274 SourceLocation ColonLoc,
3275 Stmt *SubStmt, Scope *CurScope);
3276 StmtResult ActOnLabelStmt(SourceLocation IdentLoc, LabelDecl *TheDecl,
3277 SourceLocation ColonLoc, Stmt *SubStmt);
3279 StmtResult ActOnAttributedStmt(SourceLocation AttrLoc,
3280 ArrayRef<const Attr*> Attrs,
3283 StmtResult ActOnIfStmt(SourceLocation IfLoc,
3284 FullExprArg CondVal, Decl *CondVar,
3286 SourceLocation ElseLoc, Stmt *ElseVal);
3287 StmtResult ActOnStartOfSwitchStmt(SourceLocation SwitchLoc,
3290 StmtResult ActOnFinishSwitchStmt(SourceLocation SwitchLoc,
3291 Stmt *Switch, Stmt *Body);
3292 StmtResult ActOnWhileStmt(SourceLocation WhileLoc,
3294 Decl *CondVar, Stmt *Body);
3295 StmtResult ActOnDoStmt(SourceLocation DoLoc, Stmt *Body,
3296 SourceLocation WhileLoc,
3297 SourceLocation CondLParen, Expr *Cond,
3298 SourceLocation CondRParen);
3300 StmtResult ActOnForStmt(SourceLocation ForLoc,
3301 SourceLocation LParenLoc,
3302 Stmt *First, FullExprArg Second,
3305 SourceLocation RParenLoc,
3307 ExprResult CheckObjCForCollectionOperand(SourceLocation forLoc,
3309 StmtResult ActOnObjCForCollectionStmt(SourceLocation ForColLoc,
3310 Stmt *First, Expr *collection,
3311 SourceLocation RParenLoc);
3312 StmtResult FinishObjCForCollectionStmt(Stmt *ForCollection, Stmt *Body);
3314 enum BuildForRangeKind {
3315 /// Initial building of a for-range statement.
3317 /// Instantiation or recovery rebuild of a for-range statement. Don't
3318 /// attempt any typo-correction.
3320 /// Determining whether a for-range statement could be built. Avoid any
3321 /// unnecessary or irreversible actions.
3325 StmtResult ActOnCXXForRangeStmt(SourceLocation ForLoc, Stmt *LoopVar,
3326 SourceLocation ColonLoc, Expr *Collection,
3327 SourceLocation RParenLoc,
3328 BuildForRangeKind Kind);
3329 StmtResult BuildCXXForRangeStmt(SourceLocation ForLoc,
3330 SourceLocation ColonLoc,
3331 Stmt *RangeDecl, Stmt *BeginEndDecl,
3332 Expr *Cond, Expr *Inc,
3334 SourceLocation RParenLoc,
3335 BuildForRangeKind Kind);
3336 StmtResult FinishCXXForRangeStmt(Stmt *ForRange, Stmt *Body);
3338 StmtResult ActOnGotoStmt(SourceLocation GotoLoc,
3339 SourceLocation LabelLoc,
3340 LabelDecl *TheDecl);
3341 StmtResult ActOnIndirectGotoStmt(SourceLocation GotoLoc,
3342 SourceLocation StarLoc,
3344 StmtResult ActOnContinueStmt(SourceLocation ContinueLoc, Scope *CurScope);
3345 StmtResult ActOnBreakStmt(SourceLocation BreakLoc, Scope *CurScope);
3347 void ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope,
3348 CapturedRegionKind Kind, unsigned NumParams);
3349 typedef std::pair<StringRef, QualType> CapturedParamNameType;
3350 void ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope,
3351 CapturedRegionKind Kind,
3352 ArrayRef<CapturedParamNameType> Params);
3353 StmtResult ActOnCapturedRegionEnd(Stmt *S);
3354 void ActOnCapturedRegionError();
3355 RecordDecl *CreateCapturedStmtRecordDecl(CapturedDecl *&CD,
3357 unsigned NumParams);
3358 VarDecl *getCopyElisionCandidate(QualType ReturnType, Expr *E,
3359 bool AllowFunctionParameters);
3360 bool isCopyElisionCandidate(QualType ReturnType, const VarDecl *VD,
3361 bool AllowFunctionParameters);
3363 StmtResult ActOnReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp,
3365 StmtResult BuildReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp);
3366 StmtResult ActOnCapScopeReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp);
3368 StmtResult ActOnGCCAsmStmt(SourceLocation AsmLoc, bool IsSimple,
3369 bool IsVolatile, unsigned NumOutputs,
3370 unsigned NumInputs, IdentifierInfo **Names,
3371 MultiExprArg Constraints, MultiExprArg Exprs,
3372 Expr *AsmString, MultiExprArg Clobbers,
3373 SourceLocation RParenLoc);
3375 ExprResult LookupInlineAsmIdentifier(CXXScopeSpec &SS,
3376 SourceLocation TemplateKWLoc,
3378 llvm::InlineAsmIdentifierInfo &Info,
3379 bool IsUnevaluatedContext);
3380 bool LookupInlineAsmField(StringRef Base, StringRef Member,
3381 unsigned &Offset, SourceLocation AsmLoc);
3382 StmtResult ActOnMSAsmStmt(SourceLocation AsmLoc, SourceLocation LBraceLoc,
3383 ArrayRef<Token> AsmToks,
3384 StringRef AsmString,
3385 unsigned NumOutputs, unsigned NumInputs,
3386 ArrayRef<StringRef> Constraints,
3387 ArrayRef<StringRef> Clobbers,
3388 ArrayRef<Expr*> Exprs,
3389 SourceLocation EndLoc);
3390 LabelDecl *GetOrCreateMSAsmLabel(StringRef ExternalLabelName,
3391 SourceLocation Location,
3394 VarDecl *BuildObjCExceptionDecl(TypeSourceInfo *TInfo, QualType ExceptionType,
3395 SourceLocation StartLoc,
3396 SourceLocation IdLoc, IdentifierInfo *Id,
3397 bool Invalid = false);
3399 Decl *ActOnObjCExceptionDecl(Scope *S, Declarator &D);
3401 StmtResult ActOnObjCAtCatchStmt(SourceLocation AtLoc, SourceLocation RParen,
3402 Decl *Parm, Stmt *Body);
3404 StmtResult ActOnObjCAtFinallyStmt(SourceLocation AtLoc, Stmt *Body);
3406 StmtResult ActOnObjCAtTryStmt(SourceLocation AtLoc, Stmt *Try,
3407 MultiStmtArg Catch, Stmt *Finally);
3409 StmtResult BuildObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw);
3410 StmtResult ActOnObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw,
3412 ExprResult ActOnObjCAtSynchronizedOperand(SourceLocation atLoc,
3414 StmtResult ActOnObjCAtSynchronizedStmt(SourceLocation AtLoc,
3418 StmtResult ActOnObjCAutoreleasePoolStmt(SourceLocation AtLoc, Stmt *Body);
3420 VarDecl *BuildExceptionDeclaration(Scope *S, TypeSourceInfo *TInfo,
3421 SourceLocation StartLoc,
3422 SourceLocation IdLoc,
3423 IdentifierInfo *Id);
3425 Decl *ActOnExceptionDeclarator(Scope *S, Declarator &D);
3427 StmtResult ActOnCXXCatchBlock(SourceLocation CatchLoc,
3428 Decl *ExDecl, Stmt *HandlerBlock);
3429 StmtResult ActOnCXXTryBlock(SourceLocation TryLoc, Stmt *TryBlock,
3430 ArrayRef<Stmt *> Handlers);
3432 StmtResult ActOnSEHTryBlock(bool IsCXXTry, // try (true) or __try (false) ?
3433 SourceLocation TryLoc, Stmt *TryBlock,
3435 StmtResult ActOnSEHExceptBlock(SourceLocation Loc,
3438 void ActOnStartSEHFinallyBlock();
3439 void ActOnAbortSEHFinallyBlock();
3440 StmtResult ActOnFinishSEHFinallyBlock(SourceLocation Loc, Stmt *Block);
3441 StmtResult ActOnSEHLeaveStmt(SourceLocation Loc, Scope *CurScope);
3443 void DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock);
3445 bool ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const;
3447 /// \brief If it's a file scoped decl that must warn if not used, keep track
3449 void MarkUnusedFileScopedDecl(const DeclaratorDecl *D);
3451 /// DiagnoseUnusedExprResult - If the statement passed in is an expression
3452 /// whose result is unused, warn.
3453 void DiagnoseUnusedExprResult(const Stmt *S);
3454 void DiagnoseUnusedNestedTypedefs(const RecordDecl *D);
3455 void DiagnoseUnusedDecl(const NamedDecl *ND);
3457 /// Emit \p DiagID if statement located on \p StmtLoc has a suspicious null
3458 /// statement as a \p Body, and it is located on the same line.
3460 /// This helps prevent bugs due to typos, such as:
3463 void DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
3467 /// Warn if a for/while loop statement \p S, which is followed by
3468 /// \p PossibleBody, has a suspicious null statement as a body.
3469 void DiagnoseEmptyLoopBody(const Stmt *S,
3470 const Stmt *PossibleBody);
3472 /// Warn if a value is moved to itself.
3473 void DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
3474 SourceLocation OpLoc);
3476 ParsingDeclState PushParsingDeclaration(sema::DelayedDiagnosticPool &pool) {
3477 return DelayedDiagnostics.push(pool);
3479 void PopParsingDeclaration(ParsingDeclState state, Decl *decl);
3481 typedef ProcessingContextState ParsingClassState;
3482 ParsingClassState PushParsingClass() {
3483 return DelayedDiagnostics.pushUndelayed();
3485 void PopParsingClass(ParsingClassState state) {
3486 DelayedDiagnostics.popUndelayed(state);
3489 void redelayDiagnostics(sema::DelayedDiagnosticPool &pool);
3491 enum AvailabilityDiagnostic { AD_Deprecation, AD_Unavailable, AD_Partial };
3493 void EmitAvailabilityWarning(AvailabilityDiagnostic AD,
3494 NamedDecl *D, StringRef Message,
3496 const ObjCInterfaceDecl *UnknownObjCClass,
3497 const ObjCPropertyDecl *ObjCProperty,
3498 bool ObjCPropertyAccess);
3500 bool makeUnavailableInSystemHeader(SourceLocation loc,
3503 //===--------------------------------------------------------------------===//
3504 // Expression Parsing Callbacks: SemaExpr.cpp.
3506 bool CanUseDecl(NamedDecl *D);
3507 bool DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc,
3508 const ObjCInterfaceDecl *UnknownObjCClass=nullptr,
3509 bool ObjCPropertyAccess=false);
3510 void NoteDeletedFunction(FunctionDecl *FD);
3511 std::string getDeletedOrUnavailableSuffix(const FunctionDecl *FD);
3512 bool DiagnosePropertyAccessorMismatch(ObjCPropertyDecl *PD,
3513 ObjCMethodDecl *Getter,
3514 SourceLocation Loc);
3515 void DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
3516 ArrayRef<Expr *> Args);
3518 void PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
3519 Decl *LambdaContextDecl = nullptr,
3520 bool IsDecltype = false);
3521 enum ReuseLambdaContextDecl_t { ReuseLambdaContextDecl };
3522 void PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
3523 ReuseLambdaContextDecl_t,
3524 bool IsDecltype = false);
3525 void PopExpressionEvaluationContext();
3527 void DiscardCleanupsInEvaluationContext();
3529 ExprResult TransformToPotentiallyEvaluated(Expr *E);
3530 ExprResult HandleExprEvaluationContextForTypeof(Expr *E);
3532 ExprResult ActOnConstantExpression(ExprResult Res);
3534 // Functions for marking a declaration referenced. These functions also
3535 // contain the relevant logic for marking if a reference to a function or
3536 // variable is an odr-use (in the C++11 sense). There are separate variants
3537 // for expressions referring to a decl; these exist because odr-use marking
3538 // needs to be delayed for some constant variables when we build one of the
3539 // named expressions.
3540 void MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, bool OdrUse);
3541 void MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func,
3542 bool OdrUse = true);
3543 void MarkVariableReferenced(SourceLocation Loc, VarDecl *Var);
3544 void MarkDeclRefReferenced(DeclRefExpr *E);
3545 void MarkMemberReferenced(MemberExpr *E);
3547 void UpdateMarkingForLValueToRValue(Expr *E);
3548 void CleanupVarDeclMarking();
3550 enum TryCaptureKind {
3551 TryCapture_Implicit, TryCapture_ExplicitByVal, TryCapture_ExplicitByRef
3554 /// \brief Try to capture the given variable.
3556 /// \param Var The variable to capture.
3558 /// \param Loc The location at which the capture occurs.
3560 /// \param Kind The kind of capture, which may be implicit (for either a
3561 /// block or a lambda), or explicit by-value or by-reference (for a lambda).
3563 /// \param EllipsisLoc The location of the ellipsis, if one is provided in
3564 /// an explicit lambda capture.
3566 /// \param BuildAndDiagnose Whether we are actually supposed to add the
3567 /// captures or diagnose errors. If false, this routine merely check whether
3568 /// the capture can occur without performing the capture itself or complaining
3569 /// if the variable cannot be captured.
3571 /// \param CaptureType Will be set to the type of the field used to capture
3572 /// this variable in the innermost block or lambda. Only valid when the
3573 /// variable can be captured.
3575 /// \param DeclRefType Will be set to the type of a reference to the capture
3576 /// from within the current scope. Only valid when the variable can be
3579 /// \param FunctionScopeIndexToStopAt If non-null, it points to the index
3580 /// of the FunctionScopeInfo stack beyond which we do not attempt to capture.
3581 /// This is useful when enclosing lambdas must speculatively capture
3582 /// variables that may or may not be used in certain specializations of
3583 /// a nested generic lambda.
3585 /// \returns true if an error occurred (i.e., the variable cannot be
3586 /// captured) and false if the capture succeeded.
3587 bool tryCaptureVariable(VarDecl *Var, SourceLocation Loc, TryCaptureKind Kind,
3588 SourceLocation EllipsisLoc, bool BuildAndDiagnose,
3589 QualType &CaptureType,
3590 QualType &DeclRefType,
3591 const unsigned *const FunctionScopeIndexToStopAt);
3593 /// \brief Try to capture the given variable.
3594 bool tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
3595 TryCaptureKind Kind = TryCapture_Implicit,
3596 SourceLocation EllipsisLoc = SourceLocation());
3598 /// \brief Checks if the variable must be captured.
3599 bool NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc);
3601 /// \brief Given a variable, determine the type that a reference to that
3602 /// variable will have in the given scope.
3603 QualType getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc);
3605 void MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T);
3606 void MarkDeclarationsReferencedInExpr(Expr *E,
3607 bool SkipLocalVariables = false);
3609 /// \brief Try to recover by turning the given expression into a
3610 /// call. Returns true if recovery was attempted or an error was
3611 /// emitted; this may also leave the ExprResult invalid.
3612 bool tryToRecoverWithCall(ExprResult &E, const PartialDiagnostic &PD,
3613 bool ForceComplain = false,
3614 bool (*IsPlausibleResult)(QualType) = nullptr);
3616 /// \brief Figure out if an expression could be turned into a call.
3617 bool tryExprAsCall(Expr &E, QualType &ZeroArgCallReturnTy,
3618 UnresolvedSetImpl &NonTemplateOverloads);
3620 /// \brief Conditionally issue a diagnostic based on the current
3621 /// evaluation context.
3623 /// \param Statement If Statement is non-null, delay reporting the
3624 /// diagnostic until the function body is parsed, and then do a basic
3625 /// reachability analysis to determine if the statement is reachable.
3626 /// If it is unreachable, the diagnostic will not be emitted.
3627 bool DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
3628 const PartialDiagnostic &PD);
3630 // Primary Expressions.
3631 SourceRange getExprRange(Expr *E) const;
3633 ExprResult ActOnIdExpression(
3634 Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
3635 UnqualifiedId &Id, bool HasTrailingLParen, bool IsAddressOfOperand,
3636 std::unique_ptr<CorrectionCandidateCallback> CCC = nullptr,
3637 bool IsInlineAsmIdentifier = false, Token *KeywordReplacement = nullptr);
3639 void DecomposeUnqualifiedId(const UnqualifiedId &Id,
3640 TemplateArgumentListInfo &Buffer,
3641 DeclarationNameInfo &NameInfo,
3642 const TemplateArgumentListInfo *&TemplateArgs);
3645 DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
3646 std::unique_ptr<CorrectionCandidateCallback> CCC,
3647 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr,
3648 ArrayRef<Expr *> Args = None, TypoExpr **Out = nullptr);
3650 ExprResult LookupInObjCMethod(LookupResult &LookUp, Scope *S,
3652 bool AllowBuiltinCreation=false);
3654 ExprResult ActOnDependentIdExpression(const CXXScopeSpec &SS,
3655 SourceLocation TemplateKWLoc,
3656 const DeclarationNameInfo &NameInfo,
3657 bool isAddressOfOperand,
3658 const TemplateArgumentListInfo *TemplateArgs);
3660 ExprResult BuildDeclRefExpr(ValueDecl *D, QualType Ty,
3663 const CXXScopeSpec *SS = nullptr);
3665 BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
3666 const DeclarationNameInfo &NameInfo,
3667 const CXXScopeSpec *SS = nullptr,
3668 NamedDecl *FoundD = nullptr,
3669 const TemplateArgumentListInfo *TemplateArgs = nullptr);
3671 BuildAnonymousStructUnionMemberReference(
3672 const CXXScopeSpec &SS,
3673 SourceLocation nameLoc,
3674 IndirectFieldDecl *indirectField,
3675 DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_none),
3676 Expr *baseObjectExpr = nullptr,
3677 SourceLocation opLoc = SourceLocation());
3679 ExprResult BuildPossibleImplicitMemberExpr(const CXXScopeSpec &SS,
3680 SourceLocation TemplateKWLoc,
3682 const TemplateArgumentListInfo *TemplateArgs);
3683 ExprResult BuildImplicitMemberExpr(const CXXScopeSpec &SS,
3684 SourceLocation TemplateKWLoc,
3686 const TemplateArgumentListInfo *TemplateArgs,
3687 bool IsDefiniteInstance);
3688 bool UseArgumentDependentLookup(const CXXScopeSpec &SS,
3689 const LookupResult &R,
3690 bool HasTrailingLParen);
3692 ExprResult BuildQualifiedDeclarationNameExpr(
3693 CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo,
3694 bool IsAddressOfOperand, TypeSourceInfo **RecoveryTSI = nullptr);
3696 ExprResult BuildDependentDeclRefExpr(const CXXScopeSpec &SS,
3697 SourceLocation TemplateKWLoc,
3698 const DeclarationNameInfo &NameInfo,
3699 const TemplateArgumentListInfo *TemplateArgs);
3701 ExprResult BuildDeclarationNameExpr(const CXXScopeSpec &SS,
3704 bool AcceptInvalidDecl = false);
3705 ExprResult BuildDeclarationNameExpr(
3706 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
3707 NamedDecl *FoundD = nullptr,
3708 const TemplateArgumentListInfo *TemplateArgs = nullptr,
3709 bool AcceptInvalidDecl = false);
3711 ExprResult BuildLiteralOperatorCall(LookupResult &R,
3712 DeclarationNameInfo &SuffixInfo,
3713 ArrayRef<Expr *> Args,
3714 SourceLocation LitEndLoc,
3715 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr);
3717 ExprResult BuildPredefinedExpr(SourceLocation Loc,
3718 PredefinedExpr::IdentType IT);
3719 ExprResult ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind);
3720 ExprResult ActOnIntegerConstant(SourceLocation Loc, uint64_t Val);
3722 bool CheckLoopHintExpr(Expr *E, SourceLocation Loc);
3724 ExprResult ActOnNumericConstant(const Token &Tok, Scope *UDLScope = nullptr);
3725 ExprResult ActOnCharacterConstant(const Token &Tok,
3726 Scope *UDLScope = nullptr);
3727 ExprResult ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E);
3728 ExprResult ActOnParenListExpr(SourceLocation L,
3732 /// ActOnStringLiteral - The specified tokens were lexed as pasted string
3733 /// fragments (e.g. "foo" "bar" L"baz").
3734 ExprResult ActOnStringLiteral(ArrayRef<Token> StringToks,
3735 Scope *UDLScope = nullptr);
3737 ExprResult ActOnGenericSelectionExpr(SourceLocation KeyLoc,
3738 SourceLocation DefaultLoc,
3739 SourceLocation RParenLoc,
3740 Expr *ControllingExpr,
3741 ArrayRef<ParsedType> ArgTypes,
3742 ArrayRef<Expr *> ArgExprs);
3743 ExprResult CreateGenericSelectionExpr(SourceLocation KeyLoc,
3744 SourceLocation DefaultLoc,
3745 SourceLocation RParenLoc,
3746 Expr *ControllingExpr,
3747 ArrayRef<TypeSourceInfo *> Types,
3748 ArrayRef<Expr *> Exprs);
3750 // Binary/Unary Operators. 'Tok' is the token for the operator.
3751 ExprResult CreateBuiltinUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc,
3753 ExprResult BuildUnaryOp(Scope *S, SourceLocation OpLoc,
3754 UnaryOperatorKind Opc, Expr *Input);
3755 ExprResult ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
3756 tok::TokenKind Op, Expr *Input);
3758 QualType CheckAddressOfOperand(ExprResult &Operand, SourceLocation OpLoc);
3760 ExprResult CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
3761 SourceLocation OpLoc,
3762 UnaryExprOrTypeTrait ExprKind,
3764 ExprResult CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
3765 UnaryExprOrTypeTrait ExprKind);
3767 ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
3768 UnaryExprOrTypeTrait ExprKind,
3769 bool IsType, void *TyOrEx,
3770 const SourceRange &ArgRange);
3772 ExprResult CheckPlaceholderExpr(Expr *E);
3773 bool CheckVecStepExpr(Expr *E);
3775 bool CheckUnaryExprOrTypeTraitOperand(Expr *E, UnaryExprOrTypeTrait ExprKind);
3776 bool CheckUnaryExprOrTypeTraitOperand(QualType ExprType, SourceLocation OpLoc,
3777 SourceRange ExprRange,
3778 UnaryExprOrTypeTrait ExprKind);
3779 ExprResult ActOnSizeofParameterPackExpr(Scope *S,
3780 SourceLocation OpLoc,
3781 IdentifierInfo &Name,
3782 SourceLocation NameLoc,
3783 SourceLocation RParenLoc);
3784 ExprResult ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
3785 tok::TokenKind Kind, Expr *Input);
3787 ExprResult ActOnArraySubscriptExpr(Scope *S, Expr *Base, SourceLocation LLoc,
3788 Expr *Idx, SourceLocation RLoc);
3789 ExprResult CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
3790 Expr *Idx, SourceLocation RLoc);
3792 // This struct is for use by ActOnMemberAccess to allow
3793 // BuildMemberReferenceExpr to be able to reinvoke ActOnMemberAccess after
3794 // changing the access operator from a '.' to a '->' (to see if that is the
3795 // change needed to fix an error about an unknown member, e.g. when the class
3796 // defines a custom operator->).
3797 struct ActOnMemberAccessExtraArgs {
3803 ExprResult BuildMemberReferenceExpr(
3804 Expr *Base, QualType BaseType, SourceLocation OpLoc, bool IsArrow,
3805 CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
3806 NamedDecl *FirstQualifierInScope, const DeclarationNameInfo &NameInfo,
3807 const TemplateArgumentListInfo *TemplateArgs,
3808 ActOnMemberAccessExtraArgs *ExtraArgs = nullptr);
3811 BuildMemberReferenceExpr(Expr *Base, QualType BaseType, SourceLocation OpLoc,
3812 bool IsArrow, const CXXScopeSpec &SS,
3813 SourceLocation TemplateKWLoc,
3814 NamedDecl *FirstQualifierInScope, LookupResult &R,
3815 const TemplateArgumentListInfo *TemplateArgs,
3816 bool SuppressQualifierCheck = false,
3817 ActOnMemberAccessExtraArgs *ExtraArgs = nullptr);
3819 ExprResult PerformMemberExprBaseConversion(Expr *Base, bool IsArrow);
3821 bool CheckQualifiedMemberReference(Expr *BaseExpr, QualType BaseType,
3822 const CXXScopeSpec &SS,
3823 const LookupResult &R);
3825 ExprResult ActOnDependentMemberExpr(Expr *Base, QualType BaseType,
3826 bool IsArrow, SourceLocation OpLoc,
3827 const CXXScopeSpec &SS,
3828 SourceLocation TemplateKWLoc,
3829 NamedDecl *FirstQualifierInScope,
3830 const DeclarationNameInfo &NameInfo,
3831 const TemplateArgumentListInfo *TemplateArgs);
3833 ExprResult ActOnMemberAccessExpr(Scope *S, Expr *Base,
3834 SourceLocation OpLoc,
3835 tok::TokenKind OpKind,
3837 SourceLocation TemplateKWLoc,
3838 UnqualifiedId &Member,
3841 void ActOnDefaultCtorInitializers(Decl *CDtorDecl);
3842 bool ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
3843 FunctionDecl *FDecl,
3844 const FunctionProtoType *Proto,
3845 ArrayRef<Expr *> Args,
3846 SourceLocation RParenLoc,
3847 bool ExecConfig = false);
3848 void CheckStaticArrayArgument(SourceLocation CallLoc,
3850 const Expr *ArgExpr);
3852 /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
3853 /// This provides the location of the left/right parens and a list of comma
3855 ExprResult ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
3856 MultiExprArg ArgExprs, SourceLocation RParenLoc,
3857 Expr *ExecConfig = nullptr,
3858 bool IsExecConfig = false);
3859 ExprResult BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
3860 SourceLocation LParenLoc,
3861 ArrayRef<Expr *> Arg,
3862 SourceLocation RParenLoc,
3863 Expr *Config = nullptr,
3864 bool IsExecConfig = false);
3866 ExprResult ActOnCUDAExecConfigExpr(Scope *S, SourceLocation LLLLoc,
3867 MultiExprArg ExecConfig,
3868 SourceLocation GGGLoc);
3870 ExprResult ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
3871 Declarator &D, ParsedType &Ty,
3872 SourceLocation RParenLoc, Expr *CastExpr);
3873 ExprResult BuildCStyleCastExpr(SourceLocation LParenLoc,
3875 SourceLocation RParenLoc,
3877 CastKind PrepareScalarCast(ExprResult &src, QualType destType);
3879 /// \brief Build an altivec or OpenCL literal.
3880 ExprResult BuildVectorLiteral(SourceLocation LParenLoc,
3881 SourceLocation RParenLoc, Expr *E,
3882 TypeSourceInfo *TInfo);
3884 ExprResult MaybeConvertParenListExprToParenExpr(Scope *S, Expr *ME);
3886 ExprResult ActOnCompoundLiteral(SourceLocation LParenLoc,
3888 SourceLocation RParenLoc,
3891 ExprResult BuildCompoundLiteralExpr(SourceLocation LParenLoc,
3892 TypeSourceInfo *TInfo,
3893 SourceLocation RParenLoc,
3896 ExprResult ActOnInitList(SourceLocation LBraceLoc,
3897 MultiExprArg InitArgList,
3898 SourceLocation RBraceLoc);
3900 ExprResult ActOnDesignatedInitializer(Designation &Desig,
3906 static BinaryOperatorKind ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind);
3909 ExprResult ActOnBinOp(Scope *S, SourceLocation TokLoc,
3910 tok::TokenKind Kind, Expr *LHSExpr, Expr *RHSExpr);
3911 ExprResult BuildBinOp(Scope *S, SourceLocation OpLoc,
3912 BinaryOperatorKind Opc, Expr *LHSExpr, Expr *RHSExpr);
3913 ExprResult CreateBuiltinBinOp(SourceLocation OpLoc, BinaryOperatorKind Opc,
3914 Expr *LHSExpr, Expr *RHSExpr);
3916 /// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
3917 /// in the case of a the GNU conditional expr extension.
3918 ExprResult ActOnConditionalOp(SourceLocation QuestionLoc,
3919 SourceLocation ColonLoc,
3920 Expr *CondExpr, Expr *LHSExpr, Expr *RHSExpr);
3922 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
3923 ExprResult ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
3924 LabelDecl *TheDecl);
3926 void ActOnStartStmtExpr();
3927 ExprResult ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
3928 SourceLocation RPLoc); // "({..})"
3929 void ActOnStmtExprError();
3931 // __builtin_offsetof(type, identifier(.identifier|[expr])*)
3932 struct OffsetOfComponent {
3933 SourceLocation LocStart, LocEnd;
3934 bool isBrackets; // true if [expr], false if .ident
3936 IdentifierInfo *IdentInfo;
3941 /// __builtin_offsetof(type, a.b[123][456].c)
3942 ExprResult BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
3943 TypeSourceInfo *TInfo,
3944 OffsetOfComponent *CompPtr,
3945 unsigned NumComponents,
3946 SourceLocation RParenLoc);
3947 ExprResult ActOnBuiltinOffsetOf(Scope *S,
3948 SourceLocation BuiltinLoc,
3949 SourceLocation TypeLoc,
3950 ParsedType ParsedArgTy,
3951 OffsetOfComponent *CompPtr,
3952 unsigned NumComponents,
3953 SourceLocation RParenLoc);
3955 // __builtin_choose_expr(constExpr, expr1, expr2)
3956 ExprResult ActOnChooseExpr(SourceLocation BuiltinLoc,
3957 Expr *CondExpr, Expr *LHSExpr,
3958 Expr *RHSExpr, SourceLocation RPLoc);
3960 // __builtin_va_arg(expr, type)
3961 ExprResult ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty,
3962 SourceLocation RPLoc);
3963 ExprResult BuildVAArgExpr(SourceLocation BuiltinLoc, Expr *E,
3964 TypeSourceInfo *TInfo, SourceLocation RPLoc);
3967 ExprResult ActOnGNUNullExpr(SourceLocation TokenLoc);
3969 bool CheckCaseExpression(Expr *E);
3971 /// \brief Describes the result of an "if-exists" condition check.
3972 enum IfExistsResult {
3973 /// \brief The symbol exists.
3976 /// \brief The symbol does not exist.
3979 /// \brief The name is a dependent name, so the results will differ
3980 /// from one instantiation to the next.
3983 /// \brief An error occurred.
3988 CheckMicrosoftIfExistsSymbol(Scope *S, CXXScopeSpec &SS,
3989 const DeclarationNameInfo &TargetNameInfo);
3992 CheckMicrosoftIfExistsSymbol(Scope *S, SourceLocation KeywordLoc,
3993 bool IsIfExists, CXXScopeSpec &SS,
3994 UnqualifiedId &Name);
3996 StmtResult BuildMSDependentExistsStmt(SourceLocation KeywordLoc,
3998 NestedNameSpecifierLoc QualifierLoc,
3999 DeclarationNameInfo NameInfo,
4001 StmtResult ActOnMSDependentExistsStmt(SourceLocation KeywordLoc,
4003 CXXScopeSpec &SS, UnqualifiedId &Name,
4006 //===------------------------- "Block" Extension ------------------------===//
4008 /// ActOnBlockStart - This callback is invoked when a block literal is
4010 void ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope);
4012 /// ActOnBlockArguments - This callback allows processing of block arguments.
4013 /// If there are no arguments, this is still invoked.
4014 void ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
4017 /// ActOnBlockError - If there is an error parsing a block, this callback
4018 /// is invoked to pop the information about the block from the action impl.
4019 void ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope);
4021 /// ActOnBlockStmtExpr - This is called when the body of a block statement
4022 /// literal was successfully completed. ^(int x){...}
4023 ExprResult ActOnBlockStmtExpr(SourceLocation CaretLoc, Stmt *Body,
4026 //===---------------------------- Clang Extensions ----------------------===//
4028 /// __builtin_convertvector(...)
4029 ExprResult ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy,
4030 SourceLocation BuiltinLoc,
4031 SourceLocation RParenLoc);
4033 //===---------------------------- OpenCL Features -----------------------===//
4035 /// __builtin_astype(...)
4036 ExprResult ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
4037 SourceLocation BuiltinLoc,
4038 SourceLocation RParenLoc);
4040 //===---------------------------- C++ Features --------------------------===//
4042 // Act on C++ namespaces
4043 Decl *ActOnStartNamespaceDef(Scope *S, SourceLocation InlineLoc,
4044 SourceLocation NamespaceLoc,
4045 SourceLocation IdentLoc,
4046 IdentifierInfo *Ident,
4047 SourceLocation LBrace,
4048 AttributeList *AttrList);
4049 void ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace);
4051 NamespaceDecl *getStdNamespace() const;
4052 NamespaceDecl *getOrCreateStdNamespace();
4054 CXXRecordDecl *getStdBadAlloc() const;
4056 /// \brief Tests whether Ty is an instance of std::initializer_list and, if
4057 /// it is and Element is not NULL, assigns the element type to Element.
4058 bool isStdInitializerList(QualType Ty, QualType *Element);
4060 /// \brief Looks for the std::initializer_list template and instantiates it
4061 /// with Element, or emits an error if it's not found.
4063 /// \returns The instantiated template, or null on error.
4064 QualType BuildStdInitializerList(QualType Element, SourceLocation Loc);
4066 /// \brief Determine whether Ctor is an initializer-list constructor, as
4067 /// defined in [dcl.init.list]p2.
4068 bool isInitListConstructor(const CXXConstructorDecl *Ctor);
4070 Decl *ActOnUsingDirective(Scope *CurScope,
4071 SourceLocation UsingLoc,
4072 SourceLocation NamespcLoc,
4074 SourceLocation IdentLoc,
4075 IdentifierInfo *NamespcName,
4076 AttributeList *AttrList);
4078 void PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir);
4080 Decl *ActOnNamespaceAliasDef(Scope *CurScope,
4081 SourceLocation NamespaceLoc,
4082 SourceLocation AliasLoc,
4083 IdentifierInfo *Alias,
4085 SourceLocation IdentLoc,
4086 IdentifierInfo *Ident);
4088 void HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow);
4089 bool CheckUsingShadowDecl(UsingDecl *UD, NamedDecl *Target,
4090 const LookupResult &PreviousDecls,
4091 UsingShadowDecl *&PrevShadow);
4092 UsingShadowDecl *BuildUsingShadowDecl(Scope *S, UsingDecl *UD,
4094 UsingShadowDecl *PrevDecl);
4096 bool CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
4097 bool HasTypenameKeyword,
4098 const CXXScopeSpec &SS,
4099 SourceLocation NameLoc,
4100 const LookupResult &Previous);
4101 bool CheckUsingDeclQualifier(SourceLocation UsingLoc,
4102 const CXXScopeSpec &SS,
4103 const DeclarationNameInfo &NameInfo,
4104 SourceLocation NameLoc);
4106 NamedDecl *BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
4107 SourceLocation UsingLoc,
4109 DeclarationNameInfo NameInfo,
4110 AttributeList *AttrList,
4111 bool IsInstantiation,
4112 bool HasTypenameKeyword,
4113 SourceLocation TypenameLoc);
4115 bool CheckInheritingConstructorUsingDecl(UsingDecl *UD);
4117 Decl *ActOnUsingDeclaration(Scope *CurScope,
4119 bool HasUsingKeyword,
4120 SourceLocation UsingLoc,
4122 UnqualifiedId &Name,
4123 AttributeList *AttrList,
4124 bool HasTypenameKeyword,
4125 SourceLocation TypenameLoc);
4126 Decl *ActOnAliasDeclaration(Scope *CurScope,
4128 MultiTemplateParamsArg TemplateParams,
4129 SourceLocation UsingLoc,
4130 UnqualifiedId &Name,
4131 AttributeList *AttrList,
4133 Decl *DeclFromDeclSpec);
4135 /// BuildCXXConstructExpr - Creates a complete call to a constructor,
4136 /// including handling of its default argument expressions.
4138 /// \param ConstructKind - a CXXConstructExpr::ConstructionKind
4140 BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
4141 CXXConstructorDecl *Constructor, MultiExprArg Exprs,
4142 bool HadMultipleCandidates, bool IsListInitialization,
4143 bool IsStdInitListInitialization,
4144 bool RequiresZeroInit, unsigned ConstructKind,
4145 SourceRange ParenRange);
4147 // FIXME: Can we remove this and have the above BuildCXXConstructExpr check if
4148 // the constructor can be elidable?
4150 BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
4151 CXXConstructorDecl *Constructor, bool Elidable,
4152 MultiExprArg Exprs, bool HadMultipleCandidates,
4153 bool IsListInitialization,
4154 bool IsStdInitListInitialization, bool RequiresZeroInit,
4155 unsigned ConstructKind, SourceRange ParenRange);
4157 ExprResult BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field);
4159 /// BuildCXXDefaultArgExpr - Creates a CXXDefaultArgExpr, instantiating
4160 /// the default expr if needed.
4161 ExprResult BuildCXXDefaultArgExpr(SourceLocation CallLoc,
4163 ParmVarDecl *Param);
4165 /// FinalizeVarWithDestructor - Prepare for calling destructor on the
4166 /// constructed variable.
4167 void FinalizeVarWithDestructor(VarDecl *VD, const RecordType *DeclInitType);
4169 /// \brief Helper class that collects exception specifications for
4170 /// implicitly-declared special member functions.
4171 class ImplicitExceptionSpecification {
4172 // Pointer to allow copying
4174 // We order exception specifications thus:
4175 // noexcept is the most restrictive, but is only used in C++11.
4176 // throw() comes next.
4177 // Then a throw(collected exceptions)
4178 // Finally no specification, which is expressed as noexcept(false).
4179 // throw(...) is used instead if any called function uses it.
4180 ExceptionSpecificationType ComputedEST;
4181 llvm::SmallPtrSet<CanQualType, 4> ExceptionsSeen;
4182 SmallVector<QualType, 4> Exceptions;
4184 void ClearExceptions() {
4185 ExceptionsSeen.clear();
4190 explicit ImplicitExceptionSpecification(Sema &Self)
4191 : Self(&Self), ComputedEST(EST_BasicNoexcept) {
4192 if (!Self.getLangOpts().CPlusPlus11)
4193 ComputedEST = EST_DynamicNone;
4196 /// \brief Get the computed exception specification type.
4197 ExceptionSpecificationType getExceptionSpecType() const {
4198 assert(ComputedEST != EST_ComputedNoexcept &&
4199 "noexcept(expr) should not be a possible result");
4203 /// \brief The number of exceptions in the exception specification.
4204 unsigned size() const { return Exceptions.size(); }
4206 /// \brief The set of exceptions in the exception specification.
4207 const QualType *data() const { return Exceptions.data(); }
4209 /// \brief Integrate another called method into the collected data.
4210 void CalledDecl(SourceLocation CallLoc, const CXXMethodDecl *Method);
4212 /// \brief Integrate an invoked expression into the collected data.
4213 void CalledExpr(Expr *E);
4215 /// \brief Overwrite an EPI's exception specification with this
4216 /// computed exception specification.
4217 FunctionProtoType::ExceptionSpecInfo getExceptionSpec() const {
4218 FunctionProtoType::ExceptionSpecInfo ESI;
4219 ESI.Type = getExceptionSpecType();
4220 if (ESI.Type == EST_Dynamic) {
4221 ESI.Exceptions = Exceptions;
4222 } else if (ESI.Type == EST_None) {
4223 /// C++11 [except.spec]p14:
4224 /// The exception-specification is noexcept(false) if the set of
4225 /// potential exceptions of the special member function contains "any"
4226 ESI.Type = EST_ComputedNoexcept;
4227 ESI.NoexceptExpr = Self->ActOnCXXBoolLiteral(SourceLocation(),
4228 tok::kw_false).get();
4234 /// \brief Determine what sort of exception specification a defaulted
4235 /// copy constructor of a class will have.
4236 ImplicitExceptionSpecification
4237 ComputeDefaultedDefaultCtorExceptionSpec(SourceLocation Loc,
4240 /// \brief Determine what sort of exception specification a defaulted
4241 /// default constructor of a class will have, and whether the parameter
4243 ImplicitExceptionSpecification
4244 ComputeDefaultedCopyCtorExceptionSpec(CXXMethodDecl *MD);
4246 /// \brief Determine what sort of exception specification a defautled
4247 /// copy assignment operator of a class will have, and whether the
4248 /// parameter will be const.
4249 ImplicitExceptionSpecification
4250 ComputeDefaultedCopyAssignmentExceptionSpec(CXXMethodDecl *MD);
4252 /// \brief Determine what sort of exception specification a defaulted move
4253 /// constructor of a class will have.
4254 ImplicitExceptionSpecification
4255 ComputeDefaultedMoveCtorExceptionSpec(CXXMethodDecl *MD);
4257 /// \brief Determine what sort of exception specification a defaulted move
4258 /// assignment operator of a class will have.
4259 ImplicitExceptionSpecification
4260 ComputeDefaultedMoveAssignmentExceptionSpec(CXXMethodDecl *MD);
4262 /// \brief Determine what sort of exception specification a defaulted
4263 /// destructor of a class will have.
4264 ImplicitExceptionSpecification
4265 ComputeDefaultedDtorExceptionSpec(CXXMethodDecl *MD);
4267 /// \brief Determine what sort of exception specification an inheriting
4268 /// constructor of a class will have.
4269 ImplicitExceptionSpecification
4270 ComputeInheritingCtorExceptionSpec(CXXConstructorDecl *CD);
4272 /// \brief Evaluate the implicit exception specification for a defaulted
4273 /// special member function.
4274 void EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD);
4276 /// \brief Check the given exception-specification and update the
4277 /// exception specification information with the results.
4278 void checkExceptionSpecification(bool IsTopLevel,
4279 ExceptionSpecificationType EST,
4280 ArrayRef<ParsedType> DynamicExceptions,
4281 ArrayRef<SourceRange> DynamicExceptionRanges,
4283 SmallVectorImpl<QualType> &Exceptions,
4284 FunctionProtoType::ExceptionSpecInfo &ESI);
4286 /// \brief Determine if we're in a case where we need to (incorrectly) eagerly
4287 /// parse an exception specification to work around a libstdc++ bug.
4288 bool isLibstdcxxEagerExceptionSpecHack(const Declarator &D);
4290 /// \brief Add an exception-specification to the given member function
4291 /// (or member function template). The exception-specification was parsed
4292 /// after the method itself was declared.
4293 void actOnDelayedExceptionSpecification(Decl *Method,
4294 ExceptionSpecificationType EST,
4295 SourceRange SpecificationRange,
4296 ArrayRef<ParsedType> DynamicExceptions,
4297 ArrayRef<SourceRange> DynamicExceptionRanges,
4298 Expr *NoexceptExpr);
4300 /// \brief Determine if a special member function should have a deleted
4301 /// definition when it is defaulted.
4302 bool ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
4303 bool Diagnose = false);
4305 /// \brief Declare the implicit default constructor for the given class.
4307 /// \param ClassDecl The class declaration into which the implicit
4308 /// default constructor will be added.
4310 /// \returns The implicitly-declared default constructor.
4311 CXXConstructorDecl *DeclareImplicitDefaultConstructor(
4312 CXXRecordDecl *ClassDecl);
4314 /// DefineImplicitDefaultConstructor - Checks for feasibility of
4315 /// defining this constructor as the default constructor.
4316 void DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
4317 CXXConstructorDecl *Constructor);
4319 /// \brief Declare the implicit destructor for the given class.
4321 /// \param ClassDecl The class declaration into which the implicit
4322 /// destructor will be added.
4324 /// \returns The implicitly-declared destructor.
4325 CXXDestructorDecl *DeclareImplicitDestructor(CXXRecordDecl *ClassDecl);
4327 /// DefineImplicitDestructor - Checks for feasibility of
4328 /// defining this destructor as the default destructor.
4329 void DefineImplicitDestructor(SourceLocation CurrentLocation,
4330 CXXDestructorDecl *Destructor);
4332 /// \brief Build an exception spec for destructors that don't have one.
4334 /// C++11 says that user-defined destructors with no exception spec get one
4335 /// that looks as if the destructor was implicitly declared.
4336 void AdjustDestructorExceptionSpec(CXXRecordDecl *ClassDecl,
4337 CXXDestructorDecl *Destructor);
4339 /// \brief Declare all inheriting constructors for the given class.
4341 /// \param ClassDecl The class declaration into which the inheriting
4342 /// constructors will be added.
4343 void DeclareInheritingConstructors(CXXRecordDecl *ClassDecl);
4345 /// \brief Define the specified inheriting constructor.
4346 void DefineInheritingConstructor(SourceLocation UseLoc,
4347 CXXConstructorDecl *Constructor);
4349 /// \brief Declare the implicit copy constructor for the given class.
4351 /// \param ClassDecl The class declaration into which the implicit
4352 /// copy constructor will be added.
4354 /// \returns The implicitly-declared copy constructor.
4355 CXXConstructorDecl *DeclareImplicitCopyConstructor(CXXRecordDecl *ClassDecl);
4357 /// DefineImplicitCopyConstructor - Checks for feasibility of
4358 /// defining this constructor as the copy constructor.
4359 void DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
4360 CXXConstructorDecl *Constructor);
4362 /// \brief Declare the implicit move constructor for the given class.
4364 /// \param ClassDecl The Class declaration into which the implicit
4365 /// move constructor will be added.
4367 /// \returns The implicitly-declared move constructor, or NULL if it wasn't
4369 CXXConstructorDecl *DeclareImplicitMoveConstructor(CXXRecordDecl *ClassDecl);
4371 /// DefineImplicitMoveConstructor - Checks for feasibility of
4372 /// defining this constructor as the move constructor.
4373 void DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
4374 CXXConstructorDecl *Constructor);
4376 /// \brief Declare the implicit copy assignment operator for the given class.
4378 /// \param ClassDecl The class declaration into which the implicit
4379 /// copy assignment operator will be added.
4381 /// \returns The implicitly-declared copy assignment operator.
4382 CXXMethodDecl *DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl);
4384 /// \brief Defines an implicitly-declared copy assignment operator.
4385 void DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
4386 CXXMethodDecl *MethodDecl);
4388 /// \brief Declare the implicit move assignment operator for the given class.
4390 /// \param ClassDecl The Class declaration into which the implicit
4391 /// move assignment operator will be added.
4393 /// \returns The implicitly-declared move assignment operator, or NULL if it
4394 /// wasn't declared.
4395 CXXMethodDecl *DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl);
4397 /// \brief Defines an implicitly-declared move assignment operator.
4398 void DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
4399 CXXMethodDecl *MethodDecl);
4401 /// \brief Force the declaration of any implicitly-declared members of this
4403 void ForceDeclarationOfImplicitMembers(CXXRecordDecl *Class);
4405 /// \brief Determine whether the given function is an implicitly-deleted
4406 /// special member function.
4407 bool isImplicitlyDeleted(FunctionDecl *FD);
4409 /// \brief Check whether 'this' shows up in the type of a static member
4410 /// function after the (naturally empty) cv-qualifier-seq would be.
4412 /// \returns true if an error occurred.
4413 bool checkThisInStaticMemberFunctionType(CXXMethodDecl *Method);
4415 /// \brief Whether this' shows up in the exception specification of a static
4416 /// member function.
4417 bool checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method);
4419 /// \brief Check whether 'this' shows up in the attributes of the given
4420 /// static member function.
4422 /// \returns true if an error occurred.
4423 bool checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method);
4425 /// MaybeBindToTemporary - If the passed in expression has a record type with
4426 /// a non-trivial destructor, this will return CXXBindTemporaryExpr. Otherwise
4427 /// it simply returns the passed in expression.
4428 ExprResult MaybeBindToTemporary(Expr *E);
4430 bool CompleteConstructorCall(CXXConstructorDecl *Constructor,
4431 MultiExprArg ArgsPtr,
4433 SmallVectorImpl<Expr*> &ConvertedArgs,
4434 bool AllowExplicit = false,
4435 bool IsListInitialization = false);
4437 ParsedType getInheritingConstructorName(CXXScopeSpec &SS,
4438 SourceLocation NameLoc,
4439 IdentifierInfo &Name);
4441 ParsedType getDestructorName(SourceLocation TildeLoc,
4442 IdentifierInfo &II, SourceLocation NameLoc,
4443 Scope *S, CXXScopeSpec &SS,
4444 ParsedType ObjectType,
4445 bool EnteringContext);
4447 ParsedType getDestructorType(const DeclSpec& DS, ParsedType ObjectType);
4449 // Checks that reinterpret casts don't have undefined behavior.
4450 void CheckCompatibleReinterpretCast(QualType SrcType, QualType DestType,
4451 bool IsDereference, SourceRange Range);
4453 /// ActOnCXXNamedCast - Parse {dynamic,static,reinterpret,const}_cast's.
4454 ExprResult ActOnCXXNamedCast(SourceLocation OpLoc,
4455 tok::TokenKind Kind,
4456 SourceLocation LAngleBracketLoc,
4458 SourceLocation RAngleBracketLoc,
4459 SourceLocation LParenLoc,
4461 SourceLocation RParenLoc);
4463 ExprResult BuildCXXNamedCast(SourceLocation OpLoc,
4464 tok::TokenKind Kind,
4467 SourceRange AngleBrackets,
4468 SourceRange Parens);
4470 ExprResult BuildCXXTypeId(QualType TypeInfoType,
4471 SourceLocation TypeidLoc,
4472 TypeSourceInfo *Operand,
4473 SourceLocation RParenLoc);
4474 ExprResult BuildCXXTypeId(QualType TypeInfoType,
4475 SourceLocation TypeidLoc,
4477 SourceLocation RParenLoc);
4479 /// ActOnCXXTypeid - Parse typeid( something ).
4480 ExprResult ActOnCXXTypeid(SourceLocation OpLoc,
4481 SourceLocation LParenLoc, bool isType,
4483 SourceLocation RParenLoc);
4485 ExprResult BuildCXXUuidof(QualType TypeInfoType,
4486 SourceLocation TypeidLoc,
4487 TypeSourceInfo *Operand,
4488 SourceLocation RParenLoc);
4489 ExprResult BuildCXXUuidof(QualType TypeInfoType,
4490 SourceLocation TypeidLoc,
4492 SourceLocation RParenLoc);
4494 /// ActOnCXXUuidof - Parse __uuidof( something ).
4495 ExprResult ActOnCXXUuidof(SourceLocation OpLoc,
4496 SourceLocation LParenLoc, bool isType,
4498 SourceLocation RParenLoc);
4500 /// \brief Handle a C++1z fold-expression: ( expr op ... op expr ).
4501 ExprResult ActOnCXXFoldExpr(SourceLocation LParenLoc, Expr *LHS,
4502 tok::TokenKind Operator,
4503 SourceLocation EllipsisLoc, Expr *RHS,
4504 SourceLocation RParenLoc);
4505 ExprResult BuildCXXFoldExpr(SourceLocation LParenLoc, Expr *LHS,
4506 BinaryOperatorKind Operator,
4507 SourceLocation EllipsisLoc, Expr *RHS,
4508 SourceLocation RParenLoc);
4509 ExprResult BuildEmptyCXXFoldExpr(SourceLocation EllipsisLoc,
4510 BinaryOperatorKind Operator);
4512 //// ActOnCXXThis - Parse 'this' pointer.
4513 ExprResult ActOnCXXThis(SourceLocation loc);
4515 /// \brief Try to retrieve the type of the 'this' pointer.
4517 /// \returns The type of 'this', if possible. Otherwise, returns a NULL type.
4518 QualType getCurrentThisType();
4520 /// \brief When non-NULL, the C++ 'this' expression is allowed despite the
4521 /// current context not being a non-static member function. In such cases,
4522 /// this provides the type used for 'this'.
4523 QualType CXXThisTypeOverride;
4525 /// \brief RAII object used to temporarily allow the C++ 'this' expression
4526 /// to be used, with the given qualifiers on the current class type.
4527 class CXXThisScopeRAII {
4529 QualType OldCXXThisTypeOverride;
4533 /// \brief Introduce a new scope where 'this' may be allowed (when enabled),
4534 /// using the given declaration (which is either a class template or a
4535 /// class) along with the given qualifiers.
4536 /// along with the qualifiers placed on '*this'.
4537 CXXThisScopeRAII(Sema &S, Decl *ContextDecl, unsigned CXXThisTypeQuals,
4538 bool Enabled = true);
4540 ~CXXThisScopeRAII();
4543 /// \brief Make sure the value of 'this' is actually available in the current
4544 /// context, if it is a potentially evaluated context.
4546 /// \param Loc The location at which the capture of 'this' occurs.
4548 /// \param Explicit Whether 'this' is explicitly captured in a lambda
4551 /// \param FunctionScopeIndexToStopAt If non-null, it points to the index
4552 /// of the FunctionScopeInfo stack beyond which we do not attempt to capture.
4553 /// This is useful when enclosing lambdas must speculatively capture
4554 /// 'this' that may or may not be used in certain specializations of
4555 /// a nested generic lambda (depending on whether the name resolves to
4556 /// a non-static member function or a static function).
4557 /// \return returns 'true' if failed, 'false' if success.
4558 bool CheckCXXThisCapture(SourceLocation Loc, bool Explicit = false,
4559 bool BuildAndDiagnose = true,
4560 const unsigned *const FunctionScopeIndexToStopAt = nullptr);
4562 /// \brief Determine whether the given type is the type of *this that is used
4563 /// outside of the body of a member function for a type that is currently
4565 bool isThisOutsideMemberFunctionBody(QualType BaseType);
4567 /// ActOnCXXBoolLiteral - Parse {true,false} literals.
4568 ExprResult ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind);
4571 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
4572 ExprResult ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind);
4574 /// ActOnCXXNullPtrLiteral - Parse 'nullptr'.
4575 ExprResult ActOnCXXNullPtrLiteral(SourceLocation Loc);
4577 //// ActOnCXXThrow - Parse throw expressions.
4578 ExprResult ActOnCXXThrow(Scope *S, SourceLocation OpLoc, Expr *expr);
4579 ExprResult BuildCXXThrow(SourceLocation OpLoc, Expr *Ex,
4580 bool IsThrownVarInScope);
4581 bool CheckCXXThrowOperand(SourceLocation ThrowLoc, QualType ThrowTy, Expr *E);
4583 /// ActOnCXXTypeConstructExpr - Parse construction of a specified type.
4584 /// Can be interpreted either as function-style casting ("int(x)")
4585 /// or class type construction ("ClassType(x,y,z)")
4586 /// or creation of a value-initialized type ("int()").
4587 ExprResult ActOnCXXTypeConstructExpr(ParsedType TypeRep,
4588 SourceLocation LParenLoc,
4590 SourceLocation RParenLoc);
4592 ExprResult BuildCXXTypeConstructExpr(TypeSourceInfo *Type,
4593 SourceLocation LParenLoc,
4595 SourceLocation RParenLoc);
4597 /// ActOnCXXNew - Parsed a C++ 'new' expression.
4598 ExprResult ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
4599 SourceLocation PlacementLParen,
4600 MultiExprArg PlacementArgs,
4601 SourceLocation PlacementRParen,
4602 SourceRange TypeIdParens, Declarator &D,
4604 ExprResult BuildCXXNew(SourceRange Range, bool UseGlobal,
4605 SourceLocation PlacementLParen,
4606 MultiExprArg PlacementArgs,
4607 SourceLocation PlacementRParen,
4608 SourceRange TypeIdParens,
4610 TypeSourceInfo *AllocTypeInfo,
4612 SourceRange DirectInitRange,
4614 bool TypeMayContainAuto = true);
4616 bool CheckAllocatedType(QualType AllocType, SourceLocation Loc,
4618 bool FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,
4619 bool UseGlobal, QualType AllocType, bool IsArray,
4620 MultiExprArg PlaceArgs,
4621 FunctionDecl *&OperatorNew,
4622 FunctionDecl *&OperatorDelete);
4623 bool FindAllocationOverload(SourceLocation StartLoc, SourceRange Range,
4624 DeclarationName Name, MultiExprArg Args,
4626 bool AllowMissing, FunctionDecl *&Operator,
4627 bool Diagnose = true);
4628 void DeclareGlobalNewDelete();
4629 void DeclareGlobalAllocationFunction(DeclarationName Name, QualType Return,
4631 QualType Param2 = QualType(),
4632 bool addRestrictAttr = false);
4634 bool FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD,
4635 DeclarationName Name, FunctionDecl* &Operator,
4636 bool Diagnose = true);
4637 FunctionDecl *FindUsualDeallocationFunction(SourceLocation StartLoc,
4638 bool CanProvideSize,
4639 DeclarationName Name);
4641 /// ActOnCXXDelete - Parsed a C++ 'delete' expression
4642 ExprResult ActOnCXXDelete(SourceLocation StartLoc,
4643 bool UseGlobal, bool ArrayForm,
4646 DeclResult ActOnCXXConditionDeclaration(Scope *S, Declarator &D);
4647 ExprResult CheckConditionVariable(VarDecl *ConditionVar,
4648 SourceLocation StmtLoc,
4649 bool ConvertToBoolean);
4651 ExprResult ActOnNoexceptExpr(SourceLocation KeyLoc, SourceLocation LParen,
4652 Expr *Operand, SourceLocation RParen);
4653 ExprResult BuildCXXNoexceptExpr(SourceLocation KeyLoc, Expr *Operand,
4654 SourceLocation RParen);
4656 /// \brief Parsed one of the type trait support pseudo-functions.
4657 ExprResult ActOnTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
4658 ArrayRef<ParsedType> Args,
4659 SourceLocation RParenLoc);
4660 ExprResult BuildTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
4661 ArrayRef<TypeSourceInfo *> Args,
4662 SourceLocation RParenLoc);
4664 /// ActOnArrayTypeTrait - Parsed one of the bianry type trait support
4665 /// pseudo-functions.
4666 ExprResult ActOnArrayTypeTrait(ArrayTypeTrait ATT,
4667 SourceLocation KWLoc,
4670 SourceLocation RParen);
4672 ExprResult BuildArrayTypeTrait(ArrayTypeTrait ATT,
4673 SourceLocation KWLoc,
4674 TypeSourceInfo *TSInfo,
4676 SourceLocation RParen);
4678 /// ActOnExpressionTrait - Parsed one of the unary type trait support
4679 /// pseudo-functions.
4680 ExprResult ActOnExpressionTrait(ExpressionTrait OET,
4681 SourceLocation KWLoc,
4683 SourceLocation RParen);
4685 ExprResult BuildExpressionTrait(ExpressionTrait OET,
4686 SourceLocation KWLoc,
4688 SourceLocation RParen);
4690 ExprResult ActOnStartCXXMemberReference(Scope *S,
4692 SourceLocation OpLoc,
4693 tok::TokenKind OpKind,
4694 ParsedType &ObjectType,
4695 bool &MayBePseudoDestructor);
4697 ExprResult BuildPseudoDestructorExpr(Expr *Base,
4698 SourceLocation OpLoc,
4699 tok::TokenKind OpKind,
4700 const CXXScopeSpec &SS,
4701 TypeSourceInfo *ScopeType,
4702 SourceLocation CCLoc,
4703 SourceLocation TildeLoc,
4704 PseudoDestructorTypeStorage DestroyedType);
4706 ExprResult ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
4707 SourceLocation OpLoc,
4708 tok::TokenKind OpKind,
4710 UnqualifiedId &FirstTypeName,
4711 SourceLocation CCLoc,
4712 SourceLocation TildeLoc,
4713 UnqualifiedId &SecondTypeName);
4715 ExprResult ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
4716 SourceLocation OpLoc,
4717 tok::TokenKind OpKind,
4718 SourceLocation TildeLoc,
4719 const DeclSpec& DS);
4721 /// MaybeCreateExprWithCleanups - If the current full-expression
4722 /// requires any cleanups, surround it with a ExprWithCleanups node.
4723 /// Otherwise, just returns the passed-in expression.
4724 Expr *MaybeCreateExprWithCleanups(Expr *SubExpr);
4725 Stmt *MaybeCreateStmtWithCleanups(Stmt *SubStmt);
4726 ExprResult MaybeCreateExprWithCleanups(ExprResult SubExpr);
4728 ExprResult ActOnFinishFullExpr(Expr *Expr) {
4729 return ActOnFinishFullExpr(Expr, Expr ? Expr->getExprLoc()
4730 : SourceLocation());
4732 ExprResult ActOnFinishFullExpr(Expr *Expr, SourceLocation CC,
4733 bool DiscardedValue = false,
4734 bool IsConstexpr = false,
4735 bool IsLambdaInitCaptureInitializer = false);
4736 StmtResult ActOnFinishFullStmt(Stmt *Stmt);
4738 // Marks SS invalid if it represents an incomplete type.
4739 bool RequireCompleteDeclContext(CXXScopeSpec &SS, DeclContext *DC);
4741 DeclContext *computeDeclContext(QualType T);
4742 DeclContext *computeDeclContext(const CXXScopeSpec &SS,
4743 bool EnteringContext = false);
4744 bool isDependentScopeSpecifier(const CXXScopeSpec &SS);
4745 CXXRecordDecl *getCurrentInstantiationOf(NestedNameSpecifier *NNS);
4747 /// \brief The parser has parsed a global nested-name-specifier '::'.
4749 /// \param CCLoc The location of the '::'.
4751 /// \param SS The nested-name-specifier, which will be updated in-place
4752 /// to reflect the parsed nested-name-specifier.
4754 /// \returns true if an error occurred, false otherwise.
4755 bool ActOnCXXGlobalScopeSpecifier(SourceLocation CCLoc, CXXScopeSpec &SS);
4757 /// \brief The parser has parsed a '__super' nested-name-specifier.
4759 /// \param SuperLoc The location of the '__super' keyword.
4761 /// \param ColonColonLoc The location of the '::'.
4763 /// \param SS The nested-name-specifier, which will be updated in-place
4764 /// to reflect the parsed nested-name-specifier.
4766 /// \returns true if an error occurred, false otherwise.
4767 bool ActOnSuperScopeSpecifier(SourceLocation SuperLoc,
4768 SourceLocation ColonColonLoc, CXXScopeSpec &SS);
4770 bool isAcceptableNestedNameSpecifier(const NamedDecl *SD,
4771 bool *CanCorrect = nullptr);
4772 NamedDecl *FindFirstQualifierInScope(Scope *S, NestedNameSpecifier *NNS);
4774 bool isNonTypeNestedNameSpecifier(Scope *S, CXXScopeSpec &SS,
4775 SourceLocation IdLoc,
4777 ParsedType ObjectType);
4779 bool BuildCXXNestedNameSpecifier(Scope *S,
4780 IdentifierInfo &Identifier,
4781 SourceLocation IdentifierLoc,
4782 SourceLocation CCLoc,
4783 QualType ObjectType,
4784 bool EnteringContext,
4786 NamedDecl *ScopeLookupResult,
4787 bool ErrorRecoveryLookup,
4788 bool *IsCorrectedToColon = nullptr);
4790 /// \brief The parser has parsed a nested-name-specifier 'identifier::'.
4792 /// \param S The scope in which this nested-name-specifier occurs.
4794 /// \param Identifier The identifier preceding the '::'.
4796 /// \param IdentifierLoc The location of the identifier.
4798 /// \param CCLoc The location of the '::'.
4800 /// \param ObjectType The type of the object, if we're parsing
4801 /// nested-name-specifier in a member access expression.
4803 /// \param EnteringContext Whether we're entering the context nominated by
4804 /// this nested-name-specifier.
4806 /// \param SS The nested-name-specifier, which is both an input
4807 /// parameter (the nested-name-specifier before this type) and an
4808 /// output parameter (containing the full nested-name-specifier,
4809 /// including this new type).
4811 /// \param ErrorRecoveryLookup If true, then this method is called to improve
4812 /// error recovery. In this case do not emit error message.
4814 /// \param IsCorrectedToColon If not null, suggestions to replace '::' -> ':'
4815 /// are allowed. The bool value pointed by this parameter is set to 'true'
4816 /// if the identifier is treated as if it was followed by ':', not '::'.
4818 /// \returns true if an error occurred, false otherwise.
4819 bool ActOnCXXNestedNameSpecifier(Scope *S,
4820 IdentifierInfo &Identifier,
4821 SourceLocation IdentifierLoc,
4822 SourceLocation CCLoc,
4823 ParsedType ObjectType,
4824 bool EnteringContext,
4826 bool ErrorRecoveryLookup = false,
4827 bool *IsCorrectedToColon = nullptr);
4829 ExprResult ActOnDecltypeExpression(Expr *E);
4831 bool ActOnCXXNestedNameSpecifierDecltype(CXXScopeSpec &SS,
4833 SourceLocation ColonColonLoc);
4835 bool IsInvalidUnlessNestedName(Scope *S, CXXScopeSpec &SS,
4836 IdentifierInfo &Identifier,
4837 SourceLocation IdentifierLoc,
4838 SourceLocation ColonLoc,
4839 ParsedType ObjectType,
4840 bool EnteringContext);
4842 /// \brief The parser has parsed a nested-name-specifier
4843 /// 'template[opt] template-name < template-args >::'.
4845 /// \param S The scope in which this nested-name-specifier occurs.
4847 /// \param SS The nested-name-specifier, which is both an input
4848 /// parameter (the nested-name-specifier before this type) and an
4849 /// output parameter (containing the full nested-name-specifier,
4850 /// including this new type).
4852 /// \param TemplateKWLoc the location of the 'template' keyword, if any.
4853 /// \param TemplateName the template name.
4854 /// \param TemplateNameLoc The location of the template name.
4855 /// \param LAngleLoc The location of the opening angle bracket ('<').
4856 /// \param TemplateArgs The template arguments.
4857 /// \param RAngleLoc The location of the closing angle bracket ('>').
4858 /// \param CCLoc The location of the '::'.
4860 /// \param EnteringContext Whether we're entering the context of the
4861 /// nested-name-specifier.
4864 /// \returns true if an error occurred, false otherwise.
4865 bool ActOnCXXNestedNameSpecifier(Scope *S,
4867 SourceLocation TemplateKWLoc,
4868 TemplateTy TemplateName,
4869 SourceLocation TemplateNameLoc,
4870 SourceLocation LAngleLoc,
4871 ASTTemplateArgsPtr TemplateArgs,
4872 SourceLocation RAngleLoc,
4873 SourceLocation CCLoc,
4874 bool EnteringContext);
4876 /// \brief Given a C++ nested-name-specifier, produce an annotation value
4877 /// that the parser can use later to reconstruct the given
4878 /// nested-name-specifier.
4880 /// \param SS A nested-name-specifier.
4882 /// \returns A pointer containing all of the information in the
4883 /// nested-name-specifier \p SS.
4884 void *SaveNestedNameSpecifierAnnotation(CXXScopeSpec &SS);
4886 /// \brief Given an annotation pointer for a nested-name-specifier, restore
4887 /// the nested-name-specifier structure.
4889 /// \param Annotation The annotation pointer, produced by
4890 /// \c SaveNestedNameSpecifierAnnotation().
4892 /// \param AnnotationRange The source range corresponding to the annotation.
4894 /// \param SS The nested-name-specifier that will be updated with the contents
4895 /// of the annotation pointer.
4896 void RestoreNestedNameSpecifierAnnotation(void *Annotation,
4897 SourceRange AnnotationRange,
4900 bool ShouldEnterDeclaratorScope(Scope *S, const CXXScopeSpec &SS);
4902 /// ActOnCXXEnterDeclaratorScope - Called when a C++ scope specifier (global
4903 /// scope or nested-name-specifier) is parsed, part of a declarator-id.
4904 /// After this method is called, according to [C++ 3.4.3p3], names should be
4905 /// looked up in the declarator-id's scope, until the declarator is parsed and
4906 /// ActOnCXXExitDeclaratorScope is called.
4907 /// The 'SS' should be a non-empty valid CXXScopeSpec.
4908 bool ActOnCXXEnterDeclaratorScope(Scope *S, CXXScopeSpec &SS);
4910 /// ActOnCXXExitDeclaratorScope - Called when a declarator that previously
4911 /// invoked ActOnCXXEnterDeclaratorScope(), is finished. 'SS' is the same
4912 /// CXXScopeSpec that was passed to ActOnCXXEnterDeclaratorScope as well.
4913 /// Used to indicate that names should revert to being looked up in the
4915 void ActOnCXXExitDeclaratorScope(Scope *S, const CXXScopeSpec &SS);
4917 /// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse an
4918 /// initializer for the declaration 'Dcl'.
4919 /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
4920 /// static data member of class X, names should be looked up in the scope of
4922 void ActOnCXXEnterDeclInitializer(Scope *S, Decl *Dcl);
4924 /// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
4925 /// initializer for the declaration 'Dcl'.
4926 void ActOnCXXExitDeclInitializer(Scope *S, Decl *Dcl);
4928 /// \brief Create a new lambda closure type.
4929 CXXRecordDecl *createLambdaClosureType(SourceRange IntroducerRange,
4930 TypeSourceInfo *Info,
4931 bool KnownDependent,
4932 LambdaCaptureDefault CaptureDefault);
4934 /// \brief Start the definition of a lambda expression.
4935 CXXMethodDecl *startLambdaDefinition(CXXRecordDecl *Class,
4936 SourceRange IntroducerRange,
4937 TypeSourceInfo *MethodType,
4938 SourceLocation EndLoc,
4939 ArrayRef<ParmVarDecl *> Params);
4941 /// \brief Endow the lambda scope info with the relevant properties.
4942 void buildLambdaScope(sema::LambdaScopeInfo *LSI,
4943 CXXMethodDecl *CallOperator,
4944 SourceRange IntroducerRange,
4945 LambdaCaptureDefault CaptureDefault,
4946 SourceLocation CaptureDefaultLoc,
4947 bool ExplicitParams,
4948 bool ExplicitResultType,
4951 /// \brief Perform initialization analysis of the init-capture and perform
4952 /// any implicit conversions such as an lvalue-to-rvalue conversion if
4953 /// not being used to initialize a reference.
4954 QualType performLambdaInitCaptureInitialization(SourceLocation Loc,
4955 bool ByRef, IdentifierInfo *Id, Expr *&Init);
4956 /// \brief Create a dummy variable within the declcontext of the lambda's
4957 /// call operator, for name lookup purposes for a lambda init capture.
4959 /// CodeGen handles emission of lambda captures, ignoring these dummy
4960 /// variables appropriately.
4961 VarDecl *createLambdaInitCaptureVarDecl(SourceLocation Loc,
4962 QualType InitCaptureType, IdentifierInfo *Id, Expr *Init);
4964 /// \brief Build the implicit field for an init-capture.
4965 FieldDecl *buildInitCaptureField(sema::LambdaScopeInfo *LSI, VarDecl *Var);
4967 /// \brief Note that we have finished the explicit captures for the
4969 void finishLambdaExplicitCaptures(sema::LambdaScopeInfo *LSI);
4971 /// \brief Introduce the lambda parameters into scope.
4972 void addLambdaParameters(CXXMethodDecl *CallOperator, Scope *CurScope);
4974 /// \brief Deduce a block or lambda's return type based on the return
4975 /// statements present in the body.
4976 void deduceClosureReturnType(sema::CapturingScopeInfo &CSI);
4978 /// ActOnStartOfLambdaDefinition - This is called just before we start
4979 /// parsing the body of a lambda; it analyzes the explicit captures and
4980 /// arguments, and sets up various data-structures for the body of the
4982 void ActOnStartOfLambdaDefinition(LambdaIntroducer &Intro,
4983 Declarator &ParamInfo, Scope *CurScope);
4985 /// ActOnLambdaError - If there is an error parsing a lambda, this callback
4986 /// is invoked to pop the information about the lambda.
4987 void ActOnLambdaError(SourceLocation StartLoc, Scope *CurScope,
4988 bool IsInstantiation = false);
4990 /// ActOnLambdaExpr - This is called when the body of a lambda expression
4991 /// was successfully completed.
4992 ExprResult ActOnLambdaExpr(SourceLocation StartLoc, Stmt *Body,
4995 /// \brief Complete a lambda-expression having processed and attached the
4997 ExprResult BuildLambdaExpr(SourceLocation StartLoc, SourceLocation EndLoc,
4998 sema::LambdaScopeInfo *LSI);
5000 /// \brief Define the "body" of the conversion from a lambda object to a
5001 /// function pointer.
5003 /// This routine doesn't actually define a sensible body; rather, it fills
5004 /// in the initialization expression needed to copy the lambda object into
5005 /// the block, and IR generation actually generates the real body of the
5006 /// block pointer conversion.
5007 void DefineImplicitLambdaToFunctionPointerConversion(
5008 SourceLocation CurrentLoc, CXXConversionDecl *Conv);
5010 /// \brief Define the "body" of the conversion from a lambda object to a
5013 /// This routine doesn't actually define a sensible body; rather, it fills
5014 /// in the initialization expression needed to copy the lambda object into
5015 /// the block, and IR generation actually generates the real body of the
5016 /// block pointer conversion.
5017 void DefineImplicitLambdaToBlockPointerConversion(SourceLocation CurrentLoc,
5018 CXXConversionDecl *Conv);
5020 ExprResult BuildBlockForLambdaConversion(SourceLocation CurrentLocation,
5021 SourceLocation ConvLocation,
5022 CXXConversionDecl *Conv,
5025 // ParseObjCStringLiteral - Parse Objective-C string literals.
5026 ExprResult ParseObjCStringLiteral(SourceLocation *AtLocs,
5028 unsigned NumStrings);
5030 ExprResult BuildObjCStringLiteral(SourceLocation AtLoc, StringLiteral *S);
5032 /// BuildObjCNumericLiteral - builds an ObjCBoxedExpr AST node for the
5033 /// numeric literal expression. Type of the expression will be "NSNumber *"
5034 /// or "id" if NSNumber is unavailable.
5035 ExprResult BuildObjCNumericLiteral(SourceLocation AtLoc, Expr *Number);
5036 ExprResult ActOnObjCBoolLiteral(SourceLocation AtLoc, SourceLocation ValueLoc,
5038 ExprResult BuildObjCArrayLiteral(SourceRange SR, MultiExprArg Elements);
5040 /// BuildObjCBoxedExpr - builds an ObjCBoxedExpr AST node for the
5041 /// '@' prefixed parenthesized expression. The type of the expression will
5042 /// either be "NSNumber *", "NSString *" or "NSValue *" depending on the type
5043 /// of ValueType, which is allowed to be a built-in numeric type, "char *",
5044 /// "const char *" or C structure with attribute 'objc_boxable'.
5045 ExprResult BuildObjCBoxedExpr(SourceRange SR, Expr *ValueExpr);
5047 ExprResult BuildObjCSubscriptExpression(SourceLocation RB, Expr *BaseExpr,
5049 ObjCMethodDecl *getterMethod,
5050 ObjCMethodDecl *setterMethod);
5052 ExprResult BuildObjCDictionaryLiteral(SourceRange SR,
5053 ObjCDictionaryElement *Elements,
5054 unsigned NumElements);
5056 ExprResult BuildObjCEncodeExpression(SourceLocation AtLoc,
5057 TypeSourceInfo *EncodedTypeInfo,
5058 SourceLocation RParenLoc);
5059 ExprResult BuildCXXMemberCallExpr(Expr *Exp, NamedDecl *FoundDecl,
5060 CXXConversionDecl *Method,
5061 bool HadMultipleCandidates);
5063 ExprResult ParseObjCEncodeExpression(SourceLocation AtLoc,
5064 SourceLocation EncodeLoc,
5065 SourceLocation LParenLoc,
5067 SourceLocation RParenLoc);
5069 /// ParseObjCSelectorExpression - Build selector expression for \@selector
5070 ExprResult ParseObjCSelectorExpression(Selector Sel,
5071 SourceLocation AtLoc,
5072 SourceLocation SelLoc,
5073 SourceLocation LParenLoc,
5074 SourceLocation RParenLoc,
5075 bool WarnMultipleSelectors);
5077 /// ParseObjCProtocolExpression - Build protocol expression for \@protocol
5078 ExprResult ParseObjCProtocolExpression(IdentifierInfo * ProtocolName,
5079 SourceLocation AtLoc,
5080 SourceLocation ProtoLoc,
5081 SourceLocation LParenLoc,
5082 SourceLocation ProtoIdLoc,
5083 SourceLocation RParenLoc);
5085 //===--------------------------------------------------------------------===//
5088 Decl *ActOnStartLinkageSpecification(Scope *S,
5089 SourceLocation ExternLoc,
5091 SourceLocation LBraceLoc);
5092 Decl *ActOnFinishLinkageSpecification(Scope *S,
5094 SourceLocation RBraceLoc);
5097 //===--------------------------------------------------------------------===//
5100 bool isCurrentClassName(const IdentifierInfo &II, Scope *S,
5101 const CXXScopeSpec *SS = nullptr);
5102 bool isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS);
5104 bool ActOnAccessSpecifier(AccessSpecifier Access,
5105 SourceLocation ASLoc,
5106 SourceLocation ColonLoc,
5107 AttributeList *Attrs = nullptr);
5109 NamedDecl *ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS,
5111 MultiTemplateParamsArg TemplateParameterLists,
5112 Expr *BitfieldWidth, const VirtSpecifiers &VS,
5113 InClassInitStyle InitStyle);
5115 void ActOnStartCXXInClassMemberInitializer();
5116 void ActOnFinishCXXInClassMemberInitializer(Decl *VarDecl,
5117 SourceLocation EqualLoc,
5120 MemInitResult ActOnMemInitializer(Decl *ConstructorD,
5123 IdentifierInfo *MemberOrBase,
5124 ParsedType TemplateTypeTy,
5126 SourceLocation IdLoc,
5127 SourceLocation LParenLoc,
5128 ArrayRef<Expr *> Args,
5129 SourceLocation RParenLoc,
5130 SourceLocation EllipsisLoc);
5132 MemInitResult ActOnMemInitializer(Decl *ConstructorD,
5135 IdentifierInfo *MemberOrBase,
5136 ParsedType TemplateTypeTy,
5138 SourceLocation IdLoc,
5140 SourceLocation EllipsisLoc);
5142 MemInitResult BuildMemInitializer(Decl *ConstructorD,
5145 IdentifierInfo *MemberOrBase,
5146 ParsedType TemplateTypeTy,
5148 SourceLocation IdLoc,
5150 SourceLocation EllipsisLoc);
5152 MemInitResult BuildMemberInitializer(ValueDecl *Member,
5154 SourceLocation IdLoc);
5156 MemInitResult BuildBaseInitializer(QualType BaseType,
5157 TypeSourceInfo *BaseTInfo,
5159 CXXRecordDecl *ClassDecl,
5160 SourceLocation EllipsisLoc);
5162 MemInitResult BuildDelegatingInitializer(TypeSourceInfo *TInfo,
5164 CXXRecordDecl *ClassDecl);
5166 bool SetDelegatingInitializer(CXXConstructorDecl *Constructor,
5167 CXXCtorInitializer *Initializer);
5169 bool SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
5170 ArrayRef<CXXCtorInitializer *> Initializers = None);
5172 void SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation);
5175 /// MarkBaseAndMemberDestructorsReferenced - Given a record decl,
5176 /// mark all the non-trivial destructors of its members and bases as
5178 void MarkBaseAndMemberDestructorsReferenced(SourceLocation Loc,
5179 CXXRecordDecl *Record);
5181 /// \brief The list of classes whose vtables have been used within
5182 /// this translation unit, and the source locations at which the
5183 /// first use occurred.
5184 typedef std::pair<CXXRecordDecl*, SourceLocation> VTableUse;
5186 /// \brief The list of vtables that are required but have not yet been
5188 SmallVector<VTableUse, 16> VTableUses;
5190 /// \brief The set of classes whose vtables have been used within
5191 /// this translation unit, and a bit that will be true if the vtable is
5192 /// required to be emitted (otherwise, it should be emitted only if needed
5193 /// by code generation).
5194 llvm::DenseMap<CXXRecordDecl *, bool> VTablesUsed;
5196 /// \brief Load any externally-stored vtable uses.
5197 void LoadExternalVTableUses();
5199 /// \brief Note that the vtable for the given class was used at the
5201 void MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
5202 bool DefinitionRequired = false);
5204 /// \brief Mark the exception specifications of all virtual member functions
5205 /// in the given class as needed.
5206 void MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
5207 const CXXRecordDecl *RD);
5209 /// MarkVirtualMembersReferenced - Will mark all members of the given
5210 /// CXXRecordDecl referenced.
5211 void MarkVirtualMembersReferenced(SourceLocation Loc,
5212 const CXXRecordDecl *RD);
5214 /// \brief Define all of the vtables that have been used in this
5215 /// translation unit and reference any virtual members used by those
5218 /// \returns true if any work was done, false otherwise.
5219 bool DefineUsedVTables();
5221 void AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl);
5223 void ActOnMemInitializers(Decl *ConstructorDecl,
5224 SourceLocation ColonLoc,
5225 ArrayRef<CXXCtorInitializer*> MemInits,
5228 void checkClassLevelDLLAttribute(CXXRecordDecl *Class);
5229 void propagateDLLAttrToBaseClassTemplate(
5230 CXXRecordDecl *Class, Attr *ClassAttr,
5231 ClassTemplateSpecializationDecl *BaseTemplateSpec,
5232 SourceLocation BaseLoc);
5233 void CheckCompletedCXXClass(CXXRecordDecl *Record);
5234 void ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
5236 SourceLocation LBrac,
5237 SourceLocation RBrac,
5238 AttributeList *AttrList);
5239 void ActOnFinishCXXMemberDecls();
5240 void ActOnFinishCXXMemberDefaultArgs(Decl *D);
5242 void ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param);
5243 unsigned ActOnReenterTemplateScope(Scope *S, Decl *Template);
5244 void ActOnStartDelayedMemberDeclarations(Scope *S, Decl *Record);
5245 void ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *Method);
5246 void ActOnDelayedCXXMethodParameter(Scope *S, Decl *Param);
5247 void ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *Record);
5248 void ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *Method);
5249 void ActOnFinishDelayedMemberInitializers(Decl *Record);
5250 void MarkAsLateParsedTemplate(FunctionDecl *FD, Decl *FnD,
5251 CachedTokens &Toks);
5252 void UnmarkAsLateParsedTemplate(FunctionDecl *FD);
5253 bool IsInsideALocalClassWithinATemplateFunction();
5255 Decl *ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
5257 Expr *AssertMessageExpr,
5258 SourceLocation RParenLoc);
5259 Decl *BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
5261 StringLiteral *AssertMessageExpr,
5262 SourceLocation RParenLoc,
5265 FriendDecl *CheckFriendTypeDecl(SourceLocation LocStart,
5266 SourceLocation FriendLoc,
5267 TypeSourceInfo *TSInfo);
5268 Decl *ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
5269 MultiTemplateParamsArg TemplateParams);
5270 NamedDecl *ActOnFriendFunctionDecl(Scope *S, Declarator &D,
5271 MultiTemplateParamsArg TemplateParams);
5273 QualType CheckConstructorDeclarator(Declarator &D, QualType R,
5275 void CheckConstructor(CXXConstructorDecl *Constructor);
5276 QualType CheckDestructorDeclarator(Declarator &D, QualType R,
5278 bool CheckDestructor(CXXDestructorDecl *Destructor);
5279 void CheckConversionDeclarator(Declarator &D, QualType &R,
5281 Decl *ActOnConversionDeclarator(CXXConversionDecl *Conversion);
5283 void CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD);
5284 void CheckExplicitlyDefaultedMemberExceptionSpec(CXXMethodDecl *MD,
5285 const FunctionProtoType *T);
5286 void CheckDelayedMemberExceptionSpecs();
5288 //===--------------------------------------------------------------------===//
5289 // C++ Derived Classes
5292 /// ActOnBaseSpecifier - Parsed a base specifier
5293 CXXBaseSpecifier *CheckBaseSpecifier(CXXRecordDecl *Class,
5294 SourceRange SpecifierRange,
5295 bool Virtual, AccessSpecifier Access,
5296 TypeSourceInfo *TInfo,
5297 SourceLocation EllipsisLoc);
5299 BaseResult ActOnBaseSpecifier(Decl *classdecl,
5300 SourceRange SpecifierRange,
5301 ParsedAttributes &Attrs,
5302 bool Virtual, AccessSpecifier Access,
5303 ParsedType basetype,
5304 SourceLocation BaseLoc,
5305 SourceLocation EllipsisLoc);
5307 bool AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
5309 void ActOnBaseSpecifiers(Decl *ClassDecl, CXXBaseSpecifier **Bases,
5312 bool IsDerivedFrom(QualType Derived, QualType Base);
5313 bool IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths);
5315 // FIXME: I don't like this name.
5316 void BuildBasePathArray(const CXXBasePaths &Paths, CXXCastPath &BasePath);
5318 bool CheckDerivedToBaseConversion(QualType Derived, QualType Base,
5319 SourceLocation Loc, SourceRange Range,
5320 CXXCastPath *BasePath = nullptr,
5321 bool IgnoreAccess = false);
5322 bool CheckDerivedToBaseConversion(QualType Derived, QualType Base,
5323 unsigned InaccessibleBaseID,
5324 unsigned AmbigiousBaseConvID,
5325 SourceLocation Loc, SourceRange Range,
5326 DeclarationName Name,
5327 CXXCastPath *BasePath);
5329 std::string getAmbiguousPathsDisplayString(CXXBasePaths &Paths);
5331 bool CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
5332 const CXXMethodDecl *Old);
5334 /// CheckOverridingFunctionReturnType - Checks whether the return types are
5335 /// covariant, according to C++ [class.virtual]p5.
5336 bool CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
5337 const CXXMethodDecl *Old);
5339 /// CheckOverridingFunctionExceptionSpec - Checks whether the exception
5340 /// spec is a subset of base spec.
5341 bool CheckOverridingFunctionExceptionSpec(const CXXMethodDecl *New,
5342 const CXXMethodDecl *Old);
5344 bool CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange);
5346 /// CheckOverrideControl - Check C++11 override control semantics.
5347 void CheckOverrideControl(NamedDecl *D);
5349 /// DiagnoseAbsenceOfOverrideControl - Diagnose if 'override' keyword was
5350 /// not used in the declaration of an overriding method.
5351 void DiagnoseAbsenceOfOverrideControl(NamedDecl *D);
5353 /// CheckForFunctionMarkedFinal - Checks whether a virtual member function
5354 /// overrides a virtual member function marked 'final', according to
5355 /// C++11 [class.virtual]p4.
5356 bool CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
5357 const CXXMethodDecl *Old);
5360 //===--------------------------------------------------------------------===//
5361 // C++ Access Control
5371 bool SetMemberAccessSpecifier(NamedDecl *MemberDecl,
5372 NamedDecl *PrevMemberDecl,
5373 AccessSpecifier LexicalAS);
5375 AccessResult CheckUnresolvedMemberAccess(UnresolvedMemberExpr *E,
5376 DeclAccessPair FoundDecl);
5377 AccessResult CheckUnresolvedLookupAccess(UnresolvedLookupExpr *E,
5378 DeclAccessPair FoundDecl);
5379 AccessResult CheckAllocationAccess(SourceLocation OperatorLoc,
5380 SourceRange PlacementRange,
5381 CXXRecordDecl *NamingClass,
5382 DeclAccessPair FoundDecl,
5383 bool Diagnose = true);
5384 AccessResult CheckConstructorAccess(SourceLocation Loc,
5385 CXXConstructorDecl *D,
5386 const InitializedEntity &Entity,
5387 AccessSpecifier Access,
5388 bool IsCopyBindingRefToTemp = false);
5389 AccessResult CheckConstructorAccess(SourceLocation Loc,
5390 CXXConstructorDecl *D,
5391 const InitializedEntity &Entity,
5392 AccessSpecifier Access,
5393 const PartialDiagnostic &PDiag);
5394 AccessResult CheckDestructorAccess(SourceLocation Loc,
5395 CXXDestructorDecl *Dtor,
5396 const PartialDiagnostic &PDiag,
5397 QualType objectType = QualType());
5398 AccessResult CheckFriendAccess(NamedDecl *D);
5399 AccessResult CheckMemberAccess(SourceLocation UseLoc,
5400 CXXRecordDecl *NamingClass,
5401 DeclAccessPair Found);
5402 AccessResult CheckMemberOperatorAccess(SourceLocation Loc,
5405 DeclAccessPair FoundDecl);
5406 AccessResult CheckAddressOfMemberAccess(Expr *OvlExpr,
5407 DeclAccessPair FoundDecl);
5408 AccessResult CheckBaseClassAccess(SourceLocation AccessLoc,
5409 QualType Base, QualType Derived,
5410 const CXXBasePath &Path,
5412 bool ForceCheck = false,
5413 bool ForceUnprivileged = false);
5414 void CheckLookupAccess(const LookupResult &R);
5415 bool IsSimplyAccessible(NamedDecl *decl, DeclContext *Ctx);
5416 bool isSpecialMemberAccessibleForDeletion(CXXMethodDecl *decl,
5417 AccessSpecifier access,
5418 QualType objectType);
5420 void HandleDependentAccessCheck(const DependentDiagnostic &DD,
5421 const MultiLevelTemplateArgumentList &TemplateArgs);
5422 void PerformDependentDiagnostics(const DeclContext *Pattern,
5423 const MultiLevelTemplateArgumentList &TemplateArgs);
5425 void HandleDelayedAccessCheck(sema::DelayedDiagnostic &DD, Decl *Ctx);
5427 /// \brief When true, access checking violations are treated as SFINAE
5428 /// failures rather than hard errors.
5429 bool AccessCheckingSFINAE;
5431 enum AbstractDiagSelID {
5435 AbstractVariableType,
5438 AbstractSynthesizedIvarType,
5442 bool RequireNonAbstractType(SourceLocation Loc, QualType T,
5443 TypeDiagnoser &Diagnoser);
5444 template <typename... Ts>
5445 bool RequireNonAbstractType(SourceLocation Loc, QualType T, unsigned DiagID,
5446 const Ts &...Args) {
5447 BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
5448 return RequireNonAbstractType(Loc, T, Diagnoser);
5451 void DiagnoseAbstractType(const CXXRecordDecl *RD);
5453 bool RequireNonAbstractType(SourceLocation Loc, QualType T, unsigned DiagID,
5454 AbstractDiagSelID SelID = AbstractNone);
5456 //===--------------------------------------------------------------------===//
5457 // C++ Overloaded Operators [C++ 13.5]
5460 bool CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl);
5462 bool CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl);
5464 //===--------------------------------------------------------------------===//
5465 // C++ Templates [C++ 14]
5467 void FilterAcceptableTemplateNames(LookupResult &R,
5468 bool AllowFunctionTemplates = true);
5469 bool hasAnyAcceptableTemplateNames(LookupResult &R,
5470 bool AllowFunctionTemplates = true);
5472 void LookupTemplateName(LookupResult &R, Scope *S, CXXScopeSpec &SS,
5473 QualType ObjectType, bool EnteringContext,
5474 bool &MemberOfUnknownSpecialization);
5476 TemplateNameKind isTemplateName(Scope *S,
5478 bool hasTemplateKeyword,
5479 UnqualifiedId &Name,
5480 ParsedType ObjectType,
5481 bool EnteringContext,
5482 TemplateTy &Template,
5483 bool &MemberOfUnknownSpecialization);
5485 bool DiagnoseUnknownTemplateName(const IdentifierInfo &II,
5486 SourceLocation IILoc,
5488 const CXXScopeSpec *SS,
5489 TemplateTy &SuggestedTemplate,
5490 TemplateNameKind &SuggestedKind);
5492 void DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl);
5493 TemplateDecl *AdjustDeclIfTemplate(Decl *&Decl);
5495 Decl *ActOnTypeParameter(Scope *S, bool Typename,
5496 SourceLocation EllipsisLoc,
5497 SourceLocation KeyLoc,
5498 IdentifierInfo *ParamName,
5499 SourceLocation ParamNameLoc,
5500 unsigned Depth, unsigned Position,
5501 SourceLocation EqualLoc,
5502 ParsedType DefaultArg);
5504 QualType CheckNonTypeTemplateParameterType(QualType T, SourceLocation Loc);
5505 Decl *ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
5508 SourceLocation EqualLoc,
5510 Decl *ActOnTemplateTemplateParameter(Scope *S,
5511 SourceLocation TmpLoc,
5512 TemplateParameterList *Params,
5513 SourceLocation EllipsisLoc,
5514 IdentifierInfo *ParamName,
5515 SourceLocation ParamNameLoc,
5518 SourceLocation EqualLoc,
5519 ParsedTemplateArgument DefaultArg);
5521 TemplateParameterList *
5522 ActOnTemplateParameterList(unsigned Depth,
5523 SourceLocation ExportLoc,
5524 SourceLocation TemplateLoc,
5525 SourceLocation LAngleLoc,
5526 Decl **Params, unsigned NumParams,
5527 SourceLocation RAngleLoc);
5529 /// \brief The context in which we are checking a template parameter list.
5530 enum TemplateParamListContext {
5533 TPC_FunctionTemplate,
5534 TPC_ClassTemplateMember,
5535 TPC_FriendClassTemplate,
5536 TPC_FriendFunctionTemplate,
5537 TPC_FriendFunctionTemplateDefinition,
5538 TPC_TypeAliasTemplate
5541 bool CheckTemplateParameterList(TemplateParameterList *NewParams,
5542 TemplateParameterList *OldParams,
5543 TemplateParamListContext TPC);
5544 TemplateParameterList *MatchTemplateParametersToScopeSpecifier(
5545 SourceLocation DeclStartLoc, SourceLocation DeclLoc,
5546 const CXXScopeSpec &SS, TemplateIdAnnotation *TemplateId,
5547 ArrayRef<TemplateParameterList *> ParamLists,
5548 bool IsFriend, bool &IsExplicitSpecialization, bool &Invalid);
5550 DeclResult CheckClassTemplate(Scope *S, unsigned TagSpec, TagUseKind TUK,
5551 SourceLocation KWLoc, CXXScopeSpec &SS,
5552 IdentifierInfo *Name, SourceLocation NameLoc,
5553 AttributeList *Attr,
5554 TemplateParameterList *TemplateParams,
5556 SourceLocation ModulePrivateLoc,
5557 SourceLocation FriendLoc,
5558 unsigned NumOuterTemplateParamLists,
5559 TemplateParameterList **OuterTemplateParamLists,
5560 SkipBodyInfo *SkipBody = nullptr);
5562 void translateTemplateArguments(const ASTTemplateArgsPtr &In,
5563 TemplateArgumentListInfo &Out);
5565 void NoteAllFoundTemplates(TemplateName Name);
5567 QualType CheckTemplateIdType(TemplateName Template,
5568 SourceLocation TemplateLoc,
5569 TemplateArgumentListInfo &TemplateArgs);
5572 ActOnTemplateIdType(CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
5573 TemplateTy Template, SourceLocation TemplateLoc,
5574 SourceLocation LAngleLoc,
5575 ASTTemplateArgsPtr TemplateArgs,
5576 SourceLocation RAngleLoc,
5577 bool IsCtorOrDtorName = false);
5579 /// \brief Parsed an elaborated-type-specifier that refers to a template-id,
5580 /// such as \c class T::template apply<U>.
5581 TypeResult ActOnTagTemplateIdType(TagUseKind TUK,
5582 TypeSpecifierType TagSpec,
5583 SourceLocation TagLoc,
5585 SourceLocation TemplateKWLoc,
5586 TemplateTy TemplateD,
5587 SourceLocation TemplateLoc,
5588 SourceLocation LAngleLoc,
5589 ASTTemplateArgsPtr TemplateArgsIn,
5590 SourceLocation RAngleLoc);
5592 DeclResult ActOnVarTemplateSpecialization(
5593 Scope *S, Declarator &D, TypeSourceInfo *DI,
5594 SourceLocation TemplateKWLoc, TemplateParameterList *TemplateParams,
5595 StorageClass SC, bool IsPartialSpecialization);
5597 DeclResult CheckVarTemplateId(VarTemplateDecl *Template,
5598 SourceLocation TemplateLoc,
5599 SourceLocation TemplateNameLoc,
5600 const TemplateArgumentListInfo &TemplateArgs);
5602 ExprResult CheckVarTemplateId(const CXXScopeSpec &SS,
5603 const DeclarationNameInfo &NameInfo,
5604 VarTemplateDecl *Template,
5605 SourceLocation TemplateLoc,
5606 const TemplateArgumentListInfo *TemplateArgs);
5608 ExprResult BuildTemplateIdExpr(const CXXScopeSpec &SS,
5609 SourceLocation TemplateKWLoc,
5612 const TemplateArgumentListInfo *TemplateArgs);
5614 ExprResult BuildQualifiedTemplateIdExpr(CXXScopeSpec &SS,
5615 SourceLocation TemplateKWLoc,
5616 const DeclarationNameInfo &NameInfo,
5617 const TemplateArgumentListInfo *TemplateArgs);
5619 TemplateNameKind ActOnDependentTemplateName(Scope *S,
5621 SourceLocation TemplateKWLoc,
5622 UnqualifiedId &Name,
5623 ParsedType ObjectType,
5624 bool EnteringContext,
5625 TemplateTy &Template);
5628 ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec, TagUseKind TUK,
5629 SourceLocation KWLoc,
5630 SourceLocation ModulePrivateLoc,
5631 TemplateIdAnnotation &TemplateId,
5632 AttributeList *Attr,
5633 MultiTemplateParamsArg TemplateParameterLists,
5634 SkipBodyInfo *SkipBody = nullptr);
5636 Decl *ActOnTemplateDeclarator(Scope *S,
5637 MultiTemplateParamsArg TemplateParameterLists,
5640 Decl *ActOnStartOfFunctionTemplateDef(Scope *FnBodyScope,
5641 MultiTemplateParamsArg TemplateParameterLists,
5645 CheckSpecializationInstantiationRedecl(SourceLocation NewLoc,
5646 TemplateSpecializationKind NewTSK,
5647 NamedDecl *PrevDecl,
5648 TemplateSpecializationKind PrevTSK,
5649 SourceLocation PrevPtOfInstantiation,
5652 bool CheckDependentFunctionTemplateSpecialization(FunctionDecl *FD,
5653 const TemplateArgumentListInfo &ExplicitTemplateArgs,
5654 LookupResult &Previous);
5656 bool CheckFunctionTemplateSpecialization(FunctionDecl *FD,
5657 TemplateArgumentListInfo *ExplicitTemplateArgs,
5658 LookupResult &Previous);
5659 bool CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous);
5662 ActOnExplicitInstantiation(Scope *S,
5663 SourceLocation ExternLoc,
5664 SourceLocation TemplateLoc,
5666 SourceLocation KWLoc,
5667 const CXXScopeSpec &SS,
5668 TemplateTy Template,
5669 SourceLocation TemplateNameLoc,
5670 SourceLocation LAngleLoc,
5671 ASTTemplateArgsPtr TemplateArgs,
5672 SourceLocation RAngleLoc,
5673 AttributeList *Attr);
5676 ActOnExplicitInstantiation(Scope *S,
5677 SourceLocation ExternLoc,
5678 SourceLocation TemplateLoc,
5680 SourceLocation KWLoc,
5682 IdentifierInfo *Name,
5683 SourceLocation NameLoc,
5684 AttributeList *Attr);
5686 DeclResult ActOnExplicitInstantiation(Scope *S,
5687 SourceLocation ExternLoc,
5688 SourceLocation TemplateLoc,
5692 SubstDefaultTemplateArgumentIfAvailable(TemplateDecl *Template,
5693 SourceLocation TemplateLoc,
5694 SourceLocation RAngleLoc,
5696 SmallVectorImpl<TemplateArgument>
5698 bool &HasDefaultArg);
5700 /// \brief Specifies the context in which a particular template
5701 /// argument is being checked.
5702 enum CheckTemplateArgumentKind {
5703 /// \brief The template argument was specified in the code or was
5704 /// instantiated with some deduced template arguments.
5707 /// \brief The template argument was deduced via template argument
5711 /// \brief The template argument was deduced from an array bound
5712 /// via template argument deduction.
5713 CTAK_DeducedFromArrayBound
5716 bool CheckTemplateArgument(NamedDecl *Param,
5717 TemplateArgumentLoc &Arg,
5718 NamedDecl *Template,
5719 SourceLocation TemplateLoc,
5720 SourceLocation RAngleLoc,
5721 unsigned ArgumentPackIndex,
5722 SmallVectorImpl<TemplateArgument> &Converted,
5723 CheckTemplateArgumentKind CTAK = CTAK_Specified);
5725 /// \brief Check that the given template arguments can be be provided to
5726 /// the given template, converting the arguments along the way.
5728 /// \param Template The template to which the template arguments are being
5731 /// \param TemplateLoc The location of the template name in the source.
5733 /// \param TemplateArgs The list of template arguments. If the template is
5734 /// a template template parameter, this function may extend the set of
5735 /// template arguments to also include substituted, defaulted template
5738 /// \param PartialTemplateArgs True if the list of template arguments is
5739 /// intentionally partial, e.g., because we're checking just the initial
5740 /// set of template arguments.
5742 /// \param Converted Will receive the converted, canonicalized template
5745 /// \returns true if an error occurred, false otherwise.
5746 bool CheckTemplateArgumentList(TemplateDecl *Template,
5747 SourceLocation TemplateLoc,
5748 TemplateArgumentListInfo &TemplateArgs,
5749 bool PartialTemplateArgs,
5750 SmallVectorImpl<TemplateArgument> &Converted);
5752 bool CheckTemplateTypeArgument(TemplateTypeParmDecl *Param,
5753 TemplateArgumentLoc &Arg,
5754 SmallVectorImpl<TemplateArgument> &Converted);
5756 bool CheckTemplateArgument(TemplateTypeParmDecl *Param,
5757 TypeSourceInfo *Arg);
5758 ExprResult CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
5759 QualType InstantiatedParamType, Expr *Arg,
5760 TemplateArgument &Converted,
5761 CheckTemplateArgumentKind CTAK = CTAK_Specified);
5762 bool CheckTemplateArgument(TemplateTemplateParmDecl *Param,
5763 TemplateArgumentLoc &Arg,
5764 unsigned ArgumentPackIndex);
5767 BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg,
5769 SourceLocation Loc);
5771 BuildExpressionFromIntegralTemplateArgument(const TemplateArgument &Arg,
5772 SourceLocation Loc);
5774 /// \brief Enumeration describing how template parameter lists are compared
5776 enum TemplateParameterListEqualKind {
5777 /// \brief We are matching the template parameter lists of two templates
5778 /// that might be redeclarations.
5781 /// template<typename T> struct X;
5782 /// template<typename T> struct X;
5786 /// \brief We are matching the template parameter lists of two template
5787 /// template parameters as part of matching the template parameter lists
5788 /// of two templates that might be redeclarations.
5791 /// template<template<int I> class TT> struct X;
5792 /// template<template<int Value> class Other> struct X;
5794 TPL_TemplateTemplateParmMatch,
5796 /// \brief We are matching the template parameter lists of a template
5797 /// template argument against the template parameter lists of a template
5798 /// template parameter.
5801 /// template<template<int Value> class Metafun> struct X;
5802 /// template<int Value> struct integer_c;
5803 /// X<integer_c> xic;
5805 TPL_TemplateTemplateArgumentMatch
5808 bool TemplateParameterListsAreEqual(TemplateParameterList *New,
5809 TemplateParameterList *Old,
5811 TemplateParameterListEqualKind Kind,
5812 SourceLocation TemplateArgLoc
5813 = SourceLocation());
5815 bool CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams);
5817 /// \brief Called when the parser has parsed a C++ typename
5818 /// specifier, e.g., "typename T::type".
5820 /// \param S The scope in which this typename type occurs.
5821 /// \param TypenameLoc the location of the 'typename' keyword
5822 /// \param SS the nested-name-specifier following the typename (e.g., 'T::').
5823 /// \param II the identifier we're retrieving (e.g., 'type' in the example).
5824 /// \param IdLoc the location of the identifier.
5826 ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
5827 const CXXScopeSpec &SS, const IdentifierInfo &II,
5828 SourceLocation IdLoc);
5830 /// \brief Called when the parser has parsed a C++ typename
5831 /// specifier that ends in a template-id, e.g.,
5832 /// "typename MetaFun::template apply<T1, T2>".
5834 /// \param S The scope in which this typename type occurs.
5835 /// \param TypenameLoc the location of the 'typename' keyword
5836 /// \param SS the nested-name-specifier following the typename (e.g., 'T::').
5837 /// \param TemplateLoc the location of the 'template' keyword, if any.
5838 /// \param TemplateName The template name.
5839 /// \param TemplateNameLoc The location of the template name.
5840 /// \param LAngleLoc The location of the opening angle bracket ('<').
5841 /// \param TemplateArgs The template arguments.
5842 /// \param RAngleLoc The location of the closing angle bracket ('>').
5844 ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
5845 const CXXScopeSpec &SS,
5846 SourceLocation TemplateLoc,
5847 TemplateTy TemplateName,
5848 SourceLocation TemplateNameLoc,
5849 SourceLocation LAngleLoc,
5850 ASTTemplateArgsPtr TemplateArgs,
5851 SourceLocation RAngleLoc);
5853 QualType CheckTypenameType(ElaboratedTypeKeyword Keyword,
5854 SourceLocation KeywordLoc,
5855 NestedNameSpecifierLoc QualifierLoc,
5856 const IdentifierInfo &II,
5857 SourceLocation IILoc);
5859 TypeSourceInfo *RebuildTypeInCurrentInstantiation(TypeSourceInfo *T,
5861 DeclarationName Name);
5862 bool RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS);
5864 ExprResult RebuildExprInCurrentInstantiation(Expr *E);
5865 bool RebuildTemplateParamsInCurrentInstantiation(
5866 TemplateParameterList *Params);
5869 getTemplateArgumentBindingsText(const TemplateParameterList *Params,
5870 const TemplateArgumentList &Args);
5873 getTemplateArgumentBindingsText(const TemplateParameterList *Params,
5874 const TemplateArgument *Args,
5877 //===--------------------------------------------------------------------===//
5878 // C++ Variadic Templates (C++0x [temp.variadic])
5879 //===--------------------------------------------------------------------===//
5881 /// Determine whether an unexpanded parameter pack might be permitted in this
5882 /// location. Useful for error recovery.
5883 bool isUnexpandedParameterPackPermitted();
5885 /// \brief The context in which an unexpanded parameter pack is
5886 /// being diagnosed.
5888 /// Note that the values of this enumeration line up with the first
5889 /// argument to the \c err_unexpanded_parameter_pack diagnostic.
5890 enum UnexpandedParameterPackContext {
5891 /// \brief An arbitrary expression.
5892 UPPC_Expression = 0,
5894 /// \brief The base type of a class type.
5897 /// \brief The type of an arbitrary declaration.
5898 UPPC_DeclarationType,
5900 /// \brief The type of a data member.
5901 UPPC_DataMemberType,
5903 /// \brief The size of a bit-field.
5906 /// \brief The expression in a static assertion.
5907 UPPC_StaticAssertExpression,
5909 /// \brief The fixed underlying type of an enumeration.
5910 UPPC_FixedUnderlyingType,
5912 /// \brief The enumerator value.
5913 UPPC_EnumeratorValue,
5915 /// \brief A using declaration.
5916 UPPC_UsingDeclaration,
5918 /// \brief A friend declaration.
5919 UPPC_FriendDeclaration,
5921 /// \brief A declaration qualifier.
5922 UPPC_DeclarationQualifier,
5924 /// \brief An initializer.
5927 /// \brief A default argument.
5928 UPPC_DefaultArgument,
5930 /// \brief The type of a non-type template parameter.
5931 UPPC_NonTypeTemplateParameterType,
5933 /// \brief The type of an exception.
5936 /// \brief Partial specialization.
5937 UPPC_PartialSpecialization,
5939 /// \brief Microsoft __if_exists.
5942 /// \brief Microsoft __if_not_exists.
5945 /// \brief Lambda expression.
5948 /// \brief Block expression,
5952 /// \brief Diagnose unexpanded parameter packs.
5954 /// \param Loc The location at which we should emit the diagnostic.
5956 /// \param UPPC The context in which we are diagnosing unexpanded
5957 /// parameter packs.
5959 /// \param Unexpanded the set of unexpanded parameter packs.
5961 /// \returns true if an error occurred, false otherwise.
5962 bool DiagnoseUnexpandedParameterPacks(SourceLocation Loc,
5963 UnexpandedParameterPackContext UPPC,
5964 ArrayRef<UnexpandedParameterPack> Unexpanded);
5966 /// \brief If the given type contains an unexpanded parameter pack,
5967 /// diagnose the error.
5969 /// \param Loc The source location where a diagnostc should be emitted.
5971 /// \param T The type that is being checked for unexpanded parameter
5974 /// \returns true if an error occurred, false otherwise.
5975 bool DiagnoseUnexpandedParameterPack(SourceLocation Loc, TypeSourceInfo *T,
5976 UnexpandedParameterPackContext UPPC);
5978 /// \brief If the given expression contains an unexpanded parameter
5979 /// pack, diagnose the error.
5981 /// \param E The expression that is being checked for unexpanded
5982 /// parameter packs.
5984 /// \returns true if an error occurred, false otherwise.
5985 bool DiagnoseUnexpandedParameterPack(Expr *E,
5986 UnexpandedParameterPackContext UPPC = UPPC_Expression);
5988 /// \brief If the given nested-name-specifier contains an unexpanded
5989 /// parameter pack, diagnose the error.
5991 /// \param SS The nested-name-specifier that is being checked for
5992 /// unexpanded parameter packs.
5994 /// \returns true if an error occurred, false otherwise.
5995 bool DiagnoseUnexpandedParameterPack(const CXXScopeSpec &SS,
5996 UnexpandedParameterPackContext UPPC);
5998 /// \brief If the given name contains an unexpanded parameter pack,
5999 /// diagnose the error.
6001 /// \param NameInfo The name (with source location information) that
6002 /// is being checked for unexpanded parameter packs.
6004 /// \returns true if an error occurred, false otherwise.
6005 bool DiagnoseUnexpandedParameterPack(const DeclarationNameInfo &NameInfo,
6006 UnexpandedParameterPackContext UPPC);
6008 /// \brief If the given template name contains an unexpanded parameter pack,
6009 /// diagnose the error.
6011 /// \param Loc The location of the template name.
6013 /// \param Template The template name that is being checked for unexpanded
6014 /// parameter packs.
6016 /// \returns true if an error occurred, false otherwise.
6017 bool DiagnoseUnexpandedParameterPack(SourceLocation Loc,
6018 TemplateName Template,
6019 UnexpandedParameterPackContext UPPC);
6021 /// \brief If the given template argument contains an unexpanded parameter
6022 /// pack, diagnose the error.
6024 /// \param Arg The template argument that is being checked for unexpanded
6025 /// parameter packs.
6027 /// \returns true if an error occurred, false otherwise.
6028 bool DiagnoseUnexpandedParameterPack(TemplateArgumentLoc Arg,
6029 UnexpandedParameterPackContext UPPC);
6031 /// \brief Collect the set of unexpanded parameter packs within the given
6032 /// template argument.
6034 /// \param Arg The template argument that will be traversed to find
6035 /// unexpanded parameter packs.
6036 void collectUnexpandedParameterPacks(TemplateArgument Arg,
6037 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
6039 /// \brief Collect the set of unexpanded parameter packs within the given
6040 /// template argument.
6042 /// \param Arg The template argument that will be traversed to find
6043 /// unexpanded parameter packs.
6044 void collectUnexpandedParameterPacks(TemplateArgumentLoc Arg,
6045 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
6047 /// \brief Collect the set of unexpanded parameter packs within the given
6050 /// \param T The type that will be traversed to find
6051 /// unexpanded parameter packs.
6052 void collectUnexpandedParameterPacks(QualType T,
6053 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
6055 /// \brief Collect the set of unexpanded parameter packs within the given
6058 /// \param TL The type that will be traversed to find
6059 /// unexpanded parameter packs.
6060 void collectUnexpandedParameterPacks(TypeLoc TL,
6061 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
6063 /// \brief Collect the set of unexpanded parameter packs within the given
6064 /// nested-name-specifier.
6066 /// \param SS The nested-name-specifier that will be traversed to find
6067 /// unexpanded parameter packs.
6068 void collectUnexpandedParameterPacks(CXXScopeSpec &SS,
6069 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
6071 /// \brief Collect the set of unexpanded parameter packs within the given
6074 /// \param NameInfo The name that will be traversed to find
6075 /// unexpanded parameter packs.
6076 void collectUnexpandedParameterPacks(const DeclarationNameInfo &NameInfo,
6077 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
6079 /// \brief Invoked when parsing a template argument followed by an
6080 /// ellipsis, which creates a pack expansion.
6082 /// \param Arg The template argument preceding the ellipsis, which
6083 /// may already be invalid.
6085 /// \param EllipsisLoc The location of the ellipsis.
6086 ParsedTemplateArgument ActOnPackExpansion(const ParsedTemplateArgument &Arg,
6087 SourceLocation EllipsisLoc);
6089 /// \brief Invoked when parsing a type followed by an ellipsis, which
6090 /// creates a pack expansion.
6092 /// \param Type The type preceding the ellipsis, which will become
6093 /// the pattern of the pack expansion.
6095 /// \param EllipsisLoc The location of the ellipsis.
6096 TypeResult ActOnPackExpansion(ParsedType Type, SourceLocation EllipsisLoc);
6098 /// \brief Construct a pack expansion type from the pattern of the pack
6100 TypeSourceInfo *CheckPackExpansion(TypeSourceInfo *Pattern,
6101 SourceLocation EllipsisLoc,
6102 Optional<unsigned> NumExpansions);
6104 /// \brief Construct a pack expansion type from the pattern of the pack
6106 QualType CheckPackExpansion(QualType Pattern,
6107 SourceRange PatternRange,
6108 SourceLocation EllipsisLoc,
6109 Optional<unsigned> NumExpansions);
6111 /// \brief Invoked when parsing an expression followed by an ellipsis, which
6112 /// creates a pack expansion.
6114 /// \param Pattern The expression preceding the ellipsis, which will become
6115 /// the pattern of the pack expansion.
6117 /// \param EllipsisLoc The location of the ellipsis.
6118 ExprResult ActOnPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc);
6120 /// \brief Invoked when parsing an expression followed by an ellipsis, which
6121 /// creates a pack expansion.
6123 /// \param Pattern The expression preceding the ellipsis, which will become
6124 /// the pattern of the pack expansion.
6126 /// \param EllipsisLoc The location of the ellipsis.
6127 ExprResult CheckPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc,
6128 Optional<unsigned> NumExpansions);
6130 /// \brief Determine whether we could expand a pack expansion with the
6131 /// given set of parameter packs into separate arguments by repeatedly
6132 /// transforming the pattern.
6134 /// \param EllipsisLoc The location of the ellipsis that identifies the
6137 /// \param PatternRange The source range that covers the entire pattern of
6138 /// the pack expansion.
6140 /// \param Unexpanded The set of unexpanded parameter packs within the
6143 /// \param ShouldExpand Will be set to \c true if the transformer should
6144 /// expand the corresponding pack expansions into separate arguments. When
6145 /// set, \c NumExpansions must also be set.
6147 /// \param RetainExpansion Whether the caller should add an unexpanded
6148 /// pack expansion after all of the expanded arguments. This is used
6149 /// when extending explicitly-specified template argument packs per
6150 /// C++0x [temp.arg.explicit]p9.
6152 /// \param NumExpansions The number of separate arguments that will be in
6153 /// the expanded form of the corresponding pack expansion. This is both an
6154 /// input and an output parameter, which can be set by the caller if the
6155 /// number of expansions is known a priori (e.g., due to a prior substitution)
6156 /// and will be set by the callee when the number of expansions is known.
6157 /// The callee must set this value when \c ShouldExpand is \c true; it may
6158 /// set this value in other cases.
6160 /// \returns true if an error occurred (e.g., because the parameter packs
6161 /// are to be instantiated with arguments of different lengths), false
6162 /// otherwise. If false, \c ShouldExpand (and possibly \c NumExpansions)
6164 bool CheckParameterPacksForExpansion(SourceLocation EllipsisLoc,
6165 SourceRange PatternRange,
6166 ArrayRef<UnexpandedParameterPack> Unexpanded,
6167 const MultiLevelTemplateArgumentList &TemplateArgs,
6169 bool &RetainExpansion,
6170 Optional<unsigned> &NumExpansions);
6172 /// \brief Determine the number of arguments in the given pack expansion
6175 /// This routine assumes that the number of arguments in the expansion is
6176 /// consistent across all of the unexpanded parameter packs in its pattern.
6178 /// Returns an empty Optional if the type can't be expanded.
6179 Optional<unsigned> getNumArgumentsInExpansion(QualType T,
6180 const MultiLevelTemplateArgumentList &TemplateArgs);
6182 /// \brief Determine whether the given declarator contains any unexpanded
6183 /// parameter packs.
6185 /// This routine is used by the parser to disambiguate function declarators
6186 /// with an ellipsis prior to the ')', e.g.,
6192 /// To determine whether we have an (unnamed) function parameter pack or
6193 /// a variadic function.
6195 /// \returns true if the declarator contains any unexpanded parameter packs,
6196 /// false otherwise.
6197 bool containsUnexpandedParameterPacks(Declarator &D);
6199 /// \brief Returns the pattern of the pack expansion for a template argument.
6201 /// \param OrigLoc The template argument to expand.
6203 /// \param Ellipsis Will be set to the location of the ellipsis.
6205 /// \param NumExpansions Will be set to the number of expansions that will
6206 /// be generated from this pack expansion, if known a priori.
6207 TemplateArgumentLoc getTemplateArgumentPackExpansionPattern(
6208 TemplateArgumentLoc OrigLoc,
6209 SourceLocation &Ellipsis,
6210 Optional<unsigned> &NumExpansions) const;
6212 //===--------------------------------------------------------------------===//
6213 // C++ Template Argument Deduction (C++ [temp.deduct])
6214 //===--------------------------------------------------------------------===//
6216 QualType adjustCCAndNoReturn(QualType ArgFunctionType, QualType FunctionType);
6218 /// \brief Describes the result of template argument deduction.
6220 /// The TemplateDeductionResult enumeration describes the result of
6221 /// template argument deduction, as returned from
6222 /// DeduceTemplateArguments(). The separate TemplateDeductionInfo
6223 /// structure provides additional information about the results of
6224 /// template argument deduction, e.g., the deduced template argument
6225 /// list (if successful) or the specific template parameters or
6226 /// deduced arguments that were involved in the failure.
6227 enum TemplateDeductionResult {
6228 /// \brief Template argument deduction was successful.
6230 /// \brief The declaration was invalid; do nothing.
6232 /// \brief Template argument deduction exceeded the maximum template
6233 /// instantiation depth (which has already been diagnosed).
6234 TDK_InstantiationDepth,
6235 /// \brief Template argument deduction did not deduce a value
6236 /// for every template parameter.
6238 /// \brief Template argument deduction produced inconsistent
6239 /// deduced values for the given template parameter.
6241 /// \brief Template argument deduction failed due to inconsistent
6242 /// cv-qualifiers on a template parameter type that would
6243 /// otherwise be deduced, e.g., we tried to deduce T in "const T"
6244 /// but were given a non-const "X".
6246 /// \brief Substitution of the deduced template argument values
6247 /// resulted in an error.
6248 TDK_SubstitutionFailure,
6249 /// \brief A non-depnedent component of the parameter did not match the
6250 /// corresponding component of the argument.
6251 TDK_NonDeducedMismatch,
6252 /// \brief When performing template argument deduction for a function
6253 /// template, there were too many call arguments.
6254 TDK_TooManyArguments,
6255 /// \brief When performing template argument deduction for a function
6256 /// template, there were too few call arguments.
6257 TDK_TooFewArguments,
6258 /// \brief The explicitly-specified template arguments were not valid
6259 /// template arguments for the given template.
6260 TDK_InvalidExplicitArguments,
6261 /// \brief The arguments included an overloaded function name that could
6262 /// not be resolved to a suitable function.
6263 TDK_FailedOverloadResolution,
6264 /// \brief Deduction failed; that's all we know.
6265 TDK_MiscellaneousDeductionFailure
6268 TemplateDeductionResult
6269 DeduceTemplateArguments(ClassTemplatePartialSpecializationDecl *Partial,
6270 const TemplateArgumentList &TemplateArgs,
6271 sema::TemplateDeductionInfo &Info);
6273 TemplateDeductionResult
6274 DeduceTemplateArguments(VarTemplatePartialSpecializationDecl *Partial,
6275 const TemplateArgumentList &TemplateArgs,
6276 sema::TemplateDeductionInfo &Info);
6278 TemplateDeductionResult SubstituteExplicitTemplateArguments(
6279 FunctionTemplateDecl *FunctionTemplate,
6280 TemplateArgumentListInfo &ExplicitTemplateArgs,
6281 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
6282 SmallVectorImpl<QualType> &ParamTypes, QualType *FunctionType,
6283 sema::TemplateDeductionInfo &Info);
6285 /// brief A function argument from which we performed template argument
6286 // deduction for a call.
6287 struct OriginalCallArg {
6288 OriginalCallArg(QualType OriginalParamType,
6290 QualType OriginalArgType)
6291 : OriginalParamType(OriginalParamType), ArgIdx(ArgIdx),
6292 OriginalArgType(OriginalArgType) { }
6294 QualType OriginalParamType;
6296 QualType OriginalArgType;
6299 TemplateDeductionResult
6300 FinishTemplateArgumentDeduction(FunctionTemplateDecl *FunctionTemplate,
6301 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
6302 unsigned NumExplicitlySpecified,
6303 FunctionDecl *&Specialization,
6304 sema::TemplateDeductionInfo &Info,
6305 SmallVectorImpl<OriginalCallArg> const *OriginalCallArgs = nullptr,
6306 bool PartialOverloading = false);
6308 TemplateDeductionResult
6309 DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
6310 TemplateArgumentListInfo *ExplicitTemplateArgs,
6311 ArrayRef<Expr *> Args,
6312 FunctionDecl *&Specialization,
6313 sema::TemplateDeductionInfo &Info,
6314 bool PartialOverloading = false);
6316 TemplateDeductionResult
6317 DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
6318 TemplateArgumentListInfo *ExplicitTemplateArgs,
6319 QualType ArgFunctionType,
6320 FunctionDecl *&Specialization,
6321 sema::TemplateDeductionInfo &Info,
6322 bool InOverloadResolution = false);
6324 TemplateDeductionResult
6325 DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
6327 CXXConversionDecl *&Specialization,
6328 sema::TemplateDeductionInfo &Info);
6330 TemplateDeductionResult
6331 DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
6332 TemplateArgumentListInfo *ExplicitTemplateArgs,
6333 FunctionDecl *&Specialization,
6334 sema::TemplateDeductionInfo &Info,
6335 bool InOverloadResolution = false);
6337 /// \brief Substitute Replacement for \p auto in \p TypeWithAuto
6338 QualType SubstAutoType(QualType TypeWithAuto, QualType Replacement);
6339 /// \brief Substitute Replacement for auto in TypeWithAuto
6340 TypeSourceInfo* SubstAutoTypeSourceInfo(TypeSourceInfo *TypeWithAuto,
6341 QualType Replacement);
6343 /// \brief Result type of DeduceAutoType.
6344 enum DeduceAutoResult {
6347 DAR_FailedAlreadyDiagnosed
6350 DeduceAutoResult DeduceAutoType(TypeSourceInfo *AutoType, Expr *&Initializer,
6352 DeduceAutoResult DeduceAutoType(TypeLoc AutoTypeLoc, Expr *&Initializer,
6354 void DiagnoseAutoDeductionFailure(VarDecl *VDecl, Expr *Init);
6355 bool DeduceReturnType(FunctionDecl *FD, SourceLocation Loc,
6356 bool Diagnose = true);
6358 TypeLoc getReturnTypeLoc(FunctionDecl *FD) const;
6360 bool DeduceFunctionTypeFromReturnExpr(FunctionDecl *FD,
6361 SourceLocation ReturnLoc,
6362 Expr *&RetExpr, AutoType *AT);
6364 FunctionTemplateDecl *getMoreSpecializedTemplate(FunctionTemplateDecl *FT1,
6365 FunctionTemplateDecl *FT2,
6367 TemplatePartialOrderingContext TPOC,
6368 unsigned NumCallArguments1,
6369 unsigned NumCallArguments2);
6370 UnresolvedSetIterator
6371 getMostSpecialized(UnresolvedSetIterator SBegin, UnresolvedSetIterator SEnd,
6372 TemplateSpecCandidateSet &FailedCandidates,
6374 const PartialDiagnostic &NoneDiag,
6375 const PartialDiagnostic &AmbigDiag,
6376 const PartialDiagnostic &CandidateDiag,
6377 bool Complain = true, QualType TargetType = QualType());
6379 ClassTemplatePartialSpecializationDecl *
6380 getMoreSpecializedPartialSpecialization(
6381 ClassTemplatePartialSpecializationDecl *PS1,
6382 ClassTemplatePartialSpecializationDecl *PS2,
6383 SourceLocation Loc);
6385 VarTemplatePartialSpecializationDecl *getMoreSpecializedPartialSpecialization(
6386 VarTemplatePartialSpecializationDecl *PS1,
6387 VarTemplatePartialSpecializationDecl *PS2, SourceLocation Loc);
6389 void MarkUsedTemplateParameters(const TemplateArgumentList &TemplateArgs,
6392 llvm::SmallBitVector &Used);
6393 void MarkDeducedTemplateParameters(
6394 const FunctionTemplateDecl *FunctionTemplate,
6395 llvm::SmallBitVector &Deduced) {
6396 return MarkDeducedTemplateParameters(Context, FunctionTemplate, Deduced);
6398 static void MarkDeducedTemplateParameters(ASTContext &Ctx,
6399 const FunctionTemplateDecl *FunctionTemplate,
6400 llvm::SmallBitVector &Deduced);
6402 //===--------------------------------------------------------------------===//
6403 // C++ Template Instantiation
6406 MultiLevelTemplateArgumentList
6407 getTemplateInstantiationArgs(NamedDecl *D,
6408 const TemplateArgumentList *Innermost = nullptr,
6409 bool RelativeToPrimary = false,
6410 const FunctionDecl *Pattern = nullptr);
6412 /// \brief A template instantiation that is currently in progress.
6413 struct ActiveTemplateInstantiation {
6414 /// \brief The kind of template instantiation we are performing
6415 enum InstantiationKind {
6416 /// We are instantiating a template declaration. The entity is
6417 /// the declaration we're instantiating (e.g., a CXXRecordDecl).
6418 TemplateInstantiation,
6420 /// We are instantiating a default argument for a template
6421 /// parameter. The Entity is the template, and
6422 /// TemplateArgs/NumTemplateArguments provides the template
6423 /// arguments as specified.
6424 /// FIXME: Use a TemplateArgumentList
6425 DefaultTemplateArgumentInstantiation,
6427 /// We are instantiating a default argument for a function.
6428 /// The Entity is the ParmVarDecl, and TemplateArgs/NumTemplateArgs
6429 /// provides the template arguments as specified.
6430 DefaultFunctionArgumentInstantiation,
6432 /// We are substituting explicit template arguments provided for
6433 /// a function template. The entity is a FunctionTemplateDecl.
6434 ExplicitTemplateArgumentSubstitution,
6436 /// We are substituting template argument determined as part of
6437 /// template argument deduction for either a class template
6438 /// partial specialization or a function template. The
6439 /// Entity is either a ClassTemplatePartialSpecializationDecl or
6440 /// a FunctionTemplateDecl.
6441 DeducedTemplateArgumentSubstitution,
6443 /// We are substituting prior template arguments into a new
6444 /// template parameter. The template parameter itself is either a
6445 /// NonTypeTemplateParmDecl or a TemplateTemplateParmDecl.
6446 PriorTemplateArgumentSubstitution,
6448 /// We are checking the validity of a default template argument that
6449 /// has been used when naming a template-id.
6450 DefaultTemplateArgumentChecking,
6452 /// We are instantiating the exception specification for a function
6453 /// template which was deferred until it was needed.
6454 ExceptionSpecInstantiation
6457 /// \brief The point of instantiation within the source code.
6458 SourceLocation PointOfInstantiation;
6460 /// \brief The template (or partial specialization) in which we are
6461 /// performing the instantiation, for substitutions of prior template
6463 NamedDecl *Template;
6465 /// \brief The entity that is being instantiated.
6468 /// \brief The list of template arguments we are substituting, if they
6469 /// are not part of the entity.
6470 const TemplateArgument *TemplateArgs;
6472 /// \brief The number of template arguments in TemplateArgs.
6473 unsigned NumTemplateArgs;
6475 /// \brief The template deduction info object associated with the
6476 /// substitution or checking of explicit or deduced template arguments.
6477 sema::TemplateDeductionInfo *DeductionInfo;
6479 /// \brief The source range that covers the construct that cause
6480 /// the instantiation, e.g., the template-id that causes a class
6481 /// template instantiation.
6482 SourceRange InstantiationRange;
6484 ActiveTemplateInstantiation()
6485 : Kind(TemplateInstantiation), Template(nullptr), Entity(nullptr),
6486 TemplateArgs(nullptr), NumTemplateArgs(0), DeductionInfo(nullptr) {}
6488 /// \brief Determines whether this template is an actual instantiation
6489 /// that should be counted toward the maximum instantiation depth.
6490 bool isInstantiationRecord() const;
6492 friend bool operator==(const ActiveTemplateInstantiation &X,
6493 const ActiveTemplateInstantiation &Y) {
6494 if (X.Kind != Y.Kind)
6497 if (X.Entity != Y.Entity)
6501 case TemplateInstantiation:
6502 case ExceptionSpecInstantiation:
6505 case PriorTemplateArgumentSubstitution:
6506 case DefaultTemplateArgumentChecking:
6507 return X.Template == Y.Template && X.TemplateArgs == Y.TemplateArgs;
6509 case DefaultTemplateArgumentInstantiation:
6510 case ExplicitTemplateArgumentSubstitution:
6511 case DeducedTemplateArgumentSubstitution:
6512 case DefaultFunctionArgumentInstantiation:
6513 return X.TemplateArgs == Y.TemplateArgs;
6517 llvm_unreachable("Invalid InstantiationKind!");
6520 friend bool operator!=(const ActiveTemplateInstantiation &X,
6521 const ActiveTemplateInstantiation &Y) {
6526 /// \brief List of active template instantiations.
6528 /// This vector is treated as a stack. As one template instantiation
6529 /// requires another template instantiation, additional
6530 /// instantiations are pushed onto the stack up to a
6531 /// user-configurable limit LangOptions::InstantiationDepth.
6532 SmallVector<ActiveTemplateInstantiation, 16>
6533 ActiveTemplateInstantiations;
6535 /// \brief Extra modules inspected when performing a lookup during a template
6536 /// instantiation. Computed lazily.
6537 SmallVector<Module*, 16> ActiveTemplateInstantiationLookupModules;
6539 /// \brief Cache of additional modules that should be used for name lookup
6540 /// within the current template instantiation. Computed lazily; use
6541 /// getLookupModules() to get a complete set.
6542 llvm::DenseSet<Module*> LookupModulesCache;
6544 /// \brief Get the set of additional modules that should be checked during
6545 /// name lookup. A module and its imports become visible when instanting a
6546 /// template defined within it.
6547 llvm::DenseSet<Module*> &getLookupModules();
6549 /// \brief Whether we are in a SFINAE context that is not associated with
6550 /// template instantiation.
6552 /// This is used when setting up a SFINAE trap (\c see SFINAETrap) outside
6553 /// of a template instantiation or template argument deduction.
6554 bool InNonInstantiationSFINAEContext;
6556 /// \brief The number of ActiveTemplateInstantiation entries in
6557 /// \c ActiveTemplateInstantiations that are not actual instantiations and,
6558 /// therefore, should not be counted as part of the instantiation depth.
6559 unsigned NonInstantiationEntries;
6561 /// \brief The last template from which a template instantiation
6562 /// error or warning was produced.
6564 /// This value is used to suppress printing of redundant template
6565 /// instantiation backtraces when there are multiple errors in the
6566 /// same instantiation. FIXME: Does this belong in Sema? It's tough
6567 /// to implement it anywhere else.
6568 ActiveTemplateInstantiation LastTemplateInstantiationErrorContext;
6570 /// \brief The current index into pack expansion arguments that will be
6571 /// used for substitution of parameter packs.
6573 /// The pack expansion index will be -1 to indicate that parameter packs
6574 /// should be instantiated as themselves. Otherwise, the index specifies
6575 /// which argument within the parameter pack will be used for substitution.
6576 int ArgumentPackSubstitutionIndex;
6578 /// \brief RAII object used to change the argument pack substitution index
6579 /// within a \c Sema object.
6581 /// See \c ArgumentPackSubstitutionIndex for more information.
6582 class ArgumentPackSubstitutionIndexRAII {
6584 int OldSubstitutionIndex;
6587 ArgumentPackSubstitutionIndexRAII(Sema &Self, int NewSubstitutionIndex)
6588 : Self(Self), OldSubstitutionIndex(Self.ArgumentPackSubstitutionIndex) {
6589 Self.ArgumentPackSubstitutionIndex = NewSubstitutionIndex;
6592 ~ArgumentPackSubstitutionIndexRAII() {
6593 Self.ArgumentPackSubstitutionIndex = OldSubstitutionIndex;
6597 friend class ArgumentPackSubstitutionRAII;
6599 /// \brief The stack of calls expression undergoing template instantiation.
6601 /// The top of this stack is used by a fixit instantiating unresolved
6602 /// function calls to fix the AST to match the textual change it prints.
6603 SmallVector<CallExpr *, 8> CallsUndergoingInstantiation;
6605 /// \brief For each declaration that involved template argument deduction, the
6606 /// set of diagnostics that were suppressed during that template argument
6609 /// FIXME: Serialize this structure to the AST file.
6610 typedef llvm::DenseMap<Decl *, SmallVector<PartialDiagnosticAt, 1> >
6611 SuppressedDiagnosticsMap;
6612 SuppressedDiagnosticsMap SuppressedDiagnostics;
6614 /// \brief A stack object to be created when performing template
6617 /// Construction of an object of type \c InstantiatingTemplate
6618 /// pushes the current instantiation onto the stack of active
6619 /// instantiations. If the size of this stack exceeds the maximum
6620 /// number of recursive template instantiations, construction
6621 /// produces an error and evaluates true.
6623 /// Destruction of this object will pop the named instantiation off
6625 struct InstantiatingTemplate {
6626 /// \brief Note that we are instantiating a class template,
6627 /// function template, or a member thereof.
6628 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
6630 SourceRange InstantiationRange = SourceRange());
6632 struct ExceptionSpecification {};
6633 /// \brief Note that we are instantiating an exception specification
6634 /// of a function template.
6635 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
6636 FunctionDecl *Entity, ExceptionSpecification,
6637 SourceRange InstantiationRange = SourceRange());
6639 /// \brief Note that we are instantiating a default argument in a
6641 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
6642 TemplateDecl *Template,
6643 ArrayRef<TemplateArgument> TemplateArgs,
6644 SourceRange InstantiationRange = SourceRange());
6646 /// \brief Note that we are instantiating a default argument in a
6648 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
6649 FunctionTemplateDecl *FunctionTemplate,
6650 ArrayRef<TemplateArgument> TemplateArgs,
6651 ActiveTemplateInstantiation::InstantiationKind Kind,
6652 sema::TemplateDeductionInfo &DeductionInfo,
6653 SourceRange InstantiationRange = SourceRange());
6655 /// \brief Note that we are instantiating as part of template
6656 /// argument deduction for a class template partial
6658 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
6659 ClassTemplatePartialSpecializationDecl *PartialSpec,
6660 ArrayRef<TemplateArgument> TemplateArgs,
6661 sema::TemplateDeductionInfo &DeductionInfo,
6662 SourceRange InstantiationRange = SourceRange());
6664 /// \brief Note that we are instantiating as part of template
6665 /// argument deduction for a variable template partial
6667 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
6668 VarTemplatePartialSpecializationDecl *PartialSpec,
6669 ArrayRef<TemplateArgument> TemplateArgs,
6670 sema::TemplateDeductionInfo &DeductionInfo,
6671 SourceRange InstantiationRange = SourceRange());
6673 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
6675 ArrayRef<TemplateArgument> TemplateArgs,
6676 SourceRange InstantiationRange = SourceRange());
6678 /// \brief Note that we are substituting prior template arguments into a
6679 /// non-type parameter.
6680 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
6681 NamedDecl *Template,
6682 NonTypeTemplateParmDecl *Param,
6683 ArrayRef<TemplateArgument> TemplateArgs,
6684 SourceRange InstantiationRange);
6686 /// \brief Note that we are substituting prior template arguments into a
6687 /// template template parameter.
6688 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
6689 NamedDecl *Template,
6690 TemplateTemplateParmDecl *Param,
6691 ArrayRef<TemplateArgument> TemplateArgs,
6692 SourceRange InstantiationRange);
6694 /// \brief Note that we are checking the default template argument
6695 /// against the template parameter for a given template-id.
6696 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
6697 TemplateDecl *Template,
6699 ArrayRef<TemplateArgument> TemplateArgs,
6700 SourceRange InstantiationRange);
6703 /// \brief Note that we have finished instantiating this template.
6706 ~InstantiatingTemplate() { Clear(); }
6708 /// \brief Determines whether we have exceeded the maximum
6709 /// recursive template instantiations.
6710 bool isInvalid() const { return Invalid; }
6715 bool SavedInNonInstantiationSFINAEContext;
6716 bool CheckInstantiationDepth(SourceLocation PointOfInstantiation,
6717 SourceRange InstantiationRange);
6719 InstantiatingTemplate(
6720 Sema &SemaRef, ActiveTemplateInstantiation::InstantiationKind Kind,
6721 SourceLocation PointOfInstantiation, SourceRange InstantiationRange,
6722 Decl *Entity, NamedDecl *Template = nullptr,
6723 ArrayRef<TemplateArgument> TemplateArgs = ArrayRef<TemplateArgument>(),
6724 sema::TemplateDeductionInfo *DeductionInfo = nullptr);
6726 InstantiatingTemplate(const InstantiatingTemplate&) = delete;
6728 InstantiatingTemplate&
6729 operator=(const InstantiatingTemplate&) = delete;
6732 void PrintInstantiationStack();
6734 /// \brief Determines whether we are currently in a context where
6735 /// template argument substitution failures are not considered
6738 /// \returns An empty \c Optional if we're not in a SFINAE context.
6739 /// Otherwise, contains a pointer that, if non-NULL, contains the nearest
6740 /// template-deduction context object, which can be used to capture
6741 /// diagnostics that will be suppressed.
6742 Optional<sema::TemplateDeductionInfo *> isSFINAEContext() const;
6744 /// \brief Determines whether we are currently in a context that
6745 /// is not evaluated as per C++ [expr] p5.
6746 bool isUnevaluatedContext() const {
6747 assert(!ExprEvalContexts.empty() &&
6748 "Must be in an expression evaluation context");
6749 return ExprEvalContexts.back().isUnevaluated();
6752 /// \brief RAII class used to determine whether SFINAE has
6753 /// trapped any errors that occur during template argument
6757 unsigned PrevSFINAEErrors;
6758 bool PrevInNonInstantiationSFINAEContext;
6759 bool PrevAccessCheckingSFINAE;
6762 explicit SFINAETrap(Sema &SemaRef, bool AccessCheckingSFINAE = false)
6763 : SemaRef(SemaRef), PrevSFINAEErrors(SemaRef.NumSFINAEErrors),
6764 PrevInNonInstantiationSFINAEContext(
6765 SemaRef.InNonInstantiationSFINAEContext),
6766 PrevAccessCheckingSFINAE(SemaRef.AccessCheckingSFINAE)
6768 if (!SemaRef.isSFINAEContext())
6769 SemaRef.InNonInstantiationSFINAEContext = true;
6770 SemaRef.AccessCheckingSFINAE = AccessCheckingSFINAE;
6774 SemaRef.NumSFINAEErrors = PrevSFINAEErrors;
6775 SemaRef.InNonInstantiationSFINAEContext
6776 = PrevInNonInstantiationSFINAEContext;
6777 SemaRef.AccessCheckingSFINAE = PrevAccessCheckingSFINAE;
6780 /// \brief Determine whether any SFINAE errors have been trapped.
6781 bool hasErrorOccurred() const {
6782 return SemaRef.NumSFINAEErrors > PrevSFINAEErrors;
6786 /// \brief RAII class used to indicate that we are performing provisional
6787 /// semantic analysis to determine the validity of a construct, so
6788 /// typo-correction and diagnostics in the immediate context (not within
6789 /// implicitly-instantiated templates) should be suppressed.
6790 class TentativeAnalysisScope {
6792 // FIXME: Using a SFINAETrap for this is a hack.
6794 bool PrevDisableTypoCorrection;
6796 explicit TentativeAnalysisScope(Sema &SemaRef)
6797 : SemaRef(SemaRef), Trap(SemaRef, true),
6798 PrevDisableTypoCorrection(SemaRef.DisableTypoCorrection) {
6799 SemaRef.DisableTypoCorrection = true;
6801 ~TentativeAnalysisScope() {
6802 SemaRef.DisableTypoCorrection = PrevDisableTypoCorrection;
6806 /// \brief The current instantiation scope used to store local
6808 LocalInstantiationScope *CurrentInstantiationScope;
6810 /// \brief Tracks whether we are in a context where typo correction is
6812 bool DisableTypoCorrection;
6814 /// \brief The number of typos corrected by CorrectTypo.
6815 unsigned TyposCorrected;
6817 typedef llvm::SmallSet<SourceLocation, 2> SrcLocSet;
6818 typedef llvm::DenseMap<IdentifierInfo *, SrcLocSet> IdentifierSourceLocations;
6820 /// \brief A cache containing identifiers for which typo correction failed and
6821 /// their locations, so that repeated attempts to correct an identifier in a
6822 /// given location are ignored if typo correction already failed for it.
6823 IdentifierSourceLocations TypoCorrectionFailures;
6825 /// \brief Worker object for performing CFG-based warnings.
6826 sema::AnalysisBasedWarnings AnalysisWarnings;
6827 threadSafety::BeforeSet *ThreadSafetyDeclCache;
6829 /// \brief An entity for which implicit template instantiation is required.
6831 /// The source location associated with the declaration is the first place in
6832 /// the source code where the declaration was "used". It is not necessarily
6833 /// the point of instantiation (which will be either before or after the
6834 /// namespace-scope declaration that triggered this implicit instantiation),
6835 /// However, it is the location that diagnostics should generally refer to,
6836 /// because users will need to know what code triggered the instantiation.
6837 typedef std::pair<ValueDecl *, SourceLocation> PendingImplicitInstantiation;
6839 /// \brief The queue of implicit template instantiations that are required
6840 /// but have not yet been performed.
6841 std::deque<PendingImplicitInstantiation> PendingInstantiations;
6843 class SavePendingInstantiationsAndVTableUsesRAII {
6845 SavePendingInstantiationsAndVTableUsesRAII(Sema &S, bool Enabled)
6846 : S(S), Enabled(Enabled) {
6847 if (!Enabled) return;
6849 SavedPendingInstantiations.swap(S.PendingInstantiations);
6850 SavedVTableUses.swap(S.VTableUses);
6853 ~SavePendingInstantiationsAndVTableUsesRAII() {
6854 if (!Enabled) return;
6856 // Restore the set of pending vtables.
6857 assert(S.VTableUses.empty() &&
6858 "VTableUses should be empty before it is discarded.");
6859 S.VTableUses.swap(SavedVTableUses);
6861 // Restore the set of pending implicit instantiations.
6862 assert(S.PendingInstantiations.empty() &&
6863 "PendingInstantiations should be empty before it is discarded.");
6864 S.PendingInstantiations.swap(SavedPendingInstantiations);
6869 SmallVector<VTableUse, 16> SavedVTableUses;
6870 std::deque<PendingImplicitInstantiation> SavedPendingInstantiations;
6874 /// \brief The queue of implicit template instantiations that are required
6875 /// and must be performed within the current local scope.
6877 /// This queue is only used for member functions of local classes in
6878 /// templates, which must be instantiated in the same scope as their
6879 /// enclosing function, so that they can reference function-local
6880 /// types, static variables, enumerators, etc.
6881 std::deque<PendingImplicitInstantiation> PendingLocalImplicitInstantiations;
6883 class SavePendingLocalImplicitInstantiationsRAII {
6885 SavePendingLocalImplicitInstantiationsRAII(Sema &S): S(S) {
6886 SavedPendingLocalImplicitInstantiations.swap(
6887 S.PendingLocalImplicitInstantiations);
6890 ~SavePendingLocalImplicitInstantiationsRAII() {
6891 assert(S.PendingLocalImplicitInstantiations.empty() &&
6892 "there shouldn't be any pending local implicit instantiations");
6893 SavedPendingLocalImplicitInstantiations.swap(
6894 S.PendingLocalImplicitInstantiations);
6899 std::deque<PendingImplicitInstantiation>
6900 SavedPendingLocalImplicitInstantiations;
6903 void PerformPendingInstantiations(bool LocalOnly = false);
6905 TypeSourceInfo *SubstType(TypeSourceInfo *T,
6906 const MultiLevelTemplateArgumentList &TemplateArgs,
6907 SourceLocation Loc, DeclarationName Entity);
6909 QualType SubstType(QualType T,
6910 const MultiLevelTemplateArgumentList &TemplateArgs,
6911 SourceLocation Loc, DeclarationName Entity);
6913 TypeSourceInfo *SubstType(TypeLoc TL,
6914 const MultiLevelTemplateArgumentList &TemplateArgs,
6915 SourceLocation Loc, DeclarationName Entity);
6917 TypeSourceInfo *SubstFunctionDeclType(TypeSourceInfo *T,
6918 const MultiLevelTemplateArgumentList &TemplateArgs,
6920 DeclarationName Entity,
6921 CXXRecordDecl *ThisContext,
6922 unsigned ThisTypeQuals);
6923 void SubstExceptionSpec(FunctionDecl *New, const FunctionProtoType *Proto,
6924 const MultiLevelTemplateArgumentList &Args);
6925 ParmVarDecl *SubstParmVarDecl(ParmVarDecl *D,
6926 const MultiLevelTemplateArgumentList &TemplateArgs,
6927 int indexAdjustment,
6928 Optional<unsigned> NumExpansions,
6929 bool ExpectParameterPack);
6930 bool SubstParmTypes(SourceLocation Loc,
6931 ParmVarDecl **Params, unsigned NumParams,
6932 const MultiLevelTemplateArgumentList &TemplateArgs,
6933 SmallVectorImpl<QualType> &ParamTypes,
6934 SmallVectorImpl<ParmVarDecl *> *OutParams = nullptr);
6935 ExprResult SubstExpr(Expr *E,
6936 const MultiLevelTemplateArgumentList &TemplateArgs);
6938 /// \brief Substitute the given template arguments into a list of
6939 /// expressions, expanding pack expansions if required.
6941 /// \param Exprs The list of expressions to substitute into.
6943 /// \param NumExprs The number of expressions in \p Exprs.
6945 /// \param IsCall Whether this is some form of call, in which case
6946 /// default arguments will be dropped.
6948 /// \param TemplateArgs The set of template arguments to substitute.
6950 /// \param Outputs Will receive all of the substituted arguments.
6952 /// \returns true if an error occurred, false otherwise.
6953 bool SubstExprs(Expr **Exprs, unsigned NumExprs, bool IsCall,
6954 const MultiLevelTemplateArgumentList &TemplateArgs,
6955 SmallVectorImpl<Expr *> &Outputs);
6957 StmtResult SubstStmt(Stmt *S,
6958 const MultiLevelTemplateArgumentList &TemplateArgs);
6960 Decl *SubstDecl(Decl *D, DeclContext *Owner,
6961 const MultiLevelTemplateArgumentList &TemplateArgs);
6963 ExprResult SubstInitializer(Expr *E,
6964 const MultiLevelTemplateArgumentList &TemplateArgs,
6965 bool CXXDirectInit);
6968 SubstBaseSpecifiers(CXXRecordDecl *Instantiation,
6969 CXXRecordDecl *Pattern,
6970 const MultiLevelTemplateArgumentList &TemplateArgs);
6973 InstantiateClass(SourceLocation PointOfInstantiation,
6974 CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern,
6975 const MultiLevelTemplateArgumentList &TemplateArgs,
6976 TemplateSpecializationKind TSK,
6977 bool Complain = true);
6979 bool InstantiateEnum(SourceLocation PointOfInstantiation,
6980 EnumDecl *Instantiation, EnumDecl *Pattern,
6981 const MultiLevelTemplateArgumentList &TemplateArgs,
6982 TemplateSpecializationKind TSK);
6984 bool InstantiateInClassInitializer(
6985 SourceLocation PointOfInstantiation, FieldDecl *Instantiation,
6986 FieldDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs);
6988 struct LateInstantiatedAttribute {
6989 const Attr *TmplAttr;
6990 LocalInstantiationScope *Scope;
6993 LateInstantiatedAttribute(const Attr *A, LocalInstantiationScope *S,
6995 : TmplAttr(A), Scope(S), NewDecl(D)
6998 typedef SmallVector<LateInstantiatedAttribute, 16> LateInstantiatedAttrVec;
7000 void InstantiateAttrs(const MultiLevelTemplateArgumentList &TemplateArgs,
7001 const Decl *Pattern, Decl *Inst,
7002 LateInstantiatedAttrVec *LateAttrs = nullptr,
7003 LocalInstantiationScope *OuterMostScope = nullptr);
7006 InstantiateClassTemplateSpecialization(SourceLocation PointOfInstantiation,
7007 ClassTemplateSpecializationDecl *ClassTemplateSpec,
7008 TemplateSpecializationKind TSK,
7009 bool Complain = true);
7011 void InstantiateClassMembers(SourceLocation PointOfInstantiation,
7012 CXXRecordDecl *Instantiation,
7013 const MultiLevelTemplateArgumentList &TemplateArgs,
7014 TemplateSpecializationKind TSK);
7016 void InstantiateClassTemplateSpecializationMembers(
7017 SourceLocation PointOfInstantiation,
7018 ClassTemplateSpecializationDecl *ClassTemplateSpec,
7019 TemplateSpecializationKind TSK);
7021 NestedNameSpecifierLoc
7022 SubstNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS,
7023 const MultiLevelTemplateArgumentList &TemplateArgs);
7026 SubstDeclarationNameInfo(const DeclarationNameInfo &NameInfo,
7027 const MultiLevelTemplateArgumentList &TemplateArgs);
7029 SubstTemplateName(NestedNameSpecifierLoc QualifierLoc, TemplateName Name,
7031 const MultiLevelTemplateArgumentList &TemplateArgs);
7032 bool Subst(const TemplateArgumentLoc *Args, unsigned NumArgs,
7033 TemplateArgumentListInfo &Result,
7034 const MultiLevelTemplateArgumentList &TemplateArgs);
7036 void InstantiateExceptionSpec(SourceLocation PointOfInstantiation,
7037 FunctionDecl *Function);
7038 void InstantiateFunctionDefinition(SourceLocation PointOfInstantiation,
7039 FunctionDecl *Function,
7040 bool Recursive = false,
7041 bool DefinitionRequired = false);
7042 VarTemplateSpecializationDecl *BuildVarTemplateInstantiation(
7043 VarTemplateDecl *VarTemplate, VarDecl *FromVar,
7044 const TemplateArgumentList &TemplateArgList,
7045 const TemplateArgumentListInfo &TemplateArgsInfo,
7046 SmallVectorImpl<TemplateArgument> &Converted,
7047 SourceLocation PointOfInstantiation, void *InsertPos,
7048 LateInstantiatedAttrVec *LateAttrs = nullptr,
7049 LocalInstantiationScope *StartingScope = nullptr);
7050 VarTemplateSpecializationDecl *CompleteVarTemplateSpecializationDecl(
7051 VarTemplateSpecializationDecl *VarSpec, VarDecl *PatternDecl,
7052 const MultiLevelTemplateArgumentList &TemplateArgs);
7054 BuildVariableInstantiation(VarDecl *NewVar, VarDecl *OldVar,
7055 const MultiLevelTemplateArgumentList &TemplateArgs,
7056 LateInstantiatedAttrVec *LateAttrs,
7058 LocalInstantiationScope *StartingScope,
7059 bool InstantiatingVarTemplate = false);
7060 void InstantiateVariableInitializer(
7061 VarDecl *Var, VarDecl *OldVar,
7062 const MultiLevelTemplateArgumentList &TemplateArgs);
7063 void InstantiateVariableDefinition(SourceLocation PointOfInstantiation,
7064 VarDecl *Var, bool Recursive = false,
7065 bool DefinitionRequired = false);
7066 void InstantiateStaticDataMemberDefinition(
7067 SourceLocation PointOfInstantiation,
7069 bool Recursive = false,
7070 bool DefinitionRequired = false);
7072 void InstantiateMemInitializers(CXXConstructorDecl *New,
7073 const CXXConstructorDecl *Tmpl,
7074 const MultiLevelTemplateArgumentList &TemplateArgs);
7076 NamedDecl *FindInstantiatedDecl(SourceLocation Loc, NamedDecl *D,
7077 const MultiLevelTemplateArgumentList &TemplateArgs);
7078 DeclContext *FindInstantiatedContext(SourceLocation Loc, DeclContext *DC,
7079 const MultiLevelTemplateArgumentList &TemplateArgs);
7081 // Objective-C declarations.
7082 enum ObjCContainerKind {
7089 OCK_CategoryImplementation
7091 ObjCContainerKind getObjCContainerKind() const;
7093 DeclResult actOnObjCTypeParam(Scope *S,
7094 ObjCTypeParamVariance variance,
7095 SourceLocation varianceLoc,
7097 IdentifierInfo *paramName,
7098 SourceLocation paramLoc,
7099 SourceLocation colonLoc,
7100 ParsedType typeBound);
7102 ObjCTypeParamList *actOnObjCTypeParamList(Scope *S, SourceLocation lAngleLoc,
7103 ArrayRef<Decl *> typeParams,
7104 SourceLocation rAngleLoc);
7105 void popObjCTypeParamList(Scope *S, ObjCTypeParamList *typeParamList);
7107 Decl *ActOnStartClassInterface(Scope *S,
7108 SourceLocation AtInterfaceLoc,
7109 IdentifierInfo *ClassName,
7110 SourceLocation ClassLoc,
7111 ObjCTypeParamList *typeParamList,
7112 IdentifierInfo *SuperName,
7113 SourceLocation SuperLoc,
7114 ArrayRef<ParsedType> SuperTypeArgs,
7115 SourceRange SuperTypeArgsRange,
7116 Decl * const *ProtoRefs,
7117 unsigned NumProtoRefs,
7118 const SourceLocation *ProtoLocs,
7119 SourceLocation EndProtoLoc,
7120 AttributeList *AttrList);
7122 void ActOnSuperClassOfClassInterface(Scope *S,
7123 SourceLocation AtInterfaceLoc,
7124 ObjCInterfaceDecl *IDecl,
7125 IdentifierInfo *ClassName,
7126 SourceLocation ClassLoc,
7127 IdentifierInfo *SuperName,
7128 SourceLocation SuperLoc,
7129 ArrayRef<ParsedType> SuperTypeArgs,
7130 SourceRange SuperTypeArgsRange);
7132 void ActOnTypedefedProtocols(SmallVectorImpl<Decl *> &ProtocolRefs,
7133 IdentifierInfo *SuperName,
7134 SourceLocation SuperLoc);
7136 Decl *ActOnCompatibilityAlias(
7137 SourceLocation AtCompatibilityAliasLoc,
7138 IdentifierInfo *AliasName, SourceLocation AliasLocation,
7139 IdentifierInfo *ClassName, SourceLocation ClassLocation);
7141 bool CheckForwardProtocolDeclarationForCircularDependency(
7142 IdentifierInfo *PName,
7143 SourceLocation &PLoc, SourceLocation PrevLoc,
7144 const ObjCList<ObjCProtocolDecl> &PList);
7146 Decl *ActOnStartProtocolInterface(
7147 SourceLocation AtProtoInterfaceLoc,
7148 IdentifierInfo *ProtocolName, SourceLocation ProtocolLoc,
7149 Decl * const *ProtoRefNames, unsigned NumProtoRefs,
7150 const SourceLocation *ProtoLocs,
7151 SourceLocation EndProtoLoc,
7152 AttributeList *AttrList);
7154 Decl *ActOnStartCategoryInterface(SourceLocation AtInterfaceLoc,
7155 IdentifierInfo *ClassName,
7156 SourceLocation ClassLoc,
7157 ObjCTypeParamList *typeParamList,
7158 IdentifierInfo *CategoryName,
7159 SourceLocation CategoryLoc,
7160 Decl * const *ProtoRefs,
7161 unsigned NumProtoRefs,
7162 const SourceLocation *ProtoLocs,
7163 SourceLocation EndProtoLoc);
7165 Decl *ActOnStartClassImplementation(
7166 SourceLocation AtClassImplLoc,
7167 IdentifierInfo *ClassName, SourceLocation ClassLoc,
7168 IdentifierInfo *SuperClassname,
7169 SourceLocation SuperClassLoc);
7171 Decl *ActOnStartCategoryImplementation(SourceLocation AtCatImplLoc,
7172 IdentifierInfo *ClassName,
7173 SourceLocation ClassLoc,
7174 IdentifierInfo *CatName,
7175 SourceLocation CatLoc);
7177 DeclGroupPtrTy ActOnFinishObjCImplementation(Decl *ObjCImpDecl,
7178 ArrayRef<Decl *> Decls);
7180 DeclGroupPtrTy ActOnForwardClassDeclaration(SourceLocation Loc,
7181 IdentifierInfo **IdentList,
7182 SourceLocation *IdentLocs,
7183 ArrayRef<ObjCTypeParamList *> TypeParamLists,
7186 DeclGroupPtrTy ActOnForwardProtocolDeclaration(SourceLocation AtProtoclLoc,
7187 const IdentifierLocPair *IdentList,
7189 AttributeList *attrList);
7191 void FindProtocolDeclaration(bool WarnOnDeclarations, bool ForObjCContainer,
7192 const IdentifierLocPair *ProtocolId,
7193 unsigned NumProtocols,
7194 SmallVectorImpl<Decl *> &Protocols);
7196 /// Given a list of identifiers (and their locations), resolve the
7197 /// names to either Objective-C protocol qualifiers or type
7198 /// arguments, as appropriate.
7199 void actOnObjCTypeArgsOrProtocolQualifiers(
7201 ParsedType baseType,
7202 SourceLocation lAngleLoc,
7203 ArrayRef<IdentifierInfo *> identifiers,
7204 ArrayRef<SourceLocation> identifierLocs,
7205 SourceLocation rAngleLoc,
7206 SourceLocation &typeArgsLAngleLoc,
7207 SmallVectorImpl<ParsedType> &typeArgs,
7208 SourceLocation &typeArgsRAngleLoc,
7209 SourceLocation &protocolLAngleLoc,
7210 SmallVectorImpl<Decl *> &protocols,
7211 SourceLocation &protocolRAngleLoc,
7212 bool warnOnIncompleteProtocols);
7214 /// Build a an Objective-C protocol-qualified 'id' type where no
7215 /// base type was specified.
7216 TypeResult actOnObjCProtocolQualifierType(
7217 SourceLocation lAngleLoc,
7218 ArrayRef<Decl *> protocols,
7219 ArrayRef<SourceLocation> protocolLocs,
7220 SourceLocation rAngleLoc);
7222 /// Build a specialized and/or protocol-qualified Objective-C type.
7223 TypeResult actOnObjCTypeArgsAndProtocolQualifiers(
7226 ParsedType BaseType,
7227 SourceLocation TypeArgsLAngleLoc,
7228 ArrayRef<ParsedType> TypeArgs,
7229 SourceLocation TypeArgsRAngleLoc,
7230 SourceLocation ProtocolLAngleLoc,
7231 ArrayRef<Decl *> Protocols,
7232 ArrayRef<SourceLocation> ProtocolLocs,
7233 SourceLocation ProtocolRAngleLoc);
7235 /// Build an Objective-C object pointer type.
7236 QualType BuildObjCObjectType(QualType BaseType,
7238 SourceLocation TypeArgsLAngleLoc,
7239 ArrayRef<TypeSourceInfo *> TypeArgs,
7240 SourceLocation TypeArgsRAngleLoc,
7241 SourceLocation ProtocolLAngleLoc,
7242 ArrayRef<ObjCProtocolDecl *> Protocols,
7243 ArrayRef<SourceLocation> ProtocolLocs,
7244 SourceLocation ProtocolRAngleLoc,
7245 bool FailOnError = false);
7247 /// Check the application of the Objective-C '__kindof' qualifier to
7249 bool checkObjCKindOfType(QualType &type, SourceLocation loc);
7251 /// Ensure attributes are consistent with type.
7252 /// \param [in, out] Attributes The attributes to check; they will
7253 /// be modified to be consistent with \p PropertyTy.
7254 void CheckObjCPropertyAttributes(Decl *PropertyPtrTy,
7256 unsigned &Attributes,
7257 bool propertyInPrimaryClass);
7259 /// Process the specified property declaration and create decls for the
7260 /// setters and getters as needed.
7261 /// \param property The property declaration being processed
7262 /// \param CD The semantic container for the property
7263 /// \param redeclaredProperty Declaration for property if redeclared
7264 /// in class extension.
7265 /// \param lexicalDC Container for redeclaredProperty.
7266 void ProcessPropertyDecl(ObjCPropertyDecl *property,
7267 ObjCContainerDecl *CD,
7268 ObjCPropertyDecl *redeclaredProperty = nullptr,
7269 ObjCContainerDecl *lexicalDC = nullptr);
7272 void DiagnosePropertyMismatch(ObjCPropertyDecl *Property,
7273 ObjCPropertyDecl *SuperProperty,
7274 const IdentifierInfo *Name,
7275 bool OverridingProtocolProperty);
7277 void DiagnoseClassExtensionDupMethods(ObjCCategoryDecl *CAT,
7278 ObjCInterfaceDecl *ID);
7280 Decl *ActOnAtEnd(Scope *S, SourceRange AtEnd,
7281 ArrayRef<Decl *> allMethods = None,
7282 ArrayRef<DeclGroupPtrTy> allTUVars = None);
7284 Decl *ActOnProperty(Scope *S, SourceLocation AtLoc,
7285 SourceLocation LParenLoc,
7286 FieldDeclarator &FD, ObjCDeclSpec &ODS,
7287 Selector GetterSel, Selector SetterSel,
7288 bool *OverridingProperty,
7289 tok::ObjCKeywordKind MethodImplKind,
7290 DeclContext *lexicalDC = nullptr);
7292 Decl *ActOnPropertyImplDecl(Scope *S,
7293 SourceLocation AtLoc,
7294 SourceLocation PropertyLoc,
7296 IdentifierInfo *PropertyId,
7297 IdentifierInfo *PropertyIvar,
7298 SourceLocation PropertyIvarLoc);
7300 enum ObjCSpecialMethodKind {
7306 OSMK_NonRetainingInit
7309 struct ObjCArgInfo {
7310 IdentifierInfo *Name;
7311 SourceLocation NameLoc;
7312 // The Type is null if no type was specified, and the DeclSpec is invalid
7315 ObjCDeclSpec DeclSpec;
7317 /// ArgAttrs - Attribute list for this argument.
7318 AttributeList *ArgAttrs;
7321 Decl *ActOnMethodDeclaration(
7323 SourceLocation BeginLoc, // location of the + or -.
7324 SourceLocation EndLoc, // location of the ; or {.
7325 tok::TokenKind MethodType,
7326 ObjCDeclSpec &ReturnQT, ParsedType ReturnType,
7327 ArrayRef<SourceLocation> SelectorLocs, Selector Sel,
7328 // optional arguments. The number of types/arguments is obtained
7329 // from the Sel.getNumArgs().
7330 ObjCArgInfo *ArgInfo,
7331 DeclaratorChunk::ParamInfo *CParamInfo, unsigned CNumArgs, // c-style args
7332 AttributeList *AttrList, tok::ObjCKeywordKind MethodImplKind,
7333 bool isVariadic, bool MethodDefinition);
7335 ObjCMethodDecl *LookupMethodInQualifiedType(Selector Sel,
7336 const ObjCObjectPointerType *OPT,
7338 ObjCMethodDecl *LookupMethodInObjectType(Selector Sel, QualType Ty,
7341 bool CheckARCMethodDecl(ObjCMethodDecl *method);
7342 bool inferObjCARCLifetime(ValueDecl *decl);
7345 HandleExprPropertyRefExpr(const ObjCObjectPointerType *OPT,
7347 SourceLocation OpLoc,
7348 DeclarationName MemberName,
7349 SourceLocation MemberLoc,
7350 SourceLocation SuperLoc, QualType SuperType,
7354 ActOnClassPropertyRefExpr(IdentifierInfo &receiverName,
7355 IdentifierInfo &propertyName,
7356 SourceLocation receiverNameLoc,
7357 SourceLocation propertyNameLoc);
7359 ObjCMethodDecl *tryCaptureObjCSelf(SourceLocation Loc);
7361 /// \brief Describes the kind of message expression indicated by a message
7362 /// send that starts with an identifier.
7363 enum ObjCMessageKind {
7364 /// \brief The message is sent to 'super'.
7366 /// \brief The message is an instance message.
7367 ObjCInstanceMessage,
7368 /// \brief The message is a class message, and the identifier is a type
7373 ObjCMessageKind getObjCMessageKind(Scope *S,
7374 IdentifierInfo *Name,
7375 SourceLocation NameLoc,
7377 bool HasTrailingDot,
7378 ParsedType &ReceiverType);
7380 ExprResult ActOnSuperMessage(Scope *S, SourceLocation SuperLoc,
7382 SourceLocation LBracLoc,
7383 ArrayRef<SourceLocation> SelectorLocs,
7384 SourceLocation RBracLoc,
7387 ExprResult BuildClassMessage(TypeSourceInfo *ReceiverTypeInfo,
7388 QualType ReceiverType,
7389 SourceLocation SuperLoc,
7391 ObjCMethodDecl *Method,
7392 SourceLocation LBracLoc,
7393 ArrayRef<SourceLocation> SelectorLocs,
7394 SourceLocation RBracLoc,
7396 bool isImplicit = false);
7398 ExprResult BuildClassMessageImplicit(QualType ReceiverType,
7399 bool isSuperReceiver,
7402 ObjCMethodDecl *Method,
7405 ExprResult ActOnClassMessage(Scope *S,
7406 ParsedType Receiver,
7408 SourceLocation LBracLoc,
7409 ArrayRef<SourceLocation> SelectorLocs,
7410 SourceLocation RBracLoc,
7413 ExprResult BuildInstanceMessage(Expr *Receiver,
7414 QualType ReceiverType,
7415 SourceLocation SuperLoc,
7417 ObjCMethodDecl *Method,
7418 SourceLocation LBracLoc,
7419 ArrayRef<SourceLocation> SelectorLocs,
7420 SourceLocation RBracLoc,
7422 bool isImplicit = false);
7424 ExprResult BuildInstanceMessageImplicit(Expr *Receiver,
7425 QualType ReceiverType,
7428 ObjCMethodDecl *Method,
7431 ExprResult ActOnInstanceMessage(Scope *S,
7434 SourceLocation LBracLoc,
7435 ArrayRef<SourceLocation> SelectorLocs,
7436 SourceLocation RBracLoc,
7439 ExprResult BuildObjCBridgedCast(SourceLocation LParenLoc,
7440 ObjCBridgeCastKind Kind,
7441 SourceLocation BridgeKeywordLoc,
7442 TypeSourceInfo *TSInfo,
7445 ExprResult ActOnObjCBridgedCast(Scope *S,
7446 SourceLocation LParenLoc,
7447 ObjCBridgeCastKind Kind,
7448 SourceLocation BridgeKeywordLoc,
7450 SourceLocation RParenLoc,
7453 void CheckTollFreeBridgeCast(QualType castType, Expr *castExpr);
7455 void CheckObjCBridgeRelatedCast(QualType castType, Expr *castExpr);
7457 bool CheckTollFreeBridgeStaticCast(QualType castType, Expr *castExpr,
7460 bool checkObjCBridgeRelatedComponents(SourceLocation Loc,
7461 QualType DestType, QualType SrcType,
7462 ObjCInterfaceDecl *&RelatedClass,
7463 ObjCMethodDecl *&ClassMethod,
7464 ObjCMethodDecl *&InstanceMethod,
7465 TypedefNameDecl *&TDNDecl,
7468 bool CheckObjCBridgeRelatedConversions(SourceLocation Loc,
7469 QualType DestType, QualType SrcType,
7472 bool ConversionToObjCStringLiteralCheck(QualType DstType, Expr *&SrcExpr);
7474 bool checkInitMethod(ObjCMethodDecl *method, QualType receiverTypeIfCall);
7476 /// \brief Check whether the given new method is a valid override of the
7477 /// given overridden method, and set any properties that should be inherited.
7478 void CheckObjCMethodOverride(ObjCMethodDecl *NewMethod,
7479 const ObjCMethodDecl *Overridden);
7481 /// \brief Describes the compatibility of a result type with its method.
7482 enum ResultTypeCompatibilityKind {
7488 void CheckObjCMethodOverrides(ObjCMethodDecl *ObjCMethod,
7489 ObjCInterfaceDecl *CurrentClass,
7490 ResultTypeCompatibilityKind RTC);
7492 enum PragmaOptionsAlignKind {
7493 POAK_Native, // #pragma options align=native
7494 POAK_Natural, // #pragma options align=natural
7495 POAK_Packed, // #pragma options align=packed
7496 POAK_Power, // #pragma options align=power
7497 POAK_Mac68k, // #pragma options align=mac68k
7498 POAK_Reset // #pragma options align=reset
7501 /// ActOnPragmaOptionsAlign - Called on well formed \#pragma options align.
7502 void ActOnPragmaOptionsAlign(PragmaOptionsAlignKind Kind,
7503 SourceLocation PragmaLoc);
7505 enum PragmaPackKind {
7506 PPK_Default, // #pragma pack([n])
7507 PPK_Show, // #pragma pack(show), only supported by MSVC.
7508 PPK_Push, // #pragma pack(push, [identifier], [n])
7509 PPK_Pop // #pragma pack(pop, [identifier], [n])
7512 enum PragmaMSStructKind {
7513 PMSST_OFF, // #pragms ms_struct off
7514 PMSST_ON // #pragms ms_struct on
7517 enum PragmaMSCommentKind {
7519 PCK_Linker, // #pragma comment(linker, ...)
7520 PCK_Lib, // #pragma comment(lib, ...)
7521 PCK_Compiler, // #pragma comment(compiler, ...)
7522 PCK_ExeStr, // #pragma comment(exestr, ...)
7523 PCK_User // #pragma comment(user, ...)
7526 /// ActOnPragmaPack - Called on well formed \#pragma pack(...).
7527 void ActOnPragmaPack(PragmaPackKind Kind,
7528 IdentifierInfo *Name,
7530 SourceLocation PragmaLoc,
7531 SourceLocation LParenLoc,
7532 SourceLocation RParenLoc);
7534 /// ActOnPragmaMSStruct - Called on well formed \#pragma ms_struct [on|off].
7535 void ActOnPragmaMSStruct(PragmaMSStructKind Kind);
7537 /// ActOnPragmaMSComment - Called on well formed
7538 /// \#pragma comment(kind, "arg").
7539 void ActOnPragmaMSComment(PragmaMSCommentKind Kind, StringRef Arg);
7541 /// ActOnPragmaMSPointersToMembers - called on well formed \#pragma
7542 /// pointers_to_members(representation method[, general purpose
7543 /// representation]).
7544 void ActOnPragmaMSPointersToMembers(
7545 LangOptions::PragmaMSPointersToMembersKind Kind,
7546 SourceLocation PragmaLoc);
7548 /// \brief Called on well formed \#pragma vtordisp().
7549 void ActOnPragmaMSVtorDisp(PragmaVtorDispKind Kind, SourceLocation PragmaLoc,
7550 MSVtorDispAttr::Mode Value);
7552 enum PragmaSectionKind {
7559 bool UnifySection(StringRef SectionName,
7561 DeclaratorDecl *TheDecl);
7562 bool UnifySection(StringRef SectionName,
7564 SourceLocation PragmaSectionLocation);
7566 /// \brief Called on well formed \#pragma bss_seg/data_seg/const_seg/code_seg.
7567 void ActOnPragmaMSSeg(SourceLocation PragmaLocation,
7568 PragmaMsStackAction Action,
7569 llvm::StringRef StackSlotLabel,
7570 StringLiteral *SegmentName,
7571 llvm::StringRef PragmaName);
7573 /// \brief Called on well formed \#pragma section().
7574 void ActOnPragmaMSSection(SourceLocation PragmaLocation,
7575 int SectionFlags, StringLiteral *SegmentName);
7577 /// \brief Called on well-formed \#pragma init_seg().
7578 void ActOnPragmaMSInitSeg(SourceLocation PragmaLocation,
7579 StringLiteral *SegmentName);
7581 /// ActOnPragmaDetectMismatch - Call on well-formed \#pragma detect_mismatch
7582 void ActOnPragmaDetectMismatch(StringRef Name, StringRef Value);
7584 /// ActOnPragmaUnused - Called on well-formed '\#pragma unused'.
7585 void ActOnPragmaUnused(const Token &Identifier,
7587 SourceLocation PragmaLoc);
7589 /// ActOnPragmaVisibility - Called on well formed \#pragma GCC visibility... .
7590 void ActOnPragmaVisibility(const IdentifierInfo* VisType,
7591 SourceLocation PragmaLoc);
7593 NamedDecl *DeclClonePragmaWeak(NamedDecl *ND, IdentifierInfo *II,
7594 SourceLocation Loc);
7595 void DeclApplyPragmaWeak(Scope *S, NamedDecl *ND, WeakInfo &W);
7597 /// ActOnPragmaWeakID - Called on well formed \#pragma weak ident.
7598 void ActOnPragmaWeakID(IdentifierInfo* WeakName,
7599 SourceLocation PragmaLoc,
7600 SourceLocation WeakNameLoc);
7602 /// ActOnPragmaRedefineExtname - Called on well formed
7603 /// \#pragma redefine_extname oldname newname.
7604 void ActOnPragmaRedefineExtname(IdentifierInfo* WeakName,
7605 IdentifierInfo* AliasName,
7606 SourceLocation PragmaLoc,
7607 SourceLocation WeakNameLoc,
7608 SourceLocation AliasNameLoc);
7610 /// ActOnPragmaWeakAlias - Called on well formed \#pragma weak ident = ident.
7611 void ActOnPragmaWeakAlias(IdentifierInfo* WeakName,
7612 IdentifierInfo* AliasName,
7613 SourceLocation PragmaLoc,
7614 SourceLocation WeakNameLoc,
7615 SourceLocation AliasNameLoc);
7617 /// ActOnPragmaFPContract - Called on well formed
7618 /// \#pragma {STDC,OPENCL} FP_CONTRACT
7619 void ActOnPragmaFPContract(tok::OnOffSwitch OOS);
7621 /// AddAlignmentAttributesForRecord - Adds any needed alignment attributes to
7622 /// a the record decl, to handle '\#pragma pack' and '\#pragma options align'.
7623 void AddAlignmentAttributesForRecord(RecordDecl *RD);
7625 /// AddMsStructLayoutForRecord - Adds ms_struct layout attribute to record.
7626 void AddMsStructLayoutForRecord(RecordDecl *RD);
7628 /// FreePackedContext - Deallocate and null out PackContext.
7629 void FreePackedContext();
7631 /// PushNamespaceVisibilityAttr - Note that we've entered a
7632 /// namespace with a visibility attribute.
7633 void PushNamespaceVisibilityAttr(const VisibilityAttr *Attr,
7634 SourceLocation Loc);
7636 /// AddPushedVisibilityAttribute - If '\#pragma GCC visibility' was used,
7637 /// add an appropriate visibility attribute.
7638 void AddPushedVisibilityAttribute(Decl *RD);
7640 /// PopPragmaVisibility - Pop the top element of the visibility stack; used
7641 /// for '\#pragma GCC visibility' and visibility attributes on namespaces.
7642 void PopPragmaVisibility(bool IsNamespaceEnd, SourceLocation EndLoc);
7644 /// FreeVisContext - Deallocate and null out VisContext.
7645 void FreeVisContext();
7647 /// AddCFAuditedAttribute - Check whether we're currently within
7648 /// '\#pragma clang arc_cf_code_audited' and, if so, consider adding
7649 /// the appropriate attribute.
7650 void AddCFAuditedAttribute(Decl *D);
7652 /// \brief Called on well formed \#pragma clang optimize.
7653 void ActOnPragmaOptimize(bool On, SourceLocation PragmaLoc);
7655 /// \brief Get the location for the currently active "\#pragma clang optimize
7656 /// off". If this location is invalid, then the state of the pragma is "on".
7657 SourceLocation getOptimizeOffPragmaLocation() const {
7658 return OptimizeOffPragmaLocation;
7661 /// \brief Only called on function definitions; if there is a pragma in scope
7662 /// with the effect of a range-based optnone, consider marking the function
7663 /// with attribute optnone.
7664 void AddRangeBasedOptnone(FunctionDecl *FD);
7666 /// \brief Adds the 'optnone' attribute to the function declaration if there
7667 /// are no conflicts; Loc represents the location causing the 'optnone'
7668 /// attribute to be added (usually because of a pragma).
7669 void AddOptnoneAttributeIfNoConflicts(FunctionDecl *FD, SourceLocation Loc);
7671 /// AddAlignedAttr - Adds an aligned attribute to a particular declaration.
7672 void AddAlignedAttr(SourceRange AttrRange, Decl *D, Expr *E,
7673 unsigned SpellingListIndex, bool IsPackExpansion);
7674 void AddAlignedAttr(SourceRange AttrRange, Decl *D, TypeSourceInfo *T,
7675 unsigned SpellingListIndex, bool IsPackExpansion);
7677 /// AddAssumeAlignedAttr - Adds an assume_aligned attribute to a particular
7679 void AddAssumeAlignedAttr(SourceRange AttrRange, Decl *D, Expr *E, Expr *OE,
7680 unsigned SpellingListIndex);
7682 /// AddAlignValueAttr - Adds an align_value attribute to a particular
7684 void AddAlignValueAttr(SourceRange AttrRange, Decl *D, Expr *E,
7685 unsigned SpellingListIndex);
7687 /// AddLaunchBoundsAttr - Adds a launch_bounds attribute to a particular
7689 void AddLaunchBoundsAttr(SourceRange AttrRange, Decl *D, Expr *MaxThreads,
7690 Expr *MinBlocks, unsigned SpellingListIndex);
7692 // OpenMP directives and clauses.
7694 void *VarDataSharingAttributesStack;
7695 /// \brief Initialization of data-sharing attributes stack.
7696 void InitDataSharingAttributesStack();
7697 void DestroyDataSharingAttributesStack();
7698 ExprResult VerifyPositiveIntegerConstantInClause(Expr *Op,
7699 OpenMPClauseKind CKind);
7701 /// \brief Check if the specified variable is used in a private clause in
7702 /// Checks if the specified variable is used in one of the private
7703 /// clauses in OpenMP constructs.
7704 bool IsOpenMPCapturedVar(VarDecl *VD);
7706 /// OpenMP constructs.
7707 /// \param Level Relative level of nested OpenMP construct for that the check
7709 bool isOpenMPPrivateVar(VarDecl *VD, unsigned Level);
7711 ExprResult PerformOpenMPImplicitIntegerConversion(SourceLocation OpLoc,
7713 /// \brief Called on start of new data sharing attribute block.
7714 void StartOpenMPDSABlock(OpenMPDirectiveKind K,
7715 const DeclarationNameInfo &DirName, Scope *CurScope,
7716 SourceLocation Loc);
7717 /// \brief Start analysis of clauses.
7718 void StartOpenMPClause(OpenMPClauseKind K);
7719 /// \brief End analysis of clauses.
7720 void EndOpenMPClause();
7721 /// \brief Called on end of data sharing attribute block.
7722 void EndOpenMPDSABlock(Stmt *CurDirective);
7724 /// \brief Check if the current region is an OpenMP loop region and if it is,
7725 /// mark loop control variable, used in \p Init for loop initialization, as
7726 /// private by default.
7727 /// \param Init First part of the for loop.
7728 void ActOnOpenMPLoopInitialization(SourceLocation ForLoc, Stmt *Init);
7730 // OpenMP directives and clauses.
7731 /// \brief Called on correct id-expression from the '#pragma omp
7733 ExprResult ActOnOpenMPIdExpression(Scope *CurScope,
7734 CXXScopeSpec &ScopeSpec,
7735 const DeclarationNameInfo &Id);
7736 /// \brief Called on well-formed '#pragma omp threadprivate'.
7737 DeclGroupPtrTy ActOnOpenMPThreadprivateDirective(
7739 ArrayRef<Expr *> VarList);
7740 /// \brief Builds a new OpenMPThreadPrivateDecl and checks its correctness.
7741 OMPThreadPrivateDecl *CheckOMPThreadPrivateDecl(
7743 ArrayRef<Expr *> VarList);
7745 /// \brief Initialization of captured region for OpenMP region.
7746 void ActOnOpenMPRegionStart(OpenMPDirectiveKind DKind, Scope *CurScope);
7747 /// \brief End of OpenMP region.
7749 /// \param S Statement associated with the current OpenMP region.
7750 /// \param Clauses List of clauses for the current OpenMP region.
7752 /// \returns Statement for finished OpenMP region.
7753 StmtResult ActOnOpenMPRegionEnd(StmtResult S, ArrayRef<OMPClause *> Clauses);
7754 StmtResult ActOnOpenMPExecutableDirective(
7755 OpenMPDirectiveKind Kind, const DeclarationNameInfo &DirName,
7756 OpenMPDirectiveKind CancelRegion, ArrayRef<OMPClause *> Clauses,
7757 Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc);
7758 /// \brief Called on well-formed '\#pragma omp parallel' after parsing
7759 /// of the associated statement.
7760 StmtResult ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses,
7762 SourceLocation StartLoc,
7763 SourceLocation EndLoc);
7764 /// \brief Called on well-formed '\#pragma omp simd' after parsing
7765 /// of the associated statement.
7766 StmtResult ActOnOpenMPSimdDirective(
7767 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7768 SourceLocation EndLoc,
7769 llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA);
7770 /// \brief Called on well-formed '\#pragma omp for' after parsing
7771 /// of the associated statement.
7772 StmtResult ActOnOpenMPForDirective(
7773 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7774 SourceLocation EndLoc,
7775 llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA);
7776 /// \brief Called on well-formed '\#pragma omp for simd' after parsing
7777 /// of the associated statement.
7778 StmtResult ActOnOpenMPForSimdDirective(
7779 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7780 SourceLocation EndLoc,
7781 llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA);
7782 /// \brief Called on well-formed '\#pragma omp sections' after parsing
7783 /// of the associated statement.
7784 StmtResult ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses,
7785 Stmt *AStmt, SourceLocation StartLoc,
7786 SourceLocation EndLoc);
7787 /// \brief Called on well-formed '\#pragma omp section' after parsing of the
7788 /// associated statement.
7789 StmtResult ActOnOpenMPSectionDirective(Stmt *AStmt, SourceLocation StartLoc,
7790 SourceLocation EndLoc);
7791 /// \brief Called on well-formed '\#pragma omp single' after parsing of the
7792 /// associated statement.
7793 StmtResult ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses,
7794 Stmt *AStmt, SourceLocation StartLoc,
7795 SourceLocation EndLoc);
7796 /// \brief Called on well-formed '\#pragma omp master' after parsing of the
7797 /// associated statement.
7798 StmtResult ActOnOpenMPMasterDirective(Stmt *AStmt, SourceLocation StartLoc,
7799 SourceLocation EndLoc);
7800 /// \brief Called on well-formed '\#pragma omp critical' after parsing of the
7801 /// associated statement.
7802 StmtResult ActOnOpenMPCriticalDirective(const DeclarationNameInfo &DirName,
7803 Stmt *AStmt, SourceLocation StartLoc,
7804 SourceLocation EndLoc);
7805 /// \brief Called on well-formed '\#pragma omp parallel for' after parsing
7806 /// of the associated statement.
7807 StmtResult ActOnOpenMPParallelForDirective(
7808 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7809 SourceLocation EndLoc,
7810 llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA);
7811 /// \brief Called on well-formed '\#pragma omp parallel for simd' after
7812 /// parsing of the associated statement.
7813 StmtResult ActOnOpenMPParallelForSimdDirective(
7814 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7815 SourceLocation EndLoc,
7816 llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA);
7817 /// \brief Called on well-formed '\#pragma omp parallel sections' after
7818 /// parsing of the associated statement.
7819 StmtResult ActOnOpenMPParallelSectionsDirective(ArrayRef<OMPClause *> Clauses,
7821 SourceLocation StartLoc,
7822 SourceLocation EndLoc);
7823 /// \brief Called on well-formed '\#pragma omp task' after parsing of the
7824 /// associated statement.
7825 StmtResult ActOnOpenMPTaskDirective(ArrayRef<OMPClause *> Clauses,
7826 Stmt *AStmt, SourceLocation StartLoc,
7827 SourceLocation EndLoc);
7828 /// \brief Called on well-formed '\#pragma omp taskyield'.
7829 StmtResult ActOnOpenMPTaskyieldDirective(SourceLocation StartLoc,
7830 SourceLocation EndLoc);
7831 /// \brief Called on well-formed '\#pragma omp barrier'.
7832 StmtResult ActOnOpenMPBarrierDirective(SourceLocation StartLoc,
7833 SourceLocation EndLoc);
7834 /// \brief Called on well-formed '\#pragma omp taskwait'.
7835 StmtResult ActOnOpenMPTaskwaitDirective(SourceLocation StartLoc,
7836 SourceLocation EndLoc);
7837 /// \brief Called on well-formed '\#pragma omp taskgroup'.
7838 StmtResult ActOnOpenMPTaskgroupDirective(Stmt *AStmt, SourceLocation StartLoc,
7839 SourceLocation EndLoc);
7840 /// \brief Called on well-formed '\#pragma omp flush'.
7841 StmtResult ActOnOpenMPFlushDirective(ArrayRef<OMPClause *> Clauses,
7842 SourceLocation StartLoc,
7843 SourceLocation EndLoc);
7844 /// \brief Called on well-formed '\#pragma omp ordered' after parsing of the
7845 /// associated statement.
7846 StmtResult ActOnOpenMPOrderedDirective(Stmt *AStmt, SourceLocation StartLoc,
7847 SourceLocation EndLoc);
7848 /// \brief Called on well-formed '\#pragma omp atomic' after parsing of the
7849 /// associated statement.
7850 StmtResult ActOnOpenMPAtomicDirective(ArrayRef<OMPClause *> Clauses,
7851 Stmt *AStmt, SourceLocation StartLoc,
7852 SourceLocation EndLoc);
7853 /// \brief Called on well-formed '\#pragma omp target' after parsing of the
7854 /// associated statement.
7855 StmtResult ActOnOpenMPTargetDirective(ArrayRef<OMPClause *> Clauses,
7856 Stmt *AStmt, SourceLocation StartLoc,
7857 SourceLocation EndLoc);
7858 /// \brief Called on well-formed '\#pragma omp teams' after parsing of the
7859 /// associated statement.
7860 StmtResult ActOnOpenMPTeamsDirective(ArrayRef<OMPClause *> Clauses,
7861 Stmt *AStmt, SourceLocation StartLoc,
7862 SourceLocation EndLoc);
7863 /// \brief Called on well-formed '\#pragma omp cancellation point'.
7865 ActOnOpenMPCancellationPointDirective(SourceLocation StartLoc,
7866 SourceLocation EndLoc,
7867 OpenMPDirectiveKind CancelRegion);
7868 /// \brief Called on well-formed '\#pragma omp cancel'.
7869 StmtResult ActOnOpenMPCancelDirective(SourceLocation StartLoc,
7870 SourceLocation EndLoc,
7871 OpenMPDirectiveKind CancelRegion);
7873 OMPClause *ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind,
7875 SourceLocation StartLoc,
7876 SourceLocation LParenLoc,
7877 SourceLocation EndLoc);
7878 /// \brief Called on well-formed 'if' clause.
7879 OMPClause *ActOnOpenMPIfClause(Expr *Condition, SourceLocation StartLoc,
7880 SourceLocation LParenLoc,
7881 SourceLocation EndLoc);
7882 /// \brief Called on well-formed 'final' clause.
7883 OMPClause *ActOnOpenMPFinalClause(Expr *Condition, SourceLocation StartLoc,
7884 SourceLocation LParenLoc,
7885 SourceLocation EndLoc);
7886 /// \brief Called on well-formed 'num_threads' clause.
7887 OMPClause *ActOnOpenMPNumThreadsClause(Expr *NumThreads,
7888 SourceLocation StartLoc,
7889 SourceLocation LParenLoc,
7890 SourceLocation EndLoc);
7891 /// \brief Called on well-formed 'safelen' clause.
7892 OMPClause *ActOnOpenMPSafelenClause(Expr *Length,
7893 SourceLocation StartLoc,
7894 SourceLocation LParenLoc,
7895 SourceLocation EndLoc);
7896 /// \brief Called on well-formed 'collapse' clause.
7897 OMPClause *ActOnOpenMPCollapseClause(Expr *NumForLoops,
7898 SourceLocation StartLoc,
7899 SourceLocation LParenLoc,
7900 SourceLocation EndLoc);
7902 OMPClause *ActOnOpenMPSimpleClause(OpenMPClauseKind Kind,
7904 SourceLocation ArgumentLoc,
7905 SourceLocation StartLoc,
7906 SourceLocation LParenLoc,
7907 SourceLocation EndLoc);
7908 /// \brief Called on well-formed 'default' clause.
7909 OMPClause *ActOnOpenMPDefaultClause(OpenMPDefaultClauseKind Kind,
7910 SourceLocation KindLoc,
7911 SourceLocation StartLoc,
7912 SourceLocation LParenLoc,
7913 SourceLocation EndLoc);
7914 /// \brief Called on well-formed 'proc_bind' clause.
7915 OMPClause *ActOnOpenMPProcBindClause(OpenMPProcBindClauseKind Kind,
7916 SourceLocation KindLoc,
7917 SourceLocation StartLoc,
7918 SourceLocation LParenLoc,
7919 SourceLocation EndLoc);
7921 OMPClause *ActOnOpenMPSingleExprWithArgClause(OpenMPClauseKind Kind,
7922 unsigned Argument, Expr *Expr,
7923 SourceLocation StartLoc,
7924 SourceLocation LParenLoc,
7925 SourceLocation ArgumentLoc,
7926 SourceLocation CommaLoc,
7927 SourceLocation EndLoc);
7928 /// \brief Called on well-formed 'schedule' clause.
7929 OMPClause *ActOnOpenMPScheduleClause(OpenMPScheduleClauseKind Kind,
7930 Expr *ChunkSize, SourceLocation StartLoc,
7931 SourceLocation LParenLoc,
7932 SourceLocation KindLoc,
7933 SourceLocation CommaLoc,
7934 SourceLocation EndLoc);
7936 OMPClause *ActOnOpenMPClause(OpenMPClauseKind Kind, SourceLocation StartLoc,
7937 SourceLocation EndLoc);
7938 /// \brief Called on well-formed 'ordered' clause.
7939 OMPClause *ActOnOpenMPOrderedClause(SourceLocation StartLoc,
7940 SourceLocation EndLoc);
7941 /// \brief Called on well-formed 'nowait' clause.
7942 OMPClause *ActOnOpenMPNowaitClause(SourceLocation StartLoc,
7943 SourceLocation EndLoc);
7944 /// \brief Called on well-formed 'untied' clause.
7945 OMPClause *ActOnOpenMPUntiedClause(SourceLocation StartLoc,
7946 SourceLocation EndLoc);
7947 /// \brief Called on well-formed 'mergeable' clause.
7948 OMPClause *ActOnOpenMPMergeableClause(SourceLocation StartLoc,
7949 SourceLocation EndLoc);
7950 /// \brief Called on well-formed 'read' clause.
7951 OMPClause *ActOnOpenMPReadClause(SourceLocation StartLoc,
7952 SourceLocation EndLoc);
7953 /// \brief Called on well-formed 'write' clause.
7954 OMPClause *ActOnOpenMPWriteClause(SourceLocation StartLoc,
7955 SourceLocation EndLoc);
7956 /// \brief Called on well-formed 'update' clause.
7957 OMPClause *ActOnOpenMPUpdateClause(SourceLocation StartLoc,
7958 SourceLocation EndLoc);
7959 /// \brief Called on well-formed 'capture' clause.
7960 OMPClause *ActOnOpenMPCaptureClause(SourceLocation StartLoc,
7961 SourceLocation EndLoc);
7962 /// \brief Called on well-formed 'seq_cst' clause.
7963 OMPClause *ActOnOpenMPSeqCstClause(SourceLocation StartLoc,
7964 SourceLocation EndLoc);
7966 OMPClause *ActOnOpenMPVarListClause(
7967 OpenMPClauseKind Kind, ArrayRef<Expr *> Vars, Expr *TailExpr,
7968 SourceLocation StartLoc, SourceLocation LParenLoc,
7969 SourceLocation ColonLoc, SourceLocation EndLoc,
7970 CXXScopeSpec &ReductionIdScopeSpec,
7971 const DeclarationNameInfo &ReductionId, OpenMPDependClauseKind DepKind,
7972 SourceLocation DepLoc);
7973 /// \brief Called on well-formed 'private' clause.
7974 OMPClause *ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList,
7975 SourceLocation StartLoc,
7976 SourceLocation LParenLoc,
7977 SourceLocation EndLoc);
7978 /// \brief Called on well-formed 'firstprivate' clause.
7979 OMPClause *ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList,
7980 SourceLocation StartLoc,
7981 SourceLocation LParenLoc,
7982 SourceLocation EndLoc);
7983 /// \brief Called on well-formed 'lastprivate' clause.
7984 OMPClause *ActOnOpenMPLastprivateClause(ArrayRef<Expr *> VarList,
7985 SourceLocation StartLoc,
7986 SourceLocation LParenLoc,
7987 SourceLocation EndLoc);
7988 /// \brief Called on well-formed 'shared' clause.
7989 OMPClause *ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList,
7990 SourceLocation StartLoc,
7991 SourceLocation LParenLoc,
7992 SourceLocation EndLoc);
7993 /// \brief Called on well-formed 'reduction' clause.
7995 ActOnOpenMPReductionClause(ArrayRef<Expr *> VarList, SourceLocation StartLoc,
7996 SourceLocation LParenLoc, SourceLocation ColonLoc,
7997 SourceLocation EndLoc,
7998 CXXScopeSpec &ReductionIdScopeSpec,
7999 const DeclarationNameInfo &ReductionId);
8000 /// \brief Called on well-formed 'linear' clause.
8001 OMPClause *ActOnOpenMPLinearClause(ArrayRef<Expr *> VarList,
8003 SourceLocation StartLoc,
8004 SourceLocation LParenLoc,
8005 SourceLocation ColonLoc,
8006 SourceLocation EndLoc);
8007 /// \brief Called on well-formed 'aligned' clause.
8008 OMPClause *ActOnOpenMPAlignedClause(ArrayRef<Expr *> VarList,
8010 SourceLocation StartLoc,
8011 SourceLocation LParenLoc,
8012 SourceLocation ColonLoc,
8013 SourceLocation EndLoc);
8014 /// \brief Called on well-formed 'copyin' clause.
8015 OMPClause *ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList,
8016 SourceLocation StartLoc,
8017 SourceLocation LParenLoc,
8018 SourceLocation EndLoc);
8019 /// \brief Called on well-formed 'copyprivate' clause.
8020 OMPClause *ActOnOpenMPCopyprivateClause(ArrayRef<Expr *> VarList,
8021 SourceLocation StartLoc,
8022 SourceLocation LParenLoc,
8023 SourceLocation EndLoc);
8024 /// \brief Called on well-formed 'flush' pseudo clause.
8025 OMPClause *ActOnOpenMPFlushClause(ArrayRef<Expr *> VarList,
8026 SourceLocation StartLoc,
8027 SourceLocation LParenLoc,
8028 SourceLocation EndLoc);
8029 /// \brief Called on well-formed 'depend' clause.
8031 ActOnOpenMPDependClause(OpenMPDependClauseKind DepKind, SourceLocation DepLoc,
8032 SourceLocation ColonLoc, ArrayRef<Expr *> VarList,
8033 SourceLocation StartLoc, SourceLocation LParenLoc,
8034 SourceLocation EndLoc);
8036 /// \brief The kind of conversion being performed.
8037 enum CheckedConversionKind {
8038 /// \brief An implicit conversion.
8039 CCK_ImplicitConversion,
8040 /// \brief A C-style cast.
8042 /// \brief A functional-style cast.
8044 /// \brief A cast other than a C-style cast.
8048 /// ImpCastExprToType - If Expr is not of type 'Type', insert an implicit
8049 /// cast. If there is already an implicit cast, merge into the existing one.
8050 /// If isLvalue, the result of the cast is an lvalue.
8051 ExprResult ImpCastExprToType(Expr *E, QualType Type, CastKind CK,
8052 ExprValueKind VK = VK_RValue,
8053 const CXXCastPath *BasePath = nullptr,
8054 CheckedConversionKind CCK
8055 = CCK_ImplicitConversion);
8057 /// ScalarTypeToBooleanCastKind - Returns the cast kind corresponding
8058 /// to the conversion from scalar type ScalarTy to the Boolean type.
8059 static CastKind ScalarTypeToBooleanCastKind(QualType ScalarTy);
8061 /// IgnoredValueConversions - Given that an expression's result is
8062 /// syntactically ignored, perform any conversions that are
8064 ExprResult IgnoredValueConversions(Expr *E);
8066 // UsualUnaryConversions - promotes integers (C99 6.3.1.1p2) and converts
8067 // functions and arrays to their respective pointers (C99 6.3.2.1).
8068 ExprResult UsualUnaryConversions(Expr *E);
8070 /// CallExprUnaryConversions - a special case of an unary conversion
8071 /// performed on a function designator of a call expression.
8072 ExprResult CallExprUnaryConversions(Expr *E);
8074 // DefaultFunctionArrayConversion - converts functions and arrays
8075 // to their respective pointers (C99 6.3.2.1).
8076 ExprResult DefaultFunctionArrayConversion(Expr *E);
8078 // DefaultFunctionArrayLvalueConversion - converts functions and
8079 // arrays to their respective pointers and performs the
8080 // lvalue-to-rvalue conversion.
8081 ExprResult DefaultFunctionArrayLvalueConversion(Expr *E);
8083 // DefaultLvalueConversion - performs lvalue-to-rvalue conversion on
8084 // the operand. This is DefaultFunctionArrayLvalueConversion,
8085 // except that it assumes the operand isn't of function or array
8087 ExprResult DefaultLvalueConversion(Expr *E);
8089 // DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
8090 // do not have a prototype. Integer promotions are performed on each
8091 // argument, and arguments that have type float are promoted to double.
8092 ExprResult DefaultArgumentPromotion(Expr *E);
8094 // Used for emitting the right warning by DefaultVariadicArgumentPromotion
8095 enum VariadicCallType {
8099 VariadicConstructor,
8100 VariadicDoesNotApply
8103 VariadicCallType getVariadicCallType(FunctionDecl *FDecl,
8104 const FunctionProtoType *Proto,
8107 // Used for determining in which context a type is allowed to be passed to a
8117 // Determines which VarArgKind fits an expression.
8118 VarArgKind isValidVarArgType(const QualType &Ty);
8120 /// Check to see if the given expression is a valid argument to a variadic
8121 /// function, issuing a diagnostic if not.
8122 void checkVariadicArgument(const Expr *E, VariadicCallType CT);
8124 /// Check to see if a given expression could have '.c_str()' called on it.
8125 bool hasCStrMethod(const Expr *E);
8127 /// GatherArgumentsForCall - Collector argument expressions for various
8128 /// form of call prototypes.
8129 bool GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl,
8130 const FunctionProtoType *Proto,
8131 unsigned FirstParam, ArrayRef<Expr *> Args,
8132 SmallVectorImpl<Expr *> &AllArgs,
8133 VariadicCallType CallType = VariadicDoesNotApply,
8134 bool AllowExplicit = false,
8135 bool IsListInitialization = false);
8137 // DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
8138 // will create a runtime trap if the resulting type is not a POD type.
8139 ExprResult DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
8140 FunctionDecl *FDecl);
8142 // UsualArithmeticConversions - performs the UsualUnaryConversions on it's
8143 // operands and then handles various conversions that are common to binary
8144 // operators (C99 6.3.1.8). If both operands aren't arithmetic, this
8145 // routine returns the first non-arithmetic type found. The client is
8146 // responsible for emitting appropriate error diagnostics.
8147 QualType UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
8148 bool IsCompAssign = false);
8150 /// AssignConvertType - All of the 'assignment' semantic checks return this
8151 /// enum to indicate whether the assignment was allowed. These checks are
8152 /// done for simple assignments, as well as initialization, return from
8153 /// function, argument passing, etc. The query is phrased in terms of a
8154 /// source and destination type.
8155 enum AssignConvertType {
8156 /// Compatible - the types are compatible according to the standard.
8159 /// PointerToInt - The assignment converts a pointer to an int, which we
8160 /// accept as an extension.
8163 /// IntToPointer - The assignment converts an int to a pointer, which we
8164 /// accept as an extension.
8167 /// FunctionVoidPointer - The assignment is between a function pointer and
8168 /// void*, which the standard doesn't allow, but we accept as an extension.
8169 FunctionVoidPointer,
8171 /// IncompatiblePointer - The assignment is between two pointers types that
8172 /// are not compatible, but we accept them as an extension.
8173 IncompatiblePointer,
8175 /// IncompatiblePointer - The assignment is between two pointers types which
8176 /// point to integers which have a different sign, but are otherwise
8177 /// identical. This is a subset of the above, but broken out because it's by
8178 /// far the most common case of incompatible pointers.
8179 IncompatiblePointerSign,
8181 /// CompatiblePointerDiscardsQualifiers - The assignment discards
8182 /// c/v/r qualifiers, which we accept as an extension.
8183 CompatiblePointerDiscardsQualifiers,
8185 /// IncompatiblePointerDiscardsQualifiers - The assignment
8186 /// discards qualifiers that we don't permit to be discarded,
8187 /// like address spaces.
8188 IncompatiblePointerDiscardsQualifiers,
8190 /// IncompatibleNestedPointerQualifiers - The assignment is between two
8191 /// nested pointer types, and the qualifiers other than the first two
8192 /// levels differ e.g. char ** -> const char **, but we accept them as an
8194 IncompatibleNestedPointerQualifiers,
8196 /// IncompatibleVectors - The assignment is between two vector types that
8197 /// have the same size, which we accept as an extension.
8198 IncompatibleVectors,
8200 /// IntToBlockPointer - The assignment converts an int to a block
8201 /// pointer. We disallow this.
8204 /// IncompatibleBlockPointer - The assignment is between two block
8205 /// pointers types that are not compatible.
8206 IncompatibleBlockPointer,
8208 /// IncompatibleObjCQualifiedId - The assignment is between a qualified
8209 /// id type and something else (that is incompatible with it). For example,
8210 /// "id <XXX>" = "Foo *", where "Foo *" doesn't implement the XXX protocol.
8211 IncompatibleObjCQualifiedId,
8213 /// IncompatibleObjCWeakRef - Assigning a weak-unavailable object to an
8214 /// object with __weak qualifier.
8215 IncompatibleObjCWeakRef,
8217 /// Incompatible - We reject this conversion outright, it is invalid to
8218 /// represent it in the AST.
8222 /// DiagnoseAssignmentResult - Emit a diagnostic, if required, for the
8223 /// assignment conversion type specified by ConvTy. This returns true if the
8224 /// conversion was invalid or false if the conversion was accepted.
8225 bool DiagnoseAssignmentResult(AssignConvertType ConvTy,
8227 QualType DstType, QualType SrcType,
8228 Expr *SrcExpr, AssignmentAction Action,
8229 bool *Complained = nullptr);
8231 /// IsValueInFlagEnum - Determine if a value is allowed as part of a flag
8232 /// enum. If AllowMask is true, then we also allow the complement of a valid
8233 /// value, to be used as a mask.
8234 bool IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
8235 bool AllowMask) const;
8237 /// DiagnoseAssignmentEnum - Warn if assignment to enum is a constant
8238 /// integer not in the range of enum values.
8239 void DiagnoseAssignmentEnum(QualType DstType, QualType SrcType,
8242 /// CheckAssignmentConstraints - Perform type checking for assignment,
8243 /// argument passing, variable initialization, and function return values.
8245 AssignConvertType CheckAssignmentConstraints(SourceLocation Loc,
8249 /// Check assignment constraints and prepare for a conversion of the
8250 /// RHS to the LHS type.
8251 AssignConvertType CheckAssignmentConstraints(QualType LHSType,
8255 // CheckSingleAssignmentConstraints - Currently used by
8256 // CheckAssignmentOperands, and ActOnReturnStmt. Prior to type checking,
8257 // this routine performs the default function/array converions.
8258 AssignConvertType CheckSingleAssignmentConstraints(QualType LHSType,
8260 bool Diagnose = true,
8261 bool DiagnoseCFAudited = false);
8263 // \brief If the lhs type is a transparent union, check whether we
8264 // can initialize the transparent union with the given expression.
8265 AssignConvertType CheckTransparentUnionArgumentConstraints(QualType ArgType,
8268 bool IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType);
8270 bool CheckExceptionSpecCompatibility(Expr *From, QualType ToType);
8272 ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
8273 AssignmentAction Action,
8274 bool AllowExplicit = false);
8275 ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
8276 AssignmentAction Action,
8278 ImplicitConversionSequence& ICS);
8279 ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
8280 const ImplicitConversionSequence& ICS,
8281 AssignmentAction Action,
8282 CheckedConversionKind CCK
8283 = CCK_ImplicitConversion);
8284 ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
8285 const StandardConversionSequence& SCS,
8286 AssignmentAction Action,
8287 CheckedConversionKind CCK);
8289 /// the following "Check" methods will return a valid/converted QualType
8290 /// or a null QualType (indicating an error diagnostic was issued).
8292 /// type checking binary operators (subroutines of CreateBuiltinBinOp).
8293 QualType InvalidOperands(SourceLocation Loc, ExprResult &LHS,
8295 QualType CheckPointerToMemberOperands( // C++ 5.5
8296 ExprResult &LHS, ExprResult &RHS, ExprValueKind &VK,
8297 SourceLocation OpLoc, bool isIndirect);
8298 QualType CheckMultiplyDivideOperands( // C99 6.5.5
8299 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign,
8301 QualType CheckRemainderOperands( // C99 6.5.5
8302 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
8303 bool IsCompAssign = false);
8304 QualType CheckAdditionOperands( // C99 6.5.6
8305 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc,
8306 QualType* CompLHSTy = nullptr);
8307 QualType CheckSubtractionOperands( // C99 6.5.6
8308 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
8309 QualType* CompLHSTy = nullptr);
8310 QualType CheckShiftOperands( // C99 6.5.7
8311 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc,
8312 bool IsCompAssign = false);
8313 QualType CheckCompareOperands( // C99 6.5.8/9
8314 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned OpaqueOpc,
8316 QualType CheckBitwiseOperands( // C99 6.5.[10...12]
8317 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
8318 bool IsCompAssign = false);
8319 QualType CheckLogicalOperands( // C99 6.5.[13,14]
8320 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc);
8321 // CheckAssignmentOperands is used for both simple and compound assignment.
8322 // For simple assignment, pass both expressions and a null converted type.
8323 // For compound assignment, pass both expressions and the converted type.
8324 QualType CheckAssignmentOperands( // C99 6.5.16.[1,2]
8325 Expr *LHSExpr, ExprResult &RHS, SourceLocation Loc, QualType CompoundType);
8327 ExprResult checkPseudoObjectIncDec(Scope *S, SourceLocation OpLoc,
8328 UnaryOperatorKind Opcode, Expr *Op);
8329 ExprResult checkPseudoObjectAssignment(Scope *S, SourceLocation OpLoc,
8330 BinaryOperatorKind Opcode,
8331 Expr *LHS, Expr *RHS);
8332 ExprResult checkPseudoObjectRValue(Expr *E);
8333 Expr *recreateSyntacticForm(PseudoObjectExpr *E);
8335 QualType CheckConditionalOperands( // C99 6.5.15
8336 ExprResult &Cond, ExprResult &LHS, ExprResult &RHS,
8337 ExprValueKind &VK, ExprObjectKind &OK, SourceLocation QuestionLoc);
8338 QualType CXXCheckConditionalOperands( // C++ 5.16
8339 ExprResult &cond, ExprResult &lhs, ExprResult &rhs,
8340 ExprValueKind &VK, ExprObjectKind &OK, SourceLocation questionLoc);
8341 QualType FindCompositePointerType(SourceLocation Loc, Expr *&E1, Expr *&E2,
8342 bool *NonStandardCompositeType = nullptr);
8343 QualType FindCompositePointerType(SourceLocation Loc,
8344 ExprResult &E1, ExprResult &E2,
8345 bool *NonStandardCompositeType = nullptr) {
8346 Expr *E1Tmp = E1.get(), *E2Tmp = E2.get();
8347 QualType Composite = FindCompositePointerType(Loc, E1Tmp, E2Tmp,
8348 NonStandardCompositeType);
8354 QualType FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
8355 SourceLocation QuestionLoc);
8357 bool DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
8358 SourceLocation QuestionLoc);
8360 void DiagnoseAlwaysNonNullPointer(Expr *E,
8361 Expr::NullPointerConstantKind NullType,
8362 bool IsEqual, SourceRange Range);
8364 /// type checking for vector binary operators.
8365 QualType CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
8366 SourceLocation Loc, bool IsCompAssign);
8367 QualType GetSignedVectorType(QualType V);
8368 QualType CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
8369 SourceLocation Loc, bool isRelational);
8370 QualType CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
8371 SourceLocation Loc);
8373 bool isLaxVectorConversion(QualType srcType, QualType destType);
8375 /// type checking declaration initializers (C99 6.7.8)
8376 bool CheckForConstantInitializer(Expr *e, QualType t);
8378 // type checking C++ declaration initializers (C++ [dcl.init]).
8380 /// ReferenceCompareResult - Expresses the result of comparing two
8381 /// types (cv1 T1 and cv2 T2) to determine their compatibility for the
8382 /// purposes of initialization by reference (C++ [dcl.init.ref]p4).
8383 enum ReferenceCompareResult {
8384 /// Ref_Incompatible - The two types are incompatible, so direct
8385 /// reference binding is not possible.
8386 Ref_Incompatible = 0,
8387 /// Ref_Related - The two types are reference-related, which means
8388 /// that their unqualified forms (T1 and T2) are either the same
8389 /// or T1 is a base class of T2.
8391 /// Ref_Compatible_With_Added_Qualification - The two types are
8392 /// reference-compatible with added qualification, meaning that
8393 /// they are reference-compatible and the qualifiers on T1 (cv1)
8394 /// are greater than the qualifiers on T2 (cv2).
8395 Ref_Compatible_With_Added_Qualification,
8396 /// Ref_Compatible - The two types are reference-compatible and
8397 /// have equivalent qualifiers (cv1 == cv2).
8401 ReferenceCompareResult CompareReferenceRelationship(SourceLocation Loc,
8402 QualType T1, QualType T2,
8403 bool &DerivedToBase,
8404 bool &ObjCConversion,
8405 bool &ObjCLifetimeConversion);
8407 ExprResult checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
8408 Expr *CastExpr, CastKind &CastKind,
8409 ExprValueKind &VK, CXXCastPath &Path);
8411 /// \brief Force an expression with unknown-type to an expression of the
8413 ExprResult forceUnknownAnyToType(Expr *E, QualType ToType);
8415 /// \brief Type-check an expression that's being passed to an
8416 /// __unknown_anytype parameter.
8417 ExprResult checkUnknownAnyArg(SourceLocation callLoc,
8418 Expr *result, QualType ¶mType);
8420 // CheckVectorCast - check type constraints for vectors.
8421 // Since vectors are an extension, there are no C standard reference for this.
8422 // We allow casting between vectors and integer datatypes of the same size.
8423 // returns true if the cast is invalid
8424 bool CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
8427 // CheckExtVectorCast - check type constraints for extended vectors.
8428 // Since vectors are an extension, there are no C standard reference for this.
8429 // We allow casting between vectors and integer datatypes of the same size,
8430 // or vectors and the element type of that vector.
8431 // returns the cast expr
8432 ExprResult CheckExtVectorCast(SourceRange R, QualType DestTy, Expr *CastExpr,
8435 ExprResult BuildCXXFunctionalCastExpr(TypeSourceInfo *TInfo,
8436 SourceLocation LParenLoc,
8438 SourceLocation RParenLoc);
8440 enum ARCConversionResult { ACR_okay, ACR_unbridged };
8442 /// \brief Checks for invalid conversions and casts between
8443 /// retainable pointers and other pointer kinds.
8444 ARCConversionResult CheckObjCARCConversion(SourceRange castRange,
8445 QualType castType, Expr *&op,
8446 CheckedConversionKind CCK,
8447 bool DiagnoseCFAudited = false,
8448 BinaryOperatorKind Opc = BO_PtrMemD
8451 Expr *stripARCUnbridgedCast(Expr *e);
8452 void diagnoseARCUnbridgedCast(Expr *e);
8454 bool CheckObjCARCUnavailableWeakConversion(QualType castType,
8457 /// checkRetainCycles - Check whether an Objective-C message send
8458 /// might create an obvious retain cycle.
8459 void checkRetainCycles(ObjCMessageExpr *msg);
8460 void checkRetainCycles(Expr *receiver, Expr *argument);
8461 void checkRetainCycles(VarDecl *Var, Expr *Init);
8463 /// checkUnsafeAssigns - Check whether +1 expr is being assigned
8464 /// to weak/__unsafe_unretained type.
8465 bool checkUnsafeAssigns(SourceLocation Loc, QualType LHS, Expr *RHS);
8467 /// checkUnsafeExprAssigns - Check whether +1 expr is being assigned
8468 /// to weak/__unsafe_unretained expression.
8469 void checkUnsafeExprAssigns(SourceLocation Loc, Expr *LHS, Expr *RHS);
8471 /// CheckMessageArgumentTypes - Check types in an Obj-C message send.
8472 /// \param Method - May be null.
8473 /// \param [out] ReturnType - The return type of the send.
8474 /// \return true iff there were any incompatible types.
8475 bool CheckMessageArgumentTypes(QualType ReceiverType,
8476 MultiExprArg Args, Selector Sel,
8477 ArrayRef<SourceLocation> SelectorLocs,
8478 ObjCMethodDecl *Method, bool isClassMessage,
8479 bool isSuperMessage,
8480 SourceLocation lbrac, SourceLocation rbrac,
8481 SourceRange RecRange,
8482 QualType &ReturnType, ExprValueKind &VK);
8484 /// \brief Determine the result of a message send expression based on
8485 /// the type of the receiver, the method expected to receive the message,
8486 /// and the form of the message send.
8487 QualType getMessageSendResultType(QualType ReceiverType,
8488 ObjCMethodDecl *Method,
8489 bool isClassMessage, bool isSuperMessage);
8491 /// \brief If the given expression involves a message send to a method
8492 /// with a related result type, emit a note describing what happened.
8493 void EmitRelatedResultTypeNote(const Expr *E);
8495 /// \brief Given that we had incompatible pointer types in a return
8496 /// statement, check whether we're in a method with a related result
8497 /// type, and if so, emit a note describing what happened.
8498 void EmitRelatedResultTypeNoteForReturn(QualType destType);
8500 /// CheckBooleanCondition - Diagnose problems involving the use of
8501 /// the given expression as a boolean condition (e.g. in an if
8502 /// statement). Also performs the standard function and array
8503 /// decays, possibly changing the input variable.
8505 /// \param Loc - A location associated with the condition, e.g. the
8507 /// \return true iff there were any errors
8508 ExprResult CheckBooleanCondition(Expr *E, SourceLocation Loc);
8510 ExprResult ActOnBooleanCondition(Scope *S, SourceLocation Loc,
8513 /// DiagnoseAssignmentAsCondition - Given that an expression is
8514 /// being used as a boolean condition, warn if it's an assignment.
8515 void DiagnoseAssignmentAsCondition(Expr *E);
8517 /// \brief Redundant parentheses over an equality comparison can indicate
8518 /// that the user intended an assignment used as condition.
8519 void DiagnoseEqualityWithExtraParens(ParenExpr *ParenE);
8521 /// CheckCXXBooleanCondition - Returns true if conversion to bool is invalid.
8522 ExprResult CheckCXXBooleanCondition(Expr *CondExpr);
8524 /// ConvertIntegerToTypeWarnOnOverflow - Convert the specified APInt to have
8525 /// the specified width and sign. If an overflow occurs, detect it and emit
8526 /// the specified diagnostic.
8527 void ConvertIntegerToTypeWarnOnOverflow(llvm::APSInt &OldVal,
8528 unsigned NewWidth, bool NewSign,
8529 SourceLocation Loc, unsigned DiagID);
8531 /// Checks that the Objective-C declaration is declared in the global scope.
8532 /// Emits an error and marks the declaration as invalid if it's not declared
8533 /// in the global scope.
8534 bool CheckObjCDeclScope(Decl *D);
8536 /// \brief Abstract base class used for diagnosing integer constant
8537 /// expression violations.
8538 class VerifyICEDiagnoser {
8542 VerifyICEDiagnoser(bool Suppress = false) : Suppress(Suppress) { }
8544 virtual void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) =0;
8545 virtual void diagnoseFold(Sema &S, SourceLocation Loc, SourceRange SR);
8546 virtual ~VerifyICEDiagnoser() { }
8549 /// VerifyIntegerConstantExpression - Verifies that an expression is an ICE,
8550 /// and reports the appropriate diagnostics. Returns false on success.
8551 /// Can optionally return the value of the expression.
8552 ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
8553 VerifyICEDiagnoser &Diagnoser,
8554 bool AllowFold = true);
8555 ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
8557 bool AllowFold = true);
8558 ExprResult VerifyIntegerConstantExpression(Expr *E,
8559 llvm::APSInt *Result = nullptr);
8561 /// VerifyBitField - verifies that a bit field expression is an ICE and has
8562 /// the correct width, and that the field type is valid.
8563 /// Returns false on success.
8564 /// Can optionally return whether the bit-field is of width 0
8565 ExprResult VerifyBitField(SourceLocation FieldLoc, IdentifierInfo *FieldName,
8566 QualType FieldTy, bool IsMsStruct,
8567 Expr *BitWidth, bool *ZeroWidth = nullptr);
8569 enum CUDAFunctionTarget {
8577 CUDAFunctionTarget IdentifyCUDATarget(const FunctionDecl *D);
8579 bool CheckCUDATarget(const FunctionDecl *Caller, const FunctionDecl *Callee);
8581 /// Given a implicit special member, infer its CUDA target from the
8582 /// calls it needs to make to underlying base/field special members.
8583 /// \param ClassDecl the class for which the member is being created.
8584 /// \param CSM the kind of special member.
8585 /// \param MemberDecl the special member itself.
8586 /// \param ConstRHS true if this is a copy operation with a const object on
8588 /// \param Diagnose true if this call should emit diagnostics.
8589 /// \return true if there was an error inferring.
8590 /// The result of this call is implicit CUDA target attribute(s) attached to
8591 /// the member declaration.
8592 bool inferCUDATargetForImplicitSpecialMember(CXXRecordDecl *ClassDecl,
8593 CXXSpecialMember CSM,
8594 CXXMethodDecl *MemberDecl,
8598 /// \name Code completion
8600 /// \brief Describes the context in which code completion occurs.
8601 enum ParserCompletionContext {
8602 /// \brief Code completion occurs at top-level or namespace context.
8604 /// \brief Code completion occurs within a class, struct, or union.
8606 /// \brief Code completion occurs within an Objective-C interface, protocol,
8609 /// \brief Code completion occurs within an Objective-C implementation or
8610 /// category implementation
8611 PCC_ObjCImplementation,
8612 /// \brief Code completion occurs within the list of instance variables
8613 /// in an Objective-C interface, protocol, category, or implementation.
8614 PCC_ObjCInstanceVariableList,
8615 /// \brief Code completion occurs following one or more template
8618 /// \brief Code completion occurs following one or more template
8619 /// headers within a class.
8621 /// \brief Code completion occurs within an expression.
8623 /// \brief Code completion occurs within a statement, which may
8624 /// also be an expression or a declaration.
8626 /// \brief Code completion occurs at the beginning of the
8627 /// initialization statement (or expression) in a for loop.
8629 /// \brief Code completion occurs within the condition of an if,
8630 /// while, switch, or for statement.
8632 /// \brief Code completion occurs within the body of a function on a
8633 /// recovery path, where we do not have a specific handle on our position
8635 PCC_RecoveryInFunction,
8636 /// \brief Code completion occurs where only a type is permitted.
8638 /// \brief Code completion occurs in a parenthesized expression, which
8639 /// might also be a type cast.
8640 PCC_ParenthesizedExpression,
8641 /// \brief Code completion occurs within a sequence of declaration
8642 /// specifiers within a function, method, or block.
8643 PCC_LocalDeclarationSpecifiers
8646 void CodeCompleteModuleImport(SourceLocation ImportLoc, ModuleIdPath Path);
8647 void CodeCompleteOrdinaryName(Scope *S,
8648 ParserCompletionContext CompletionContext);
8649 void CodeCompleteDeclSpec(Scope *S, DeclSpec &DS,
8650 bool AllowNonIdentifiers,
8651 bool AllowNestedNameSpecifiers);
8653 struct CodeCompleteExpressionData;
8654 void CodeCompleteExpression(Scope *S,
8655 const CodeCompleteExpressionData &Data);
8656 void CodeCompleteMemberReferenceExpr(Scope *S, Expr *Base,
8657 SourceLocation OpLoc,
8659 void CodeCompletePostfixExpression(Scope *S, ExprResult LHS);
8660 void CodeCompleteTag(Scope *S, unsigned TagSpec);
8661 void CodeCompleteTypeQualifiers(DeclSpec &DS);
8662 void CodeCompleteCase(Scope *S);
8663 void CodeCompleteCall(Scope *S, Expr *Fn, ArrayRef<Expr *> Args);
8664 void CodeCompleteConstructor(Scope *S, QualType Type, SourceLocation Loc,
8665 ArrayRef<Expr *> Args);
8666 void CodeCompleteInitializer(Scope *S, Decl *D);
8667 void CodeCompleteReturn(Scope *S);
8668 void CodeCompleteAfterIf(Scope *S);
8669 void CodeCompleteAssignmentRHS(Scope *S, Expr *LHS);
8671 void CodeCompleteQualifiedId(Scope *S, CXXScopeSpec &SS,
8672 bool EnteringContext);
8673 void CodeCompleteUsing(Scope *S);
8674 void CodeCompleteUsingDirective(Scope *S);
8675 void CodeCompleteNamespaceDecl(Scope *S);
8676 void CodeCompleteNamespaceAliasDecl(Scope *S);
8677 void CodeCompleteOperatorName(Scope *S);
8678 void CodeCompleteConstructorInitializer(
8680 ArrayRef<CXXCtorInitializer *> Initializers);
8682 void CodeCompleteLambdaIntroducer(Scope *S, LambdaIntroducer &Intro,
8683 bool AfterAmpersand);
8685 void CodeCompleteObjCAtDirective(Scope *S);
8686 void CodeCompleteObjCAtVisibility(Scope *S);
8687 void CodeCompleteObjCAtStatement(Scope *S);
8688 void CodeCompleteObjCAtExpression(Scope *S);
8689 void CodeCompleteObjCPropertyFlags(Scope *S, ObjCDeclSpec &ODS);
8690 void CodeCompleteObjCPropertyGetter(Scope *S);
8691 void CodeCompleteObjCPropertySetter(Scope *S);
8692 void CodeCompleteObjCPassingType(Scope *S, ObjCDeclSpec &DS,
8694 void CodeCompleteObjCMessageReceiver(Scope *S);
8695 void CodeCompleteObjCSuperMessage(Scope *S, SourceLocation SuperLoc,
8696 ArrayRef<IdentifierInfo *> SelIdents,
8697 bool AtArgumentExpression);
8698 void CodeCompleteObjCClassMessage(Scope *S, ParsedType Receiver,
8699 ArrayRef<IdentifierInfo *> SelIdents,
8700 bool AtArgumentExpression,
8701 bool IsSuper = false);
8702 void CodeCompleteObjCInstanceMessage(Scope *S, Expr *Receiver,
8703 ArrayRef<IdentifierInfo *> SelIdents,
8704 bool AtArgumentExpression,
8705 ObjCInterfaceDecl *Super = nullptr);
8706 void CodeCompleteObjCForCollection(Scope *S,
8707 DeclGroupPtrTy IterationVar);
8708 void CodeCompleteObjCSelector(Scope *S,
8709 ArrayRef<IdentifierInfo *> SelIdents);
8710 void CodeCompleteObjCProtocolReferences(IdentifierLocPair *Protocols,
8711 unsigned NumProtocols);
8712 void CodeCompleteObjCProtocolDecl(Scope *S);
8713 void CodeCompleteObjCInterfaceDecl(Scope *S);
8714 void CodeCompleteObjCSuperclass(Scope *S,
8715 IdentifierInfo *ClassName,
8716 SourceLocation ClassNameLoc);
8717 void CodeCompleteObjCImplementationDecl(Scope *S);
8718 void CodeCompleteObjCInterfaceCategory(Scope *S,
8719 IdentifierInfo *ClassName,
8720 SourceLocation ClassNameLoc);
8721 void CodeCompleteObjCImplementationCategory(Scope *S,
8722 IdentifierInfo *ClassName,
8723 SourceLocation ClassNameLoc);
8724 void CodeCompleteObjCPropertyDefinition(Scope *S);
8725 void CodeCompleteObjCPropertySynthesizeIvar(Scope *S,
8726 IdentifierInfo *PropertyName);
8727 void CodeCompleteObjCMethodDecl(Scope *S,
8728 bool IsInstanceMethod,
8729 ParsedType ReturnType);
8730 void CodeCompleteObjCMethodDeclSelector(Scope *S,
8731 bool IsInstanceMethod,
8732 bool AtParameterName,
8733 ParsedType ReturnType,
8734 ArrayRef<IdentifierInfo *> SelIdents);
8735 void CodeCompletePreprocessorDirective(bool InConditional);
8736 void CodeCompleteInPreprocessorConditionalExclusion(Scope *S);
8737 void CodeCompletePreprocessorMacroName(bool IsDefinition);
8738 void CodeCompletePreprocessorExpression();
8739 void CodeCompletePreprocessorMacroArgument(Scope *S,
8740 IdentifierInfo *Macro,
8741 MacroInfo *MacroInfo,
8743 void CodeCompleteNaturalLanguage();
8744 void GatherGlobalCodeCompletions(CodeCompletionAllocator &Allocator,
8745 CodeCompletionTUInfo &CCTUInfo,
8746 SmallVectorImpl<CodeCompletionResult> &Results);
8749 //===--------------------------------------------------------------------===//
8750 // Extra semantic analysis beyond the C type system
8753 SourceLocation getLocationOfStringLiteralByte(const StringLiteral *SL,
8754 unsigned ByteNo) const;
8757 void CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
8758 const ArraySubscriptExpr *ASE=nullptr,
8759 bool AllowOnePastEnd=true, bool IndexNegated=false);
8760 void CheckArrayAccess(const Expr *E);
8761 // Used to grab the relevant information from a FormatAttr and a
8762 // FunctionDeclaration.
8763 struct FormatStringInfo {
8765 unsigned FirstDataArg;
8769 bool getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
8770 FormatStringInfo *FSI);
8771 bool CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
8772 const FunctionProtoType *Proto);
8773 bool CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation loc,
8774 ArrayRef<const Expr *> Args);
8775 bool CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
8776 const FunctionProtoType *Proto);
8777 bool CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto);
8778 void CheckConstructorCall(FunctionDecl *FDecl,
8779 ArrayRef<const Expr *> Args,
8780 const FunctionProtoType *Proto,
8781 SourceLocation Loc);
8783 void checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
8784 ArrayRef<const Expr *> Args, bool IsMemberFunction,
8785 SourceLocation Loc, SourceRange Range,
8786 VariadicCallType CallType);
8788 bool CheckObjCString(Expr *Arg);
8790 ExprResult CheckBuiltinFunctionCall(FunctionDecl *FDecl,
8791 unsigned BuiltinID, CallExpr *TheCall);
8793 bool CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
8795 bool CheckNeonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
8796 bool CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
8798 bool CheckAArch64BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
8799 bool CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
8800 bool CheckSystemZBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
8801 bool CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
8802 bool CheckPPCBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
8804 bool SemaBuiltinVAStart(CallExpr *TheCall);
8805 bool SemaBuiltinVAStartARM(CallExpr *Call);
8806 bool SemaBuiltinUnorderedCompare(CallExpr *TheCall);
8807 bool SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs);
8810 // Used by C++ template instantiation.
8811 ExprResult SemaBuiltinShuffleVector(CallExpr *TheCall);
8812 ExprResult SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
8813 SourceLocation BuiltinLoc,
8814 SourceLocation RParenLoc);
8817 bool SemaBuiltinPrefetch(CallExpr *TheCall);
8818 bool SemaBuiltinAssume(CallExpr *TheCall);
8819 bool SemaBuiltinAssumeAligned(CallExpr *TheCall);
8820 bool SemaBuiltinLongjmp(CallExpr *TheCall);
8821 bool SemaBuiltinSetjmp(CallExpr *TheCall);
8822 ExprResult SemaBuiltinAtomicOverloaded(ExprResult TheCallResult);
8823 ExprResult SemaAtomicOpsOverloaded(ExprResult TheCallResult,
8824 AtomicExpr::AtomicOp Op);
8825 bool SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
8826 llvm::APSInt &Result);
8827 bool SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
8829 bool SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall,
8830 int ArgNum, unsigned ExpectedFieldNum,
8832 bool SemaBuiltinCpuSupports(CallExpr *TheCall);
8834 enum FormatStringType {
8845 static FormatStringType GetFormatStringType(const FormatAttr *Format);
8847 void CheckFormatString(const StringLiteral *FExpr, const Expr *OrigFormatExpr,
8848 ArrayRef<const Expr *> Args, bool HasVAListArg,
8849 unsigned format_idx, unsigned firstDataArg,
8850 FormatStringType Type, bool inFunctionCall,
8851 VariadicCallType CallType,
8852 llvm::SmallBitVector &CheckedVarArgs);
8854 bool FormatStringHasSArg(const StringLiteral *FExpr);
8856 bool GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx);
8859 bool CheckFormatArguments(const FormatAttr *Format,
8860 ArrayRef<const Expr *> Args,
8862 VariadicCallType CallType,
8863 SourceLocation Loc, SourceRange Range,
8864 llvm::SmallBitVector &CheckedVarArgs);
8865 bool CheckFormatArguments(ArrayRef<const Expr *> Args,
8866 bool HasVAListArg, unsigned format_idx,
8867 unsigned firstDataArg, FormatStringType Type,
8868 VariadicCallType CallType,
8869 SourceLocation Loc, SourceRange range,
8870 llvm::SmallBitVector &CheckedVarArgs);
8872 void CheckAbsoluteValueFunction(const CallExpr *Call,
8873 const FunctionDecl *FDecl,
8874 IdentifierInfo *FnInfo);
8876 void CheckMemaccessArguments(const CallExpr *Call,
8878 IdentifierInfo *FnName);
8880 void CheckStrlcpycatArguments(const CallExpr *Call,
8881 IdentifierInfo *FnName);
8883 void CheckStrncatArguments(const CallExpr *Call,
8884 IdentifierInfo *FnName);
8886 void CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
8887 SourceLocation ReturnLoc,
8888 bool isObjCMethod = false,
8889 const AttrVec *Attrs = nullptr,
8890 const FunctionDecl *FD = nullptr);
8892 void CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr* RHS);
8893 void CheckImplicitConversions(Expr *E, SourceLocation CC = SourceLocation());
8894 void CheckBoolLikeConversion(Expr *E, SourceLocation CC);
8895 void CheckForIntOverflow(Expr *E);
8896 void CheckUnsequencedOperations(Expr *E);
8898 /// \brief Perform semantic checks on a completed expression. This will either
8899 /// be a full-expression or a default argument expression.
8900 void CheckCompletedExpr(Expr *E, SourceLocation CheckLoc = SourceLocation(),
8901 bool IsConstexpr = false);
8903 void CheckBitFieldInitialization(SourceLocation InitLoc, FieldDecl *Field,
8906 /// \brief Check if the given expression contains 'break' or 'continue'
8907 /// statement that produces control flow different from GCC.
8908 void CheckBreakContinueBinding(Expr *E);
8910 /// \brief Check whether receiver is mutable ObjC container which
8911 /// attempts to add itself into the container
8912 void CheckObjCCircularContainer(ObjCMessageExpr *Message);
8914 void AnalyzeDeleteExprMismatch(const CXXDeleteExpr *DE);
8915 void AnalyzeDeleteExprMismatch(FieldDecl *Field, SourceLocation DeleteLoc,
8916 bool DeleteWasArrayForm);
8918 /// \brief Register a magic integral constant to be used as a type tag.
8919 void RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
8920 uint64_t MagicValue, QualType Type,
8921 bool LayoutCompatible, bool MustBeNull);
8923 struct TypeTagData {
8926 TypeTagData(QualType Type, bool LayoutCompatible, bool MustBeNull) :
8927 Type(Type), LayoutCompatible(LayoutCompatible),
8928 MustBeNull(MustBeNull)
8933 /// If true, \c Type should be compared with other expression's types for
8934 /// layout-compatibility.
8935 unsigned LayoutCompatible : 1;
8936 unsigned MustBeNull : 1;
8939 /// A pair of ArgumentKind identifier and magic value. This uniquely
8940 /// identifies the magic value.
8941 typedef std::pair<const IdentifierInfo *, uint64_t> TypeTagMagicValue;
8944 /// \brief A map from magic value to type information.
8945 std::unique_ptr<llvm::DenseMap<TypeTagMagicValue, TypeTagData>>
8946 TypeTagForDatatypeMagicValues;
8948 /// \brief Peform checks on a call of a function with argument_with_type_tag
8949 /// or pointer_with_type_tag attributes.
8950 void CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
8951 const Expr * const *ExprArgs);
8953 /// \brief The parser's current scope.
8955 /// The parser maintains this state here.
8958 mutable IdentifierInfo *Ident_super;
8959 mutable IdentifierInfo *Ident___float128;
8961 /// Nullability type specifiers.
8962 IdentifierInfo *Ident__Nonnull = nullptr;
8963 IdentifierInfo *Ident__Nullable = nullptr;
8964 IdentifierInfo *Ident__Null_unspecified = nullptr;
8966 IdentifierInfo *Ident_NSError = nullptr;
8969 friend class Parser;
8970 friend class InitializationSequence;
8971 friend class ASTReader;
8972 friend class ASTDeclReader;
8973 friend class ASTWriter;
8976 /// Retrieve the keyword associated
8977 IdentifierInfo *getNullabilityKeyword(NullabilityKind nullability);
8979 /// The struct behind the CFErrorRef pointer.
8980 RecordDecl *CFError = nullptr;
8982 /// Retrieve the identifier "NSError".
8983 IdentifierInfo *getNSErrorIdent();
8985 /// \brief Retrieve the parser's current scope.
8987 /// This routine must only be used when it is certain that semantic analysis
8988 /// and the parser are in precisely the same context, which is not the case
8989 /// when, e.g., we are performing any kind of template instantiation.
8990 /// Therefore, the only safe places to use this scope are in the parser
8991 /// itself and in routines directly invoked from the parser and *never* from
8992 /// template substitution or instantiation.
8993 Scope *getCurScope() const { return CurScope; }
8995 void incrementMSManglingNumber() const {
8996 return CurScope->incrementMSManglingNumber();
8999 IdentifierInfo *getSuperIdentifier() const;
9000 IdentifierInfo *getFloat128Identifier() const;
9002 Decl *getObjCDeclContext() const;
9004 DeclContext *getCurLexicalContext() const {
9005 return OriginalLexicalContext ? OriginalLexicalContext : CurContext;
9008 AvailabilityResult getCurContextAvailability() const;
9010 const DeclContext *getCurObjCLexicalContext() const {
9011 const DeclContext *DC = getCurLexicalContext();
9012 // A category implicitly has the attribute of the interface.
9013 if (const ObjCCategoryDecl *CatD = dyn_cast<ObjCCategoryDecl>(DC))
9014 DC = CatD->getClassInterface();
9018 /// \brief To be used for checking whether the arguments being passed to
9019 /// function exceeds the number of parameters expected for it.
9020 static bool TooManyArguments(size_t NumParams, size_t NumArgs,
9021 bool PartialOverloading = false) {
9022 // We check whether we're just after a comma in code-completion.
9023 if (NumArgs > 0 && PartialOverloading)
9024 return NumArgs + 1 > NumParams; // If so, we view as an extra argument.
9025 return NumArgs > NumParams;
9029 /// \brief RAII object that enters a new expression evaluation context.
9030 class EnterExpressionEvaluationContext {
9034 EnterExpressionEvaluationContext(Sema &Actions,
9035 Sema::ExpressionEvaluationContext NewContext,
9036 Decl *LambdaContextDecl = nullptr,
9037 bool IsDecltype = false)
9038 : Actions(Actions) {
9039 Actions.PushExpressionEvaluationContext(NewContext, LambdaContextDecl,
9042 EnterExpressionEvaluationContext(Sema &Actions,
9043 Sema::ExpressionEvaluationContext NewContext,
9044 Sema::ReuseLambdaContextDecl_t,
9045 bool IsDecltype = false)
9046 : Actions(Actions) {
9047 Actions.PushExpressionEvaluationContext(NewContext,
9048 Sema::ReuseLambdaContextDecl,
9052 ~EnterExpressionEvaluationContext() {
9053 Actions.PopExpressionEvaluationContext();
9057 DeductionFailureInfo
9058 MakeDeductionFailureInfo(ASTContext &Context, Sema::TemplateDeductionResult TDK,
9059 sema::TemplateDeductionInfo &Info);
9061 /// \brief Contains a late templated function.
9062 /// Will be parsed at the end of the translation unit, used by Sema & Parser.
9063 struct LateParsedTemplate {
9065 /// \brief The template function declaration to be late parsed.
9069 } // end namespace clang