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 return isVisible(Old) || New->isExternallyVisible();
284 typedef OpaquePtr<DeclGroupRef> DeclGroupPtrTy;
285 typedef OpaquePtr<TemplateName> TemplateTy;
286 typedef OpaquePtr<QualType> TypeTy;
288 OpenCLOptions OpenCLFeatures;
289 FPOptions FPFeatures;
291 const LangOptions &LangOpts;
294 ASTConsumer &Consumer;
295 DiagnosticsEngine &Diags;
296 SourceManager &SourceMgr;
298 /// \brief Flag indicating whether or not to collect detailed statistics.
301 /// \brief Code-completion consumer.
302 CodeCompleteConsumer *CodeCompleter;
304 /// CurContext - This is the current declaration context of parsing.
305 DeclContext *CurContext;
307 /// \brief Generally null except when we temporarily switch decl contexts,
308 /// like in \see ActOnObjCTemporaryExitContainerContext.
309 DeclContext *OriginalLexicalContext;
311 /// VAListTagName - The declaration name corresponding to __va_list_tag.
312 /// This is used as part of a hack to omit that class from ADL results.
313 DeclarationName VAListTagName;
315 /// PackContext - Manages the stack for \#pragma pack. An alignment
316 /// of 0 indicates default alignment.
317 void *PackContext; // Really a "PragmaPackStack*"
319 bool MSStructPragmaOn; // True when \#pragma ms_struct on
321 /// \brief Controls member pointer representation format under the MS ABI.
322 LangOptions::PragmaMSPointersToMembersKind
323 MSPointerToMemberRepresentationMethod;
325 enum PragmaVtorDispKind {
326 PVDK_Push, ///< #pragma vtordisp(push, mode)
327 PVDK_Set, ///< #pragma vtordisp(mode)
328 PVDK_Pop, ///< #pragma vtordisp(pop)
329 PVDK_Reset ///< #pragma vtordisp()
332 enum PragmaMsStackAction {
333 PSK_Reset, // #pragma ()
334 PSK_Set, // #pragma ("name")
335 PSK_Push, // #pragma (push[, id])
336 PSK_Push_Set, // #pragma (push[, id], "name")
337 PSK_Pop, // #pragma (pop[, id])
338 PSK_Pop_Set, // #pragma (pop[, id], "name")
341 /// \brief Whether to insert vtordisps prior to virtual bases in the Microsoft
342 /// C++ ABI. Possible values are 0, 1, and 2, which mean:
344 /// 0: Suppress all vtordisps
345 /// 1: Insert vtordisps in the presence of vbase overrides and non-trivial
347 /// 2: Always insert vtordisps to support RTTI on partially constructed
350 /// The stack always has at least one element in it.
351 SmallVector<MSVtorDispAttr::Mode, 2> VtorDispModeStack;
353 /// Stack of active SEH __finally scopes. Can be empty.
354 SmallVector<Scope*, 2> CurrentSEHFinally;
356 /// \brief Source location for newly created implicit MSInheritanceAttrs
357 SourceLocation ImplicitMSInheritanceAttrLoc;
359 template<typename ValueType>
362 llvm::StringRef StackSlotLabel;
364 SourceLocation PragmaLocation;
365 Slot(llvm::StringRef StackSlotLabel,
367 SourceLocation PragmaLocation)
368 : StackSlotLabel(StackSlotLabel), Value(Value),
369 PragmaLocation(PragmaLocation) {}
371 void Act(SourceLocation PragmaLocation,
372 PragmaMsStackAction Action,
373 llvm::StringRef StackSlotLabel,
375 explicit PragmaStack(const ValueType &Value)
376 : CurrentValue(Value) {}
377 SmallVector<Slot, 2> Stack;
378 ValueType CurrentValue;
379 SourceLocation CurrentPragmaLocation;
381 // FIXME: We should serialize / deserialize these if they occur in a PCH (but
382 // we shouldn't do so if they're in a module).
383 PragmaStack<StringLiteral *> DataSegStack;
384 PragmaStack<StringLiteral *> BSSSegStack;
385 PragmaStack<StringLiteral *> ConstSegStack;
386 PragmaStack<StringLiteral *> CodeSegStack;
388 /// A mapping that describes the nullability we've seen in each header file.
389 FileNullabilityMap NullabilityMap;
391 /// Last section used with #pragma init_seg.
392 StringLiteral *CurInitSeg;
393 SourceLocation CurInitSegLoc;
395 /// VisContext - Manages the stack for \#pragma GCC visibility.
396 void *VisContext; // Really a "PragmaVisStack*"
398 /// \brief This represents the last location of a "#pragma clang optimize off"
399 /// directive if such a directive has not been closed by an "on" yet. If
400 /// optimizations are currently "on", this is set to an invalid location.
401 SourceLocation OptimizeOffPragmaLocation;
403 /// \brief Flag indicating if Sema is building a recovery call expression.
405 /// This flag is used to avoid building recovery call expressions
406 /// if Sema is already doing so, which would cause infinite recursions.
407 bool IsBuildingRecoveryCallExpr;
409 /// ExprNeedsCleanups - True if the current evaluation context
410 /// requires cleanups to be run at its conclusion.
411 bool ExprNeedsCleanups;
413 /// ExprCleanupObjects - This is the stack of objects requiring
414 /// cleanup that are created by the current full expression. The
415 /// element type here is ExprWithCleanups::Object.
416 SmallVector<BlockDecl*, 8> ExprCleanupObjects;
418 /// \brief Store a list of either DeclRefExprs or MemberExprs
419 /// that contain a reference to a variable (constant) that may or may not
420 /// be odr-used in this Expr, and we won't know until all lvalue-to-rvalue
421 /// and discarded value conversions have been applied to all subexpressions
422 /// of the enclosing full expression. This is cleared at the end of each
424 llvm::SmallPtrSet<Expr*, 2> MaybeODRUseExprs;
426 /// \brief Stack containing information about each of the nested
427 /// function, block, and method scopes that are currently active.
429 /// This array is never empty. Clients should ignore the first
430 /// element, which is used to cache a single FunctionScopeInfo
431 /// that's used to parse every top-level function.
432 SmallVector<sema::FunctionScopeInfo *, 4> FunctionScopes;
434 typedef LazyVector<TypedefNameDecl *, ExternalSemaSource,
435 &ExternalSemaSource::ReadExtVectorDecls, 2, 2>
438 /// ExtVectorDecls - This is a list all the extended vector types. This allows
439 /// us to associate a raw vector type with one of the ext_vector type names.
440 /// This is only necessary for issuing pretty diagnostics.
441 ExtVectorDeclsType ExtVectorDecls;
443 /// FieldCollector - Collects CXXFieldDecls during parsing of C++ classes.
444 std::unique_ptr<CXXFieldCollector> FieldCollector;
446 typedef llvm::SmallSetVector<const NamedDecl*, 16> NamedDeclSetType;
448 /// \brief Set containing all declared private fields that are not used.
449 NamedDeclSetType UnusedPrivateFields;
451 /// \brief Set containing all typedefs that are likely unused.
452 llvm::SmallSetVector<const TypedefNameDecl *, 4>
453 UnusedLocalTypedefNameCandidates;
455 /// \brief Delete-expressions to be analyzed at the end of translation unit
457 /// This list contains class members, and locations of delete-expressions
458 /// that could not be proven as to whether they mismatch with new-expression
459 /// used in initializer of the field.
460 typedef std::pair<SourceLocation, bool> DeleteExprLoc;
461 typedef llvm::SmallVector<DeleteExprLoc, 4> DeleteLocs;
462 llvm::MapVector<FieldDecl *, DeleteLocs> DeleteExprs;
464 typedef llvm::SmallPtrSet<const CXXRecordDecl*, 8> RecordDeclSetTy;
466 /// PureVirtualClassDiagSet - a set of class declarations which we have
467 /// emitted a list of pure virtual functions. Used to prevent emitting the
468 /// same list more than once.
469 std::unique_ptr<RecordDeclSetTy> PureVirtualClassDiagSet;
471 /// ParsingInitForAutoVars - a set of declarations with auto types for which
472 /// we are currently parsing the initializer.
473 llvm::SmallPtrSet<const Decl*, 4> ParsingInitForAutoVars;
475 /// \brief Look for a locally scoped extern "C" declaration by the given name.
476 NamedDecl *findLocallyScopedExternCDecl(DeclarationName Name);
478 typedef LazyVector<VarDecl *, ExternalSemaSource,
479 &ExternalSemaSource::ReadTentativeDefinitions, 2, 2>
480 TentativeDefinitionsType;
482 /// \brief All the tentative definitions encountered in the TU.
483 TentativeDefinitionsType TentativeDefinitions;
485 typedef LazyVector<const DeclaratorDecl *, ExternalSemaSource,
486 &ExternalSemaSource::ReadUnusedFileScopedDecls, 2, 2>
487 UnusedFileScopedDeclsType;
489 /// \brief The set of file scoped decls seen so far that have not been used
490 /// and must warn if not used. Only contains the first declaration.
491 UnusedFileScopedDeclsType UnusedFileScopedDecls;
493 typedef LazyVector<CXXConstructorDecl *, ExternalSemaSource,
494 &ExternalSemaSource::ReadDelegatingConstructors, 2, 2>
495 DelegatingCtorDeclsType;
497 /// \brief All the delegating constructors seen so far in the file, used for
498 /// cycle detection at the end of the TU.
499 DelegatingCtorDeclsType DelegatingCtorDecls;
501 /// \brief All the overriding functions seen during a class definition
502 /// that had their exception spec checks delayed, plus the overridden
504 SmallVector<std::pair<const CXXMethodDecl*, const CXXMethodDecl*>, 2>
505 DelayedExceptionSpecChecks;
507 /// \brief All the members seen during a class definition which were both
508 /// explicitly defaulted and had explicitly-specified exception
509 /// specifications, along with the function type containing their
510 /// user-specified exception specification. Those exception specifications
511 /// were overridden with the default specifications, but we still need to
512 /// check whether they are compatible with the default specification, and
513 /// we can't do that until the nesting set of class definitions is complete.
514 SmallVector<std::pair<CXXMethodDecl*, const FunctionProtoType*>, 2>
515 DelayedDefaultedMemberExceptionSpecs;
517 typedef llvm::MapVector<const FunctionDecl *, LateParsedTemplate *>
518 LateParsedTemplateMapT;
519 LateParsedTemplateMapT LateParsedTemplateMap;
521 /// \brief Callback to the parser to parse templated functions when needed.
522 typedef void LateTemplateParserCB(void *P, LateParsedTemplate &LPT);
523 typedef void LateTemplateParserCleanupCB(void *P);
524 LateTemplateParserCB *LateTemplateParser;
525 LateTemplateParserCleanupCB *LateTemplateParserCleanup;
528 void SetLateTemplateParser(LateTemplateParserCB *LTP,
529 LateTemplateParserCleanupCB *LTPCleanup,
531 LateTemplateParser = LTP;
532 LateTemplateParserCleanup = LTPCleanup;
536 class DelayedDiagnostics;
538 class DelayedDiagnosticsState {
539 sema::DelayedDiagnosticPool *SavedPool;
540 friend class Sema::DelayedDiagnostics;
542 typedef DelayedDiagnosticsState ParsingDeclState;
543 typedef DelayedDiagnosticsState ProcessingContextState;
545 /// A class which encapsulates the logic for delaying diagnostics
546 /// during parsing and other processing.
547 class DelayedDiagnostics {
548 /// \brief The current pool of diagnostics into which delayed
549 /// diagnostics should go.
550 sema::DelayedDiagnosticPool *CurPool;
553 DelayedDiagnostics() : CurPool(nullptr) {}
555 /// Adds a delayed diagnostic.
556 void add(const sema::DelayedDiagnostic &diag); // in DelayedDiagnostic.h
558 /// Determines whether diagnostics should be delayed.
559 bool shouldDelayDiagnostics() { return CurPool != nullptr; }
561 /// Returns the current delayed-diagnostics pool.
562 sema::DelayedDiagnosticPool *getCurrentPool() const {
566 /// Enter a new scope. Access and deprecation diagnostics will be
567 /// collected in this pool.
568 DelayedDiagnosticsState push(sema::DelayedDiagnosticPool &pool) {
569 DelayedDiagnosticsState state;
570 state.SavedPool = CurPool;
575 /// Leave a delayed-diagnostic state that was previously pushed.
576 /// Do not emit any of the diagnostics. This is performed as part
577 /// of the bookkeeping of popping a pool "properly".
578 void popWithoutEmitting(DelayedDiagnosticsState state) {
579 CurPool = state.SavedPool;
582 /// Enter a new scope where access and deprecation diagnostics are
584 DelayedDiagnosticsState pushUndelayed() {
585 DelayedDiagnosticsState state;
586 state.SavedPool = CurPool;
591 /// Undo a previous pushUndelayed().
592 void popUndelayed(DelayedDiagnosticsState state) {
593 assert(CurPool == nullptr);
594 CurPool = state.SavedPool;
596 } DelayedDiagnostics;
598 /// A RAII object to temporarily push a declaration context.
602 DeclContext *SavedContext;
603 ProcessingContextState SavedContextState;
604 QualType SavedCXXThisTypeOverride;
607 ContextRAII(Sema &S, DeclContext *ContextToPush, bool NewThisContext = true)
608 : S(S), SavedContext(S.CurContext),
609 SavedContextState(S.DelayedDiagnostics.pushUndelayed()),
610 SavedCXXThisTypeOverride(S.CXXThisTypeOverride)
612 assert(ContextToPush && "pushing null context");
613 S.CurContext = ContextToPush;
615 S.CXXThisTypeOverride = QualType();
619 if (!SavedContext) return;
620 S.CurContext = SavedContext;
621 S.DelayedDiagnostics.popUndelayed(SavedContextState);
622 S.CXXThisTypeOverride = SavedCXXThisTypeOverride;
623 SavedContext = nullptr;
631 /// \brief RAII object to handle the state changes required to synthesize
633 class SynthesizedFunctionScope {
635 Sema::ContextRAII SavedContext;
638 SynthesizedFunctionScope(Sema &S, DeclContext *DC)
639 : S(S), SavedContext(S, DC)
641 S.PushFunctionScope();
642 S.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated);
645 ~SynthesizedFunctionScope() {
646 S.PopExpressionEvaluationContext();
647 S.PopFunctionScopeInfo();
651 /// WeakUndeclaredIdentifiers - Identifiers contained in
652 /// \#pragma weak before declared. rare. may alias another
653 /// identifier, declared or undeclared
654 llvm::MapVector<IdentifierInfo *, WeakInfo> WeakUndeclaredIdentifiers;
656 /// ExtnameUndeclaredIdentifiers - Identifiers contained in
657 /// \#pragma redefine_extname before declared. Used in Solaris system headers
658 /// to define functions that occur in multiple standards to call the version
659 /// in the currently selected standard.
660 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*> ExtnameUndeclaredIdentifiers;
663 /// \brief Load weak undeclared identifiers from the external source.
664 void LoadExternalWeakUndeclaredIdentifiers();
666 /// WeakTopLevelDecl - Translation-unit scoped declarations generated by
667 /// \#pragma weak during processing of other Decls.
668 /// I couldn't figure out a clean way to generate these in-line, so
669 /// we store them here and handle separately -- which is a hack.
670 /// It would be best to refactor this.
671 SmallVector<Decl*,2> WeakTopLevelDecl;
673 IdentifierResolver IdResolver;
675 /// Translation Unit Scope - useful to Objective-C actions that need
676 /// to lookup file scope declarations in the "ordinary" C decl namespace.
677 /// For example, user-defined classes, built-in "id" type, etc.
680 /// \brief The C++ "std" namespace, where the standard library resides.
681 LazyDeclPtr StdNamespace;
683 /// \brief The C++ "std::bad_alloc" class, which is defined by the C++
684 /// standard library.
685 LazyDeclPtr StdBadAlloc;
687 /// \brief The C++ "std::initializer_list" template, which is defined in
688 /// \<initializer_list>.
689 ClassTemplateDecl *StdInitializerList;
691 /// \brief The C++ "type_info" declaration, which is defined in \<typeinfo>.
692 RecordDecl *CXXTypeInfoDecl;
694 /// \brief The MSVC "_GUID" struct, which is defined in MSVC header files.
695 RecordDecl *MSVCGuidDecl;
697 /// \brief Caches identifiers/selectors for NSFoundation APIs.
698 std::unique_ptr<NSAPI> NSAPIObj;
700 /// \brief The declaration of the Objective-C NSNumber class.
701 ObjCInterfaceDecl *NSNumberDecl;
703 /// \brief Pointer to NSNumber type (NSNumber *).
704 QualType NSNumberPointer;
706 /// \brief The Objective-C NSNumber methods used to create NSNumber literals.
707 ObjCMethodDecl *NSNumberLiteralMethods[NSAPI::NumNSNumberLiteralMethods];
709 /// \brief The declaration of the Objective-C NSString class.
710 ObjCInterfaceDecl *NSStringDecl;
712 /// \brief Pointer to NSString type (NSString *).
713 QualType NSStringPointer;
715 /// \brief The declaration of the stringWithUTF8String: method.
716 ObjCMethodDecl *StringWithUTF8StringMethod;
718 /// \brief The declaration of the Objective-C NSArray class.
719 ObjCInterfaceDecl *NSArrayDecl;
721 /// \brief Pointer to NSMutableArray type (NSMutableArray *).
722 QualType NSMutableArrayPointer;
724 /// \brief The declaration of the arrayWithObjects:count: method.
725 ObjCMethodDecl *ArrayWithObjectsMethod;
727 /// \brief The declaration of the Objective-C NSDictionary class.
728 ObjCInterfaceDecl *NSDictionaryDecl;
730 /// \brief Pointer to NSMutableDictionary type (NSMutableDictionary *).
731 QualType NSMutableDictionaryPointer;
733 /// \brief Pointer to NSMutableSet type (NSMutableSet *).
734 QualType NSMutableSetPointer;
736 /// \brief Pointer to NSCountedSet type (NSCountedSet *).
737 QualType NSCountedSetPointer;
739 /// \brief Pointer to NSMutableOrderedSet type (NSMutableOrderedSet *).
740 QualType NSMutableOrderedSetPointer;
742 /// \brief The declaration of the dictionaryWithObjects:forKeys:count: method.
743 ObjCMethodDecl *DictionaryWithObjectsMethod;
745 /// \brief id<NSCopying> type.
746 QualType QIDNSCopying;
748 /// \brief will hold 'respondsToSelector:'
749 Selector RespondsToSelectorSel;
751 /// \brief counter for internal MS Asm label names.
752 unsigned MSAsmLabelNameCounter;
754 /// A flag to remember whether the implicit forms of operator new and delete
755 /// have been declared.
756 bool GlobalNewDeleteDeclared;
758 /// A flag to indicate that we're in a context that permits abstract
759 /// references to fields. This is really a
760 bool AllowAbstractFieldReference;
762 /// \brief Describes how the expressions currently being parsed are
763 /// evaluated at run-time, if at all.
764 enum ExpressionEvaluationContext {
765 /// \brief The current expression and its subexpressions occur within an
766 /// unevaluated operand (C++11 [expr]p7), such as the subexpression of
767 /// \c sizeof, where the type of the expression may be significant but
768 /// no code will be generated to evaluate the value of the expression at
772 /// \brief The current expression occurs within an unevaluated
773 /// operand that unconditionally permits abstract references to
774 /// fields, such as a SIZE operator in MS-style inline assembly.
777 /// \brief The current context is "potentially evaluated" in C++11 terms,
778 /// but the expression is evaluated at compile-time (like the values of
779 /// cases in a switch statement).
782 /// \brief The current expression is potentially evaluated at run time,
783 /// which means that code may be generated to evaluate the value of the
784 /// expression at run time.
785 PotentiallyEvaluated,
787 /// \brief The current expression is potentially evaluated, but any
788 /// declarations referenced inside that expression are only used if
789 /// in fact the current expression is used.
791 /// This value is used when parsing default function arguments, for which
792 /// we would like to provide diagnostics (e.g., passing non-POD arguments
793 /// through varargs) but do not want to mark declarations as "referenced"
794 /// until the default argument is used.
795 PotentiallyEvaluatedIfUsed
798 /// \brief Data structure used to record current or nested
799 /// expression evaluation contexts.
800 struct ExpressionEvaluationContextRecord {
801 /// \brief The expression evaluation context.
802 ExpressionEvaluationContext Context;
804 /// \brief Whether the enclosing context needed a cleanup.
805 bool ParentNeedsCleanups;
807 /// \brief Whether we are in a decltype expression.
810 /// \brief The number of active cleanup objects when we entered
811 /// this expression evaluation context.
812 unsigned NumCleanupObjects;
814 /// \brief The number of typos encountered during this expression evaluation
815 /// context (i.e. the number of TypoExprs created).
818 llvm::SmallPtrSet<Expr*, 2> SavedMaybeODRUseExprs;
820 /// \brief The lambdas that are present within this context, if it
821 /// is indeed an unevaluated context.
822 SmallVector<LambdaExpr *, 2> Lambdas;
824 /// \brief The declaration that provides context for lambda expressions
825 /// and block literals if the normal declaration context does not
826 /// suffice, e.g., in a default function argument.
827 Decl *ManglingContextDecl;
829 /// \brief The context information used to mangle lambda expressions
830 /// and block literals within this context.
832 /// This mangling information is allocated lazily, since most contexts
833 /// do not have lambda expressions or block literals.
834 IntrusiveRefCntPtr<MangleNumberingContext> MangleNumbering;
836 /// \brief If we are processing a decltype type, a set of call expressions
837 /// for which we have deferred checking the completeness of the return type.
838 SmallVector<CallExpr *, 8> DelayedDecltypeCalls;
840 /// \brief If we are processing a decltype type, a set of temporary binding
841 /// expressions for which we have deferred checking the destructor.
842 SmallVector<CXXBindTemporaryExpr *, 8> DelayedDecltypeBinds;
844 ExpressionEvaluationContextRecord(ExpressionEvaluationContext Context,
845 unsigned NumCleanupObjects,
846 bool ParentNeedsCleanups,
847 Decl *ManglingContextDecl,
849 : Context(Context), ParentNeedsCleanups(ParentNeedsCleanups),
850 IsDecltype(IsDecltype), NumCleanupObjects(NumCleanupObjects),
852 ManglingContextDecl(ManglingContextDecl), MangleNumbering() { }
854 /// \brief Retrieve the mangling numbering context, used to consistently
855 /// number constructs like lambdas for mangling.
856 MangleNumberingContext &getMangleNumberingContext(ASTContext &Ctx);
858 bool isUnevaluated() const {
859 return Context == Unevaluated || Context == UnevaluatedAbstract;
863 /// A stack of expression evaluation contexts.
864 SmallVector<ExpressionEvaluationContextRecord, 8> ExprEvalContexts;
866 /// \brief Compute the mangling number context for a lambda expression or
869 /// \param DC - The DeclContext containing the lambda expression or
871 /// \param[out] ManglingContextDecl - Returns the ManglingContextDecl
872 /// associated with the context, if relevant.
873 MangleNumberingContext *getCurrentMangleNumberContext(
874 const DeclContext *DC,
875 Decl *&ManglingContextDecl);
878 /// SpecialMemberOverloadResult - The overloading result for a special member
881 /// This is basically a wrapper around PointerIntPair. The lowest bits of the
882 /// integer are used to determine whether overload resolution succeeded.
883 class SpecialMemberOverloadResult : public llvm::FastFoldingSetNode {
892 llvm::PointerIntPair<CXXMethodDecl*, 2> Pair;
895 SpecialMemberOverloadResult(const llvm::FoldingSetNodeID &ID)
896 : FastFoldingSetNode(ID)
899 CXXMethodDecl *getMethod() const { return Pair.getPointer(); }
900 void setMethod(CXXMethodDecl *MD) { Pair.setPointer(MD); }
902 Kind getKind() const { return static_cast<Kind>(Pair.getInt()); }
903 void setKind(Kind K) { Pair.setInt(K); }
906 /// \brief A cache of special member function overload resolution results
908 llvm::FoldingSet<SpecialMemberOverloadResult> SpecialMemberCache;
910 /// \brief The kind of translation unit we are processing.
912 /// When we're processing a complete translation unit, Sema will perform
913 /// end-of-translation-unit semantic tasks (such as creating
914 /// initializers for tentative definitions in C) once parsing has
915 /// completed. Modules and precompiled headers perform different kinds of
917 TranslationUnitKind TUKind;
919 llvm::BumpPtrAllocator BumpAlloc;
921 /// \brief The number of SFINAE diagnostics that have been trapped.
922 unsigned NumSFINAEErrors;
924 typedef llvm::DenseMap<ParmVarDecl *, llvm::TinyPtrVector<ParmVarDecl *>>
925 UnparsedDefaultArgInstantiationsMap;
927 /// \brief A mapping from parameters with unparsed default arguments to the
928 /// set of instantiations of each parameter.
930 /// This mapping is a temporary data structure used when parsing
931 /// nested class templates or nested classes of class templates,
932 /// where we might end up instantiating an inner class before the
933 /// default arguments of its methods have been parsed.
934 UnparsedDefaultArgInstantiationsMap UnparsedDefaultArgInstantiations;
936 // Contains the locations of the beginning of unparsed default
937 // argument locations.
938 llvm::DenseMap<ParmVarDecl *, SourceLocation> UnparsedDefaultArgLocs;
940 /// UndefinedInternals - all the used, undefined objects which require a
941 /// definition in this translation unit.
942 llvm::DenseMap<NamedDecl *, SourceLocation> UndefinedButUsed;
944 /// Obtain a sorted list of functions that are undefined but ODR-used.
945 void getUndefinedButUsed(
946 SmallVectorImpl<std::pair<NamedDecl *, SourceLocation> > &Undefined);
948 /// Retrieves list of suspicious delete-expressions that will be checked at
949 /// the end of translation unit.
950 const llvm::MapVector<FieldDecl *, DeleteLocs> &
951 getMismatchingDeleteExpressions() const;
953 typedef std::pair<ObjCMethodList, ObjCMethodList> GlobalMethods;
954 typedef llvm::DenseMap<Selector, GlobalMethods> GlobalMethodPool;
956 /// Method Pool - allows efficient lookup when typechecking messages to "id".
957 /// We need to maintain a list, since selectors can have differing signatures
958 /// across classes. In Cocoa, this happens to be extremely uncommon (only 1%
959 /// of selectors are "overloaded").
960 /// At the head of the list it is recorded whether there were 0, 1, or >= 2
961 /// methods inside categories with a particular selector.
962 GlobalMethodPool MethodPool;
964 /// Method selectors used in a \@selector expression. Used for implementation
966 llvm::MapVector<Selector, SourceLocation> ReferencedSelectors;
968 /// Kinds of C++ special members.
969 enum CXXSpecialMember {
970 CXXDefaultConstructor,
979 typedef std::pair<CXXRecordDecl*, CXXSpecialMember> SpecialMemberDecl;
981 /// The C++ special members which we are currently in the process of
982 /// declaring. If this process recursively triggers the declaration of the
983 /// same special member, we should act as if it is not yet declared.
984 llvm::SmallSet<SpecialMemberDecl, 4> SpecialMembersBeingDeclared;
986 void ReadMethodPool(Selector Sel);
988 /// Private Helper predicate to check for 'self'.
989 bool isSelfExpr(Expr *RExpr);
990 bool isSelfExpr(Expr *RExpr, const ObjCMethodDecl *Method);
992 /// \brief Cause the active diagnostic on the DiagosticsEngine to be
993 /// emitted. This is closely coupled to the SemaDiagnosticBuilder class and
994 /// should not be used elsewhere.
995 void EmitCurrentDiagnostic(unsigned DiagID);
997 /// Records and restores the FP_CONTRACT state on entry/exit of compound
999 class FPContractStateRAII {
1001 FPContractStateRAII(Sema& S)
1002 : S(S), OldFPContractState(S.FPFeatures.fp_contract) {}
1003 ~FPContractStateRAII() {
1004 S.FPFeatures.fp_contract = OldFPContractState;
1008 bool OldFPContractState : 1;
1011 void addImplicitTypedef(StringRef Name, QualType T);
1014 Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer,
1015 TranslationUnitKind TUKind = TU_Complete,
1016 CodeCompleteConsumer *CompletionConsumer = nullptr);
1019 /// \brief Perform initialization that occurs after the parser has been
1020 /// initialized but before it parses anything.
1023 const LangOptions &getLangOpts() const { return LangOpts; }
1024 OpenCLOptions &getOpenCLOptions() { return OpenCLFeatures; }
1025 FPOptions &getFPOptions() { return FPFeatures; }
1027 DiagnosticsEngine &getDiagnostics() const { return Diags; }
1028 SourceManager &getSourceManager() const { return SourceMgr; }
1029 Preprocessor &getPreprocessor() const { return PP; }
1030 ASTContext &getASTContext() const { return Context; }
1031 ASTConsumer &getASTConsumer() const { return Consumer; }
1032 ASTMutationListener *getASTMutationListener() const;
1033 ExternalSemaSource* getExternalSource() const { return ExternalSource; }
1035 ///\brief Registers an external source. If an external source already exists,
1036 /// creates a multiplex external source and appends to it.
1038 ///\param[in] E - A non-null external sema source.
1040 void addExternalSource(ExternalSemaSource *E);
1042 void PrintStats() const;
1044 /// \brief Helper class that creates diagnostics with optional
1045 /// template instantiation stacks.
1047 /// This class provides a wrapper around the basic DiagnosticBuilder
1048 /// class that emits diagnostics. SemaDiagnosticBuilder is
1049 /// responsible for emitting the diagnostic (as DiagnosticBuilder
1050 /// does) and, if the diagnostic comes from inside a template
1051 /// instantiation, printing the template instantiation stack as
1053 class SemaDiagnosticBuilder : public DiagnosticBuilder {
1058 SemaDiagnosticBuilder(DiagnosticBuilder &DB, Sema &SemaRef, unsigned DiagID)
1059 : DiagnosticBuilder(DB), SemaRef(SemaRef), DiagID(DiagID) { }
1061 ~SemaDiagnosticBuilder() {
1062 // If we aren't active, there is nothing to do.
1063 if (!isActive()) return;
1065 // Otherwise, we need to emit the diagnostic. First flush the underlying
1066 // DiagnosticBuilder data, and clear the diagnostic builder itself so it
1067 // won't emit the diagnostic in its own destructor.
1069 // This seems wasteful, in that as written the DiagnosticBuilder dtor will
1070 // do its own needless checks to see if the diagnostic needs to be
1071 // emitted. However, because we take care to ensure that the builder
1072 // objects never escape, a sufficiently smart compiler will be able to
1073 // eliminate that code.
1077 // Dispatch to Sema to emit the diagnostic.
1078 SemaRef.EmitCurrentDiagnostic(DiagID);
1081 /// Teach operator<< to produce an object of the correct type.
1082 template<typename T>
1083 friend const SemaDiagnosticBuilder &operator<<(
1084 const SemaDiagnosticBuilder &Diag, const T &Value) {
1085 const DiagnosticBuilder &BaseDiag = Diag;
1091 /// \brief Emit a diagnostic.
1092 SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID) {
1093 DiagnosticBuilder DB = Diags.Report(Loc, DiagID);
1094 return SemaDiagnosticBuilder(DB, *this, DiagID);
1097 /// \brief Emit a partial diagnostic.
1098 SemaDiagnosticBuilder Diag(SourceLocation Loc, const PartialDiagnostic& PD);
1100 /// \brief Build a partial diagnostic.
1101 PartialDiagnostic PDiag(unsigned DiagID = 0); // in SemaInternal.h
1103 bool findMacroSpelling(SourceLocation &loc, StringRef name);
1105 /// \brief Get a string to suggest for zero-initialization of a type.
1107 getFixItZeroInitializerForType(QualType T, SourceLocation Loc) const;
1108 std::string getFixItZeroLiteralForType(QualType T, SourceLocation Loc) const;
1110 /// \brief Calls \c Lexer::getLocForEndOfToken()
1111 SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset = 0);
1113 /// \brief Retrieve the module loader associated with the preprocessor.
1114 ModuleLoader &getModuleLoader() const;
1116 void emitAndClearUnusedLocalTypedefWarnings();
1118 void ActOnEndOfTranslationUnit();
1120 void CheckDelegatingCtorCycles();
1122 Scope *getScopeForContext(DeclContext *Ctx);
1124 void PushFunctionScope();
1125 void PushBlockScope(Scope *BlockScope, BlockDecl *Block);
1126 sema::LambdaScopeInfo *PushLambdaScope();
1128 /// \brief This is used to inform Sema what the current TemplateParameterDepth
1129 /// is during Parsing. Currently it is used to pass on the depth
1130 /// when parsing generic lambda 'auto' parameters.
1131 void RecordParsingTemplateParameterDepth(unsigned Depth);
1133 void PushCapturedRegionScope(Scope *RegionScope, CapturedDecl *CD,
1135 CapturedRegionKind K);
1137 PopFunctionScopeInfo(const sema::AnalysisBasedWarnings::Policy *WP = nullptr,
1138 const Decl *D = nullptr,
1139 const BlockExpr *blkExpr = nullptr);
1141 sema::FunctionScopeInfo *getCurFunction() const {
1142 return FunctionScopes.back();
1145 sema::FunctionScopeInfo *getEnclosingFunction() const {
1146 if (FunctionScopes.empty())
1149 for (int e = FunctionScopes.size()-1; e >= 0; --e) {
1150 if (isa<sema::BlockScopeInfo>(FunctionScopes[e]))
1152 return FunctionScopes[e];
1157 template <typename ExprT>
1158 void recordUseOfEvaluatedWeak(const ExprT *E, bool IsRead=true) {
1159 if (!isUnevaluatedContext())
1160 getCurFunction()->recordUseOfWeak(E, IsRead);
1163 void PushCompoundScope();
1164 void PopCompoundScope();
1166 sema::CompoundScopeInfo &getCurCompoundScope() const;
1168 bool hasAnyUnrecoverableErrorsInThisFunction() const;
1170 /// \brief Retrieve the current block, if any.
1171 sema::BlockScopeInfo *getCurBlock();
1173 /// \brief Retrieve the current lambda scope info, if any.
1174 sema::LambdaScopeInfo *getCurLambda();
1176 /// \brief Retrieve the current generic lambda info, if any.
1177 sema::LambdaScopeInfo *getCurGenericLambda();
1179 /// \brief Retrieve the current captured region, if any.
1180 sema::CapturedRegionScopeInfo *getCurCapturedRegion();
1182 /// WeakTopLevelDeclDecls - access to \#pragma weak-generated Decls
1183 SmallVectorImpl<Decl *> &WeakTopLevelDecls() { return WeakTopLevelDecl; }
1185 void ActOnComment(SourceRange Comment);
1187 //===--------------------------------------------------------------------===//
1188 // Type Analysis / Processing: SemaType.cpp.
1191 QualType BuildQualifiedType(QualType T, SourceLocation Loc, Qualifiers Qs,
1192 const DeclSpec *DS = nullptr);
1193 QualType BuildQualifiedType(QualType T, SourceLocation Loc, unsigned CVRA,
1194 const DeclSpec *DS = nullptr);
1195 QualType BuildPointerType(QualType T,
1196 SourceLocation Loc, DeclarationName Entity);
1197 QualType BuildReferenceType(QualType T, bool LValueRef,
1198 SourceLocation Loc, DeclarationName Entity);
1199 QualType BuildArrayType(QualType T, ArrayType::ArraySizeModifier ASM,
1200 Expr *ArraySize, unsigned Quals,
1201 SourceRange Brackets, DeclarationName Entity);
1202 QualType BuildExtVectorType(QualType T, Expr *ArraySize,
1203 SourceLocation AttrLoc);
1205 bool CheckFunctionReturnType(QualType T, SourceLocation Loc);
1207 unsigned deduceWeakPropertyFromType(QualType T) {
1208 if ((getLangOpts().getGC() != LangOptions::NonGC &&
1209 T.isObjCGCWeak()) ||
1210 (getLangOpts().ObjCAutoRefCount &&
1211 T.getObjCLifetime() == Qualifiers::OCL_Weak))
1212 return ObjCDeclSpec::DQ_PR_weak;
1217 /// \brief Build a function type.
1219 /// This routine checks the function type according to C++ rules and
1220 /// under the assumption that the result type and parameter types have
1221 /// just been instantiated from a template. It therefore duplicates
1222 /// some of the behavior of GetTypeForDeclarator, but in a much
1223 /// simpler form that is only suitable for this narrow use case.
1225 /// \param T The return type of the function.
1227 /// \param ParamTypes The parameter types of the function. This array
1228 /// will be modified to account for adjustments to the types of the
1229 /// function parameters.
1231 /// \param Loc The location of the entity whose type involves this
1232 /// function type or, if there is no such entity, the location of the
1233 /// type that will have function type.
1235 /// \param Entity The name of the entity that involves the function
1238 /// \param EPI Extra information about the function type. Usually this will
1239 /// be taken from an existing function with the same prototype.
1241 /// \returns A suitable function type, if there are no errors. The
1242 /// unqualified type will always be a FunctionProtoType.
1243 /// Otherwise, returns a NULL type.
1244 QualType BuildFunctionType(QualType T,
1245 MutableArrayRef<QualType> ParamTypes,
1246 SourceLocation Loc, DeclarationName Entity,
1247 const FunctionProtoType::ExtProtoInfo &EPI);
1249 QualType BuildMemberPointerType(QualType T, QualType Class,
1251 DeclarationName Entity);
1252 QualType BuildBlockPointerType(QualType T,
1253 SourceLocation Loc, DeclarationName Entity);
1254 QualType BuildParenType(QualType T);
1255 QualType BuildAtomicType(QualType T, SourceLocation Loc);
1257 TypeSourceInfo *GetTypeForDeclarator(Declarator &D, Scope *S);
1258 TypeSourceInfo *GetTypeForDeclaratorCast(Declarator &D, QualType FromTy);
1259 TypeSourceInfo *GetTypeSourceInfoForDeclarator(Declarator &D, QualType T,
1260 TypeSourceInfo *ReturnTypeInfo);
1262 /// \brief Package the given type and TSI into a ParsedType.
1263 ParsedType CreateParsedType(QualType T, TypeSourceInfo *TInfo);
1264 DeclarationNameInfo GetNameForDeclarator(Declarator &D);
1265 DeclarationNameInfo GetNameFromUnqualifiedId(const UnqualifiedId &Name);
1266 static QualType GetTypeFromParser(ParsedType Ty,
1267 TypeSourceInfo **TInfo = nullptr);
1268 CanThrowResult canThrow(const Expr *E);
1269 const FunctionProtoType *ResolveExceptionSpec(SourceLocation Loc,
1270 const FunctionProtoType *FPT);
1271 void UpdateExceptionSpec(FunctionDecl *FD,
1272 const FunctionProtoType::ExceptionSpecInfo &ESI);
1273 bool CheckSpecifiedExceptionType(QualType &T, const SourceRange &Range);
1274 bool CheckDistantExceptionSpec(QualType T);
1275 bool CheckEquivalentExceptionSpec(FunctionDecl *Old, FunctionDecl *New);
1276 bool CheckEquivalentExceptionSpec(
1277 const FunctionProtoType *Old, SourceLocation OldLoc,
1278 const FunctionProtoType *New, SourceLocation NewLoc);
1279 bool CheckEquivalentExceptionSpec(
1280 const PartialDiagnostic &DiagID, const PartialDiagnostic & NoteID,
1281 const FunctionProtoType *Old, SourceLocation OldLoc,
1282 const FunctionProtoType *New, SourceLocation NewLoc,
1283 bool *MissingExceptionSpecification = nullptr,
1284 bool *MissingEmptyExceptionSpecification = nullptr,
1285 bool AllowNoexceptAllMatchWithNoSpec = false,
1286 bool IsOperatorNew = false);
1287 bool CheckExceptionSpecSubset(
1288 const PartialDiagnostic &DiagID, const PartialDiagnostic & NoteID,
1289 const FunctionProtoType *Superset, SourceLocation SuperLoc,
1290 const FunctionProtoType *Subset, SourceLocation SubLoc);
1291 bool CheckParamExceptionSpec(const PartialDiagnostic & NoteID,
1292 const FunctionProtoType *Target, SourceLocation TargetLoc,
1293 const FunctionProtoType *Source, SourceLocation SourceLoc);
1295 TypeResult ActOnTypeName(Scope *S, Declarator &D);
1297 /// \brief The parser has parsed the context-sensitive type 'instancetype'
1298 /// in an Objective-C message declaration. Return the appropriate type.
1299 ParsedType ActOnObjCInstanceType(SourceLocation Loc);
1301 /// \brief Abstract class used to diagnose incomplete types.
1302 struct TypeDiagnoser {
1305 TypeDiagnoser(bool Suppressed = false) : Suppressed(Suppressed) { }
1307 virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) = 0;
1308 virtual ~TypeDiagnoser() {}
1311 static int getPrintable(int I) { return I; }
1312 static unsigned getPrintable(unsigned I) { return I; }
1313 static bool getPrintable(bool B) { return B; }
1314 static const char * getPrintable(const char *S) { return S; }
1315 static StringRef getPrintable(StringRef S) { return S; }
1316 static const std::string &getPrintable(const std::string &S) { return S; }
1317 static const IdentifierInfo *getPrintable(const IdentifierInfo *II) {
1320 static DeclarationName getPrintable(DeclarationName N) { return N; }
1321 static QualType getPrintable(QualType T) { return T; }
1322 static SourceRange getPrintable(SourceRange R) { return R; }
1323 static SourceRange getPrintable(SourceLocation L) { return L; }
1324 static SourceRange getPrintable(const Expr *E) { return E->getSourceRange(); }
1325 static SourceRange getPrintable(TypeLoc TL) { return TL.getSourceRange();}
1327 template <typename... Ts> class BoundTypeDiagnoser : public TypeDiagnoser {
1329 std::tuple<const Ts &...> Args;
1331 template <std::size_t... Is>
1332 void emit(const SemaDiagnosticBuilder &DB,
1333 llvm::index_sequence<Is...>) const {
1334 // Apply all tuple elements to the builder in order.
1335 bool Dummy[] = {(DB << getPrintable(std::get<Is>(Args)))...};
1340 BoundTypeDiagnoser(unsigned DiagID, const Ts &...Args)
1341 : TypeDiagnoser(DiagID == 0), DiagID(DiagID), Args(Args...) {}
1343 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
1346 const SemaDiagnosticBuilder &DB = S.Diag(Loc, DiagID);
1347 emit(DB, llvm::index_sequence_for<Ts...>());
1353 bool RequireCompleteTypeImpl(SourceLocation Loc, QualType T,
1354 TypeDiagnoser &Diagnoser);
1356 VisibleModuleSet VisibleModules;
1357 llvm::SmallVector<VisibleModuleSet, 16> VisibleModulesStack;
1359 Module *CachedFakeTopLevelModule;
1362 /// \brief Get the module owning an entity.
1363 Module *getOwningModule(Decl *Entity);
1365 /// \brief Make a merged definition of an existing hidden definition \p ND
1366 /// visible at the specified location.
1367 void makeMergedDefinitionVisible(NamedDecl *ND, SourceLocation Loc);
1369 bool isModuleVisible(Module *M) { return VisibleModules.isVisible(M); }
1371 /// Determine whether a declaration is visible to name lookup.
1372 bool isVisible(const NamedDecl *D) {
1373 return !D->isHidden() || isVisibleSlow(D);
1375 bool hasVisibleMergedDefinition(NamedDecl *Def);
1377 /// Determine if \p D has a visible definition. If not, suggest a declaration
1378 /// that should be made visible to expose the definition.
1379 bool hasVisibleDefinition(NamedDecl *D, NamedDecl **Suggested);
1380 bool hasVisibleDefinition(const NamedDecl *D) {
1382 return hasVisibleDefinition(const_cast<NamedDecl*>(D), &Hidden);
1385 /// Determine if the template parameter \p D has a visible default argument.
1387 hasVisibleDefaultArgument(const NamedDecl *D,
1388 llvm::SmallVectorImpl<Module *> *Modules = nullptr);
1390 bool RequireCompleteType(SourceLocation Loc, QualType T,
1391 TypeDiagnoser &Diagnoser);
1392 bool RequireCompleteType(SourceLocation Loc, QualType T,
1395 template <typename... Ts>
1396 bool RequireCompleteType(SourceLocation Loc, QualType T, unsigned DiagID,
1397 const Ts &...Args) {
1398 BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
1399 return RequireCompleteType(Loc, T, Diagnoser);
1402 bool RequireCompleteExprType(Expr *E, TypeDiagnoser &Diagnoser);
1403 bool RequireCompleteExprType(Expr *E, unsigned DiagID);
1405 template <typename... Ts>
1406 bool RequireCompleteExprType(Expr *E, unsigned DiagID, const Ts &...Args) {
1407 BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
1408 return RequireCompleteExprType(E, Diagnoser);
1411 bool RequireLiteralType(SourceLocation Loc, QualType T,
1412 TypeDiagnoser &Diagnoser);
1413 bool RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID);
1415 template <typename... Ts>
1416 bool RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID,
1417 const Ts &...Args) {
1418 BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
1419 return RequireLiteralType(Loc, T, Diagnoser);
1422 QualType getElaboratedType(ElaboratedTypeKeyword Keyword,
1423 const CXXScopeSpec &SS, QualType T);
1425 QualType BuildTypeofExprType(Expr *E, SourceLocation Loc);
1426 /// If AsUnevaluated is false, E is treated as though it were an evaluated
1427 /// context, such as when building a type for decltype(auto).
1428 QualType BuildDecltypeType(Expr *E, SourceLocation Loc,
1429 bool AsUnevaluated = true);
1430 QualType BuildUnaryTransformType(QualType BaseType,
1431 UnaryTransformType::UTTKind UKind,
1432 SourceLocation Loc);
1434 //===--------------------------------------------------------------------===//
1435 // Symbol table / Decl tracking callbacks: SemaDecl.cpp.
1438 /// List of decls defined in a function prototype. This contains EnumConstants
1439 /// that incorrectly end up in translation unit scope because there is no
1440 /// function to pin them on. ActOnFunctionDeclarator reads this list and patches
1441 /// them into the FunctionDecl.
1442 std::vector<NamedDecl*> DeclsInPrototypeScope;
1444 DeclGroupPtrTy ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType = nullptr);
1446 void DiagnoseUseOfUnimplementedSelectors();
1448 bool isSimpleTypeSpecifier(tok::TokenKind Kind) const;
1450 ParsedType getTypeName(const IdentifierInfo &II, SourceLocation NameLoc,
1451 Scope *S, CXXScopeSpec *SS = nullptr,
1452 bool isClassName = false,
1453 bool HasTrailingDot = false,
1454 ParsedType ObjectType = ParsedType(),
1455 bool IsCtorOrDtorName = false,
1456 bool WantNontrivialTypeSourceInfo = false,
1457 IdentifierInfo **CorrectedII = nullptr);
1458 TypeSpecifierType isTagName(IdentifierInfo &II, Scope *S);
1459 bool isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S);
1460 void DiagnoseUnknownTypeName(IdentifierInfo *&II,
1461 SourceLocation IILoc,
1464 ParsedType &SuggestedType,
1465 bool AllowClassTemplates = false);
1467 /// \brief For compatibility with MSVC, we delay parsing of some default
1468 /// template type arguments until instantiation time. Emits a warning and
1469 /// returns a synthesized DependentNameType that isn't really dependent on any
1470 /// other template arguments.
1471 ParsedType ActOnDelayedDefaultTemplateArg(const IdentifierInfo &II,
1472 SourceLocation NameLoc);
1474 /// \brief Describes the result of the name lookup and resolution performed
1475 /// by \c ClassifyName().
1476 enum NameClassificationKind {
1482 NC_NestedNameSpecifier,
1488 class NameClassification {
1489 NameClassificationKind Kind;
1491 TemplateName Template;
1493 const IdentifierInfo *Keyword;
1495 explicit NameClassification(NameClassificationKind Kind) : Kind(Kind) {}
1498 NameClassification(ExprResult Expr) : Kind(NC_Expression), Expr(Expr) {}
1500 NameClassification(ParsedType Type) : Kind(NC_Type), Type(Type) {}
1502 NameClassification(const IdentifierInfo *Keyword)
1503 : Kind(NC_Keyword), Keyword(Keyword) { }
1505 static NameClassification Error() {
1506 return NameClassification(NC_Error);
1509 static NameClassification Unknown() {
1510 return NameClassification(NC_Unknown);
1513 static NameClassification NestedNameSpecifier() {
1514 return NameClassification(NC_NestedNameSpecifier);
1517 static NameClassification TypeTemplate(TemplateName Name) {
1518 NameClassification Result(NC_TypeTemplate);
1519 Result.Template = Name;
1523 static NameClassification VarTemplate(TemplateName Name) {
1524 NameClassification Result(NC_VarTemplate);
1525 Result.Template = Name;
1529 static NameClassification FunctionTemplate(TemplateName Name) {
1530 NameClassification Result(NC_FunctionTemplate);
1531 Result.Template = Name;
1535 NameClassificationKind getKind() const { return Kind; }
1537 ParsedType getType() const {
1538 assert(Kind == NC_Type);
1542 ExprResult getExpression() const {
1543 assert(Kind == NC_Expression);
1547 TemplateName getTemplateName() const {
1548 assert(Kind == NC_TypeTemplate || Kind == NC_FunctionTemplate ||
1549 Kind == NC_VarTemplate);
1553 TemplateNameKind getTemplateNameKind() const {
1555 case NC_TypeTemplate:
1556 return TNK_Type_template;
1557 case NC_FunctionTemplate:
1558 return TNK_Function_template;
1559 case NC_VarTemplate:
1560 return TNK_Var_template;
1562 llvm_unreachable("unsupported name classification.");
1567 /// \brief Perform name lookup on the given name, classifying it based on
1568 /// the results of name lookup and the following token.
1570 /// This routine is used by the parser to resolve identifiers and help direct
1571 /// parsing. When the identifier cannot be found, this routine will attempt
1572 /// to correct the typo and classify based on the resulting name.
1574 /// \param S The scope in which we're performing name lookup.
1576 /// \param SS The nested-name-specifier that precedes the name.
1578 /// \param Name The identifier. If typo correction finds an alternative name,
1579 /// this pointer parameter will be updated accordingly.
1581 /// \param NameLoc The location of the identifier.
1583 /// \param NextToken The token following the identifier. Used to help
1584 /// disambiguate the name.
1586 /// \param IsAddressOfOperand True if this name is the operand of a unary
1587 /// address of ('&') expression, assuming it is classified as an
1590 /// \param CCC The correction callback, if typo correction is desired.
1592 ClassifyName(Scope *S, CXXScopeSpec &SS, IdentifierInfo *&Name,
1593 SourceLocation NameLoc, const Token &NextToken,
1594 bool IsAddressOfOperand,
1595 std::unique_ptr<CorrectionCandidateCallback> CCC = nullptr);
1597 Decl *ActOnDeclarator(Scope *S, Declarator &D);
1599 NamedDecl *HandleDeclarator(Scope *S, Declarator &D,
1600 MultiTemplateParamsArg TemplateParameterLists);
1601 void RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S);
1602 bool DiagnoseClassNameShadow(DeclContext *DC, DeclarationNameInfo Info);
1603 bool diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
1604 DeclarationName Name,
1605 SourceLocation Loc);
1607 diagnoseIgnoredQualifiers(unsigned DiagID, unsigned Quals,
1608 SourceLocation FallbackLoc,
1609 SourceLocation ConstQualLoc = SourceLocation(),
1610 SourceLocation VolatileQualLoc = SourceLocation(),
1611 SourceLocation RestrictQualLoc = SourceLocation(),
1612 SourceLocation AtomicQualLoc = SourceLocation());
1614 static bool adjustContextForLocalExternDecl(DeclContext *&DC);
1615 void DiagnoseFunctionSpecifiers(const DeclSpec &DS);
1616 void CheckShadow(Scope *S, VarDecl *D, const LookupResult& R);
1617 void CheckShadow(Scope *S, VarDecl *D);
1618 void CheckCastAlign(Expr *Op, QualType T, SourceRange TRange);
1619 void handleTagNumbering(const TagDecl *Tag, Scope *TagScope);
1620 void setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
1621 TypedefNameDecl *NewTD);
1622 void CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *D);
1623 NamedDecl* ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
1624 TypeSourceInfo *TInfo,
1625 LookupResult &Previous);
1626 NamedDecl* ActOnTypedefNameDecl(Scope* S, DeclContext* DC, TypedefNameDecl *D,
1627 LookupResult &Previous, bool &Redeclaration);
1628 NamedDecl *ActOnVariableDeclarator(Scope *S, Declarator &D, DeclContext *DC,
1629 TypeSourceInfo *TInfo,
1630 LookupResult &Previous,
1631 MultiTemplateParamsArg TemplateParamLists,
1633 // Returns true if the variable declaration is a redeclaration
1634 bool CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous);
1635 void CheckVariableDeclarationType(VarDecl *NewVD);
1636 void CheckCompleteVariableDeclaration(VarDecl *var);
1637 void MaybeSuggestAddingStaticToDecl(const FunctionDecl *D);
1639 NamedDecl* ActOnFunctionDeclarator(Scope* S, Declarator& D, DeclContext* DC,
1640 TypeSourceInfo *TInfo,
1641 LookupResult &Previous,
1642 MultiTemplateParamsArg TemplateParamLists,
1644 bool AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD);
1646 bool CheckConstexprFunctionDecl(const FunctionDecl *FD);
1647 bool CheckConstexprFunctionBody(const FunctionDecl *FD, Stmt *Body);
1649 void DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD);
1650 void FindHiddenVirtualMethods(CXXMethodDecl *MD,
1651 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods);
1652 void NoteHiddenVirtualMethods(CXXMethodDecl *MD,
1653 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods);
1654 // Returns true if the function declaration is a redeclaration
1655 bool CheckFunctionDeclaration(Scope *S,
1656 FunctionDecl *NewFD, LookupResult &Previous,
1657 bool IsExplicitSpecialization);
1658 void CheckMain(FunctionDecl *FD, const DeclSpec &D);
1659 void CheckMSVCRTEntryPoint(FunctionDecl *FD);
1660 Decl *ActOnParamDeclarator(Scope *S, Declarator &D);
1661 ParmVarDecl *BuildParmVarDeclForTypedef(DeclContext *DC,
1664 ParmVarDecl *CheckParameter(DeclContext *DC, SourceLocation StartLoc,
1665 SourceLocation NameLoc, IdentifierInfo *Name,
1666 QualType T, TypeSourceInfo *TSInfo,
1668 void ActOnParamDefaultArgument(Decl *param,
1669 SourceLocation EqualLoc,
1671 void ActOnParamUnparsedDefaultArgument(Decl *param,
1672 SourceLocation EqualLoc,
1673 SourceLocation ArgLoc);
1674 void ActOnParamDefaultArgumentError(Decl *param, SourceLocation EqualLoc);
1675 bool SetParamDefaultArgument(ParmVarDecl *Param, Expr *DefaultArg,
1676 SourceLocation EqualLoc);
1678 void AddInitializerToDecl(Decl *dcl, Expr *init, bool DirectInit,
1679 bool TypeMayContainAuto);
1680 void ActOnUninitializedDecl(Decl *dcl, bool TypeMayContainAuto);
1681 void ActOnInitializerError(Decl *Dcl);
1682 void ActOnCXXForRangeDecl(Decl *D);
1683 StmtResult ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc,
1684 IdentifierInfo *Ident,
1685 ParsedAttributes &Attrs,
1686 SourceLocation AttrEnd);
1687 void SetDeclDeleted(Decl *dcl, SourceLocation DelLoc);
1688 void SetDeclDefaulted(Decl *dcl, SourceLocation DefaultLoc);
1689 void FinalizeDeclaration(Decl *D);
1690 DeclGroupPtrTy FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
1691 ArrayRef<Decl *> Group);
1692 DeclGroupPtrTy BuildDeclaratorGroup(MutableArrayRef<Decl *> Group,
1693 bool TypeMayContainAuto = true);
1695 /// Should be called on all declarations that might have attached
1696 /// documentation comments.
1697 void ActOnDocumentableDecl(Decl *D);
1698 void ActOnDocumentableDecls(ArrayRef<Decl *> Group);
1700 void ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
1701 SourceLocation LocAfterDecls);
1702 void CheckForFunctionRedefinition(FunctionDecl *FD,
1703 const FunctionDecl *EffectiveDefinition =
1705 Decl *ActOnStartOfFunctionDef(Scope *S, Declarator &D);
1706 Decl *ActOnStartOfFunctionDef(Scope *S, Decl *D);
1707 void ActOnStartOfObjCMethodDef(Scope *S, Decl *D);
1708 bool isObjCMethodDecl(Decl *D) {
1709 return D && isa<ObjCMethodDecl>(D);
1712 /// \brief Determine whether we can delay parsing the body of a function or
1713 /// function template until it is used, assuming we don't care about emitting
1714 /// code for that function.
1716 /// This will be \c false if we may need the body of the function in the
1717 /// middle of parsing an expression (where it's impractical to switch to
1718 /// parsing a different function), for instance, if it's constexpr in C++11
1719 /// or has an 'auto' return type in C++14. These cases are essentially bugs.
1720 bool canDelayFunctionBody(const Declarator &D);
1722 /// \brief Determine whether we can skip parsing the body of a function
1723 /// definition, assuming we don't care about analyzing its body or emitting
1724 /// code for that function.
1726 /// This will be \c false only if we may need the body of the function in
1727 /// order to parse the rest of the program (for instance, if it is
1728 /// \c constexpr in C++11 or has an 'auto' return type in C++14).
1729 bool canSkipFunctionBody(Decl *D);
1731 void computeNRVO(Stmt *Body, sema::FunctionScopeInfo *Scope);
1732 Decl *ActOnFinishFunctionBody(Decl *Decl, Stmt *Body);
1733 Decl *ActOnFinishFunctionBody(Decl *Decl, Stmt *Body, bool IsInstantiation);
1734 Decl *ActOnSkippedFunctionBody(Decl *Decl);
1735 void ActOnFinishInlineMethodDef(CXXMethodDecl *D);
1737 /// ActOnFinishDelayedAttribute - Invoked when we have finished parsing an
1738 /// attribute for which parsing is delayed.
1739 void ActOnFinishDelayedAttribute(Scope *S, Decl *D, ParsedAttributes &Attrs);
1741 /// \brief Diagnose any unused parameters in the given sequence of
1742 /// ParmVarDecl pointers.
1743 void DiagnoseUnusedParameters(ParmVarDecl * const *Begin,
1744 ParmVarDecl * const *End);
1746 /// \brief Diagnose whether the size of parameters or return value of a
1747 /// function or obj-c method definition is pass-by-value and larger than a
1748 /// specified threshold.
1749 void DiagnoseSizeOfParametersAndReturnValue(ParmVarDecl * const *Begin,
1750 ParmVarDecl * const *End,
1754 void DiagnoseInvalidJumps(Stmt *Body);
1755 Decl *ActOnFileScopeAsmDecl(Expr *expr,
1756 SourceLocation AsmLoc,
1757 SourceLocation RParenLoc);
1759 /// \brief Handle a C++11 empty-declaration and attribute-declaration.
1760 Decl *ActOnEmptyDeclaration(Scope *S,
1761 AttributeList *AttrList,
1762 SourceLocation SemiLoc);
1764 /// \brief The parser has processed a module import declaration.
1766 /// \param AtLoc The location of the '@' symbol, if any.
1768 /// \param ImportLoc The location of the 'import' keyword.
1770 /// \param Path The module access path.
1771 DeclResult ActOnModuleImport(SourceLocation AtLoc, SourceLocation ImportLoc,
1774 /// \brief The parser has processed a module import translated from a
1775 /// #include or similar preprocessing directive.
1776 void ActOnModuleInclude(SourceLocation DirectiveLoc, Module *Mod);
1778 /// \brief The parsed has entered a submodule.
1779 void ActOnModuleBegin(SourceLocation DirectiveLoc, Module *Mod);
1780 /// \brief The parser has left a submodule.
1781 void ActOnModuleEnd(SourceLocation DirectiveLoc, Module *Mod);
1783 /// \brief Create an implicit import of the given module at the given
1784 /// source location, for error recovery, if possible.
1786 /// This routine is typically used when an entity found by name lookup
1787 /// is actually hidden within a module that we know about but the user
1788 /// has forgotten to import.
1789 void createImplicitModuleImportForErrorRecovery(SourceLocation Loc,
1792 /// Kinds of missing import. Note, the values of these enumerators correspond
1793 /// to %select values in diagnostics.
1794 enum class MissingImportKind {
1800 /// \brief Diagnose that the specified declaration needs to be visible but
1801 /// isn't, and suggest a module import that would resolve the problem.
1802 void diagnoseMissingImport(SourceLocation Loc, NamedDecl *Decl,
1803 bool NeedDefinition, bool Recover = true);
1804 void diagnoseMissingImport(SourceLocation Loc, NamedDecl *Decl,
1805 SourceLocation DeclLoc, ArrayRef<Module *> Modules,
1806 MissingImportKind MIK, bool Recover);
1808 /// \brief Retrieve a suitable printing policy.
1809 PrintingPolicy getPrintingPolicy() const {
1810 return getPrintingPolicy(Context, PP);
1813 /// \brief Retrieve a suitable printing policy.
1814 static PrintingPolicy getPrintingPolicy(const ASTContext &Ctx,
1815 const Preprocessor &PP);
1818 void ActOnPopScope(SourceLocation Loc, Scope *S);
1819 void ActOnTranslationUnitScope(Scope *S);
1821 Decl *ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS,
1823 Decl *ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS,
1825 MultiTemplateParamsArg TemplateParams,
1826 bool IsExplicitInstantiation = false);
1828 Decl *BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
1831 const PrintingPolicy &Policy);
1833 Decl *BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
1834 RecordDecl *Record);
1836 bool isAcceptableTagRedeclaration(const TagDecl *Previous,
1837 TagTypeKind NewTag, bool isDefinition,
1838 SourceLocation NewTagLoc,
1839 const IdentifierInfo &Name);
1842 TUK_Reference, // Reference to a tag: 'struct foo *X;'
1843 TUK_Declaration, // Fwd decl of a tag: 'struct foo;'
1844 TUK_Definition, // Definition of a tag: 'struct foo { int X; } Y;'
1845 TUK_Friend // Friend declaration: 'friend struct foo;'
1848 struct SkipBodyInfo {
1849 SkipBodyInfo() : ShouldSkip(false), Previous(nullptr) {}
1851 NamedDecl *Previous;
1854 Decl *ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
1855 SourceLocation KWLoc, CXXScopeSpec &SS,
1856 IdentifierInfo *Name, SourceLocation NameLoc,
1857 AttributeList *Attr, AccessSpecifier AS,
1858 SourceLocation ModulePrivateLoc,
1859 MultiTemplateParamsArg TemplateParameterLists,
1860 bool &OwnedDecl, bool &IsDependent,
1861 SourceLocation ScopedEnumKWLoc,
1862 bool ScopedEnumUsesClassTag, TypeResult UnderlyingType,
1863 bool IsTypeSpecifier, SkipBodyInfo *SkipBody = nullptr);
1865 Decl *ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
1866 unsigned TagSpec, SourceLocation TagLoc,
1868 IdentifierInfo *Name, SourceLocation NameLoc,
1869 AttributeList *Attr,
1870 MultiTemplateParamsArg TempParamLists);
1872 TypeResult ActOnDependentTag(Scope *S,
1875 const CXXScopeSpec &SS,
1876 IdentifierInfo *Name,
1877 SourceLocation TagLoc,
1878 SourceLocation NameLoc);
1880 void ActOnDefs(Scope *S, Decl *TagD, SourceLocation DeclStart,
1881 IdentifierInfo *ClassName,
1882 SmallVectorImpl<Decl *> &Decls);
1883 Decl *ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
1884 Declarator &D, Expr *BitfieldWidth);
1886 FieldDecl *HandleField(Scope *S, RecordDecl *TagD, SourceLocation DeclStart,
1887 Declarator &D, Expr *BitfieldWidth,
1888 InClassInitStyle InitStyle,
1889 AccessSpecifier AS);
1890 MSPropertyDecl *HandleMSProperty(Scope *S, RecordDecl *TagD,
1891 SourceLocation DeclStart,
1892 Declarator &D, Expr *BitfieldWidth,
1893 InClassInitStyle InitStyle,
1895 AttributeList *MSPropertyAttr);
1897 FieldDecl *CheckFieldDecl(DeclarationName Name, QualType T,
1898 TypeSourceInfo *TInfo,
1899 RecordDecl *Record, SourceLocation Loc,
1900 bool Mutable, Expr *BitfieldWidth,
1901 InClassInitStyle InitStyle,
1902 SourceLocation TSSL,
1903 AccessSpecifier AS, NamedDecl *PrevDecl,
1904 Declarator *D = nullptr);
1906 bool CheckNontrivialField(FieldDecl *FD);
1907 void DiagnoseNontrivial(const CXXRecordDecl *Record, CXXSpecialMember CSM);
1908 bool SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
1909 bool Diagnose = false);
1910 CXXSpecialMember getSpecialMember(const CXXMethodDecl *MD);
1911 void ActOnLastBitfield(SourceLocation DeclStart,
1912 SmallVectorImpl<Decl *> &AllIvarDecls);
1913 Decl *ActOnIvar(Scope *S, SourceLocation DeclStart,
1914 Declarator &D, Expr *BitfieldWidth,
1915 tok::ObjCKeywordKind visibility);
1917 // This is used for both record definitions and ObjC interface declarations.
1918 void ActOnFields(Scope* S, SourceLocation RecLoc, Decl *TagDecl,
1919 ArrayRef<Decl *> Fields,
1920 SourceLocation LBrac, SourceLocation RBrac,
1921 AttributeList *AttrList);
1923 /// ActOnTagStartDefinition - Invoked when we have entered the
1924 /// scope of a tag's definition (e.g., for an enumeration, class,
1925 /// struct, or union).
1926 void ActOnTagStartDefinition(Scope *S, Decl *TagDecl);
1928 typedef void *SkippedDefinitionContext;
1930 /// \brief Invoked when we enter a tag definition that we're skipping.
1931 SkippedDefinitionContext ActOnTagStartSkippedDefinition(Scope *S, Decl *TD);
1933 Decl *ActOnObjCContainerStartDefinition(Decl *IDecl);
1935 /// ActOnStartCXXMemberDeclarations - Invoked when we have parsed a
1936 /// C++ record definition's base-specifiers clause and are starting its
1937 /// member declarations.
1938 void ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagDecl,
1939 SourceLocation FinalLoc,
1940 bool IsFinalSpelledSealed,
1941 SourceLocation LBraceLoc);
1943 /// ActOnTagFinishDefinition - Invoked once we have finished parsing
1944 /// the definition of a tag (enumeration, class, struct, or union).
1945 void ActOnTagFinishDefinition(Scope *S, Decl *TagDecl,
1946 SourceLocation RBraceLoc);
1948 void ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context);
1950 void ActOnObjCContainerFinishDefinition();
1952 /// \brief Invoked when we must temporarily exit the objective-c container
1953 /// scope for parsing/looking-up C constructs.
1955 /// Must be followed by a call to \see ActOnObjCReenterContainerContext
1956 void ActOnObjCTemporaryExitContainerContext(DeclContext *DC);
1957 void ActOnObjCReenterContainerContext(DeclContext *DC);
1959 /// ActOnTagDefinitionError - Invoked when there was an unrecoverable
1960 /// error parsing the definition of a tag.
1961 void ActOnTagDefinitionError(Scope *S, Decl *TagDecl);
1963 EnumConstantDecl *CheckEnumConstant(EnumDecl *Enum,
1964 EnumConstantDecl *LastEnumConst,
1965 SourceLocation IdLoc,
1968 bool CheckEnumUnderlyingType(TypeSourceInfo *TI);
1969 bool CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
1970 QualType EnumUnderlyingTy, const EnumDecl *Prev);
1972 /// Determine whether the body of an anonymous enumeration should be skipped.
1973 /// \param II The name of the first enumerator.
1974 SkipBodyInfo shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II,
1975 SourceLocation IILoc);
1977 Decl *ActOnEnumConstant(Scope *S, Decl *EnumDecl, Decl *LastEnumConstant,
1978 SourceLocation IdLoc, IdentifierInfo *Id,
1979 AttributeList *Attrs,
1980 SourceLocation EqualLoc, Expr *Val);
1981 void ActOnEnumBody(SourceLocation EnumLoc, SourceLocation LBraceLoc,
1982 SourceLocation RBraceLoc, Decl *EnumDecl,
1983 ArrayRef<Decl *> Elements,
1984 Scope *S, AttributeList *Attr);
1986 DeclContext *getContainingDC(DeclContext *DC);
1988 /// Set the current declaration context until it gets popped.
1989 void PushDeclContext(Scope *S, DeclContext *DC);
1990 void PopDeclContext();
1992 /// EnterDeclaratorContext - Used when we must lookup names in the context
1993 /// of a declarator's nested name specifier.
1994 void EnterDeclaratorContext(Scope *S, DeclContext *DC);
1995 void ExitDeclaratorContext(Scope *S);
1997 /// Push the parameters of D, which must be a function, into scope.
1998 void ActOnReenterFunctionContext(Scope* S, Decl* D);
1999 void ActOnExitFunctionContext();
2001 DeclContext *getFunctionLevelDeclContext();
2003 /// getCurFunctionDecl - If inside of a function body, this returns a pointer
2004 /// to the function decl for the function being parsed. If we're currently
2005 /// in a 'block', this returns the containing context.
2006 FunctionDecl *getCurFunctionDecl();
2008 /// getCurMethodDecl - If inside of a method body, this returns a pointer to
2009 /// the method decl for the method being parsed. If we're currently
2010 /// in a 'block', this returns the containing context.
2011 ObjCMethodDecl *getCurMethodDecl();
2013 /// getCurFunctionOrMethodDecl - Return the Decl for the current ObjC method
2014 /// or C function we're in, otherwise return null. If we're currently
2015 /// in a 'block', this returns the containing context.
2016 NamedDecl *getCurFunctionOrMethodDecl();
2018 /// Add this decl to the scope shadowed decl chains.
2019 void PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext = true);
2021 /// \brief Make the given externally-produced declaration visible at the
2022 /// top level scope.
2024 /// \param D The externally-produced declaration to push.
2026 /// \param Name The name of the externally-produced declaration.
2027 void pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name);
2029 /// isDeclInScope - If 'Ctx' is a function/method, isDeclInScope returns true
2030 /// if 'D' is in Scope 'S', otherwise 'S' is ignored and isDeclInScope returns
2031 /// true if 'D' belongs to the given declaration context.
2033 /// \param AllowInlineNamespace If \c true, allow the declaration to be in the
2034 /// enclosing namespace set of the context, rather than contained
2035 /// directly within it.
2036 bool isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S = nullptr,
2037 bool AllowInlineNamespace = false);
2039 /// Finds the scope corresponding to the given decl context, if it
2040 /// happens to be an enclosing scope. Otherwise return NULL.
2041 static Scope *getScopeForDeclContext(Scope *S, DeclContext *DC);
2043 /// Subroutines of ActOnDeclarator().
2044 TypedefDecl *ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
2045 TypeSourceInfo *TInfo);
2046 bool isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New);
2048 /// Attribute merging methods. Return true if a new attribute was added.
2049 AvailabilityAttr *mergeAvailabilityAttr(NamedDecl *D, SourceRange Range,
2050 IdentifierInfo *Platform,
2051 VersionTuple Introduced,
2052 VersionTuple Deprecated,
2053 VersionTuple Obsoleted,
2057 unsigned AttrSpellingListIndex);
2058 TypeVisibilityAttr *mergeTypeVisibilityAttr(Decl *D, SourceRange Range,
2059 TypeVisibilityAttr::VisibilityType Vis,
2060 unsigned AttrSpellingListIndex);
2061 VisibilityAttr *mergeVisibilityAttr(Decl *D, SourceRange Range,
2062 VisibilityAttr::VisibilityType Vis,
2063 unsigned AttrSpellingListIndex);
2064 DLLImportAttr *mergeDLLImportAttr(Decl *D, SourceRange Range,
2065 unsigned AttrSpellingListIndex);
2066 DLLExportAttr *mergeDLLExportAttr(Decl *D, SourceRange Range,
2067 unsigned AttrSpellingListIndex);
2069 mergeMSInheritanceAttr(Decl *D, SourceRange Range, bool BestCase,
2070 unsigned AttrSpellingListIndex,
2071 MSInheritanceAttr::Spelling SemanticSpelling);
2072 FormatAttr *mergeFormatAttr(Decl *D, SourceRange Range,
2073 IdentifierInfo *Format, int FormatIdx,
2074 int FirstArg, unsigned AttrSpellingListIndex);
2075 SectionAttr *mergeSectionAttr(Decl *D, SourceRange Range, StringRef Name,
2076 unsigned AttrSpellingListIndex);
2077 AlwaysInlineAttr *mergeAlwaysInlineAttr(Decl *D, SourceRange Range,
2078 IdentifierInfo *Ident,
2079 unsigned AttrSpellingListIndex);
2080 MinSizeAttr *mergeMinSizeAttr(Decl *D, SourceRange Range,
2081 unsigned AttrSpellingListIndex);
2082 OptimizeNoneAttr *mergeOptimizeNoneAttr(Decl *D, SourceRange Range,
2083 unsigned AttrSpellingListIndex);
2085 /// \brief Describes the kind of merge to perform for availability
2086 /// attributes (including "deprecated", "unavailable", and "availability").
2087 enum AvailabilityMergeKind {
2088 /// \brief Don't merge availability attributes at all.
2090 /// \brief Merge availability attributes for a redeclaration, which requires
2093 /// \brief Merge availability attributes for an override, which requires
2094 /// an exact match or a weakening of constraints.
2098 void mergeDeclAttributes(NamedDecl *New, Decl *Old,
2099 AvailabilityMergeKind AMK = AMK_Redeclaration);
2100 void MergeTypedefNameDecl(TypedefNameDecl *New, LookupResult &OldDecls);
2101 bool MergeFunctionDecl(FunctionDecl *New, NamedDecl *&Old, Scope *S,
2102 bool MergeTypeWithOld);
2103 bool MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
2104 Scope *S, bool MergeTypeWithOld);
2105 void mergeObjCMethodDecls(ObjCMethodDecl *New, ObjCMethodDecl *Old);
2106 void MergeVarDecl(VarDecl *New, LookupResult &Previous);
2107 void MergeVarDeclTypes(VarDecl *New, VarDecl *Old, bool MergeTypeWithOld);
2108 void MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old);
2109 bool MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old, Scope *S);
2111 // AssignmentAction - This is used by all the assignment diagnostic functions
2112 // to represent what is actually causing the operation
2113 enum AssignmentAction {
2121 AA_Passing_CFAudited
2124 /// C++ Overloading.
2126 /// This is a legitimate overload: the existing declarations are
2127 /// functions or function templates with different signatures.
2130 /// This is not an overload because the signature exactly matches
2131 /// an existing declaration.
2134 /// This is not an overload because the lookup results contain a
2138 OverloadKind CheckOverload(Scope *S,
2140 const LookupResult &OldDecls,
2141 NamedDecl *&OldDecl,
2142 bool IsForUsingDecl);
2143 bool IsOverload(FunctionDecl *New, FunctionDecl *Old, bool IsForUsingDecl);
2145 /// \brief Checks availability of the function depending on the current
2146 /// function context.Inside an unavailable function,unavailability is ignored.
2148 /// \returns true if \p FD is unavailable and current context is inside
2149 /// an available function, false otherwise.
2150 bool isFunctionConsideredUnavailable(FunctionDecl *FD);
2152 ImplicitConversionSequence
2153 TryImplicitConversion(Expr *From, QualType ToType,
2154 bool SuppressUserConversions,
2156 bool InOverloadResolution,
2158 bool AllowObjCWritebackConversion);
2160 bool IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType);
2161 bool IsFloatingPointPromotion(QualType FromType, QualType ToType);
2162 bool IsComplexPromotion(QualType FromType, QualType ToType);
2163 bool IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
2164 bool InOverloadResolution,
2165 QualType& ConvertedType, bool &IncompatibleObjC);
2166 bool isObjCPointerConversion(QualType FromType, QualType ToType,
2167 QualType& ConvertedType, bool &IncompatibleObjC);
2168 bool isObjCWritebackConversion(QualType FromType, QualType ToType,
2169 QualType &ConvertedType);
2170 bool IsBlockPointerConversion(QualType FromType, QualType ToType,
2171 QualType& ConvertedType);
2172 bool FunctionParamTypesAreEqual(const FunctionProtoType *OldType,
2173 const FunctionProtoType *NewType,
2174 unsigned *ArgPos = nullptr);
2175 void HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
2176 QualType FromType, QualType ToType);
2178 CastKind PrepareCastToObjCObjectPointer(ExprResult &E);
2179 bool CheckPointerConversion(Expr *From, QualType ToType,
2181 CXXCastPath& BasePath,
2182 bool IgnoreBaseAccess);
2183 bool IsMemberPointerConversion(Expr *From, QualType FromType, QualType ToType,
2184 bool InOverloadResolution,
2185 QualType &ConvertedType);
2186 bool CheckMemberPointerConversion(Expr *From, QualType ToType,
2188 CXXCastPath &BasePath,
2189 bool IgnoreBaseAccess);
2190 bool IsQualificationConversion(QualType FromType, QualType ToType,
2191 bool CStyle, bool &ObjCLifetimeConversion);
2192 bool IsNoReturnConversion(QualType FromType, QualType ToType,
2193 QualType &ResultTy);
2194 bool DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType);
2195 bool isSameOrCompatibleFunctionType(CanQualType Param, CanQualType Arg);
2197 ExprResult PerformMoveOrCopyInitialization(const InitializedEntity &Entity,
2198 const VarDecl *NRVOCandidate,
2199 QualType ResultType,
2201 bool AllowNRVO = true);
2203 bool CanPerformCopyInitialization(const InitializedEntity &Entity,
2205 ExprResult PerformCopyInitialization(const InitializedEntity &Entity,
2206 SourceLocation EqualLoc,
2208 bool TopLevelOfInitList = false,
2209 bool AllowExplicit = false);
2210 ExprResult PerformObjectArgumentInitialization(Expr *From,
2211 NestedNameSpecifier *Qualifier,
2212 NamedDecl *FoundDecl,
2213 CXXMethodDecl *Method);
2215 ExprResult PerformContextuallyConvertToBool(Expr *From);
2216 ExprResult PerformContextuallyConvertToObjCPointer(Expr *From);
2218 /// Contexts in which a converted constant expression is required.
2220 CCEK_CaseValue, ///< Expression in a case label.
2221 CCEK_Enumerator, ///< Enumerator value with fixed underlying type.
2222 CCEK_TemplateArg, ///< Value of a non-type template parameter.
2223 CCEK_NewExpr ///< Constant expression in a noptr-new-declarator.
2225 ExprResult CheckConvertedConstantExpression(Expr *From, QualType T,
2226 llvm::APSInt &Value, CCEKind CCE);
2227 ExprResult CheckConvertedConstantExpression(Expr *From, QualType T,
2228 APValue &Value, CCEKind CCE);
2230 /// \brief Abstract base class used to perform a contextual implicit
2231 /// conversion from an expression to any type passing a filter.
2232 class ContextualImplicitConverter {
2235 bool SuppressConversion;
2237 ContextualImplicitConverter(bool Suppress = false,
2238 bool SuppressConversion = false)
2239 : Suppress(Suppress), SuppressConversion(SuppressConversion) {}
2241 /// \brief Determine whether the specified type is a valid destination type
2242 /// for this conversion.
2243 virtual bool match(QualType T) = 0;
2245 /// \brief Emits a diagnostic complaining that the expression does not have
2246 /// integral or enumeration type.
2247 virtual SemaDiagnosticBuilder
2248 diagnoseNoMatch(Sema &S, SourceLocation Loc, QualType T) = 0;
2250 /// \brief Emits a diagnostic when the expression has incomplete class type.
2251 virtual SemaDiagnosticBuilder
2252 diagnoseIncomplete(Sema &S, SourceLocation Loc, QualType T) = 0;
2254 /// \brief Emits a diagnostic when the only matching conversion function
2256 virtual SemaDiagnosticBuilder diagnoseExplicitConv(
2257 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) = 0;
2259 /// \brief Emits a note for the explicit conversion function.
2260 virtual SemaDiagnosticBuilder
2261 noteExplicitConv(Sema &S, CXXConversionDecl *Conv, QualType ConvTy) = 0;
2263 /// \brief Emits a diagnostic when there are multiple possible conversion
2265 virtual SemaDiagnosticBuilder
2266 diagnoseAmbiguous(Sema &S, SourceLocation Loc, QualType T) = 0;
2268 /// \brief Emits a note for one of the candidate conversions.
2269 virtual SemaDiagnosticBuilder
2270 noteAmbiguous(Sema &S, CXXConversionDecl *Conv, QualType ConvTy) = 0;
2272 /// \brief Emits a diagnostic when we picked a conversion function
2273 /// (for cases when we are not allowed to pick a conversion function).
2274 virtual SemaDiagnosticBuilder diagnoseConversion(
2275 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) = 0;
2277 virtual ~ContextualImplicitConverter() {}
2280 class ICEConvertDiagnoser : public ContextualImplicitConverter {
2281 bool AllowScopedEnumerations;
2284 ICEConvertDiagnoser(bool AllowScopedEnumerations,
2285 bool Suppress, bool SuppressConversion)
2286 : ContextualImplicitConverter(Suppress, SuppressConversion),
2287 AllowScopedEnumerations(AllowScopedEnumerations) {}
2289 /// Match an integral or (possibly scoped) enumeration type.
2290 bool match(QualType T) override;
2292 SemaDiagnosticBuilder
2293 diagnoseNoMatch(Sema &S, SourceLocation Loc, QualType T) override {
2294 return diagnoseNotInt(S, Loc, T);
2297 /// \brief Emits a diagnostic complaining that the expression does not have
2298 /// integral or enumeration type.
2299 virtual SemaDiagnosticBuilder
2300 diagnoseNotInt(Sema &S, SourceLocation Loc, QualType T) = 0;
2303 /// Perform a contextual implicit conversion.
2304 ExprResult PerformContextualImplicitConversion(
2305 SourceLocation Loc, Expr *FromE, ContextualImplicitConverter &Converter);
2308 enum ObjCSubscriptKind {
2313 ObjCSubscriptKind CheckSubscriptingKind(Expr *FromE);
2315 // Note that LK_String is intentionally after the other literals, as
2316 // this is used for diagnostics logic.
2317 enum ObjCLiteralKind {
2326 ObjCLiteralKind CheckLiteralKind(Expr *FromE);
2328 ExprResult PerformObjectMemberConversion(Expr *From,
2329 NestedNameSpecifier *Qualifier,
2330 NamedDecl *FoundDecl,
2333 // Members have to be NamespaceDecl* or TranslationUnitDecl*.
2334 // TODO: make this is a typesafe union.
2335 typedef llvm::SmallPtrSet<DeclContext *, 16> AssociatedNamespaceSet;
2336 typedef llvm::SmallPtrSet<CXXRecordDecl *, 16> AssociatedClassSet;
2338 void AddOverloadCandidate(FunctionDecl *Function,
2339 DeclAccessPair FoundDecl,
2340 ArrayRef<Expr *> Args,
2341 OverloadCandidateSet& CandidateSet,
2342 bool SuppressUserConversions = false,
2343 bool PartialOverloading = false,
2344 bool AllowExplicit = false);
2345 void AddFunctionCandidates(const UnresolvedSetImpl &Functions,
2346 ArrayRef<Expr *> Args,
2347 OverloadCandidateSet &CandidateSet,
2348 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr,
2349 bool SuppressUserConversions = false,
2350 bool PartialOverloading = false);
2351 void AddMethodCandidate(DeclAccessPair FoundDecl,
2352 QualType ObjectType,
2353 Expr::Classification ObjectClassification,
2354 ArrayRef<Expr *> Args,
2355 OverloadCandidateSet& CandidateSet,
2356 bool SuppressUserConversion = false);
2357 void AddMethodCandidate(CXXMethodDecl *Method,
2358 DeclAccessPair FoundDecl,
2359 CXXRecordDecl *ActingContext, QualType ObjectType,
2360 Expr::Classification ObjectClassification,
2361 ArrayRef<Expr *> Args,
2362 OverloadCandidateSet& CandidateSet,
2363 bool SuppressUserConversions = false,
2364 bool PartialOverloading = false);
2365 void AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
2366 DeclAccessPair FoundDecl,
2367 CXXRecordDecl *ActingContext,
2368 TemplateArgumentListInfo *ExplicitTemplateArgs,
2369 QualType ObjectType,
2370 Expr::Classification ObjectClassification,
2371 ArrayRef<Expr *> Args,
2372 OverloadCandidateSet& CandidateSet,
2373 bool SuppressUserConversions = false,
2374 bool PartialOverloading = false);
2375 void AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
2376 DeclAccessPair FoundDecl,
2377 TemplateArgumentListInfo *ExplicitTemplateArgs,
2378 ArrayRef<Expr *> Args,
2379 OverloadCandidateSet& CandidateSet,
2380 bool SuppressUserConversions = false,
2381 bool PartialOverloading = false);
2382 void AddConversionCandidate(CXXConversionDecl *Conversion,
2383 DeclAccessPair FoundDecl,
2384 CXXRecordDecl *ActingContext,
2385 Expr *From, QualType ToType,
2386 OverloadCandidateSet& CandidateSet,
2387 bool AllowObjCConversionOnExplicit);
2388 void AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
2389 DeclAccessPair FoundDecl,
2390 CXXRecordDecl *ActingContext,
2391 Expr *From, QualType ToType,
2392 OverloadCandidateSet &CandidateSet,
2393 bool AllowObjCConversionOnExplicit);
2394 void AddSurrogateCandidate(CXXConversionDecl *Conversion,
2395 DeclAccessPair FoundDecl,
2396 CXXRecordDecl *ActingContext,
2397 const FunctionProtoType *Proto,
2398 Expr *Object, ArrayRef<Expr *> Args,
2399 OverloadCandidateSet& CandidateSet);
2400 void AddMemberOperatorCandidates(OverloadedOperatorKind Op,
2401 SourceLocation OpLoc, ArrayRef<Expr *> Args,
2402 OverloadCandidateSet& CandidateSet,
2403 SourceRange OpRange = SourceRange());
2404 void AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
2405 ArrayRef<Expr *> Args,
2406 OverloadCandidateSet& CandidateSet,
2407 bool IsAssignmentOperator = false,
2408 unsigned NumContextualBoolArguments = 0);
2409 void AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
2410 SourceLocation OpLoc, ArrayRef<Expr *> Args,
2411 OverloadCandidateSet& CandidateSet);
2412 void AddArgumentDependentLookupCandidates(DeclarationName Name,
2414 ArrayRef<Expr *> Args,
2415 TemplateArgumentListInfo *ExplicitTemplateArgs,
2416 OverloadCandidateSet& CandidateSet,
2417 bool PartialOverloading = false);
2419 // Emit as a 'note' the specific overload candidate
2420 void NoteOverloadCandidate(FunctionDecl *Fn, QualType DestType = QualType());
2422 // Emit as a series of 'note's all template and non-templates
2423 // identified by the expression Expr
2424 void NoteAllOverloadCandidates(Expr* E, QualType DestType = QualType());
2426 /// Check the enable_if expressions on the given function. Returns the first
2427 /// failing attribute, or NULL if they were all successful.
2428 EnableIfAttr *CheckEnableIf(FunctionDecl *Function, ArrayRef<Expr *> Args,
2429 bool MissingImplicitThis = false);
2431 // [PossiblyAFunctionType] --> [Return]
2432 // NonFunctionType --> NonFunctionType
2434 // R (*)(A) --> R (A)
2435 // R (&)(A) --> R (A)
2436 // R (S::*)(A) --> R (A)
2437 QualType ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType);
2440 ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
2441 QualType TargetType,
2443 DeclAccessPair &Found,
2444 bool *pHadMultipleCandidates = nullptr);
2447 ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
2448 bool Complain = false,
2449 DeclAccessPair *Found = nullptr);
2451 bool ResolveAndFixSingleFunctionTemplateSpecialization(
2452 ExprResult &SrcExpr,
2453 bool DoFunctionPointerConverion = false,
2454 bool Complain = false,
2455 const SourceRange& OpRangeForComplaining = SourceRange(),
2456 QualType DestTypeForComplaining = QualType(),
2457 unsigned DiagIDForComplaining = 0);
2460 Expr *FixOverloadedFunctionReference(Expr *E,
2461 DeclAccessPair FoundDecl,
2463 ExprResult FixOverloadedFunctionReference(ExprResult,
2464 DeclAccessPair FoundDecl,
2467 void AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
2468 ArrayRef<Expr *> Args,
2469 OverloadCandidateSet &CandidateSet,
2470 bool PartialOverloading = false);
2472 // An enum used to represent the different possible results of building a
2473 // range-based for loop.
2474 enum ForRangeStatus {
2476 FRS_NoViableFunction,
2477 FRS_DiagnosticIssued
2480 // An enum to represent whether something is dealing with a call to begin()
2481 // or a call to end() in a range-based for loop.
2482 enum BeginEndFunction {
2487 ForRangeStatus BuildForRangeBeginEndCall(Scope *S, SourceLocation Loc,
2488 SourceLocation RangeLoc,
2490 BeginEndFunction BEF,
2491 const DeclarationNameInfo &NameInfo,
2492 LookupResult &MemberLookup,
2493 OverloadCandidateSet *CandidateSet,
2494 Expr *Range, ExprResult *CallExpr);
2496 ExprResult BuildOverloadedCallExpr(Scope *S, Expr *Fn,
2497 UnresolvedLookupExpr *ULE,
2498 SourceLocation LParenLoc,
2500 SourceLocation RParenLoc,
2502 bool AllowTypoCorrection=true);
2504 bool buildOverloadedCallSet(Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE,
2505 MultiExprArg Args, SourceLocation RParenLoc,
2506 OverloadCandidateSet *CandidateSet,
2507 ExprResult *Result);
2509 ExprResult CreateOverloadedUnaryOp(SourceLocation OpLoc,
2511 const UnresolvedSetImpl &Fns,
2514 ExprResult CreateOverloadedBinOp(SourceLocation OpLoc,
2516 const UnresolvedSetImpl &Fns,
2517 Expr *LHS, Expr *RHS);
2519 ExprResult CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
2520 SourceLocation RLoc,
2521 Expr *Base,Expr *Idx);
2524 BuildCallToMemberFunction(Scope *S, Expr *MemExpr,
2525 SourceLocation LParenLoc,
2527 SourceLocation RParenLoc);
2529 BuildCallToObjectOfClassType(Scope *S, Expr *Object, SourceLocation LParenLoc,
2531 SourceLocation RParenLoc);
2533 ExprResult BuildOverloadedArrowExpr(Scope *S, Expr *Base,
2534 SourceLocation OpLoc,
2535 bool *NoArrowOperatorFound = nullptr);
2537 /// CheckCallReturnType - Checks that a call expression's return type is
2538 /// complete. Returns true on failure. The location passed in is the location
2539 /// that best represents the call.
2540 bool CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
2541 CallExpr *CE, FunctionDecl *FD);
2543 /// Helpers for dealing with blocks and functions.
2544 bool CheckParmsForFunctionDef(ParmVarDecl *const *Param,
2545 ParmVarDecl *const *ParamEnd,
2546 bool CheckParameterNames);
2547 void CheckCXXDefaultArguments(FunctionDecl *FD);
2548 void CheckExtraCXXDefaultArguments(Declarator &D);
2549 Scope *getNonFieldDeclScope(Scope *S);
2551 /// \name Name lookup
2553 /// These routines provide name lookup that is used during semantic
2554 /// analysis to resolve the various kinds of names (identifiers,
2555 /// overloaded operator names, constructor names, etc.) into zero or
2556 /// more declarations within a particular scope. The major entry
2557 /// points are LookupName, which performs unqualified name lookup,
2558 /// and LookupQualifiedName, which performs qualified name lookup.
2560 /// All name lookup is performed based on some specific criteria,
2561 /// which specify what names will be visible to name lookup and how
2562 /// far name lookup should work. These criteria are important both
2563 /// for capturing language semantics (certain lookups will ignore
2564 /// certain names, for example) and for performance, since name
2565 /// lookup is often a bottleneck in the compilation of C++. Name
2566 /// lookup criteria is specified via the LookupCriteria enumeration.
2568 /// The results of name lookup can vary based on the kind of name
2569 /// lookup performed, the current language, and the translation
2570 /// unit. In C, for example, name lookup will either return nothing
2571 /// (no entity found) or a single declaration. In C++, name lookup
2572 /// can additionally refer to a set of overloaded functions or
2573 /// result in an ambiguity. All of the possible results of name
2574 /// lookup are captured by the LookupResult class, which provides
2575 /// the ability to distinguish among them.
2578 /// @brief Describes the kind of name lookup to perform.
2579 enum LookupNameKind {
2580 /// Ordinary name lookup, which finds ordinary names (functions,
2581 /// variables, typedefs, etc.) in C and most kinds of names
2582 /// (functions, variables, members, types, etc.) in C++.
2583 LookupOrdinaryName = 0,
2584 /// Tag name lookup, which finds the names of enums, classes,
2585 /// structs, and unions.
2587 /// Label name lookup.
2589 /// Member name lookup, which finds the names of
2590 /// class/struct/union members.
2592 /// Look up of an operator name (e.g., operator+) for use with
2593 /// operator overloading. This lookup is similar to ordinary name
2594 /// lookup, but will ignore any declarations that are class members.
2596 /// Look up of a name that precedes the '::' scope resolution
2597 /// operator in C++. This lookup completely ignores operator, object,
2598 /// function, and enumerator names (C++ [basic.lookup.qual]p1).
2599 LookupNestedNameSpecifierName,
2600 /// Look up a namespace name within a C++ using directive or
2601 /// namespace alias definition, ignoring non-namespace names (C++
2602 /// [basic.lookup.udir]p1).
2603 LookupNamespaceName,
2604 /// Look up all declarations in a scope with the given name,
2605 /// including resolved using declarations. This is appropriate
2606 /// for checking redeclarations for a using declaration.
2607 LookupUsingDeclName,
2608 /// Look up an ordinary name that is going to be redeclared as a
2609 /// name with linkage. This lookup ignores any declarations that
2610 /// are outside of the current scope unless they have linkage. See
2611 /// C99 6.2.2p4-5 and C++ [basic.link]p6.
2612 LookupRedeclarationWithLinkage,
2613 /// Look up a friend of a local class. This lookup does not look
2614 /// outside the innermost non-class scope. See C++11 [class.friend]p11.
2615 LookupLocalFriendName,
2616 /// Look up the name of an Objective-C protocol.
2617 LookupObjCProtocolName,
2618 /// Look up implicit 'self' parameter of an objective-c method.
2619 LookupObjCImplicitSelfParam,
2620 /// \brief Look up any declaration with any name.
2624 /// \brief Specifies whether (or how) name lookup is being performed for a
2625 /// redeclaration (vs. a reference).
2626 enum RedeclarationKind {
2627 /// \brief The lookup is a reference to this name that is not for the
2628 /// purpose of redeclaring the name.
2629 NotForRedeclaration = 0,
2630 /// \brief The lookup results will be used for redeclaration of a name,
2631 /// if an entity by that name already exists.
2635 /// \brief The possible outcomes of name lookup for a literal operator.
2636 enum LiteralOperatorLookupResult {
2637 /// \brief The lookup resulted in an error.
2639 /// \brief The lookup found a single 'cooked' literal operator, which
2640 /// expects a normal literal to be built and passed to it.
2642 /// \brief The lookup found a single 'raw' literal operator, which expects
2643 /// a string literal containing the spelling of the literal token.
2645 /// \brief The lookup found an overload set of literal operator templates,
2646 /// which expect the characters of the spelling of the literal token to be
2647 /// passed as a non-type template argument pack.
2649 /// \brief The lookup found an overload set of literal operator templates,
2650 /// which expect the character type and characters of the spelling of the
2651 /// string literal token to be passed as template arguments.
2655 SpecialMemberOverloadResult *LookupSpecialMember(CXXRecordDecl *D,
2656 CXXSpecialMember SM,
2663 typedef std::function<void(const TypoCorrection &)> TypoDiagnosticGenerator;
2664 typedef std::function<ExprResult(Sema &, TypoExpr *, TypoCorrection)>
2665 TypoRecoveryCallback;
2668 bool CppLookupName(LookupResult &R, Scope *S);
2670 struct TypoExprState {
2671 std::unique_ptr<TypoCorrectionConsumer> Consumer;
2672 TypoDiagnosticGenerator DiagHandler;
2673 TypoRecoveryCallback RecoveryHandler;
2675 TypoExprState(TypoExprState&& other) LLVM_NOEXCEPT;
2676 TypoExprState& operator=(TypoExprState&& other) LLVM_NOEXCEPT;
2679 /// \brief The set of unhandled TypoExprs and their associated state.
2680 llvm::MapVector<TypoExpr *, TypoExprState> DelayedTypos;
2682 /// \brief Creates a new TypoExpr AST node.
2683 TypoExpr *createDelayedTypo(std::unique_ptr<TypoCorrectionConsumer> TCC,
2684 TypoDiagnosticGenerator TDG,
2685 TypoRecoveryCallback TRC);
2687 // \brief The set of known/encountered (unique, canonicalized) NamespaceDecls.
2689 // The boolean value will be true to indicate that the namespace was loaded
2690 // from an AST/PCH file, or false otherwise.
2691 llvm::MapVector<NamespaceDecl*, bool> KnownNamespaces;
2693 /// \brief Whether we have already loaded known namespaces from an extenal
2695 bool LoadedExternalKnownNamespaces;
2697 /// \brief Helper for CorrectTypo and CorrectTypoDelayed used to create and
2698 /// populate a new TypoCorrectionConsumer. Returns nullptr if typo correction
2699 /// should be skipped entirely.
2700 std::unique_ptr<TypoCorrectionConsumer>
2701 makeTypoCorrectionConsumer(const DeclarationNameInfo &Typo,
2702 Sema::LookupNameKind LookupKind, Scope *S,
2704 std::unique_ptr<CorrectionCandidateCallback> CCC,
2705 DeclContext *MemberContext, bool EnteringContext,
2706 const ObjCObjectPointerType *OPT,
2707 bool ErrorRecovery);
2710 const TypoExprState &getTypoExprState(TypoExpr *TE) const;
2712 /// \brief Clears the state of the given TypoExpr.
2713 void clearDelayedTypo(TypoExpr *TE);
2715 /// \brief Look up a name, looking for a single declaration. Return
2716 /// null if the results were absent, ambiguous, or overloaded.
2718 /// It is preferable to use the elaborated form and explicitly handle
2719 /// ambiguity and overloaded.
2720 NamedDecl *LookupSingleName(Scope *S, DeclarationName Name,
2722 LookupNameKind NameKind,
2723 RedeclarationKind Redecl
2724 = NotForRedeclaration);
2725 bool LookupName(LookupResult &R, Scope *S,
2726 bool AllowBuiltinCreation = false);
2727 bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
2728 bool InUnqualifiedLookup = false);
2729 bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
2731 bool LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS,
2732 bool AllowBuiltinCreation = false,
2733 bool EnteringContext = false);
2734 ObjCProtocolDecl *LookupProtocol(IdentifierInfo *II, SourceLocation IdLoc,
2735 RedeclarationKind Redecl
2736 = NotForRedeclaration);
2737 bool LookupInSuper(LookupResult &R, CXXRecordDecl *Class);
2739 void LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S,
2740 QualType T1, QualType T2,
2741 UnresolvedSetImpl &Functions);
2742 void addOverloadedOperatorToUnresolvedSet(UnresolvedSetImpl &Functions,
2743 DeclAccessPair Operator,
2744 QualType T1, QualType T2);
2746 LabelDecl *LookupOrCreateLabel(IdentifierInfo *II, SourceLocation IdentLoc,
2747 SourceLocation GnuLabelLoc = SourceLocation());
2749 DeclContextLookupResult LookupConstructors(CXXRecordDecl *Class);
2750 CXXConstructorDecl *LookupDefaultConstructor(CXXRecordDecl *Class);
2751 CXXConstructorDecl *LookupCopyingConstructor(CXXRecordDecl *Class,
2753 CXXMethodDecl *LookupCopyingAssignment(CXXRecordDecl *Class, unsigned Quals,
2754 bool RValueThis, unsigned ThisQuals);
2755 CXXConstructorDecl *LookupMovingConstructor(CXXRecordDecl *Class,
2757 CXXMethodDecl *LookupMovingAssignment(CXXRecordDecl *Class, unsigned Quals,
2758 bool RValueThis, unsigned ThisQuals);
2759 CXXDestructorDecl *LookupDestructor(CXXRecordDecl *Class);
2761 bool checkLiteralOperatorId(const CXXScopeSpec &SS, const UnqualifiedId &Id);
2762 LiteralOperatorLookupResult LookupLiteralOperator(Scope *S, LookupResult &R,
2763 ArrayRef<QualType> ArgTys,
2766 bool AllowStringTemplate);
2767 bool isKnownName(StringRef name);
2769 void ArgumentDependentLookup(DeclarationName Name, SourceLocation Loc,
2770 ArrayRef<Expr *> Args, ADLResult &Functions);
2772 void LookupVisibleDecls(Scope *S, LookupNameKind Kind,
2773 VisibleDeclConsumer &Consumer,
2774 bool IncludeGlobalScope = true);
2775 void LookupVisibleDecls(DeclContext *Ctx, LookupNameKind Kind,
2776 VisibleDeclConsumer &Consumer,
2777 bool IncludeGlobalScope = true);
2779 enum CorrectTypoKind {
2780 CTK_NonError, // CorrectTypo used in a non error recovery situation.
2781 CTK_ErrorRecovery // CorrectTypo used in normal error recovery.
2784 TypoCorrection CorrectTypo(const DeclarationNameInfo &Typo,
2785 Sema::LookupNameKind LookupKind,
2786 Scope *S, CXXScopeSpec *SS,
2787 std::unique_ptr<CorrectionCandidateCallback> CCC,
2788 CorrectTypoKind Mode,
2789 DeclContext *MemberContext = nullptr,
2790 bool EnteringContext = false,
2791 const ObjCObjectPointerType *OPT = nullptr,
2792 bool RecordFailure = true);
2794 TypoExpr *CorrectTypoDelayed(const DeclarationNameInfo &Typo,
2795 Sema::LookupNameKind LookupKind, Scope *S,
2797 std::unique_ptr<CorrectionCandidateCallback> CCC,
2798 TypoDiagnosticGenerator TDG,
2799 TypoRecoveryCallback TRC, CorrectTypoKind Mode,
2800 DeclContext *MemberContext = nullptr,
2801 bool EnteringContext = false,
2802 const ObjCObjectPointerType *OPT = nullptr);
2804 /// \brief Process any TypoExprs in the given Expr and its children,
2805 /// generating diagnostics as appropriate and returning a new Expr if there
2806 /// were typos that were all successfully corrected and ExprError if one or
2807 /// more typos could not be corrected.
2809 /// \param E The Expr to check for TypoExprs.
2811 /// \param InitDecl A VarDecl to avoid because the Expr being corrected is its
2814 /// \param Filter A function applied to a newly rebuilt Expr to determine if
2815 /// it is an acceptable/usable result from a single combination of typo
2816 /// corrections. As long as the filter returns ExprError, different
2817 /// combinations of corrections will be tried until all are exhausted.
2819 CorrectDelayedTyposInExpr(Expr *E, VarDecl *InitDecl = nullptr,
2820 llvm::function_ref<ExprResult(Expr *)> Filter =
2821 [](Expr *E) -> ExprResult { return E; });
2824 CorrectDelayedTyposInExpr(Expr *E,
2825 llvm::function_ref<ExprResult(Expr *)> Filter) {
2826 return CorrectDelayedTyposInExpr(E, nullptr, Filter);
2830 CorrectDelayedTyposInExpr(ExprResult ER, VarDecl *InitDecl = nullptr,
2831 llvm::function_ref<ExprResult(Expr *)> Filter =
2832 [](Expr *E) -> ExprResult { return E; }) {
2833 return ER.isInvalid() ? ER : CorrectDelayedTyposInExpr(ER.get(), Filter);
2837 CorrectDelayedTyposInExpr(ExprResult ER,
2838 llvm::function_ref<ExprResult(Expr *)> Filter) {
2839 return CorrectDelayedTyposInExpr(ER, nullptr, Filter);
2842 void diagnoseTypo(const TypoCorrection &Correction,
2843 const PartialDiagnostic &TypoDiag,
2844 bool ErrorRecovery = true);
2846 void diagnoseTypo(const TypoCorrection &Correction,
2847 const PartialDiagnostic &TypoDiag,
2848 const PartialDiagnostic &PrevNote,
2849 bool ErrorRecovery = true);
2851 void FindAssociatedClassesAndNamespaces(SourceLocation InstantiationLoc,
2852 ArrayRef<Expr *> Args,
2853 AssociatedNamespaceSet &AssociatedNamespaces,
2854 AssociatedClassSet &AssociatedClasses);
2856 void FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S,
2857 bool ConsiderLinkage, bool AllowInlineNamespace);
2859 void DiagnoseAmbiguousLookup(LookupResult &Result);
2862 ObjCInterfaceDecl *getObjCInterfaceDecl(IdentifierInfo *&Id,
2863 SourceLocation IdLoc,
2864 bool TypoCorrection = false);
2865 NamedDecl *LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID,
2866 Scope *S, bool ForRedeclaration,
2867 SourceLocation Loc);
2868 NamedDecl *ImplicitlyDefineFunction(SourceLocation Loc, IdentifierInfo &II,
2870 void AddKnownFunctionAttributes(FunctionDecl *FD);
2872 // More parsing and symbol table subroutines.
2874 void ProcessPragmaWeak(Scope *S, Decl *D);
2875 // Decl attributes - this routine is the top level dispatcher.
2876 void ProcessDeclAttributes(Scope *S, Decl *D, const Declarator &PD);
2877 void ProcessDeclAttributeList(Scope *S, Decl *D, const AttributeList *AL,
2878 bool IncludeCXX11Attributes = true);
2879 bool ProcessAccessDeclAttributeList(AccessSpecDecl *ASDecl,
2880 const AttributeList *AttrList);
2882 void checkUnusedDeclAttributes(Declarator &D);
2884 /// Determine if type T is a valid subject for a nonnull and similar
2885 /// attributes. By default, we look through references (the behavior used by
2886 /// nonnull), but if the second parameter is true, then we treat a reference
2888 bool isValidPointerAttrType(QualType T, bool RefOkay = false);
2890 bool CheckRegparmAttr(const AttributeList &attr, unsigned &value);
2891 bool CheckCallingConvAttr(const AttributeList &attr, CallingConv &CC,
2892 const FunctionDecl *FD = nullptr);
2893 bool CheckNoReturnAttr(const AttributeList &attr);
2894 bool checkStringLiteralArgumentAttr(const AttributeList &Attr,
2895 unsigned ArgNum, StringRef &Str,
2896 SourceLocation *ArgLocation = nullptr);
2897 bool checkSectionName(SourceLocation LiteralLoc, StringRef Str);
2898 void checkTargetAttr(SourceLocation LiteralLoc, StringRef Str);
2899 bool checkMSInheritanceAttrOnDefinition(
2900 CXXRecordDecl *RD, SourceRange Range, bool BestCase,
2901 MSInheritanceAttr::Spelling SemanticSpelling);
2903 void CheckAlignasUnderalignment(Decl *D);
2905 /// Adjust the calling convention of a method to be the ABI default if it
2906 /// wasn't specified explicitly. This handles method types formed from
2907 /// function type typedefs and typename template arguments.
2908 void adjustMemberFunctionCC(QualType &T, bool IsStatic);
2910 // Check if there is an explicit attribute, but only look through parens.
2911 // The intent is to look for an attribute on the current declarator, but not
2912 // one that came from a typedef.
2913 bool hasExplicitCallingConv(QualType &T);
2915 /// Get the outermost AttributedType node that sets a calling convention.
2916 /// Valid types should not have multiple attributes with different CCs.
2917 const AttributedType *getCallingConvAttributedType(QualType T) const;
2919 /// Check whether a nullability type specifier can be added to the given
2922 /// \param type The type to which the nullability specifier will be
2923 /// added. On success, this type will be updated appropriately.
2925 /// \param nullability The nullability specifier to add.
2927 /// \param nullabilityLoc The location of the nullability specifier.
2929 /// \param isContextSensitive Whether this nullability specifier was
2930 /// written as a context-sensitive keyword (in an Objective-C
2931 /// method) or an Objective-C property attribute, rather than as an
2932 /// underscored type specifier.
2934 /// \returns true if nullability cannot be applied, false otherwise.
2935 bool checkNullabilityTypeSpecifier(QualType &type, NullabilityKind nullability,
2936 SourceLocation nullabilityLoc,
2937 bool isContextSensitive);
2939 /// \brief Stmt attributes - this routine is the top level dispatcher.
2940 StmtResult ProcessStmtAttributes(Stmt *Stmt, AttributeList *Attrs,
2943 void WarnConflictingTypedMethods(ObjCMethodDecl *Method,
2944 ObjCMethodDecl *MethodDecl,
2945 bool IsProtocolMethodDecl);
2947 void CheckConflictingOverridingMethod(ObjCMethodDecl *Method,
2948 ObjCMethodDecl *Overridden,
2949 bool IsProtocolMethodDecl);
2951 /// WarnExactTypedMethods - This routine issues a warning if method
2952 /// implementation declaration matches exactly that of its declaration.
2953 void WarnExactTypedMethods(ObjCMethodDecl *Method,
2954 ObjCMethodDecl *MethodDecl,
2955 bool IsProtocolMethodDecl);
2957 typedef llvm::SmallPtrSet<Selector, 8> SelectorSet;
2958 typedef llvm::DenseMap<Selector, ObjCMethodDecl*> ProtocolsMethodsMap;
2960 /// CheckImplementationIvars - This routine checks if the instance variables
2961 /// listed in the implelementation match those listed in the interface.
2962 void CheckImplementationIvars(ObjCImplementationDecl *ImpDecl,
2963 ObjCIvarDecl **Fields, unsigned nIvars,
2964 SourceLocation Loc);
2966 /// ImplMethodsVsClassMethods - This is main routine to warn if any method
2967 /// remains unimplemented in the class or category \@implementation.
2968 void ImplMethodsVsClassMethods(Scope *S, ObjCImplDecl* IMPDecl,
2969 ObjCContainerDecl* IDecl,
2970 bool IncompleteImpl = false);
2972 /// DiagnoseUnimplementedProperties - This routine warns on those properties
2973 /// which must be implemented by this implementation.
2974 void DiagnoseUnimplementedProperties(Scope *S, ObjCImplDecl* IMPDecl,
2975 ObjCContainerDecl *CDecl,
2976 bool SynthesizeProperties);
2978 /// Diagnose any null-resettable synthesized setters.
2979 void diagnoseNullResettableSynthesizedSetters(ObjCImplDecl *impDecl);
2981 /// DefaultSynthesizeProperties - This routine default synthesizes all
2982 /// properties which must be synthesized in the class's \@implementation.
2983 void DefaultSynthesizeProperties (Scope *S, ObjCImplDecl* IMPDecl,
2984 ObjCInterfaceDecl *IDecl);
2985 void DefaultSynthesizeProperties(Scope *S, Decl *D);
2987 /// IvarBacksCurrentMethodAccessor - This routine returns 'true' if 'IV' is
2988 /// an ivar synthesized for 'Method' and 'Method' is a property accessor
2989 /// declared in class 'IFace'.
2990 bool IvarBacksCurrentMethodAccessor(ObjCInterfaceDecl *IFace,
2991 ObjCMethodDecl *Method, ObjCIvarDecl *IV);
2993 /// DiagnoseUnusedBackingIvarInAccessor - Issue an 'unused' warning if ivar which
2994 /// backs the property is not used in the property's accessor.
2995 void DiagnoseUnusedBackingIvarInAccessor(Scope *S,
2996 const ObjCImplementationDecl *ImplD);
2998 /// GetIvarBackingPropertyAccessor - If method is a property setter/getter and
2999 /// it property has a backing ivar, returns this ivar; otherwise, returns NULL.
3000 /// It also returns ivar's property on success.
3001 ObjCIvarDecl *GetIvarBackingPropertyAccessor(const ObjCMethodDecl *Method,
3002 const ObjCPropertyDecl *&PDecl) const;
3004 /// Called by ActOnProperty to handle \@property declarations in
3005 /// class extensions.
3006 ObjCPropertyDecl *HandlePropertyInClassExtension(Scope *S,
3007 SourceLocation AtLoc,
3008 SourceLocation LParenLoc,
3009 FieldDeclarator &FD,
3012 const bool isAssign,
3013 const bool isReadWrite,
3014 const unsigned Attributes,
3015 const unsigned AttributesAsWritten,
3016 bool *isOverridingProperty,
3018 TypeSourceInfo *TSI,
3019 tok::ObjCKeywordKind MethodImplKind);
3021 /// Called by ActOnProperty and HandlePropertyInClassExtension to
3022 /// handle creating the ObjcPropertyDecl for a category or \@interface.
3023 ObjCPropertyDecl *CreatePropertyDecl(Scope *S,
3024 ObjCContainerDecl *CDecl,
3025 SourceLocation AtLoc,
3026 SourceLocation LParenLoc,
3027 FieldDeclarator &FD,
3030 const bool isAssign,
3031 const bool isReadWrite,
3032 const unsigned Attributes,
3033 const unsigned AttributesAsWritten,
3035 TypeSourceInfo *TSI,
3036 tok::ObjCKeywordKind MethodImplKind,
3037 DeclContext *lexicalDC = nullptr);
3039 /// AtomicPropertySetterGetterRules - This routine enforces the rule (via
3040 /// warning) when atomic property has one but not the other user-declared
3041 /// setter or getter.
3042 void AtomicPropertySetterGetterRules(ObjCImplDecl* IMPDecl,
3043 ObjCContainerDecl* IDecl);
3045 void DiagnoseOwningPropertyGetterSynthesis(const ObjCImplementationDecl *D);
3047 void DiagnoseMissingDesignatedInitOverrides(
3048 const ObjCImplementationDecl *ImplD,
3049 const ObjCInterfaceDecl *IFD);
3051 void DiagnoseDuplicateIvars(ObjCInterfaceDecl *ID, ObjCInterfaceDecl *SID);
3053 enum MethodMatchStrategy {
3058 /// MatchTwoMethodDeclarations - Checks if two methods' type match and returns
3059 /// true, or false, accordingly.
3060 bool MatchTwoMethodDeclarations(const ObjCMethodDecl *Method,
3061 const ObjCMethodDecl *PrevMethod,
3062 MethodMatchStrategy strategy = MMS_strict);
3064 /// MatchAllMethodDeclarations - Check methods declaraed in interface or
3065 /// or protocol against those declared in their implementations.
3066 void MatchAllMethodDeclarations(const SelectorSet &InsMap,
3067 const SelectorSet &ClsMap,
3068 SelectorSet &InsMapSeen,
3069 SelectorSet &ClsMapSeen,
3070 ObjCImplDecl* IMPDecl,
3071 ObjCContainerDecl* IDecl,
3072 bool &IncompleteImpl,
3073 bool ImmediateClass,
3074 bool WarnCategoryMethodImpl=false);
3076 /// CheckCategoryVsClassMethodMatches - Checks that methods implemented in
3077 /// category matches with those implemented in its primary class and
3078 /// warns each time an exact match is found.
3079 void CheckCategoryVsClassMethodMatches(ObjCCategoryImplDecl *CatIMP);
3081 /// \brief Add the given method to the list of globally-known methods.
3082 void addMethodToGlobalList(ObjCMethodList *List, ObjCMethodDecl *Method);
3085 /// AddMethodToGlobalPool - Add an instance or factory method to the global
3086 /// pool. See descriptoin of AddInstanceMethodToGlobalPool.
3087 void AddMethodToGlobalPool(ObjCMethodDecl *Method, bool impl, bool instance);
3089 /// LookupMethodInGlobalPool - Returns the instance or factory method and
3090 /// optionally warns if there are multiple signatures.
3091 ObjCMethodDecl *LookupMethodInGlobalPool(Selector Sel, SourceRange R,
3092 bool receiverIdOrClass,
3096 /// \brief - Returns instance or factory methods in global method pool for
3097 /// given selector. If no such method or only one method found, function returns
3098 /// false; otherwise, it returns true
3099 bool CollectMultipleMethodsInGlobalPool(Selector Sel,
3100 SmallVectorImpl<ObjCMethodDecl*>& Methods,
3103 bool AreMultipleMethodsInGlobalPool(Selector Sel, ObjCMethodDecl *BestMethod,
3105 bool receiverIdOrClass);
3107 void DiagnoseMultipleMethodInGlobalPool(SmallVectorImpl<ObjCMethodDecl*> &Methods,
3108 Selector Sel, SourceRange R,
3109 bool receiverIdOrClass);
3112 /// \brief - Returns a selector which best matches given argument list or
3113 /// nullptr if none could be found
3114 ObjCMethodDecl *SelectBestMethod(Selector Sel, MultiExprArg Args,
3118 /// \brief Record the typo correction failure and return an empty correction.
3119 TypoCorrection FailedCorrection(IdentifierInfo *Typo, SourceLocation TypoLoc,
3120 bool RecordFailure = true) {
3122 TypoCorrectionFailures[Typo].insert(TypoLoc);
3123 return TypoCorrection();
3127 /// AddInstanceMethodToGlobalPool - All instance methods in a translation
3128 /// unit are added to a global pool. This allows us to efficiently associate
3129 /// a selector with a method declaraation for purposes of typechecking
3130 /// messages sent to "id" (where the class of the object is unknown).
3131 void AddInstanceMethodToGlobalPool(ObjCMethodDecl *Method, bool impl=false) {
3132 AddMethodToGlobalPool(Method, impl, /*instance*/true);
3135 /// AddFactoryMethodToGlobalPool - Same as above, but for factory methods.
3136 void AddFactoryMethodToGlobalPool(ObjCMethodDecl *Method, bool impl=false) {
3137 AddMethodToGlobalPool(Method, impl, /*instance*/false);
3140 /// AddAnyMethodToGlobalPool - Add any method, instance or factory to global
3142 void AddAnyMethodToGlobalPool(Decl *D);
3144 /// LookupInstanceMethodInGlobalPool - Returns the method and warns if
3145 /// there are multiple signatures.
3146 ObjCMethodDecl *LookupInstanceMethodInGlobalPool(Selector Sel, SourceRange R,
3147 bool receiverIdOrClass=false) {
3148 return LookupMethodInGlobalPool(Sel, R, receiverIdOrClass,
3152 /// LookupFactoryMethodInGlobalPool - Returns the method and warns if
3153 /// there are multiple signatures.
3154 ObjCMethodDecl *LookupFactoryMethodInGlobalPool(Selector Sel, SourceRange R,
3155 bool receiverIdOrClass=false) {
3156 return LookupMethodInGlobalPool(Sel, R, receiverIdOrClass,
3160 const ObjCMethodDecl *SelectorsForTypoCorrection(Selector Sel,
3161 QualType ObjectType=QualType());
3162 /// LookupImplementedMethodInGlobalPool - Returns the method which has an
3164 ObjCMethodDecl *LookupImplementedMethodInGlobalPool(Selector Sel);
3166 /// CollectIvarsToConstructOrDestruct - Collect those ivars which require
3168 void CollectIvarsToConstructOrDestruct(ObjCInterfaceDecl *OI,
3169 SmallVectorImpl<ObjCIvarDecl*> &Ivars);
3171 //===--------------------------------------------------------------------===//
3172 // Statement Parsing Callbacks: SemaStmt.cpp.
3176 FullExprArg(Sema &actions) : E(nullptr) { }
3178 ExprResult release() {
3182 Expr *get() const { return E; }
3184 Expr *operator->() {
3189 // FIXME: No need to make the entire Sema class a friend when it's just
3190 // Sema::MakeFullExpr that needs access to the constructor below.
3193 explicit FullExprArg(Expr *expr) : E(expr) {}
3198 FullExprArg MakeFullExpr(Expr *Arg) {
3199 return MakeFullExpr(Arg, Arg ? Arg->getExprLoc() : SourceLocation());
3201 FullExprArg MakeFullExpr(Expr *Arg, SourceLocation CC) {
3202 return FullExprArg(ActOnFinishFullExpr(Arg, CC).get());
3204 FullExprArg MakeFullDiscardedValueExpr(Expr *Arg) {
3206 ActOnFinishFullExpr(Arg, Arg ? Arg->getExprLoc() : SourceLocation(),
3207 /*DiscardedValue*/ true);
3208 return FullExprArg(FE.get());
3211 StmtResult ActOnExprStmt(ExprResult Arg);
3212 StmtResult ActOnExprStmtError();
3214 StmtResult ActOnNullStmt(SourceLocation SemiLoc,
3215 bool HasLeadingEmptyMacro = false);
3217 void ActOnStartOfCompoundStmt();
3218 void ActOnFinishOfCompoundStmt();
3219 StmtResult ActOnCompoundStmt(SourceLocation L, SourceLocation R,
3220 ArrayRef<Stmt *> Elts, bool isStmtExpr);
3222 /// \brief A RAII object to enter scope of a compound statement.
3223 class CompoundScopeRAII {
3225 CompoundScopeRAII(Sema &S): S(S) {
3226 S.ActOnStartOfCompoundStmt();
3229 ~CompoundScopeRAII() {
3230 S.ActOnFinishOfCompoundStmt();
3237 /// An RAII helper that pops function a function scope on exit.
3238 struct FunctionScopeRAII {
3241 FunctionScopeRAII(Sema &S) : S(S), Active(true) {}
3242 ~FunctionScopeRAII() {
3244 S.PopFunctionScopeInfo();
3246 void disable() { Active = false; }
3249 StmtResult ActOnDeclStmt(DeclGroupPtrTy Decl,
3250 SourceLocation StartLoc,
3251 SourceLocation EndLoc);
3252 void ActOnForEachDeclStmt(DeclGroupPtrTy Decl);
3253 StmtResult ActOnForEachLValueExpr(Expr *E);
3254 StmtResult ActOnCaseStmt(SourceLocation CaseLoc, Expr *LHSVal,
3255 SourceLocation DotDotDotLoc, Expr *RHSVal,
3256 SourceLocation ColonLoc);
3257 void ActOnCaseStmtBody(Stmt *CaseStmt, Stmt *SubStmt);
3259 StmtResult ActOnDefaultStmt(SourceLocation DefaultLoc,
3260 SourceLocation ColonLoc,
3261 Stmt *SubStmt, Scope *CurScope);
3262 StmtResult ActOnLabelStmt(SourceLocation IdentLoc, LabelDecl *TheDecl,
3263 SourceLocation ColonLoc, Stmt *SubStmt);
3265 StmtResult ActOnAttributedStmt(SourceLocation AttrLoc,
3266 ArrayRef<const Attr*> Attrs,
3269 StmtResult ActOnIfStmt(SourceLocation IfLoc,
3270 FullExprArg CondVal, Decl *CondVar,
3272 SourceLocation ElseLoc, Stmt *ElseVal);
3273 StmtResult ActOnStartOfSwitchStmt(SourceLocation SwitchLoc,
3276 StmtResult ActOnFinishSwitchStmt(SourceLocation SwitchLoc,
3277 Stmt *Switch, Stmt *Body);
3278 StmtResult ActOnWhileStmt(SourceLocation WhileLoc,
3280 Decl *CondVar, Stmt *Body);
3281 StmtResult ActOnDoStmt(SourceLocation DoLoc, Stmt *Body,
3282 SourceLocation WhileLoc,
3283 SourceLocation CondLParen, Expr *Cond,
3284 SourceLocation CondRParen);
3286 StmtResult ActOnForStmt(SourceLocation ForLoc,
3287 SourceLocation LParenLoc,
3288 Stmt *First, FullExprArg Second,
3291 SourceLocation RParenLoc,
3293 ExprResult CheckObjCForCollectionOperand(SourceLocation forLoc,
3295 StmtResult ActOnObjCForCollectionStmt(SourceLocation ForColLoc,
3296 Stmt *First, Expr *collection,
3297 SourceLocation RParenLoc);
3298 StmtResult FinishObjCForCollectionStmt(Stmt *ForCollection, Stmt *Body);
3300 enum BuildForRangeKind {
3301 /// Initial building of a for-range statement.
3303 /// Instantiation or recovery rebuild of a for-range statement. Don't
3304 /// attempt any typo-correction.
3306 /// Determining whether a for-range statement could be built. Avoid any
3307 /// unnecessary or irreversible actions.
3311 StmtResult ActOnCXXForRangeStmt(SourceLocation ForLoc, Stmt *LoopVar,
3312 SourceLocation ColonLoc, Expr *Collection,
3313 SourceLocation RParenLoc,
3314 BuildForRangeKind Kind);
3315 StmtResult BuildCXXForRangeStmt(SourceLocation ForLoc,
3316 SourceLocation ColonLoc,
3317 Stmt *RangeDecl, Stmt *BeginEndDecl,
3318 Expr *Cond, Expr *Inc,
3320 SourceLocation RParenLoc,
3321 BuildForRangeKind Kind);
3322 StmtResult FinishCXXForRangeStmt(Stmt *ForRange, Stmt *Body);
3324 StmtResult ActOnGotoStmt(SourceLocation GotoLoc,
3325 SourceLocation LabelLoc,
3326 LabelDecl *TheDecl);
3327 StmtResult ActOnIndirectGotoStmt(SourceLocation GotoLoc,
3328 SourceLocation StarLoc,
3330 StmtResult ActOnContinueStmt(SourceLocation ContinueLoc, Scope *CurScope);
3331 StmtResult ActOnBreakStmt(SourceLocation BreakLoc, Scope *CurScope);
3333 void ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope,
3334 CapturedRegionKind Kind, unsigned NumParams);
3335 typedef std::pair<StringRef, QualType> CapturedParamNameType;
3336 void ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope,
3337 CapturedRegionKind Kind,
3338 ArrayRef<CapturedParamNameType> Params);
3339 StmtResult ActOnCapturedRegionEnd(Stmt *S);
3340 void ActOnCapturedRegionError();
3341 RecordDecl *CreateCapturedStmtRecordDecl(CapturedDecl *&CD,
3343 unsigned NumParams);
3344 VarDecl *getCopyElisionCandidate(QualType ReturnType, Expr *E,
3345 bool AllowFunctionParameters);
3346 bool isCopyElisionCandidate(QualType ReturnType, const VarDecl *VD,
3347 bool AllowFunctionParameters);
3349 StmtResult ActOnReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp,
3351 StmtResult BuildReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp);
3352 StmtResult ActOnCapScopeReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp);
3354 StmtResult ActOnGCCAsmStmt(SourceLocation AsmLoc, bool IsSimple,
3355 bool IsVolatile, unsigned NumOutputs,
3356 unsigned NumInputs, IdentifierInfo **Names,
3357 MultiExprArg Constraints, MultiExprArg Exprs,
3358 Expr *AsmString, MultiExprArg Clobbers,
3359 SourceLocation RParenLoc);
3361 ExprResult LookupInlineAsmIdentifier(CXXScopeSpec &SS,
3362 SourceLocation TemplateKWLoc,
3364 llvm::InlineAsmIdentifierInfo &Info,
3365 bool IsUnevaluatedContext);
3366 bool LookupInlineAsmField(StringRef Base, StringRef Member,
3367 unsigned &Offset, SourceLocation AsmLoc);
3368 StmtResult ActOnMSAsmStmt(SourceLocation AsmLoc, SourceLocation LBraceLoc,
3369 ArrayRef<Token> AsmToks,
3370 StringRef AsmString,
3371 unsigned NumOutputs, unsigned NumInputs,
3372 ArrayRef<StringRef> Constraints,
3373 ArrayRef<StringRef> Clobbers,
3374 ArrayRef<Expr*> Exprs,
3375 SourceLocation EndLoc);
3376 LabelDecl *GetOrCreateMSAsmLabel(StringRef ExternalLabelName,
3377 SourceLocation Location,
3380 VarDecl *BuildObjCExceptionDecl(TypeSourceInfo *TInfo, QualType ExceptionType,
3381 SourceLocation StartLoc,
3382 SourceLocation IdLoc, IdentifierInfo *Id,
3383 bool Invalid = false);
3385 Decl *ActOnObjCExceptionDecl(Scope *S, Declarator &D);
3387 StmtResult ActOnObjCAtCatchStmt(SourceLocation AtLoc, SourceLocation RParen,
3388 Decl *Parm, Stmt *Body);
3390 StmtResult ActOnObjCAtFinallyStmt(SourceLocation AtLoc, Stmt *Body);
3392 StmtResult ActOnObjCAtTryStmt(SourceLocation AtLoc, Stmt *Try,
3393 MultiStmtArg Catch, Stmt *Finally);
3395 StmtResult BuildObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw);
3396 StmtResult ActOnObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw,
3398 ExprResult ActOnObjCAtSynchronizedOperand(SourceLocation atLoc,
3400 StmtResult ActOnObjCAtSynchronizedStmt(SourceLocation AtLoc,
3404 StmtResult ActOnObjCAutoreleasePoolStmt(SourceLocation AtLoc, Stmt *Body);
3406 VarDecl *BuildExceptionDeclaration(Scope *S, TypeSourceInfo *TInfo,
3407 SourceLocation StartLoc,
3408 SourceLocation IdLoc,
3409 IdentifierInfo *Id);
3411 Decl *ActOnExceptionDeclarator(Scope *S, Declarator &D);
3413 StmtResult ActOnCXXCatchBlock(SourceLocation CatchLoc,
3414 Decl *ExDecl, Stmt *HandlerBlock);
3415 StmtResult ActOnCXXTryBlock(SourceLocation TryLoc, Stmt *TryBlock,
3416 ArrayRef<Stmt *> Handlers);
3418 StmtResult ActOnSEHTryBlock(bool IsCXXTry, // try (true) or __try (false) ?
3419 SourceLocation TryLoc, Stmt *TryBlock,
3421 StmtResult ActOnSEHExceptBlock(SourceLocation Loc,
3424 void ActOnStartSEHFinallyBlock();
3425 void ActOnAbortSEHFinallyBlock();
3426 StmtResult ActOnFinishSEHFinallyBlock(SourceLocation Loc, Stmt *Block);
3427 StmtResult ActOnSEHLeaveStmt(SourceLocation Loc, Scope *CurScope);
3429 void DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock);
3431 bool ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const;
3433 /// \brief If it's a file scoped decl that must warn if not used, keep track
3435 void MarkUnusedFileScopedDecl(const DeclaratorDecl *D);
3437 /// DiagnoseUnusedExprResult - If the statement passed in is an expression
3438 /// whose result is unused, warn.
3439 void DiagnoseUnusedExprResult(const Stmt *S);
3440 void DiagnoseUnusedNestedTypedefs(const RecordDecl *D);
3441 void DiagnoseUnusedDecl(const NamedDecl *ND);
3443 /// Emit \p DiagID if statement located on \p StmtLoc has a suspicious null
3444 /// statement as a \p Body, and it is located on the same line.
3446 /// This helps prevent bugs due to typos, such as:
3449 void DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
3453 /// Warn if a for/while loop statement \p S, which is followed by
3454 /// \p PossibleBody, has a suspicious null statement as a body.
3455 void DiagnoseEmptyLoopBody(const Stmt *S,
3456 const Stmt *PossibleBody);
3458 /// Warn if a value is moved to itself.
3459 void DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
3460 SourceLocation OpLoc);
3462 ParsingDeclState PushParsingDeclaration(sema::DelayedDiagnosticPool &pool) {
3463 return DelayedDiagnostics.push(pool);
3465 void PopParsingDeclaration(ParsingDeclState state, Decl *decl);
3467 typedef ProcessingContextState ParsingClassState;
3468 ParsingClassState PushParsingClass() {
3469 return DelayedDiagnostics.pushUndelayed();
3471 void PopParsingClass(ParsingClassState state) {
3472 DelayedDiagnostics.popUndelayed(state);
3475 void redelayDiagnostics(sema::DelayedDiagnosticPool &pool);
3477 enum AvailabilityDiagnostic { AD_Deprecation, AD_Unavailable, AD_Partial };
3479 void EmitAvailabilityWarning(AvailabilityDiagnostic AD,
3480 NamedDecl *D, StringRef Message,
3482 const ObjCInterfaceDecl *UnknownObjCClass,
3483 const ObjCPropertyDecl *ObjCProperty,
3484 bool ObjCPropertyAccess);
3486 bool makeUnavailableInSystemHeader(SourceLocation loc,
3489 //===--------------------------------------------------------------------===//
3490 // Expression Parsing Callbacks: SemaExpr.cpp.
3492 bool CanUseDecl(NamedDecl *D);
3493 bool DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc,
3494 const ObjCInterfaceDecl *UnknownObjCClass=nullptr,
3495 bool ObjCPropertyAccess=false);
3496 void NoteDeletedFunction(FunctionDecl *FD);
3497 std::string getDeletedOrUnavailableSuffix(const FunctionDecl *FD);
3498 bool DiagnosePropertyAccessorMismatch(ObjCPropertyDecl *PD,
3499 ObjCMethodDecl *Getter,
3500 SourceLocation Loc);
3501 void DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
3502 ArrayRef<Expr *> Args);
3504 void PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
3505 Decl *LambdaContextDecl = nullptr,
3506 bool IsDecltype = false);
3507 enum ReuseLambdaContextDecl_t { ReuseLambdaContextDecl };
3508 void PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
3509 ReuseLambdaContextDecl_t,
3510 bool IsDecltype = false);
3511 void PopExpressionEvaluationContext();
3513 void DiscardCleanupsInEvaluationContext();
3515 ExprResult TransformToPotentiallyEvaluated(Expr *E);
3516 ExprResult HandleExprEvaluationContextForTypeof(Expr *E);
3518 ExprResult ActOnConstantExpression(ExprResult Res);
3520 // Functions for marking a declaration referenced. These functions also
3521 // contain the relevant logic for marking if a reference to a function or
3522 // variable is an odr-use (in the C++11 sense). There are separate variants
3523 // for expressions referring to a decl; these exist because odr-use marking
3524 // needs to be delayed for some constant variables when we build one of the
3525 // named expressions.
3526 void MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, bool OdrUse);
3527 void MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func,
3528 bool OdrUse = true);
3529 void MarkVariableReferenced(SourceLocation Loc, VarDecl *Var);
3530 void MarkDeclRefReferenced(DeclRefExpr *E);
3531 void MarkMemberReferenced(MemberExpr *E);
3533 void UpdateMarkingForLValueToRValue(Expr *E);
3534 void CleanupVarDeclMarking();
3536 enum TryCaptureKind {
3537 TryCapture_Implicit, TryCapture_ExplicitByVal, TryCapture_ExplicitByRef
3540 /// \brief Try to capture the given variable.
3542 /// \param Var The variable to capture.
3544 /// \param Loc The location at which the capture occurs.
3546 /// \param Kind The kind of capture, which may be implicit (for either a
3547 /// block or a lambda), or explicit by-value or by-reference (for a lambda).
3549 /// \param EllipsisLoc The location of the ellipsis, if one is provided in
3550 /// an explicit lambda capture.
3552 /// \param BuildAndDiagnose Whether we are actually supposed to add the
3553 /// captures or diagnose errors. If false, this routine merely check whether
3554 /// the capture can occur without performing the capture itself or complaining
3555 /// if the variable cannot be captured.
3557 /// \param CaptureType Will be set to the type of the field used to capture
3558 /// this variable in the innermost block or lambda. Only valid when the
3559 /// variable can be captured.
3561 /// \param DeclRefType Will be set to the type of a reference to the capture
3562 /// from within the current scope. Only valid when the variable can be
3565 /// \param FunctionScopeIndexToStopAt If non-null, it points to the index
3566 /// of the FunctionScopeInfo stack beyond which we do not attempt to capture.
3567 /// This is useful when enclosing lambdas must speculatively capture
3568 /// variables that may or may not be used in certain specializations of
3569 /// a nested generic lambda.
3571 /// \returns true if an error occurred (i.e., the variable cannot be
3572 /// captured) and false if the capture succeeded.
3573 bool tryCaptureVariable(VarDecl *Var, SourceLocation Loc, TryCaptureKind Kind,
3574 SourceLocation EllipsisLoc, bool BuildAndDiagnose,
3575 QualType &CaptureType,
3576 QualType &DeclRefType,
3577 const unsigned *const FunctionScopeIndexToStopAt);
3579 /// \brief Try to capture the given variable.
3580 bool tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
3581 TryCaptureKind Kind = TryCapture_Implicit,
3582 SourceLocation EllipsisLoc = SourceLocation());
3584 /// \brief Checks if the variable must be captured.
3585 bool NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc);
3587 /// \brief Given a variable, determine the type that a reference to that
3588 /// variable will have in the given scope.
3589 QualType getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc);
3591 void MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T);
3592 void MarkDeclarationsReferencedInExpr(Expr *E,
3593 bool SkipLocalVariables = false);
3595 /// \brief Try to recover by turning the given expression into a
3596 /// call. Returns true if recovery was attempted or an error was
3597 /// emitted; this may also leave the ExprResult invalid.
3598 bool tryToRecoverWithCall(ExprResult &E, const PartialDiagnostic &PD,
3599 bool ForceComplain = false,
3600 bool (*IsPlausibleResult)(QualType) = nullptr);
3602 /// \brief Figure out if an expression could be turned into a call.
3603 bool tryExprAsCall(Expr &E, QualType &ZeroArgCallReturnTy,
3604 UnresolvedSetImpl &NonTemplateOverloads);
3606 /// \brief Conditionally issue a diagnostic based on the current
3607 /// evaluation context.
3609 /// \param Statement If Statement is non-null, delay reporting the
3610 /// diagnostic until the function body is parsed, and then do a basic
3611 /// reachability analysis to determine if the statement is reachable.
3612 /// If it is unreachable, the diagnostic will not be emitted.
3613 bool DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
3614 const PartialDiagnostic &PD);
3616 // Primary Expressions.
3617 SourceRange getExprRange(Expr *E) const;
3619 ExprResult ActOnIdExpression(
3620 Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
3621 UnqualifiedId &Id, bool HasTrailingLParen, bool IsAddressOfOperand,
3622 std::unique_ptr<CorrectionCandidateCallback> CCC = nullptr,
3623 bool IsInlineAsmIdentifier = false, Token *KeywordReplacement = nullptr);
3625 void DecomposeUnqualifiedId(const UnqualifiedId &Id,
3626 TemplateArgumentListInfo &Buffer,
3627 DeclarationNameInfo &NameInfo,
3628 const TemplateArgumentListInfo *&TemplateArgs);
3631 DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
3632 std::unique_ptr<CorrectionCandidateCallback> CCC,
3633 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr,
3634 ArrayRef<Expr *> Args = None, TypoExpr **Out = nullptr);
3636 ExprResult LookupInObjCMethod(LookupResult &LookUp, Scope *S,
3638 bool AllowBuiltinCreation=false);
3640 ExprResult ActOnDependentIdExpression(const CXXScopeSpec &SS,
3641 SourceLocation TemplateKWLoc,
3642 const DeclarationNameInfo &NameInfo,
3643 bool isAddressOfOperand,
3644 const TemplateArgumentListInfo *TemplateArgs);
3646 ExprResult BuildDeclRefExpr(ValueDecl *D, QualType Ty,
3649 const CXXScopeSpec *SS = nullptr);
3651 BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
3652 const DeclarationNameInfo &NameInfo,
3653 const CXXScopeSpec *SS = nullptr,
3654 NamedDecl *FoundD = nullptr,
3655 const TemplateArgumentListInfo *TemplateArgs = nullptr);
3657 BuildAnonymousStructUnionMemberReference(
3658 const CXXScopeSpec &SS,
3659 SourceLocation nameLoc,
3660 IndirectFieldDecl *indirectField,
3661 DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_none),
3662 Expr *baseObjectExpr = nullptr,
3663 SourceLocation opLoc = SourceLocation());
3665 ExprResult BuildPossibleImplicitMemberExpr(const CXXScopeSpec &SS,
3666 SourceLocation TemplateKWLoc,
3668 const TemplateArgumentListInfo *TemplateArgs);
3669 ExprResult BuildImplicitMemberExpr(const CXXScopeSpec &SS,
3670 SourceLocation TemplateKWLoc,
3672 const TemplateArgumentListInfo *TemplateArgs,
3673 bool IsDefiniteInstance);
3674 bool UseArgumentDependentLookup(const CXXScopeSpec &SS,
3675 const LookupResult &R,
3676 bool HasTrailingLParen);
3678 ExprResult BuildQualifiedDeclarationNameExpr(
3679 CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo,
3680 bool IsAddressOfOperand, TypeSourceInfo **RecoveryTSI = nullptr);
3682 ExprResult BuildDependentDeclRefExpr(const CXXScopeSpec &SS,
3683 SourceLocation TemplateKWLoc,
3684 const DeclarationNameInfo &NameInfo,
3685 const TemplateArgumentListInfo *TemplateArgs);
3687 ExprResult BuildDeclarationNameExpr(const CXXScopeSpec &SS,
3690 bool AcceptInvalidDecl = false);
3691 ExprResult BuildDeclarationNameExpr(
3692 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
3693 NamedDecl *FoundD = nullptr,
3694 const TemplateArgumentListInfo *TemplateArgs = nullptr,
3695 bool AcceptInvalidDecl = false);
3697 ExprResult BuildLiteralOperatorCall(LookupResult &R,
3698 DeclarationNameInfo &SuffixInfo,
3699 ArrayRef<Expr *> Args,
3700 SourceLocation LitEndLoc,
3701 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr);
3703 ExprResult BuildPredefinedExpr(SourceLocation Loc,
3704 PredefinedExpr::IdentType IT);
3705 ExprResult ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind);
3706 ExprResult ActOnIntegerConstant(SourceLocation Loc, uint64_t Val);
3708 bool CheckLoopHintExpr(Expr *E, SourceLocation Loc);
3710 ExprResult ActOnNumericConstant(const Token &Tok, Scope *UDLScope = nullptr);
3711 ExprResult ActOnCharacterConstant(const Token &Tok,
3712 Scope *UDLScope = nullptr);
3713 ExprResult ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E);
3714 ExprResult ActOnParenListExpr(SourceLocation L,
3718 /// ActOnStringLiteral - The specified tokens were lexed as pasted string
3719 /// fragments (e.g. "foo" "bar" L"baz").
3720 ExprResult ActOnStringLiteral(ArrayRef<Token> StringToks,
3721 Scope *UDLScope = nullptr);
3723 ExprResult ActOnGenericSelectionExpr(SourceLocation KeyLoc,
3724 SourceLocation DefaultLoc,
3725 SourceLocation RParenLoc,
3726 Expr *ControllingExpr,
3727 ArrayRef<ParsedType> ArgTypes,
3728 ArrayRef<Expr *> ArgExprs);
3729 ExprResult CreateGenericSelectionExpr(SourceLocation KeyLoc,
3730 SourceLocation DefaultLoc,
3731 SourceLocation RParenLoc,
3732 Expr *ControllingExpr,
3733 ArrayRef<TypeSourceInfo *> Types,
3734 ArrayRef<Expr *> Exprs);
3736 // Binary/Unary Operators. 'Tok' is the token for the operator.
3737 ExprResult CreateBuiltinUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc,
3739 ExprResult BuildUnaryOp(Scope *S, SourceLocation OpLoc,
3740 UnaryOperatorKind Opc, Expr *Input);
3741 ExprResult ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
3742 tok::TokenKind Op, Expr *Input);
3744 QualType CheckAddressOfOperand(ExprResult &Operand, SourceLocation OpLoc);
3746 ExprResult CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
3747 SourceLocation OpLoc,
3748 UnaryExprOrTypeTrait ExprKind,
3750 ExprResult CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
3751 UnaryExprOrTypeTrait ExprKind);
3753 ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
3754 UnaryExprOrTypeTrait ExprKind,
3755 bool IsType, void *TyOrEx,
3756 const SourceRange &ArgRange);
3758 ExprResult CheckPlaceholderExpr(Expr *E);
3759 bool CheckVecStepExpr(Expr *E);
3761 bool CheckUnaryExprOrTypeTraitOperand(Expr *E, UnaryExprOrTypeTrait ExprKind);
3762 bool CheckUnaryExprOrTypeTraitOperand(QualType ExprType, SourceLocation OpLoc,
3763 SourceRange ExprRange,
3764 UnaryExprOrTypeTrait ExprKind);
3765 ExprResult ActOnSizeofParameterPackExpr(Scope *S,
3766 SourceLocation OpLoc,
3767 IdentifierInfo &Name,
3768 SourceLocation NameLoc,
3769 SourceLocation RParenLoc);
3770 ExprResult ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
3771 tok::TokenKind Kind, Expr *Input);
3773 ExprResult ActOnArraySubscriptExpr(Scope *S, Expr *Base, SourceLocation LLoc,
3774 Expr *Idx, SourceLocation RLoc);
3775 ExprResult CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
3776 Expr *Idx, SourceLocation RLoc);
3778 // This struct is for use by ActOnMemberAccess to allow
3779 // BuildMemberReferenceExpr to be able to reinvoke ActOnMemberAccess after
3780 // changing the access operator from a '.' to a '->' (to see if that is the
3781 // change needed to fix an error about an unknown member, e.g. when the class
3782 // defines a custom operator->).
3783 struct ActOnMemberAccessExtraArgs {
3789 ExprResult BuildMemberReferenceExpr(
3790 Expr *Base, QualType BaseType, SourceLocation OpLoc, bool IsArrow,
3791 CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
3792 NamedDecl *FirstQualifierInScope, const DeclarationNameInfo &NameInfo,
3793 const TemplateArgumentListInfo *TemplateArgs,
3794 ActOnMemberAccessExtraArgs *ExtraArgs = nullptr);
3797 BuildMemberReferenceExpr(Expr *Base, QualType BaseType, SourceLocation OpLoc,
3798 bool IsArrow, const CXXScopeSpec &SS,
3799 SourceLocation TemplateKWLoc,
3800 NamedDecl *FirstQualifierInScope, LookupResult &R,
3801 const TemplateArgumentListInfo *TemplateArgs,
3802 bool SuppressQualifierCheck = false,
3803 ActOnMemberAccessExtraArgs *ExtraArgs = nullptr);
3805 ExprResult PerformMemberExprBaseConversion(Expr *Base, bool IsArrow);
3807 bool CheckQualifiedMemberReference(Expr *BaseExpr, QualType BaseType,
3808 const CXXScopeSpec &SS,
3809 const LookupResult &R);
3811 ExprResult ActOnDependentMemberExpr(Expr *Base, QualType BaseType,
3812 bool IsArrow, SourceLocation OpLoc,
3813 const CXXScopeSpec &SS,
3814 SourceLocation TemplateKWLoc,
3815 NamedDecl *FirstQualifierInScope,
3816 const DeclarationNameInfo &NameInfo,
3817 const TemplateArgumentListInfo *TemplateArgs);
3819 ExprResult ActOnMemberAccessExpr(Scope *S, Expr *Base,
3820 SourceLocation OpLoc,
3821 tok::TokenKind OpKind,
3823 SourceLocation TemplateKWLoc,
3824 UnqualifiedId &Member,
3827 void ActOnDefaultCtorInitializers(Decl *CDtorDecl);
3828 bool ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
3829 FunctionDecl *FDecl,
3830 const FunctionProtoType *Proto,
3831 ArrayRef<Expr *> Args,
3832 SourceLocation RParenLoc,
3833 bool ExecConfig = false);
3834 void CheckStaticArrayArgument(SourceLocation CallLoc,
3836 const Expr *ArgExpr);
3838 /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
3839 /// This provides the location of the left/right parens and a list of comma
3841 ExprResult ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
3842 MultiExprArg ArgExprs, SourceLocation RParenLoc,
3843 Expr *ExecConfig = nullptr,
3844 bool IsExecConfig = false);
3845 ExprResult BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
3846 SourceLocation LParenLoc,
3847 ArrayRef<Expr *> Arg,
3848 SourceLocation RParenLoc,
3849 Expr *Config = nullptr,
3850 bool IsExecConfig = false);
3852 ExprResult ActOnCUDAExecConfigExpr(Scope *S, SourceLocation LLLLoc,
3853 MultiExprArg ExecConfig,
3854 SourceLocation GGGLoc);
3856 ExprResult ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
3857 Declarator &D, ParsedType &Ty,
3858 SourceLocation RParenLoc, Expr *CastExpr);
3859 ExprResult BuildCStyleCastExpr(SourceLocation LParenLoc,
3861 SourceLocation RParenLoc,
3863 CastKind PrepareScalarCast(ExprResult &src, QualType destType);
3865 /// \brief Build an altivec or OpenCL literal.
3866 ExprResult BuildVectorLiteral(SourceLocation LParenLoc,
3867 SourceLocation RParenLoc, Expr *E,
3868 TypeSourceInfo *TInfo);
3870 ExprResult MaybeConvertParenListExprToParenExpr(Scope *S, Expr *ME);
3872 ExprResult ActOnCompoundLiteral(SourceLocation LParenLoc,
3874 SourceLocation RParenLoc,
3877 ExprResult BuildCompoundLiteralExpr(SourceLocation LParenLoc,
3878 TypeSourceInfo *TInfo,
3879 SourceLocation RParenLoc,
3882 ExprResult ActOnInitList(SourceLocation LBraceLoc,
3883 MultiExprArg InitArgList,
3884 SourceLocation RBraceLoc);
3886 ExprResult ActOnDesignatedInitializer(Designation &Desig,
3892 static BinaryOperatorKind ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind);
3895 ExprResult ActOnBinOp(Scope *S, SourceLocation TokLoc,
3896 tok::TokenKind Kind, Expr *LHSExpr, Expr *RHSExpr);
3897 ExprResult BuildBinOp(Scope *S, SourceLocation OpLoc,
3898 BinaryOperatorKind Opc, Expr *LHSExpr, Expr *RHSExpr);
3899 ExprResult CreateBuiltinBinOp(SourceLocation OpLoc, BinaryOperatorKind Opc,
3900 Expr *LHSExpr, Expr *RHSExpr);
3902 /// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
3903 /// in the case of a the GNU conditional expr extension.
3904 ExprResult ActOnConditionalOp(SourceLocation QuestionLoc,
3905 SourceLocation ColonLoc,
3906 Expr *CondExpr, Expr *LHSExpr, Expr *RHSExpr);
3908 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
3909 ExprResult ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
3910 LabelDecl *TheDecl);
3912 void ActOnStartStmtExpr();
3913 ExprResult ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
3914 SourceLocation RPLoc); // "({..})"
3915 void ActOnStmtExprError();
3917 // __builtin_offsetof(type, identifier(.identifier|[expr])*)
3918 struct OffsetOfComponent {
3919 SourceLocation LocStart, LocEnd;
3920 bool isBrackets; // true if [expr], false if .ident
3922 IdentifierInfo *IdentInfo;
3927 /// __builtin_offsetof(type, a.b[123][456].c)
3928 ExprResult BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
3929 TypeSourceInfo *TInfo,
3930 OffsetOfComponent *CompPtr,
3931 unsigned NumComponents,
3932 SourceLocation RParenLoc);
3933 ExprResult ActOnBuiltinOffsetOf(Scope *S,
3934 SourceLocation BuiltinLoc,
3935 SourceLocation TypeLoc,
3936 ParsedType ParsedArgTy,
3937 OffsetOfComponent *CompPtr,
3938 unsigned NumComponents,
3939 SourceLocation RParenLoc);
3941 // __builtin_choose_expr(constExpr, expr1, expr2)
3942 ExprResult ActOnChooseExpr(SourceLocation BuiltinLoc,
3943 Expr *CondExpr, Expr *LHSExpr,
3944 Expr *RHSExpr, SourceLocation RPLoc);
3946 // __builtin_va_arg(expr, type)
3947 ExprResult ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty,
3948 SourceLocation RPLoc);
3949 ExprResult BuildVAArgExpr(SourceLocation BuiltinLoc, Expr *E,
3950 TypeSourceInfo *TInfo, SourceLocation RPLoc);
3953 ExprResult ActOnGNUNullExpr(SourceLocation TokenLoc);
3955 bool CheckCaseExpression(Expr *E);
3957 /// \brief Describes the result of an "if-exists" condition check.
3958 enum IfExistsResult {
3959 /// \brief The symbol exists.
3962 /// \brief The symbol does not exist.
3965 /// \brief The name is a dependent name, so the results will differ
3966 /// from one instantiation to the next.
3969 /// \brief An error occurred.
3974 CheckMicrosoftIfExistsSymbol(Scope *S, CXXScopeSpec &SS,
3975 const DeclarationNameInfo &TargetNameInfo);
3978 CheckMicrosoftIfExistsSymbol(Scope *S, SourceLocation KeywordLoc,
3979 bool IsIfExists, CXXScopeSpec &SS,
3980 UnqualifiedId &Name);
3982 StmtResult BuildMSDependentExistsStmt(SourceLocation KeywordLoc,
3984 NestedNameSpecifierLoc QualifierLoc,
3985 DeclarationNameInfo NameInfo,
3987 StmtResult ActOnMSDependentExistsStmt(SourceLocation KeywordLoc,
3989 CXXScopeSpec &SS, UnqualifiedId &Name,
3992 //===------------------------- "Block" Extension ------------------------===//
3994 /// ActOnBlockStart - This callback is invoked when a block literal is
3996 void ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope);
3998 /// ActOnBlockArguments - This callback allows processing of block arguments.
3999 /// If there are no arguments, this is still invoked.
4000 void ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
4003 /// ActOnBlockError - If there is an error parsing a block, this callback
4004 /// is invoked to pop the information about the block from the action impl.
4005 void ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope);
4007 /// ActOnBlockStmtExpr - This is called when the body of a block statement
4008 /// literal was successfully completed. ^(int x){...}
4009 ExprResult ActOnBlockStmtExpr(SourceLocation CaretLoc, Stmt *Body,
4012 //===---------------------------- Clang Extensions ----------------------===//
4014 /// __builtin_convertvector(...)
4015 ExprResult ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy,
4016 SourceLocation BuiltinLoc,
4017 SourceLocation RParenLoc);
4019 //===---------------------------- OpenCL Features -----------------------===//
4021 /// __builtin_astype(...)
4022 ExprResult ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
4023 SourceLocation BuiltinLoc,
4024 SourceLocation RParenLoc);
4026 //===---------------------------- C++ Features --------------------------===//
4028 // Act on C++ namespaces
4029 Decl *ActOnStartNamespaceDef(Scope *S, SourceLocation InlineLoc,
4030 SourceLocation NamespaceLoc,
4031 SourceLocation IdentLoc,
4032 IdentifierInfo *Ident,
4033 SourceLocation LBrace,
4034 AttributeList *AttrList);
4035 void ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace);
4037 NamespaceDecl *getStdNamespace() const;
4038 NamespaceDecl *getOrCreateStdNamespace();
4040 CXXRecordDecl *getStdBadAlloc() const;
4042 /// \brief Tests whether Ty is an instance of std::initializer_list and, if
4043 /// it is and Element is not NULL, assigns the element type to Element.
4044 bool isStdInitializerList(QualType Ty, QualType *Element);
4046 /// \brief Looks for the std::initializer_list template and instantiates it
4047 /// with Element, or emits an error if it's not found.
4049 /// \returns The instantiated template, or null on error.
4050 QualType BuildStdInitializerList(QualType Element, SourceLocation Loc);
4052 /// \brief Determine whether Ctor is an initializer-list constructor, as
4053 /// defined in [dcl.init.list]p2.
4054 bool isInitListConstructor(const CXXConstructorDecl *Ctor);
4056 Decl *ActOnUsingDirective(Scope *CurScope,
4057 SourceLocation UsingLoc,
4058 SourceLocation NamespcLoc,
4060 SourceLocation IdentLoc,
4061 IdentifierInfo *NamespcName,
4062 AttributeList *AttrList);
4064 void PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir);
4066 Decl *ActOnNamespaceAliasDef(Scope *CurScope,
4067 SourceLocation NamespaceLoc,
4068 SourceLocation AliasLoc,
4069 IdentifierInfo *Alias,
4071 SourceLocation IdentLoc,
4072 IdentifierInfo *Ident);
4074 void HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow);
4075 bool CheckUsingShadowDecl(UsingDecl *UD, NamedDecl *Target,
4076 const LookupResult &PreviousDecls,
4077 UsingShadowDecl *&PrevShadow);
4078 UsingShadowDecl *BuildUsingShadowDecl(Scope *S, UsingDecl *UD,
4080 UsingShadowDecl *PrevDecl);
4082 bool CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
4083 bool HasTypenameKeyword,
4084 const CXXScopeSpec &SS,
4085 SourceLocation NameLoc,
4086 const LookupResult &Previous);
4087 bool CheckUsingDeclQualifier(SourceLocation UsingLoc,
4088 const CXXScopeSpec &SS,
4089 const DeclarationNameInfo &NameInfo,
4090 SourceLocation NameLoc);
4092 NamedDecl *BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
4093 SourceLocation UsingLoc,
4095 DeclarationNameInfo NameInfo,
4096 AttributeList *AttrList,
4097 bool IsInstantiation,
4098 bool HasTypenameKeyword,
4099 SourceLocation TypenameLoc);
4101 bool CheckInheritingConstructorUsingDecl(UsingDecl *UD);
4103 Decl *ActOnUsingDeclaration(Scope *CurScope,
4105 bool HasUsingKeyword,
4106 SourceLocation UsingLoc,
4108 UnqualifiedId &Name,
4109 AttributeList *AttrList,
4110 bool HasTypenameKeyword,
4111 SourceLocation TypenameLoc);
4112 Decl *ActOnAliasDeclaration(Scope *CurScope,
4114 MultiTemplateParamsArg TemplateParams,
4115 SourceLocation UsingLoc,
4116 UnqualifiedId &Name,
4117 AttributeList *AttrList,
4119 Decl *DeclFromDeclSpec);
4121 /// BuildCXXConstructExpr - Creates a complete call to a constructor,
4122 /// including handling of its default argument expressions.
4124 /// \param ConstructKind - a CXXConstructExpr::ConstructionKind
4126 BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
4127 CXXConstructorDecl *Constructor, MultiExprArg Exprs,
4128 bool HadMultipleCandidates, bool IsListInitialization,
4129 bool IsStdInitListInitialization,
4130 bool RequiresZeroInit, unsigned ConstructKind,
4131 SourceRange ParenRange);
4133 // FIXME: Can we remove this and have the above BuildCXXConstructExpr check if
4134 // the constructor can be elidable?
4136 BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
4137 CXXConstructorDecl *Constructor, bool Elidable,
4138 MultiExprArg Exprs, bool HadMultipleCandidates,
4139 bool IsListInitialization,
4140 bool IsStdInitListInitialization, bool RequiresZeroInit,
4141 unsigned ConstructKind, SourceRange ParenRange);
4143 ExprResult BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field);
4145 /// BuildCXXDefaultArgExpr - Creates a CXXDefaultArgExpr, instantiating
4146 /// the default expr if needed.
4147 ExprResult BuildCXXDefaultArgExpr(SourceLocation CallLoc,
4149 ParmVarDecl *Param);
4151 /// FinalizeVarWithDestructor - Prepare for calling destructor on the
4152 /// constructed variable.
4153 void FinalizeVarWithDestructor(VarDecl *VD, const RecordType *DeclInitType);
4155 /// \brief Helper class that collects exception specifications for
4156 /// implicitly-declared special member functions.
4157 class ImplicitExceptionSpecification {
4158 // Pointer to allow copying
4160 // We order exception specifications thus:
4161 // noexcept is the most restrictive, but is only used in C++11.
4162 // throw() comes next.
4163 // Then a throw(collected exceptions)
4164 // Finally no specification, which is expressed as noexcept(false).
4165 // throw(...) is used instead if any called function uses it.
4166 ExceptionSpecificationType ComputedEST;
4167 llvm::SmallPtrSet<CanQualType, 4> ExceptionsSeen;
4168 SmallVector<QualType, 4> Exceptions;
4170 void ClearExceptions() {
4171 ExceptionsSeen.clear();
4176 explicit ImplicitExceptionSpecification(Sema &Self)
4177 : Self(&Self), ComputedEST(EST_BasicNoexcept) {
4178 if (!Self.getLangOpts().CPlusPlus11)
4179 ComputedEST = EST_DynamicNone;
4182 /// \brief Get the computed exception specification type.
4183 ExceptionSpecificationType getExceptionSpecType() const {
4184 assert(ComputedEST != EST_ComputedNoexcept &&
4185 "noexcept(expr) should not be a possible result");
4189 /// \brief The number of exceptions in the exception specification.
4190 unsigned size() const { return Exceptions.size(); }
4192 /// \brief The set of exceptions in the exception specification.
4193 const QualType *data() const { return Exceptions.data(); }
4195 /// \brief Integrate another called method into the collected data.
4196 void CalledDecl(SourceLocation CallLoc, const CXXMethodDecl *Method);
4198 /// \brief Integrate an invoked expression into the collected data.
4199 void CalledExpr(Expr *E);
4201 /// \brief Overwrite an EPI's exception specification with this
4202 /// computed exception specification.
4203 FunctionProtoType::ExceptionSpecInfo getExceptionSpec() const {
4204 FunctionProtoType::ExceptionSpecInfo ESI;
4205 ESI.Type = getExceptionSpecType();
4206 if (ESI.Type == EST_Dynamic) {
4207 ESI.Exceptions = Exceptions;
4208 } else if (ESI.Type == EST_None) {
4209 /// C++11 [except.spec]p14:
4210 /// The exception-specification is noexcept(false) if the set of
4211 /// potential exceptions of the special member function contains "any"
4212 ESI.Type = EST_ComputedNoexcept;
4213 ESI.NoexceptExpr = Self->ActOnCXXBoolLiteral(SourceLocation(),
4214 tok::kw_false).get();
4220 /// \brief Determine what sort of exception specification a defaulted
4221 /// copy constructor of a class will have.
4222 ImplicitExceptionSpecification
4223 ComputeDefaultedDefaultCtorExceptionSpec(SourceLocation Loc,
4226 /// \brief Determine what sort of exception specification a defaulted
4227 /// default constructor of a class will have, and whether the parameter
4229 ImplicitExceptionSpecification
4230 ComputeDefaultedCopyCtorExceptionSpec(CXXMethodDecl *MD);
4232 /// \brief Determine what sort of exception specification a defautled
4233 /// copy assignment operator of a class will have, and whether the
4234 /// parameter will be const.
4235 ImplicitExceptionSpecification
4236 ComputeDefaultedCopyAssignmentExceptionSpec(CXXMethodDecl *MD);
4238 /// \brief Determine what sort of exception specification a defaulted move
4239 /// constructor of a class will have.
4240 ImplicitExceptionSpecification
4241 ComputeDefaultedMoveCtorExceptionSpec(CXXMethodDecl *MD);
4243 /// \brief Determine what sort of exception specification a defaulted move
4244 /// assignment operator of a class will have.
4245 ImplicitExceptionSpecification
4246 ComputeDefaultedMoveAssignmentExceptionSpec(CXXMethodDecl *MD);
4248 /// \brief Determine what sort of exception specification a defaulted
4249 /// destructor of a class will have.
4250 ImplicitExceptionSpecification
4251 ComputeDefaultedDtorExceptionSpec(CXXMethodDecl *MD);
4253 /// \brief Determine what sort of exception specification an inheriting
4254 /// constructor of a class will have.
4255 ImplicitExceptionSpecification
4256 ComputeInheritingCtorExceptionSpec(CXXConstructorDecl *CD);
4258 /// \brief Evaluate the implicit exception specification for a defaulted
4259 /// special member function.
4260 void EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD);
4262 /// \brief Check the given exception-specification and update the
4263 /// exception specification information with the results.
4264 void checkExceptionSpecification(bool IsTopLevel,
4265 ExceptionSpecificationType EST,
4266 ArrayRef<ParsedType> DynamicExceptions,
4267 ArrayRef<SourceRange> DynamicExceptionRanges,
4269 SmallVectorImpl<QualType> &Exceptions,
4270 FunctionProtoType::ExceptionSpecInfo &ESI);
4272 /// \brief Determine if we're in a case where we need to (incorrectly) eagerly
4273 /// parse an exception specification to work around a libstdc++ bug.
4274 bool isLibstdcxxEagerExceptionSpecHack(const Declarator &D);
4276 /// \brief Add an exception-specification to the given member function
4277 /// (or member function template). The exception-specification was parsed
4278 /// after the method itself was declared.
4279 void actOnDelayedExceptionSpecification(Decl *Method,
4280 ExceptionSpecificationType EST,
4281 SourceRange SpecificationRange,
4282 ArrayRef<ParsedType> DynamicExceptions,
4283 ArrayRef<SourceRange> DynamicExceptionRanges,
4284 Expr *NoexceptExpr);
4286 /// \brief Determine if a special member function should have a deleted
4287 /// definition when it is defaulted.
4288 bool ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
4289 bool Diagnose = false);
4291 /// \brief Declare the implicit default constructor for the given class.
4293 /// \param ClassDecl The class declaration into which the implicit
4294 /// default constructor will be added.
4296 /// \returns The implicitly-declared default constructor.
4297 CXXConstructorDecl *DeclareImplicitDefaultConstructor(
4298 CXXRecordDecl *ClassDecl);
4300 /// DefineImplicitDefaultConstructor - Checks for feasibility of
4301 /// defining this constructor as the default constructor.
4302 void DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
4303 CXXConstructorDecl *Constructor);
4305 /// \brief Declare the implicit destructor for the given class.
4307 /// \param ClassDecl The class declaration into which the implicit
4308 /// destructor will be added.
4310 /// \returns The implicitly-declared destructor.
4311 CXXDestructorDecl *DeclareImplicitDestructor(CXXRecordDecl *ClassDecl);
4313 /// DefineImplicitDestructor - Checks for feasibility of
4314 /// defining this destructor as the default destructor.
4315 void DefineImplicitDestructor(SourceLocation CurrentLocation,
4316 CXXDestructorDecl *Destructor);
4318 /// \brief Build an exception spec for destructors that don't have one.
4320 /// C++11 says that user-defined destructors with no exception spec get one
4321 /// that looks as if the destructor was implicitly declared.
4322 void AdjustDestructorExceptionSpec(CXXRecordDecl *ClassDecl,
4323 CXXDestructorDecl *Destructor);
4325 /// \brief Declare all inheriting constructors for the given class.
4327 /// \param ClassDecl The class declaration into which the inheriting
4328 /// constructors will be added.
4329 void DeclareInheritingConstructors(CXXRecordDecl *ClassDecl);
4331 /// \brief Define the specified inheriting constructor.
4332 void DefineInheritingConstructor(SourceLocation UseLoc,
4333 CXXConstructorDecl *Constructor);
4335 /// \brief Declare the implicit copy constructor for the given class.
4337 /// \param ClassDecl The class declaration into which the implicit
4338 /// copy constructor will be added.
4340 /// \returns The implicitly-declared copy constructor.
4341 CXXConstructorDecl *DeclareImplicitCopyConstructor(CXXRecordDecl *ClassDecl);
4343 /// DefineImplicitCopyConstructor - Checks for feasibility of
4344 /// defining this constructor as the copy constructor.
4345 void DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
4346 CXXConstructorDecl *Constructor);
4348 /// \brief Declare the implicit move constructor for the given class.
4350 /// \param ClassDecl The Class declaration into which the implicit
4351 /// move constructor will be added.
4353 /// \returns The implicitly-declared move constructor, or NULL if it wasn't
4355 CXXConstructorDecl *DeclareImplicitMoveConstructor(CXXRecordDecl *ClassDecl);
4357 /// DefineImplicitMoveConstructor - Checks for feasibility of
4358 /// defining this constructor as the move constructor.
4359 void DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
4360 CXXConstructorDecl *Constructor);
4362 /// \brief Declare the implicit copy assignment operator for the given class.
4364 /// \param ClassDecl The class declaration into which the implicit
4365 /// copy assignment operator will be added.
4367 /// \returns The implicitly-declared copy assignment operator.
4368 CXXMethodDecl *DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl);
4370 /// \brief Defines an implicitly-declared copy assignment operator.
4371 void DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
4372 CXXMethodDecl *MethodDecl);
4374 /// \brief Declare the implicit move assignment operator for the given class.
4376 /// \param ClassDecl The Class declaration into which the implicit
4377 /// move assignment operator will be added.
4379 /// \returns The implicitly-declared move assignment operator, or NULL if it
4380 /// wasn't declared.
4381 CXXMethodDecl *DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl);
4383 /// \brief Defines an implicitly-declared move assignment operator.
4384 void DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
4385 CXXMethodDecl *MethodDecl);
4387 /// \brief Force the declaration of any implicitly-declared members of this
4389 void ForceDeclarationOfImplicitMembers(CXXRecordDecl *Class);
4391 /// \brief Determine whether the given function is an implicitly-deleted
4392 /// special member function.
4393 bool isImplicitlyDeleted(FunctionDecl *FD);
4395 /// \brief Check whether 'this' shows up in the type of a static member
4396 /// function after the (naturally empty) cv-qualifier-seq would be.
4398 /// \returns true if an error occurred.
4399 bool checkThisInStaticMemberFunctionType(CXXMethodDecl *Method);
4401 /// \brief Whether this' shows up in the exception specification of a static
4402 /// member function.
4403 bool checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method);
4405 /// \brief Check whether 'this' shows up in the attributes of the given
4406 /// static member function.
4408 /// \returns true if an error occurred.
4409 bool checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method);
4411 /// MaybeBindToTemporary - If the passed in expression has a record type with
4412 /// a non-trivial destructor, this will return CXXBindTemporaryExpr. Otherwise
4413 /// it simply returns the passed in expression.
4414 ExprResult MaybeBindToTemporary(Expr *E);
4416 bool CompleteConstructorCall(CXXConstructorDecl *Constructor,
4417 MultiExprArg ArgsPtr,
4419 SmallVectorImpl<Expr*> &ConvertedArgs,
4420 bool AllowExplicit = false,
4421 bool IsListInitialization = false);
4423 ParsedType getInheritingConstructorName(CXXScopeSpec &SS,
4424 SourceLocation NameLoc,
4425 IdentifierInfo &Name);
4427 ParsedType getDestructorName(SourceLocation TildeLoc,
4428 IdentifierInfo &II, SourceLocation NameLoc,
4429 Scope *S, CXXScopeSpec &SS,
4430 ParsedType ObjectType,
4431 bool EnteringContext);
4433 ParsedType getDestructorType(const DeclSpec& DS, ParsedType ObjectType);
4435 // Checks that reinterpret casts don't have undefined behavior.
4436 void CheckCompatibleReinterpretCast(QualType SrcType, QualType DestType,
4437 bool IsDereference, SourceRange Range);
4439 /// ActOnCXXNamedCast - Parse {dynamic,static,reinterpret,const}_cast's.
4440 ExprResult ActOnCXXNamedCast(SourceLocation OpLoc,
4441 tok::TokenKind Kind,
4442 SourceLocation LAngleBracketLoc,
4444 SourceLocation RAngleBracketLoc,
4445 SourceLocation LParenLoc,
4447 SourceLocation RParenLoc);
4449 ExprResult BuildCXXNamedCast(SourceLocation OpLoc,
4450 tok::TokenKind Kind,
4453 SourceRange AngleBrackets,
4454 SourceRange Parens);
4456 ExprResult BuildCXXTypeId(QualType TypeInfoType,
4457 SourceLocation TypeidLoc,
4458 TypeSourceInfo *Operand,
4459 SourceLocation RParenLoc);
4460 ExprResult BuildCXXTypeId(QualType TypeInfoType,
4461 SourceLocation TypeidLoc,
4463 SourceLocation RParenLoc);
4465 /// ActOnCXXTypeid - Parse typeid( something ).
4466 ExprResult ActOnCXXTypeid(SourceLocation OpLoc,
4467 SourceLocation LParenLoc, bool isType,
4469 SourceLocation RParenLoc);
4471 ExprResult BuildCXXUuidof(QualType TypeInfoType,
4472 SourceLocation TypeidLoc,
4473 TypeSourceInfo *Operand,
4474 SourceLocation RParenLoc);
4475 ExprResult BuildCXXUuidof(QualType TypeInfoType,
4476 SourceLocation TypeidLoc,
4478 SourceLocation RParenLoc);
4480 /// ActOnCXXUuidof - Parse __uuidof( something ).
4481 ExprResult ActOnCXXUuidof(SourceLocation OpLoc,
4482 SourceLocation LParenLoc, bool isType,
4484 SourceLocation RParenLoc);
4486 /// \brief Handle a C++1z fold-expression: ( expr op ... op expr ).
4487 ExprResult ActOnCXXFoldExpr(SourceLocation LParenLoc, Expr *LHS,
4488 tok::TokenKind Operator,
4489 SourceLocation EllipsisLoc, Expr *RHS,
4490 SourceLocation RParenLoc);
4491 ExprResult BuildCXXFoldExpr(SourceLocation LParenLoc, Expr *LHS,
4492 BinaryOperatorKind Operator,
4493 SourceLocation EllipsisLoc, Expr *RHS,
4494 SourceLocation RParenLoc);
4495 ExprResult BuildEmptyCXXFoldExpr(SourceLocation EllipsisLoc,
4496 BinaryOperatorKind Operator);
4498 //// ActOnCXXThis - Parse 'this' pointer.
4499 ExprResult ActOnCXXThis(SourceLocation loc);
4501 /// \brief Try to retrieve the type of the 'this' pointer.
4503 /// \returns The type of 'this', if possible. Otherwise, returns a NULL type.
4504 QualType getCurrentThisType();
4506 /// \brief When non-NULL, the C++ 'this' expression is allowed despite the
4507 /// current context not being a non-static member function. In such cases,
4508 /// this provides the type used for 'this'.
4509 QualType CXXThisTypeOverride;
4511 /// \brief RAII object used to temporarily allow the C++ 'this' expression
4512 /// to be used, with the given qualifiers on the current class type.
4513 class CXXThisScopeRAII {
4515 QualType OldCXXThisTypeOverride;
4519 /// \brief Introduce a new scope where 'this' may be allowed (when enabled),
4520 /// using the given declaration (which is either a class template or a
4521 /// class) along with the given qualifiers.
4522 /// along with the qualifiers placed on '*this'.
4523 CXXThisScopeRAII(Sema &S, Decl *ContextDecl, unsigned CXXThisTypeQuals,
4524 bool Enabled = true);
4526 ~CXXThisScopeRAII();
4529 /// \brief Make sure the value of 'this' is actually available in the current
4530 /// context, if it is a potentially evaluated context.
4532 /// \param Loc The location at which the capture of 'this' occurs.
4534 /// \param Explicit Whether 'this' is explicitly captured in a lambda
4537 /// \param FunctionScopeIndexToStopAt If non-null, it points to the index
4538 /// of the FunctionScopeInfo stack beyond which we do not attempt to capture.
4539 /// This is useful when enclosing lambdas must speculatively capture
4540 /// 'this' that may or may not be used in certain specializations of
4541 /// a nested generic lambda (depending on whether the name resolves to
4542 /// a non-static member function or a static function).
4543 /// \return returns 'true' if failed, 'false' if success.
4544 bool CheckCXXThisCapture(SourceLocation Loc, bool Explicit = false,
4545 bool BuildAndDiagnose = true,
4546 const unsigned *const FunctionScopeIndexToStopAt = nullptr);
4548 /// \brief Determine whether the given type is the type of *this that is used
4549 /// outside of the body of a member function for a type that is currently
4551 bool isThisOutsideMemberFunctionBody(QualType BaseType);
4553 /// ActOnCXXBoolLiteral - Parse {true,false} literals.
4554 ExprResult ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind);
4557 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
4558 ExprResult ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind);
4560 /// ActOnCXXNullPtrLiteral - Parse 'nullptr'.
4561 ExprResult ActOnCXXNullPtrLiteral(SourceLocation Loc);
4563 //// ActOnCXXThrow - Parse throw expressions.
4564 ExprResult ActOnCXXThrow(Scope *S, SourceLocation OpLoc, Expr *expr);
4565 ExprResult BuildCXXThrow(SourceLocation OpLoc, Expr *Ex,
4566 bool IsThrownVarInScope);
4567 bool CheckCXXThrowOperand(SourceLocation ThrowLoc, QualType ThrowTy, Expr *E);
4569 /// ActOnCXXTypeConstructExpr - Parse construction of a specified type.
4570 /// Can be interpreted either as function-style casting ("int(x)")
4571 /// or class type construction ("ClassType(x,y,z)")
4572 /// or creation of a value-initialized type ("int()").
4573 ExprResult ActOnCXXTypeConstructExpr(ParsedType TypeRep,
4574 SourceLocation LParenLoc,
4576 SourceLocation RParenLoc);
4578 ExprResult BuildCXXTypeConstructExpr(TypeSourceInfo *Type,
4579 SourceLocation LParenLoc,
4581 SourceLocation RParenLoc);
4583 /// ActOnCXXNew - Parsed a C++ 'new' expression.
4584 ExprResult ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
4585 SourceLocation PlacementLParen,
4586 MultiExprArg PlacementArgs,
4587 SourceLocation PlacementRParen,
4588 SourceRange TypeIdParens, Declarator &D,
4590 ExprResult BuildCXXNew(SourceRange Range, bool UseGlobal,
4591 SourceLocation PlacementLParen,
4592 MultiExprArg PlacementArgs,
4593 SourceLocation PlacementRParen,
4594 SourceRange TypeIdParens,
4596 TypeSourceInfo *AllocTypeInfo,
4598 SourceRange DirectInitRange,
4600 bool TypeMayContainAuto = true);
4602 bool CheckAllocatedType(QualType AllocType, SourceLocation Loc,
4604 bool FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,
4605 bool UseGlobal, QualType AllocType, bool IsArray,
4606 MultiExprArg PlaceArgs,
4607 FunctionDecl *&OperatorNew,
4608 FunctionDecl *&OperatorDelete);
4609 bool FindAllocationOverload(SourceLocation StartLoc, SourceRange Range,
4610 DeclarationName Name, MultiExprArg Args,
4612 bool AllowMissing, FunctionDecl *&Operator,
4613 bool Diagnose = true);
4614 void DeclareGlobalNewDelete();
4615 void DeclareGlobalAllocationFunction(DeclarationName Name, QualType Return,
4617 QualType Param2 = QualType(),
4618 bool addRestrictAttr = false);
4620 bool FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD,
4621 DeclarationName Name, FunctionDecl* &Operator,
4622 bool Diagnose = true);
4623 FunctionDecl *FindUsualDeallocationFunction(SourceLocation StartLoc,
4624 bool CanProvideSize,
4625 DeclarationName Name);
4627 /// ActOnCXXDelete - Parsed a C++ 'delete' expression
4628 ExprResult ActOnCXXDelete(SourceLocation StartLoc,
4629 bool UseGlobal, bool ArrayForm,
4632 DeclResult ActOnCXXConditionDeclaration(Scope *S, Declarator &D);
4633 ExprResult CheckConditionVariable(VarDecl *ConditionVar,
4634 SourceLocation StmtLoc,
4635 bool ConvertToBoolean);
4637 ExprResult ActOnNoexceptExpr(SourceLocation KeyLoc, SourceLocation LParen,
4638 Expr *Operand, SourceLocation RParen);
4639 ExprResult BuildCXXNoexceptExpr(SourceLocation KeyLoc, Expr *Operand,
4640 SourceLocation RParen);
4642 /// \brief Parsed one of the type trait support pseudo-functions.
4643 ExprResult ActOnTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
4644 ArrayRef<ParsedType> Args,
4645 SourceLocation RParenLoc);
4646 ExprResult BuildTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
4647 ArrayRef<TypeSourceInfo *> Args,
4648 SourceLocation RParenLoc);
4650 /// ActOnArrayTypeTrait - Parsed one of the bianry type trait support
4651 /// pseudo-functions.
4652 ExprResult ActOnArrayTypeTrait(ArrayTypeTrait ATT,
4653 SourceLocation KWLoc,
4656 SourceLocation RParen);
4658 ExprResult BuildArrayTypeTrait(ArrayTypeTrait ATT,
4659 SourceLocation KWLoc,
4660 TypeSourceInfo *TSInfo,
4662 SourceLocation RParen);
4664 /// ActOnExpressionTrait - Parsed one of the unary type trait support
4665 /// pseudo-functions.
4666 ExprResult ActOnExpressionTrait(ExpressionTrait OET,
4667 SourceLocation KWLoc,
4669 SourceLocation RParen);
4671 ExprResult BuildExpressionTrait(ExpressionTrait OET,
4672 SourceLocation KWLoc,
4674 SourceLocation RParen);
4676 ExprResult ActOnStartCXXMemberReference(Scope *S,
4678 SourceLocation OpLoc,
4679 tok::TokenKind OpKind,
4680 ParsedType &ObjectType,
4681 bool &MayBePseudoDestructor);
4683 ExprResult BuildPseudoDestructorExpr(Expr *Base,
4684 SourceLocation OpLoc,
4685 tok::TokenKind OpKind,
4686 const CXXScopeSpec &SS,
4687 TypeSourceInfo *ScopeType,
4688 SourceLocation CCLoc,
4689 SourceLocation TildeLoc,
4690 PseudoDestructorTypeStorage DestroyedType);
4692 ExprResult ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
4693 SourceLocation OpLoc,
4694 tok::TokenKind OpKind,
4696 UnqualifiedId &FirstTypeName,
4697 SourceLocation CCLoc,
4698 SourceLocation TildeLoc,
4699 UnqualifiedId &SecondTypeName);
4701 ExprResult ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
4702 SourceLocation OpLoc,
4703 tok::TokenKind OpKind,
4704 SourceLocation TildeLoc,
4705 const DeclSpec& DS);
4707 /// MaybeCreateExprWithCleanups - If the current full-expression
4708 /// requires any cleanups, surround it with a ExprWithCleanups node.
4709 /// Otherwise, just returns the passed-in expression.
4710 Expr *MaybeCreateExprWithCleanups(Expr *SubExpr);
4711 Stmt *MaybeCreateStmtWithCleanups(Stmt *SubStmt);
4712 ExprResult MaybeCreateExprWithCleanups(ExprResult SubExpr);
4714 ExprResult ActOnFinishFullExpr(Expr *Expr) {
4715 return ActOnFinishFullExpr(Expr, Expr ? Expr->getExprLoc()
4716 : SourceLocation());
4718 ExprResult ActOnFinishFullExpr(Expr *Expr, SourceLocation CC,
4719 bool DiscardedValue = false,
4720 bool IsConstexpr = false,
4721 bool IsLambdaInitCaptureInitializer = false);
4722 StmtResult ActOnFinishFullStmt(Stmt *Stmt);
4724 // Marks SS invalid if it represents an incomplete type.
4725 bool RequireCompleteDeclContext(CXXScopeSpec &SS, DeclContext *DC);
4727 DeclContext *computeDeclContext(QualType T);
4728 DeclContext *computeDeclContext(const CXXScopeSpec &SS,
4729 bool EnteringContext = false);
4730 bool isDependentScopeSpecifier(const CXXScopeSpec &SS);
4731 CXXRecordDecl *getCurrentInstantiationOf(NestedNameSpecifier *NNS);
4733 /// \brief The parser has parsed a global nested-name-specifier '::'.
4735 /// \param CCLoc The location of the '::'.
4737 /// \param SS The nested-name-specifier, which will be updated in-place
4738 /// to reflect the parsed nested-name-specifier.
4740 /// \returns true if an error occurred, false otherwise.
4741 bool ActOnCXXGlobalScopeSpecifier(SourceLocation CCLoc, CXXScopeSpec &SS);
4743 /// \brief The parser has parsed a '__super' nested-name-specifier.
4745 /// \param SuperLoc The location of the '__super' keyword.
4747 /// \param ColonColonLoc The location of the '::'.
4749 /// \param SS The nested-name-specifier, which will be updated in-place
4750 /// to reflect the parsed nested-name-specifier.
4752 /// \returns true if an error occurred, false otherwise.
4753 bool ActOnSuperScopeSpecifier(SourceLocation SuperLoc,
4754 SourceLocation ColonColonLoc, CXXScopeSpec &SS);
4756 bool isAcceptableNestedNameSpecifier(const NamedDecl *SD,
4757 bool *CanCorrect = nullptr);
4758 NamedDecl *FindFirstQualifierInScope(Scope *S, NestedNameSpecifier *NNS);
4760 bool isNonTypeNestedNameSpecifier(Scope *S, CXXScopeSpec &SS,
4761 SourceLocation IdLoc,
4763 ParsedType ObjectType);
4765 bool BuildCXXNestedNameSpecifier(Scope *S,
4766 IdentifierInfo &Identifier,
4767 SourceLocation IdentifierLoc,
4768 SourceLocation CCLoc,
4769 QualType ObjectType,
4770 bool EnteringContext,
4772 NamedDecl *ScopeLookupResult,
4773 bool ErrorRecoveryLookup,
4774 bool *IsCorrectedToColon = nullptr);
4776 /// \brief The parser has parsed a nested-name-specifier 'identifier::'.
4778 /// \param S The scope in which this nested-name-specifier occurs.
4780 /// \param Identifier The identifier preceding the '::'.
4782 /// \param IdentifierLoc The location of the identifier.
4784 /// \param CCLoc The location of the '::'.
4786 /// \param ObjectType The type of the object, if we're parsing
4787 /// nested-name-specifier in a member access expression.
4789 /// \param EnteringContext Whether we're entering the context nominated by
4790 /// this nested-name-specifier.
4792 /// \param SS The nested-name-specifier, which is both an input
4793 /// parameter (the nested-name-specifier before this type) and an
4794 /// output parameter (containing the full nested-name-specifier,
4795 /// including this new type).
4797 /// \param ErrorRecoveryLookup If true, then this method is called to improve
4798 /// error recovery. In this case do not emit error message.
4800 /// \param IsCorrectedToColon If not null, suggestions to replace '::' -> ':'
4801 /// are allowed. The bool value pointed by this parameter is set to 'true'
4802 /// if the identifier is treated as if it was followed by ':', not '::'.
4804 /// \returns true if an error occurred, false otherwise.
4805 bool ActOnCXXNestedNameSpecifier(Scope *S,
4806 IdentifierInfo &Identifier,
4807 SourceLocation IdentifierLoc,
4808 SourceLocation CCLoc,
4809 ParsedType ObjectType,
4810 bool EnteringContext,
4812 bool ErrorRecoveryLookup = false,
4813 bool *IsCorrectedToColon = nullptr);
4815 ExprResult ActOnDecltypeExpression(Expr *E);
4817 bool ActOnCXXNestedNameSpecifierDecltype(CXXScopeSpec &SS,
4819 SourceLocation ColonColonLoc);
4821 bool IsInvalidUnlessNestedName(Scope *S, CXXScopeSpec &SS,
4822 IdentifierInfo &Identifier,
4823 SourceLocation IdentifierLoc,
4824 SourceLocation ColonLoc,
4825 ParsedType ObjectType,
4826 bool EnteringContext);
4828 /// \brief The parser has parsed a nested-name-specifier
4829 /// 'template[opt] template-name < template-args >::'.
4831 /// \param S The scope in which this nested-name-specifier occurs.
4833 /// \param SS The nested-name-specifier, which is both an input
4834 /// parameter (the nested-name-specifier before this type) and an
4835 /// output parameter (containing the full nested-name-specifier,
4836 /// including this new type).
4838 /// \param TemplateKWLoc the location of the 'template' keyword, if any.
4839 /// \param TemplateName the template name.
4840 /// \param TemplateNameLoc The location of the template name.
4841 /// \param LAngleLoc The location of the opening angle bracket ('<').
4842 /// \param TemplateArgs The template arguments.
4843 /// \param RAngleLoc The location of the closing angle bracket ('>').
4844 /// \param CCLoc The location of the '::'.
4846 /// \param EnteringContext Whether we're entering the context of the
4847 /// nested-name-specifier.
4850 /// \returns true if an error occurred, false otherwise.
4851 bool ActOnCXXNestedNameSpecifier(Scope *S,
4853 SourceLocation TemplateKWLoc,
4854 TemplateTy TemplateName,
4855 SourceLocation TemplateNameLoc,
4856 SourceLocation LAngleLoc,
4857 ASTTemplateArgsPtr TemplateArgs,
4858 SourceLocation RAngleLoc,
4859 SourceLocation CCLoc,
4860 bool EnteringContext);
4862 /// \brief Given a C++ nested-name-specifier, produce an annotation value
4863 /// that the parser can use later to reconstruct the given
4864 /// nested-name-specifier.
4866 /// \param SS A nested-name-specifier.
4868 /// \returns A pointer containing all of the information in the
4869 /// nested-name-specifier \p SS.
4870 void *SaveNestedNameSpecifierAnnotation(CXXScopeSpec &SS);
4872 /// \brief Given an annotation pointer for a nested-name-specifier, restore
4873 /// the nested-name-specifier structure.
4875 /// \param Annotation The annotation pointer, produced by
4876 /// \c SaveNestedNameSpecifierAnnotation().
4878 /// \param AnnotationRange The source range corresponding to the annotation.
4880 /// \param SS The nested-name-specifier that will be updated with the contents
4881 /// of the annotation pointer.
4882 void RestoreNestedNameSpecifierAnnotation(void *Annotation,
4883 SourceRange AnnotationRange,
4886 bool ShouldEnterDeclaratorScope(Scope *S, const CXXScopeSpec &SS);
4888 /// ActOnCXXEnterDeclaratorScope - Called when a C++ scope specifier (global
4889 /// scope or nested-name-specifier) is parsed, part of a declarator-id.
4890 /// After this method is called, according to [C++ 3.4.3p3], names should be
4891 /// looked up in the declarator-id's scope, until the declarator is parsed and
4892 /// ActOnCXXExitDeclaratorScope is called.
4893 /// The 'SS' should be a non-empty valid CXXScopeSpec.
4894 bool ActOnCXXEnterDeclaratorScope(Scope *S, CXXScopeSpec &SS);
4896 /// ActOnCXXExitDeclaratorScope - Called when a declarator that previously
4897 /// invoked ActOnCXXEnterDeclaratorScope(), is finished. 'SS' is the same
4898 /// CXXScopeSpec that was passed to ActOnCXXEnterDeclaratorScope as well.
4899 /// Used to indicate that names should revert to being looked up in the
4901 void ActOnCXXExitDeclaratorScope(Scope *S, const CXXScopeSpec &SS);
4903 /// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse an
4904 /// initializer for the declaration 'Dcl'.
4905 /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
4906 /// static data member of class X, names should be looked up in the scope of
4908 void ActOnCXXEnterDeclInitializer(Scope *S, Decl *Dcl);
4910 /// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
4911 /// initializer for the declaration 'Dcl'.
4912 void ActOnCXXExitDeclInitializer(Scope *S, Decl *Dcl);
4914 /// \brief Create a new lambda closure type.
4915 CXXRecordDecl *createLambdaClosureType(SourceRange IntroducerRange,
4916 TypeSourceInfo *Info,
4917 bool KnownDependent,
4918 LambdaCaptureDefault CaptureDefault);
4920 /// \brief Start the definition of a lambda expression.
4921 CXXMethodDecl *startLambdaDefinition(CXXRecordDecl *Class,
4922 SourceRange IntroducerRange,
4923 TypeSourceInfo *MethodType,
4924 SourceLocation EndLoc,
4925 ArrayRef<ParmVarDecl *> Params);
4927 /// \brief Endow the lambda scope info with the relevant properties.
4928 void buildLambdaScope(sema::LambdaScopeInfo *LSI,
4929 CXXMethodDecl *CallOperator,
4930 SourceRange IntroducerRange,
4931 LambdaCaptureDefault CaptureDefault,
4932 SourceLocation CaptureDefaultLoc,
4933 bool ExplicitParams,
4934 bool ExplicitResultType,
4937 /// \brief Perform initialization analysis of the init-capture and perform
4938 /// any implicit conversions such as an lvalue-to-rvalue conversion if
4939 /// not being used to initialize a reference.
4940 QualType performLambdaInitCaptureInitialization(SourceLocation Loc,
4941 bool ByRef, IdentifierInfo *Id, Expr *&Init);
4942 /// \brief Create a dummy variable within the declcontext of the lambda's
4943 /// call operator, for name lookup purposes for a lambda init capture.
4945 /// CodeGen handles emission of lambda captures, ignoring these dummy
4946 /// variables appropriately.
4947 VarDecl *createLambdaInitCaptureVarDecl(SourceLocation Loc,
4948 QualType InitCaptureType, IdentifierInfo *Id, Expr *Init);
4950 /// \brief Build the implicit field for an init-capture.
4951 FieldDecl *buildInitCaptureField(sema::LambdaScopeInfo *LSI, VarDecl *Var);
4953 /// \brief Note that we have finished the explicit captures for the
4955 void finishLambdaExplicitCaptures(sema::LambdaScopeInfo *LSI);
4957 /// \brief Introduce the lambda parameters into scope.
4958 void addLambdaParameters(CXXMethodDecl *CallOperator, Scope *CurScope);
4960 /// \brief Deduce a block or lambda's return type based on the return
4961 /// statements present in the body.
4962 void deduceClosureReturnType(sema::CapturingScopeInfo &CSI);
4964 /// ActOnStartOfLambdaDefinition - This is called just before we start
4965 /// parsing the body of a lambda; it analyzes the explicit captures and
4966 /// arguments, and sets up various data-structures for the body of the
4968 void ActOnStartOfLambdaDefinition(LambdaIntroducer &Intro,
4969 Declarator &ParamInfo, Scope *CurScope);
4971 /// ActOnLambdaError - If there is an error parsing a lambda, this callback
4972 /// is invoked to pop the information about the lambda.
4973 void ActOnLambdaError(SourceLocation StartLoc, Scope *CurScope,
4974 bool IsInstantiation = false);
4976 /// ActOnLambdaExpr - This is called when the body of a lambda expression
4977 /// was successfully completed.
4978 ExprResult ActOnLambdaExpr(SourceLocation StartLoc, Stmt *Body,
4981 /// \brief Complete a lambda-expression having processed and attached the
4983 ExprResult BuildLambdaExpr(SourceLocation StartLoc, SourceLocation EndLoc,
4984 sema::LambdaScopeInfo *LSI);
4986 /// \brief Define the "body" of the conversion from a lambda object to a
4987 /// function pointer.
4989 /// This routine doesn't actually define a sensible body; rather, it fills
4990 /// in the initialization expression needed to copy the lambda object into
4991 /// the block, and IR generation actually generates the real body of the
4992 /// block pointer conversion.
4993 void DefineImplicitLambdaToFunctionPointerConversion(
4994 SourceLocation CurrentLoc, CXXConversionDecl *Conv);
4996 /// \brief Define the "body" of the conversion from a lambda object to a
4999 /// This routine doesn't actually define a sensible body; rather, it fills
5000 /// in the initialization expression needed to copy the lambda object into
5001 /// the block, and IR generation actually generates the real body of the
5002 /// block pointer conversion.
5003 void DefineImplicitLambdaToBlockPointerConversion(SourceLocation CurrentLoc,
5004 CXXConversionDecl *Conv);
5006 ExprResult BuildBlockForLambdaConversion(SourceLocation CurrentLocation,
5007 SourceLocation ConvLocation,
5008 CXXConversionDecl *Conv,
5011 // ParseObjCStringLiteral - Parse Objective-C string literals.
5012 ExprResult ParseObjCStringLiteral(SourceLocation *AtLocs,
5014 unsigned NumStrings);
5016 ExprResult BuildObjCStringLiteral(SourceLocation AtLoc, StringLiteral *S);
5018 /// BuildObjCNumericLiteral - builds an ObjCBoxedExpr AST node for the
5019 /// numeric literal expression. Type of the expression will be "NSNumber *"
5020 /// or "id" if NSNumber is unavailable.
5021 ExprResult BuildObjCNumericLiteral(SourceLocation AtLoc, Expr *Number);
5022 ExprResult ActOnObjCBoolLiteral(SourceLocation AtLoc, SourceLocation ValueLoc,
5024 ExprResult BuildObjCArrayLiteral(SourceRange SR, MultiExprArg Elements);
5026 /// BuildObjCBoxedExpr - builds an ObjCBoxedExpr AST node for the
5027 /// '@' prefixed parenthesized expression. The type of the expression will
5028 /// either be "NSNumber *" or "NSString *" depending on the type of
5029 /// ValueType, which is allowed to be a built-in numeric type or
5030 /// "char *" or "const char *".
5031 ExprResult BuildObjCBoxedExpr(SourceRange SR, Expr *ValueExpr);
5033 ExprResult BuildObjCSubscriptExpression(SourceLocation RB, Expr *BaseExpr,
5035 ObjCMethodDecl *getterMethod,
5036 ObjCMethodDecl *setterMethod);
5038 ExprResult BuildObjCDictionaryLiteral(SourceRange SR,
5039 ObjCDictionaryElement *Elements,
5040 unsigned NumElements);
5042 ExprResult BuildObjCEncodeExpression(SourceLocation AtLoc,
5043 TypeSourceInfo *EncodedTypeInfo,
5044 SourceLocation RParenLoc);
5045 ExprResult BuildCXXMemberCallExpr(Expr *Exp, NamedDecl *FoundDecl,
5046 CXXConversionDecl *Method,
5047 bool HadMultipleCandidates);
5049 ExprResult ParseObjCEncodeExpression(SourceLocation AtLoc,
5050 SourceLocation EncodeLoc,
5051 SourceLocation LParenLoc,
5053 SourceLocation RParenLoc);
5055 /// ParseObjCSelectorExpression - Build selector expression for \@selector
5056 ExprResult ParseObjCSelectorExpression(Selector Sel,
5057 SourceLocation AtLoc,
5058 SourceLocation SelLoc,
5059 SourceLocation LParenLoc,
5060 SourceLocation RParenLoc,
5061 bool WarnMultipleSelectors);
5063 /// ParseObjCProtocolExpression - Build protocol expression for \@protocol
5064 ExprResult ParseObjCProtocolExpression(IdentifierInfo * ProtocolName,
5065 SourceLocation AtLoc,
5066 SourceLocation ProtoLoc,
5067 SourceLocation LParenLoc,
5068 SourceLocation ProtoIdLoc,
5069 SourceLocation RParenLoc);
5071 //===--------------------------------------------------------------------===//
5074 Decl *ActOnStartLinkageSpecification(Scope *S,
5075 SourceLocation ExternLoc,
5077 SourceLocation LBraceLoc);
5078 Decl *ActOnFinishLinkageSpecification(Scope *S,
5080 SourceLocation RBraceLoc);
5083 //===--------------------------------------------------------------------===//
5086 bool isCurrentClassName(const IdentifierInfo &II, Scope *S,
5087 const CXXScopeSpec *SS = nullptr);
5088 bool isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS);
5090 bool ActOnAccessSpecifier(AccessSpecifier Access,
5091 SourceLocation ASLoc,
5092 SourceLocation ColonLoc,
5093 AttributeList *Attrs = nullptr);
5095 NamedDecl *ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS,
5097 MultiTemplateParamsArg TemplateParameterLists,
5098 Expr *BitfieldWidth, const VirtSpecifiers &VS,
5099 InClassInitStyle InitStyle);
5101 void ActOnStartCXXInClassMemberInitializer();
5102 void ActOnFinishCXXInClassMemberInitializer(Decl *VarDecl,
5103 SourceLocation EqualLoc,
5106 MemInitResult ActOnMemInitializer(Decl *ConstructorD,
5109 IdentifierInfo *MemberOrBase,
5110 ParsedType TemplateTypeTy,
5112 SourceLocation IdLoc,
5113 SourceLocation LParenLoc,
5114 ArrayRef<Expr *> Args,
5115 SourceLocation RParenLoc,
5116 SourceLocation EllipsisLoc);
5118 MemInitResult ActOnMemInitializer(Decl *ConstructorD,
5121 IdentifierInfo *MemberOrBase,
5122 ParsedType TemplateTypeTy,
5124 SourceLocation IdLoc,
5126 SourceLocation EllipsisLoc);
5128 MemInitResult BuildMemInitializer(Decl *ConstructorD,
5131 IdentifierInfo *MemberOrBase,
5132 ParsedType TemplateTypeTy,
5134 SourceLocation IdLoc,
5136 SourceLocation EllipsisLoc);
5138 MemInitResult BuildMemberInitializer(ValueDecl *Member,
5140 SourceLocation IdLoc);
5142 MemInitResult BuildBaseInitializer(QualType BaseType,
5143 TypeSourceInfo *BaseTInfo,
5145 CXXRecordDecl *ClassDecl,
5146 SourceLocation EllipsisLoc);
5148 MemInitResult BuildDelegatingInitializer(TypeSourceInfo *TInfo,
5150 CXXRecordDecl *ClassDecl);
5152 bool SetDelegatingInitializer(CXXConstructorDecl *Constructor,
5153 CXXCtorInitializer *Initializer);
5155 bool SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
5156 ArrayRef<CXXCtorInitializer *> Initializers = None);
5158 void SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation);
5161 /// MarkBaseAndMemberDestructorsReferenced - Given a record decl,
5162 /// mark all the non-trivial destructors of its members and bases as
5164 void MarkBaseAndMemberDestructorsReferenced(SourceLocation Loc,
5165 CXXRecordDecl *Record);
5167 /// \brief The list of classes whose vtables have been used within
5168 /// this translation unit, and the source locations at which the
5169 /// first use occurred.
5170 typedef std::pair<CXXRecordDecl*, SourceLocation> VTableUse;
5172 /// \brief The list of vtables that are required but have not yet been
5174 SmallVector<VTableUse, 16> VTableUses;
5176 /// \brief The set of classes whose vtables have been used within
5177 /// this translation unit, and a bit that will be true if the vtable is
5178 /// required to be emitted (otherwise, it should be emitted only if needed
5179 /// by code generation).
5180 llvm::DenseMap<CXXRecordDecl *, bool> VTablesUsed;
5182 /// \brief Load any externally-stored vtable uses.
5183 void LoadExternalVTableUses();
5185 /// \brief Note that the vtable for the given class was used at the
5187 void MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
5188 bool DefinitionRequired = false);
5190 /// \brief Mark the exception specifications of all virtual member functions
5191 /// in the given class as needed.
5192 void MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
5193 const CXXRecordDecl *RD);
5195 /// MarkVirtualMembersReferenced - Will mark all members of the given
5196 /// CXXRecordDecl referenced.
5197 void MarkVirtualMembersReferenced(SourceLocation Loc,
5198 const CXXRecordDecl *RD);
5200 /// \brief Define all of the vtables that have been used in this
5201 /// translation unit and reference any virtual members used by those
5204 /// \returns true if any work was done, false otherwise.
5205 bool DefineUsedVTables();
5207 void AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl);
5209 void ActOnMemInitializers(Decl *ConstructorDecl,
5210 SourceLocation ColonLoc,
5211 ArrayRef<CXXCtorInitializer*> MemInits,
5214 void checkClassLevelDLLAttribute(CXXRecordDecl *Class);
5215 void propagateDLLAttrToBaseClassTemplate(
5216 CXXRecordDecl *Class, Attr *ClassAttr,
5217 ClassTemplateSpecializationDecl *BaseTemplateSpec,
5218 SourceLocation BaseLoc);
5219 void CheckCompletedCXXClass(CXXRecordDecl *Record);
5220 void ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
5222 SourceLocation LBrac,
5223 SourceLocation RBrac,
5224 AttributeList *AttrList);
5225 void ActOnFinishCXXMemberDecls();
5226 void ActOnFinishCXXMemberDefaultArgs(Decl *D);
5228 void ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param);
5229 unsigned ActOnReenterTemplateScope(Scope *S, Decl *Template);
5230 void ActOnStartDelayedMemberDeclarations(Scope *S, Decl *Record);
5231 void ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *Method);
5232 void ActOnDelayedCXXMethodParameter(Scope *S, Decl *Param);
5233 void ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *Record);
5234 void ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *Method);
5235 void ActOnFinishDelayedMemberInitializers(Decl *Record);
5236 void MarkAsLateParsedTemplate(FunctionDecl *FD, Decl *FnD,
5237 CachedTokens &Toks);
5238 void UnmarkAsLateParsedTemplate(FunctionDecl *FD);
5239 bool IsInsideALocalClassWithinATemplateFunction();
5241 Decl *ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
5243 Expr *AssertMessageExpr,
5244 SourceLocation RParenLoc);
5245 Decl *BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
5247 StringLiteral *AssertMessageExpr,
5248 SourceLocation RParenLoc,
5251 FriendDecl *CheckFriendTypeDecl(SourceLocation LocStart,
5252 SourceLocation FriendLoc,
5253 TypeSourceInfo *TSInfo);
5254 Decl *ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
5255 MultiTemplateParamsArg TemplateParams);
5256 NamedDecl *ActOnFriendFunctionDecl(Scope *S, Declarator &D,
5257 MultiTemplateParamsArg TemplateParams);
5259 QualType CheckConstructorDeclarator(Declarator &D, QualType R,
5261 void CheckConstructor(CXXConstructorDecl *Constructor);
5262 QualType CheckDestructorDeclarator(Declarator &D, QualType R,
5264 bool CheckDestructor(CXXDestructorDecl *Destructor);
5265 void CheckConversionDeclarator(Declarator &D, QualType &R,
5267 Decl *ActOnConversionDeclarator(CXXConversionDecl *Conversion);
5269 void CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD);
5270 void CheckExplicitlyDefaultedMemberExceptionSpec(CXXMethodDecl *MD,
5271 const FunctionProtoType *T);
5272 void CheckDelayedMemberExceptionSpecs();
5274 //===--------------------------------------------------------------------===//
5275 // C++ Derived Classes
5278 /// ActOnBaseSpecifier - Parsed a base specifier
5279 CXXBaseSpecifier *CheckBaseSpecifier(CXXRecordDecl *Class,
5280 SourceRange SpecifierRange,
5281 bool Virtual, AccessSpecifier Access,
5282 TypeSourceInfo *TInfo,
5283 SourceLocation EllipsisLoc);
5285 BaseResult ActOnBaseSpecifier(Decl *classdecl,
5286 SourceRange SpecifierRange,
5287 ParsedAttributes &Attrs,
5288 bool Virtual, AccessSpecifier Access,
5289 ParsedType basetype,
5290 SourceLocation BaseLoc,
5291 SourceLocation EllipsisLoc);
5293 bool AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
5295 void ActOnBaseSpecifiers(Decl *ClassDecl, CXXBaseSpecifier **Bases,
5298 bool IsDerivedFrom(QualType Derived, QualType Base);
5299 bool IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths);
5301 // FIXME: I don't like this name.
5302 void BuildBasePathArray(const CXXBasePaths &Paths, CXXCastPath &BasePath);
5304 bool CheckDerivedToBaseConversion(QualType Derived, QualType Base,
5305 SourceLocation Loc, SourceRange Range,
5306 CXXCastPath *BasePath = nullptr,
5307 bool IgnoreAccess = false);
5308 bool CheckDerivedToBaseConversion(QualType Derived, QualType Base,
5309 unsigned InaccessibleBaseID,
5310 unsigned AmbigiousBaseConvID,
5311 SourceLocation Loc, SourceRange Range,
5312 DeclarationName Name,
5313 CXXCastPath *BasePath);
5315 std::string getAmbiguousPathsDisplayString(CXXBasePaths &Paths);
5317 bool CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
5318 const CXXMethodDecl *Old);
5320 /// CheckOverridingFunctionReturnType - Checks whether the return types are
5321 /// covariant, according to C++ [class.virtual]p5.
5322 bool CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
5323 const CXXMethodDecl *Old);
5325 /// CheckOverridingFunctionExceptionSpec - Checks whether the exception
5326 /// spec is a subset of base spec.
5327 bool CheckOverridingFunctionExceptionSpec(const CXXMethodDecl *New,
5328 const CXXMethodDecl *Old);
5330 bool CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange);
5332 /// CheckOverrideControl - Check C++11 override control semantics.
5333 void CheckOverrideControl(NamedDecl *D);
5335 /// DiagnoseAbsenceOfOverrideControl - Diagnose if 'override' keyword was
5336 /// not used in the declaration of an overriding method.
5337 void DiagnoseAbsenceOfOverrideControl(NamedDecl *D);
5339 /// CheckForFunctionMarkedFinal - Checks whether a virtual member function
5340 /// overrides a virtual member function marked 'final', according to
5341 /// C++11 [class.virtual]p4.
5342 bool CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
5343 const CXXMethodDecl *Old);
5346 //===--------------------------------------------------------------------===//
5347 // C++ Access Control
5357 bool SetMemberAccessSpecifier(NamedDecl *MemberDecl,
5358 NamedDecl *PrevMemberDecl,
5359 AccessSpecifier LexicalAS);
5361 AccessResult CheckUnresolvedMemberAccess(UnresolvedMemberExpr *E,
5362 DeclAccessPair FoundDecl);
5363 AccessResult CheckUnresolvedLookupAccess(UnresolvedLookupExpr *E,
5364 DeclAccessPair FoundDecl);
5365 AccessResult CheckAllocationAccess(SourceLocation OperatorLoc,
5366 SourceRange PlacementRange,
5367 CXXRecordDecl *NamingClass,
5368 DeclAccessPair FoundDecl,
5369 bool Diagnose = true);
5370 AccessResult CheckConstructorAccess(SourceLocation Loc,
5371 CXXConstructorDecl *D,
5372 const InitializedEntity &Entity,
5373 AccessSpecifier Access,
5374 bool IsCopyBindingRefToTemp = false);
5375 AccessResult CheckConstructorAccess(SourceLocation Loc,
5376 CXXConstructorDecl *D,
5377 const InitializedEntity &Entity,
5378 AccessSpecifier Access,
5379 const PartialDiagnostic &PDiag);
5380 AccessResult CheckDestructorAccess(SourceLocation Loc,
5381 CXXDestructorDecl *Dtor,
5382 const PartialDiagnostic &PDiag,
5383 QualType objectType = QualType());
5384 AccessResult CheckFriendAccess(NamedDecl *D);
5385 AccessResult CheckMemberAccess(SourceLocation UseLoc,
5386 CXXRecordDecl *NamingClass,
5387 DeclAccessPair Found);
5388 AccessResult CheckMemberOperatorAccess(SourceLocation Loc,
5391 DeclAccessPair FoundDecl);
5392 AccessResult CheckAddressOfMemberAccess(Expr *OvlExpr,
5393 DeclAccessPair FoundDecl);
5394 AccessResult CheckBaseClassAccess(SourceLocation AccessLoc,
5395 QualType Base, QualType Derived,
5396 const CXXBasePath &Path,
5398 bool ForceCheck = false,
5399 bool ForceUnprivileged = false);
5400 void CheckLookupAccess(const LookupResult &R);
5401 bool IsSimplyAccessible(NamedDecl *decl, DeclContext *Ctx);
5402 bool isSpecialMemberAccessibleForDeletion(CXXMethodDecl *decl,
5403 AccessSpecifier access,
5404 QualType objectType);
5406 void HandleDependentAccessCheck(const DependentDiagnostic &DD,
5407 const MultiLevelTemplateArgumentList &TemplateArgs);
5408 void PerformDependentDiagnostics(const DeclContext *Pattern,
5409 const MultiLevelTemplateArgumentList &TemplateArgs);
5411 void HandleDelayedAccessCheck(sema::DelayedDiagnostic &DD, Decl *Ctx);
5413 /// \brief When true, access checking violations are treated as SFINAE
5414 /// failures rather than hard errors.
5415 bool AccessCheckingSFINAE;
5417 enum AbstractDiagSelID {
5421 AbstractVariableType,
5424 AbstractSynthesizedIvarType,
5428 bool RequireNonAbstractType(SourceLocation Loc, QualType T,
5429 TypeDiagnoser &Diagnoser);
5430 template <typename... Ts>
5431 bool RequireNonAbstractType(SourceLocation Loc, QualType T, unsigned DiagID,
5432 const Ts &...Args) {
5433 BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
5434 return RequireNonAbstractType(Loc, T, Diagnoser);
5437 void DiagnoseAbstractType(const CXXRecordDecl *RD);
5439 bool RequireNonAbstractType(SourceLocation Loc, QualType T, unsigned DiagID,
5440 AbstractDiagSelID SelID = AbstractNone);
5442 //===--------------------------------------------------------------------===//
5443 // C++ Overloaded Operators [C++ 13.5]
5446 bool CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl);
5448 bool CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl);
5450 //===--------------------------------------------------------------------===//
5451 // C++ Templates [C++ 14]
5453 void FilterAcceptableTemplateNames(LookupResult &R,
5454 bool AllowFunctionTemplates = true);
5455 bool hasAnyAcceptableTemplateNames(LookupResult &R,
5456 bool AllowFunctionTemplates = true);
5458 void LookupTemplateName(LookupResult &R, Scope *S, CXXScopeSpec &SS,
5459 QualType ObjectType, bool EnteringContext,
5460 bool &MemberOfUnknownSpecialization);
5462 TemplateNameKind isTemplateName(Scope *S,
5464 bool hasTemplateKeyword,
5465 UnqualifiedId &Name,
5466 ParsedType ObjectType,
5467 bool EnteringContext,
5468 TemplateTy &Template,
5469 bool &MemberOfUnknownSpecialization);
5471 bool DiagnoseUnknownTemplateName(const IdentifierInfo &II,
5472 SourceLocation IILoc,
5474 const CXXScopeSpec *SS,
5475 TemplateTy &SuggestedTemplate,
5476 TemplateNameKind &SuggestedKind);
5478 void DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl);
5479 TemplateDecl *AdjustDeclIfTemplate(Decl *&Decl);
5481 Decl *ActOnTypeParameter(Scope *S, bool Typename,
5482 SourceLocation EllipsisLoc,
5483 SourceLocation KeyLoc,
5484 IdentifierInfo *ParamName,
5485 SourceLocation ParamNameLoc,
5486 unsigned Depth, unsigned Position,
5487 SourceLocation EqualLoc,
5488 ParsedType DefaultArg);
5490 QualType CheckNonTypeTemplateParameterType(QualType T, SourceLocation Loc);
5491 Decl *ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
5494 SourceLocation EqualLoc,
5496 Decl *ActOnTemplateTemplateParameter(Scope *S,
5497 SourceLocation TmpLoc,
5498 TemplateParameterList *Params,
5499 SourceLocation EllipsisLoc,
5500 IdentifierInfo *ParamName,
5501 SourceLocation ParamNameLoc,
5504 SourceLocation EqualLoc,
5505 ParsedTemplateArgument DefaultArg);
5507 TemplateParameterList *
5508 ActOnTemplateParameterList(unsigned Depth,
5509 SourceLocation ExportLoc,
5510 SourceLocation TemplateLoc,
5511 SourceLocation LAngleLoc,
5512 Decl **Params, unsigned NumParams,
5513 SourceLocation RAngleLoc);
5515 /// \brief The context in which we are checking a template parameter list.
5516 enum TemplateParamListContext {
5519 TPC_FunctionTemplate,
5520 TPC_ClassTemplateMember,
5521 TPC_FriendClassTemplate,
5522 TPC_FriendFunctionTemplate,
5523 TPC_FriendFunctionTemplateDefinition,
5524 TPC_TypeAliasTemplate
5527 bool CheckTemplateParameterList(TemplateParameterList *NewParams,
5528 TemplateParameterList *OldParams,
5529 TemplateParamListContext TPC);
5530 TemplateParameterList *MatchTemplateParametersToScopeSpecifier(
5531 SourceLocation DeclStartLoc, SourceLocation DeclLoc,
5532 const CXXScopeSpec &SS, TemplateIdAnnotation *TemplateId,
5533 ArrayRef<TemplateParameterList *> ParamLists,
5534 bool IsFriend, bool &IsExplicitSpecialization, bool &Invalid);
5536 DeclResult CheckClassTemplate(Scope *S, unsigned TagSpec, TagUseKind TUK,
5537 SourceLocation KWLoc, CXXScopeSpec &SS,
5538 IdentifierInfo *Name, SourceLocation NameLoc,
5539 AttributeList *Attr,
5540 TemplateParameterList *TemplateParams,
5542 SourceLocation ModulePrivateLoc,
5543 SourceLocation FriendLoc,
5544 unsigned NumOuterTemplateParamLists,
5545 TemplateParameterList **OuterTemplateParamLists,
5546 SkipBodyInfo *SkipBody = nullptr);
5548 void translateTemplateArguments(const ASTTemplateArgsPtr &In,
5549 TemplateArgumentListInfo &Out);
5551 void NoteAllFoundTemplates(TemplateName Name);
5553 QualType CheckTemplateIdType(TemplateName Template,
5554 SourceLocation TemplateLoc,
5555 TemplateArgumentListInfo &TemplateArgs);
5558 ActOnTemplateIdType(CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
5559 TemplateTy Template, SourceLocation TemplateLoc,
5560 SourceLocation LAngleLoc,
5561 ASTTemplateArgsPtr TemplateArgs,
5562 SourceLocation RAngleLoc,
5563 bool IsCtorOrDtorName = false);
5565 /// \brief Parsed an elaborated-type-specifier that refers to a template-id,
5566 /// such as \c class T::template apply<U>.
5567 TypeResult ActOnTagTemplateIdType(TagUseKind TUK,
5568 TypeSpecifierType TagSpec,
5569 SourceLocation TagLoc,
5571 SourceLocation TemplateKWLoc,
5572 TemplateTy TemplateD,
5573 SourceLocation TemplateLoc,
5574 SourceLocation LAngleLoc,
5575 ASTTemplateArgsPtr TemplateArgsIn,
5576 SourceLocation RAngleLoc);
5578 DeclResult ActOnVarTemplateSpecialization(
5579 Scope *S, Declarator &D, TypeSourceInfo *DI,
5580 SourceLocation TemplateKWLoc, TemplateParameterList *TemplateParams,
5581 StorageClass SC, bool IsPartialSpecialization);
5583 DeclResult CheckVarTemplateId(VarTemplateDecl *Template,
5584 SourceLocation TemplateLoc,
5585 SourceLocation TemplateNameLoc,
5586 const TemplateArgumentListInfo &TemplateArgs);
5588 ExprResult CheckVarTemplateId(const CXXScopeSpec &SS,
5589 const DeclarationNameInfo &NameInfo,
5590 VarTemplateDecl *Template,
5591 SourceLocation TemplateLoc,
5592 const TemplateArgumentListInfo *TemplateArgs);
5594 ExprResult BuildTemplateIdExpr(const CXXScopeSpec &SS,
5595 SourceLocation TemplateKWLoc,
5598 const TemplateArgumentListInfo *TemplateArgs);
5600 ExprResult BuildQualifiedTemplateIdExpr(CXXScopeSpec &SS,
5601 SourceLocation TemplateKWLoc,
5602 const DeclarationNameInfo &NameInfo,
5603 const TemplateArgumentListInfo *TemplateArgs);
5605 TemplateNameKind ActOnDependentTemplateName(Scope *S,
5607 SourceLocation TemplateKWLoc,
5608 UnqualifiedId &Name,
5609 ParsedType ObjectType,
5610 bool EnteringContext,
5611 TemplateTy &Template);
5614 ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec, TagUseKind TUK,
5615 SourceLocation KWLoc,
5616 SourceLocation ModulePrivateLoc,
5617 TemplateIdAnnotation &TemplateId,
5618 AttributeList *Attr,
5619 MultiTemplateParamsArg TemplateParameterLists,
5620 SkipBodyInfo *SkipBody = nullptr);
5622 Decl *ActOnTemplateDeclarator(Scope *S,
5623 MultiTemplateParamsArg TemplateParameterLists,
5626 Decl *ActOnStartOfFunctionTemplateDef(Scope *FnBodyScope,
5627 MultiTemplateParamsArg TemplateParameterLists,
5631 CheckSpecializationInstantiationRedecl(SourceLocation NewLoc,
5632 TemplateSpecializationKind NewTSK,
5633 NamedDecl *PrevDecl,
5634 TemplateSpecializationKind PrevTSK,
5635 SourceLocation PrevPtOfInstantiation,
5638 bool CheckDependentFunctionTemplateSpecialization(FunctionDecl *FD,
5639 const TemplateArgumentListInfo &ExplicitTemplateArgs,
5640 LookupResult &Previous);
5642 bool CheckFunctionTemplateSpecialization(FunctionDecl *FD,
5643 TemplateArgumentListInfo *ExplicitTemplateArgs,
5644 LookupResult &Previous);
5645 bool CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous);
5648 ActOnExplicitInstantiation(Scope *S,
5649 SourceLocation ExternLoc,
5650 SourceLocation TemplateLoc,
5652 SourceLocation KWLoc,
5653 const CXXScopeSpec &SS,
5654 TemplateTy Template,
5655 SourceLocation TemplateNameLoc,
5656 SourceLocation LAngleLoc,
5657 ASTTemplateArgsPtr TemplateArgs,
5658 SourceLocation RAngleLoc,
5659 AttributeList *Attr);
5662 ActOnExplicitInstantiation(Scope *S,
5663 SourceLocation ExternLoc,
5664 SourceLocation TemplateLoc,
5666 SourceLocation KWLoc,
5668 IdentifierInfo *Name,
5669 SourceLocation NameLoc,
5670 AttributeList *Attr);
5672 DeclResult ActOnExplicitInstantiation(Scope *S,
5673 SourceLocation ExternLoc,
5674 SourceLocation TemplateLoc,
5678 SubstDefaultTemplateArgumentIfAvailable(TemplateDecl *Template,
5679 SourceLocation TemplateLoc,
5680 SourceLocation RAngleLoc,
5682 SmallVectorImpl<TemplateArgument>
5684 bool &HasDefaultArg);
5686 /// \brief Specifies the context in which a particular template
5687 /// argument is being checked.
5688 enum CheckTemplateArgumentKind {
5689 /// \brief The template argument was specified in the code or was
5690 /// instantiated with some deduced template arguments.
5693 /// \brief The template argument was deduced via template argument
5697 /// \brief The template argument was deduced from an array bound
5698 /// via template argument deduction.
5699 CTAK_DeducedFromArrayBound
5702 bool CheckTemplateArgument(NamedDecl *Param,
5703 TemplateArgumentLoc &Arg,
5704 NamedDecl *Template,
5705 SourceLocation TemplateLoc,
5706 SourceLocation RAngleLoc,
5707 unsigned ArgumentPackIndex,
5708 SmallVectorImpl<TemplateArgument> &Converted,
5709 CheckTemplateArgumentKind CTAK = CTAK_Specified);
5711 /// \brief Check that the given template arguments can be be provided to
5712 /// the given template, converting the arguments along the way.
5714 /// \param Template The template to which the template arguments are being
5717 /// \param TemplateLoc The location of the template name in the source.
5719 /// \param TemplateArgs The list of template arguments. If the template is
5720 /// a template template parameter, this function may extend the set of
5721 /// template arguments to also include substituted, defaulted template
5724 /// \param PartialTemplateArgs True if the list of template arguments is
5725 /// intentionally partial, e.g., because we're checking just the initial
5726 /// set of template arguments.
5728 /// \param Converted Will receive the converted, canonicalized template
5731 /// \returns true if an error occurred, false otherwise.
5732 bool CheckTemplateArgumentList(TemplateDecl *Template,
5733 SourceLocation TemplateLoc,
5734 TemplateArgumentListInfo &TemplateArgs,
5735 bool PartialTemplateArgs,
5736 SmallVectorImpl<TemplateArgument> &Converted);
5738 bool CheckTemplateTypeArgument(TemplateTypeParmDecl *Param,
5739 TemplateArgumentLoc &Arg,
5740 SmallVectorImpl<TemplateArgument> &Converted);
5742 bool CheckTemplateArgument(TemplateTypeParmDecl *Param,
5743 TypeSourceInfo *Arg);
5744 ExprResult CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
5745 QualType InstantiatedParamType, Expr *Arg,
5746 TemplateArgument &Converted,
5747 CheckTemplateArgumentKind CTAK = CTAK_Specified);
5748 bool CheckTemplateArgument(TemplateTemplateParmDecl *Param,
5749 TemplateArgumentLoc &Arg,
5750 unsigned ArgumentPackIndex);
5753 BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg,
5755 SourceLocation Loc);
5757 BuildExpressionFromIntegralTemplateArgument(const TemplateArgument &Arg,
5758 SourceLocation Loc);
5760 /// \brief Enumeration describing how template parameter lists are compared
5762 enum TemplateParameterListEqualKind {
5763 /// \brief We are matching the template parameter lists of two templates
5764 /// that might be redeclarations.
5767 /// template<typename T> struct X;
5768 /// template<typename T> struct X;
5772 /// \brief We are matching the template parameter lists of two template
5773 /// template parameters as part of matching the template parameter lists
5774 /// of two templates that might be redeclarations.
5777 /// template<template<int I> class TT> struct X;
5778 /// template<template<int Value> class Other> struct X;
5780 TPL_TemplateTemplateParmMatch,
5782 /// \brief We are matching the template parameter lists of a template
5783 /// template argument against the template parameter lists of a template
5784 /// template parameter.
5787 /// template<template<int Value> class Metafun> struct X;
5788 /// template<int Value> struct integer_c;
5789 /// X<integer_c> xic;
5791 TPL_TemplateTemplateArgumentMatch
5794 bool TemplateParameterListsAreEqual(TemplateParameterList *New,
5795 TemplateParameterList *Old,
5797 TemplateParameterListEqualKind Kind,
5798 SourceLocation TemplateArgLoc
5799 = SourceLocation());
5801 bool CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams);
5803 /// \brief Called when the parser has parsed a C++ typename
5804 /// specifier, e.g., "typename T::type".
5806 /// \param S The scope in which this typename type occurs.
5807 /// \param TypenameLoc the location of the 'typename' keyword
5808 /// \param SS the nested-name-specifier following the typename (e.g., 'T::').
5809 /// \param II the identifier we're retrieving (e.g., 'type' in the example).
5810 /// \param IdLoc the location of the identifier.
5812 ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
5813 const CXXScopeSpec &SS, const IdentifierInfo &II,
5814 SourceLocation IdLoc);
5816 /// \brief Called when the parser has parsed a C++ typename
5817 /// specifier that ends in a template-id, e.g.,
5818 /// "typename MetaFun::template apply<T1, T2>".
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 TemplateLoc the location of the 'template' keyword, if any.
5824 /// \param TemplateName The template name.
5825 /// \param TemplateNameLoc The location of the template name.
5826 /// \param LAngleLoc The location of the opening angle bracket ('<').
5827 /// \param TemplateArgs The template arguments.
5828 /// \param RAngleLoc The location of the closing angle bracket ('>').
5830 ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
5831 const CXXScopeSpec &SS,
5832 SourceLocation TemplateLoc,
5833 TemplateTy TemplateName,
5834 SourceLocation TemplateNameLoc,
5835 SourceLocation LAngleLoc,
5836 ASTTemplateArgsPtr TemplateArgs,
5837 SourceLocation RAngleLoc);
5839 QualType CheckTypenameType(ElaboratedTypeKeyword Keyword,
5840 SourceLocation KeywordLoc,
5841 NestedNameSpecifierLoc QualifierLoc,
5842 const IdentifierInfo &II,
5843 SourceLocation IILoc);
5845 TypeSourceInfo *RebuildTypeInCurrentInstantiation(TypeSourceInfo *T,
5847 DeclarationName Name);
5848 bool RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS);
5850 ExprResult RebuildExprInCurrentInstantiation(Expr *E);
5851 bool RebuildTemplateParamsInCurrentInstantiation(
5852 TemplateParameterList *Params);
5855 getTemplateArgumentBindingsText(const TemplateParameterList *Params,
5856 const TemplateArgumentList &Args);
5859 getTemplateArgumentBindingsText(const TemplateParameterList *Params,
5860 const TemplateArgument *Args,
5863 //===--------------------------------------------------------------------===//
5864 // C++ Variadic Templates (C++0x [temp.variadic])
5865 //===--------------------------------------------------------------------===//
5867 /// Determine whether an unexpanded parameter pack might be permitted in this
5868 /// location. Useful for error recovery.
5869 bool isUnexpandedParameterPackPermitted();
5871 /// \brief The context in which an unexpanded parameter pack is
5872 /// being diagnosed.
5874 /// Note that the values of this enumeration line up with the first
5875 /// argument to the \c err_unexpanded_parameter_pack diagnostic.
5876 enum UnexpandedParameterPackContext {
5877 /// \brief An arbitrary expression.
5878 UPPC_Expression = 0,
5880 /// \brief The base type of a class type.
5883 /// \brief The type of an arbitrary declaration.
5884 UPPC_DeclarationType,
5886 /// \brief The type of a data member.
5887 UPPC_DataMemberType,
5889 /// \brief The size of a bit-field.
5892 /// \brief The expression in a static assertion.
5893 UPPC_StaticAssertExpression,
5895 /// \brief The fixed underlying type of an enumeration.
5896 UPPC_FixedUnderlyingType,
5898 /// \brief The enumerator value.
5899 UPPC_EnumeratorValue,
5901 /// \brief A using declaration.
5902 UPPC_UsingDeclaration,
5904 /// \brief A friend declaration.
5905 UPPC_FriendDeclaration,
5907 /// \brief A declaration qualifier.
5908 UPPC_DeclarationQualifier,
5910 /// \brief An initializer.
5913 /// \brief A default argument.
5914 UPPC_DefaultArgument,
5916 /// \brief The type of a non-type template parameter.
5917 UPPC_NonTypeTemplateParameterType,
5919 /// \brief The type of an exception.
5922 /// \brief Partial specialization.
5923 UPPC_PartialSpecialization,
5925 /// \brief Microsoft __if_exists.
5928 /// \brief Microsoft __if_not_exists.
5931 /// \brief Lambda expression.
5934 /// \brief Block expression,
5938 /// \brief Diagnose unexpanded parameter packs.
5940 /// \param Loc The location at which we should emit the diagnostic.
5942 /// \param UPPC The context in which we are diagnosing unexpanded
5943 /// parameter packs.
5945 /// \param Unexpanded the set of unexpanded parameter packs.
5947 /// \returns true if an error occurred, false otherwise.
5948 bool DiagnoseUnexpandedParameterPacks(SourceLocation Loc,
5949 UnexpandedParameterPackContext UPPC,
5950 ArrayRef<UnexpandedParameterPack> Unexpanded);
5952 /// \brief If the given type contains an unexpanded parameter pack,
5953 /// diagnose the error.
5955 /// \param Loc The source location where a diagnostc should be emitted.
5957 /// \param T The type that is being checked for unexpanded parameter
5960 /// \returns true if an error occurred, false otherwise.
5961 bool DiagnoseUnexpandedParameterPack(SourceLocation Loc, TypeSourceInfo *T,
5962 UnexpandedParameterPackContext UPPC);
5964 /// \brief If the given expression contains an unexpanded parameter
5965 /// pack, diagnose the error.
5967 /// \param E The expression that is being checked for unexpanded
5968 /// parameter packs.
5970 /// \returns true if an error occurred, false otherwise.
5971 bool DiagnoseUnexpandedParameterPack(Expr *E,
5972 UnexpandedParameterPackContext UPPC = UPPC_Expression);
5974 /// \brief If the given nested-name-specifier contains an unexpanded
5975 /// parameter pack, diagnose the error.
5977 /// \param SS The nested-name-specifier that is being checked for
5978 /// unexpanded parameter packs.
5980 /// \returns true if an error occurred, false otherwise.
5981 bool DiagnoseUnexpandedParameterPack(const CXXScopeSpec &SS,
5982 UnexpandedParameterPackContext UPPC);
5984 /// \brief If the given name contains an unexpanded parameter pack,
5985 /// diagnose the error.
5987 /// \param NameInfo The name (with source location information) that
5988 /// is being checked for unexpanded parameter packs.
5990 /// \returns true if an error occurred, false otherwise.
5991 bool DiagnoseUnexpandedParameterPack(const DeclarationNameInfo &NameInfo,
5992 UnexpandedParameterPackContext UPPC);
5994 /// \brief If the given template name contains an unexpanded parameter pack,
5995 /// diagnose the error.
5997 /// \param Loc The location of the template name.
5999 /// \param Template The template name that is being checked for unexpanded
6000 /// parameter packs.
6002 /// \returns true if an error occurred, false otherwise.
6003 bool DiagnoseUnexpandedParameterPack(SourceLocation Loc,
6004 TemplateName Template,
6005 UnexpandedParameterPackContext UPPC);
6007 /// \brief If the given template argument contains an unexpanded parameter
6008 /// pack, diagnose the error.
6010 /// \param Arg The template argument that is being checked for unexpanded
6011 /// parameter packs.
6013 /// \returns true if an error occurred, false otherwise.
6014 bool DiagnoseUnexpandedParameterPack(TemplateArgumentLoc Arg,
6015 UnexpandedParameterPackContext UPPC);
6017 /// \brief Collect the set of unexpanded parameter packs within the given
6018 /// template argument.
6020 /// \param Arg The template argument that will be traversed to find
6021 /// unexpanded parameter packs.
6022 void collectUnexpandedParameterPacks(TemplateArgument Arg,
6023 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
6025 /// \brief Collect the set of unexpanded parameter packs within the given
6026 /// template argument.
6028 /// \param Arg The template argument that will be traversed to find
6029 /// unexpanded parameter packs.
6030 void collectUnexpandedParameterPacks(TemplateArgumentLoc Arg,
6031 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
6033 /// \brief Collect the set of unexpanded parameter packs within the given
6036 /// \param T The type that will be traversed to find
6037 /// unexpanded parameter packs.
6038 void collectUnexpandedParameterPacks(QualType T,
6039 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
6041 /// \brief Collect the set of unexpanded parameter packs within the given
6044 /// \param TL The type that will be traversed to find
6045 /// unexpanded parameter packs.
6046 void collectUnexpandedParameterPacks(TypeLoc TL,
6047 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
6049 /// \brief Collect the set of unexpanded parameter packs within the given
6050 /// nested-name-specifier.
6052 /// \param SS The nested-name-specifier that will be traversed to find
6053 /// unexpanded parameter packs.
6054 void collectUnexpandedParameterPacks(CXXScopeSpec &SS,
6055 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
6057 /// \brief Collect the set of unexpanded parameter packs within the given
6060 /// \param NameInfo The name that will be traversed to find
6061 /// unexpanded parameter packs.
6062 void collectUnexpandedParameterPacks(const DeclarationNameInfo &NameInfo,
6063 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
6065 /// \brief Invoked when parsing a template argument followed by an
6066 /// ellipsis, which creates a pack expansion.
6068 /// \param Arg The template argument preceding the ellipsis, which
6069 /// may already be invalid.
6071 /// \param EllipsisLoc The location of the ellipsis.
6072 ParsedTemplateArgument ActOnPackExpansion(const ParsedTemplateArgument &Arg,
6073 SourceLocation EllipsisLoc);
6075 /// \brief Invoked when parsing a type followed by an ellipsis, which
6076 /// creates a pack expansion.
6078 /// \param Type The type preceding the ellipsis, which will become
6079 /// the pattern of the pack expansion.
6081 /// \param EllipsisLoc The location of the ellipsis.
6082 TypeResult ActOnPackExpansion(ParsedType Type, SourceLocation EllipsisLoc);
6084 /// \brief Construct a pack expansion type from the pattern of the pack
6086 TypeSourceInfo *CheckPackExpansion(TypeSourceInfo *Pattern,
6087 SourceLocation EllipsisLoc,
6088 Optional<unsigned> NumExpansions);
6090 /// \brief Construct a pack expansion type from the pattern of the pack
6092 QualType CheckPackExpansion(QualType Pattern,
6093 SourceRange PatternRange,
6094 SourceLocation EllipsisLoc,
6095 Optional<unsigned> NumExpansions);
6097 /// \brief Invoked when parsing an expression followed by an ellipsis, which
6098 /// creates a pack expansion.
6100 /// \param Pattern The expression preceding the ellipsis, which will become
6101 /// the pattern of the pack expansion.
6103 /// \param EllipsisLoc The location of the ellipsis.
6104 ExprResult ActOnPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc);
6106 /// \brief Invoked when parsing an expression followed by an ellipsis, which
6107 /// creates a pack expansion.
6109 /// \param Pattern The expression preceding the ellipsis, which will become
6110 /// the pattern of the pack expansion.
6112 /// \param EllipsisLoc The location of the ellipsis.
6113 ExprResult CheckPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc,
6114 Optional<unsigned> NumExpansions);
6116 /// \brief Determine whether we could expand a pack expansion with the
6117 /// given set of parameter packs into separate arguments by repeatedly
6118 /// transforming the pattern.
6120 /// \param EllipsisLoc The location of the ellipsis that identifies the
6123 /// \param PatternRange The source range that covers the entire pattern of
6124 /// the pack expansion.
6126 /// \param Unexpanded The set of unexpanded parameter packs within the
6129 /// \param ShouldExpand Will be set to \c true if the transformer should
6130 /// expand the corresponding pack expansions into separate arguments. When
6131 /// set, \c NumExpansions must also be set.
6133 /// \param RetainExpansion Whether the caller should add an unexpanded
6134 /// pack expansion after all of the expanded arguments. This is used
6135 /// when extending explicitly-specified template argument packs per
6136 /// C++0x [temp.arg.explicit]p9.
6138 /// \param NumExpansions The number of separate arguments that will be in
6139 /// the expanded form of the corresponding pack expansion. This is both an
6140 /// input and an output parameter, which can be set by the caller if the
6141 /// number of expansions is known a priori (e.g., due to a prior substitution)
6142 /// and will be set by the callee when the number of expansions is known.
6143 /// The callee must set this value when \c ShouldExpand is \c true; it may
6144 /// set this value in other cases.
6146 /// \returns true if an error occurred (e.g., because the parameter packs
6147 /// are to be instantiated with arguments of different lengths), false
6148 /// otherwise. If false, \c ShouldExpand (and possibly \c NumExpansions)
6150 bool CheckParameterPacksForExpansion(SourceLocation EllipsisLoc,
6151 SourceRange PatternRange,
6152 ArrayRef<UnexpandedParameterPack> Unexpanded,
6153 const MultiLevelTemplateArgumentList &TemplateArgs,
6155 bool &RetainExpansion,
6156 Optional<unsigned> &NumExpansions);
6158 /// \brief Determine the number of arguments in the given pack expansion
6161 /// This routine assumes that the number of arguments in the expansion is
6162 /// consistent across all of the unexpanded parameter packs in its pattern.
6164 /// Returns an empty Optional if the type can't be expanded.
6165 Optional<unsigned> getNumArgumentsInExpansion(QualType T,
6166 const MultiLevelTemplateArgumentList &TemplateArgs);
6168 /// \brief Determine whether the given declarator contains any unexpanded
6169 /// parameter packs.
6171 /// This routine is used by the parser to disambiguate function declarators
6172 /// with an ellipsis prior to the ')', e.g.,
6178 /// To determine whether we have an (unnamed) function parameter pack or
6179 /// a variadic function.
6181 /// \returns true if the declarator contains any unexpanded parameter packs,
6182 /// false otherwise.
6183 bool containsUnexpandedParameterPacks(Declarator &D);
6185 /// \brief Returns the pattern of the pack expansion for a template argument.
6187 /// \param OrigLoc The template argument to expand.
6189 /// \param Ellipsis Will be set to the location of the ellipsis.
6191 /// \param NumExpansions Will be set to the number of expansions that will
6192 /// be generated from this pack expansion, if known a priori.
6193 TemplateArgumentLoc getTemplateArgumentPackExpansionPattern(
6194 TemplateArgumentLoc OrigLoc,
6195 SourceLocation &Ellipsis,
6196 Optional<unsigned> &NumExpansions) const;
6198 //===--------------------------------------------------------------------===//
6199 // C++ Template Argument Deduction (C++ [temp.deduct])
6200 //===--------------------------------------------------------------------===//
6202 QualType adjustCCAndNoReturn(QualType ArgFunctionType, QualType FunctionType);
6204 /// \brief Describes the result of template argument deduction.
6206 /// The TemplateDeductionResult enumeration describes the result of
6207 /// template argument deduction, as returned from
6208 /// DeduceTemplateArguments(). The separate TemplateDeductionInfo
6209 /// structure provides additional information about the results of
6210 /// template argument deduction, e.g., the deduced template argument
6211 /// list (if successful) or the specific template parameters or
6212 /// deduced arguments that were involved in the failure.
6213 enum TemplateDeductionResult {
6214 /// \brief Template argument deduction was successful.
6216 /// \brief The declaration was invalid; do nothing.
6218 /// \brief Template argument deduction exceeded the maximum template
6219 /// instantiation depth (which has already been diagnosed).
6220 TDK_InstantiationDepth,
6221 /// \brief Template argument deduction did not deduce a value
6222 /// for every template parameter.
6224 /// \brief Template argument deduction produced inconsistent
6225 /// deduced values for the given template parameter.
6227 /// \brief Template argument deduction failed due to inconsistent
6228 /// cv-qualifiers on a template parameter type that would
6229 /// otherwise be deduced, e.g., we tried to deduce T in "const T"
6230 /// but were given a non-const "X".
6232 /// \brief Substitution of the deduced template argument values
6233 /// resulted in an error.
6234 TDK_SubstitutionFailure,
6235 /// \brief A non-depnedent component of the parameter did not match the
6236 /// corresponding component of the argument.
6237 TDK_NonDeducedMismatch,
6238 /// \brief When performing template argument deduction for a function
6239 /// template, there were too many call arguments.
6240 TDK_TooManyArguments,
6241 /// \brief When performing template argument deduction for a function
6242 /// template, there were too few call arguments.
6243 TDK_TooFewArguments,
6244 /// \brief The explicitly-specified template arguments were not valid
6245 /// template arguments for the given template.
6246 TDK_InvalidExplicitArguments,
6247 /// \brief The arguments included an overloaded function name that could
6248 /// not be resolved to a suitable function.
6249 TDK_FailedOverloadResolution,
6250 /// \brief Deduction failed; that's all we know.
6251 TDK_MiscellaneousDeductionFailure
6254 TemplateDeductionResult
6255 DeduceTemplateArguments(ClassTemplatePartialSpecializationDecl *Partial,
6256 const TemplateArgumentList &TemplateArgs,
6257 sema::TemplateDeductionInfo &Info);
6259 TemplateDeductionResult
6260 DeduceTemplateArguments(VarTemplatePartialSpecializationDecl *Partial,
6261 const TemplateArgumentList &TemplateArgs,
6262 sema::TemplateDeductionInfo &Info);
6264 TemplateDeductionResult SubstituteExplicitTemplateArguments(
6265 FunctionTemplateDecl *FunctionTemplate,
6266 TemplateArgumentListInfo &ExplicitTemplateArgs,
6267 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
6268 SmallVectorImpl<QualType> &ParamTypes, QualType *FunctionType,
6269 sema::TemplateDeductionInfo &Info);
6271 /// brief A function argument from which we performed template argument
6272 // deduction for a call.
6273 struct OriginalCallArg {
6274 OriginalCallArg(QualType OriginalParamType,
6276 QualType OriginalArgType)
6277 : OriginalParamType(OriginalParamType), ArgIdx(ArgIdx),
6278 OriginalArgType(OriginalArgType) { }
6280 QualType OriginalParamType;
6282 QualType OriginalArgType;
6285 TemplateDeductionResult
6286 FinishTemplateArgumentDeduction(FunctionTemplateDecl *FunctionTemplate,
6287 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
6288 unsigned NumExplicitlySpecified,
6289 FunctionDecl *&Specialization,
6290 sema::TemplateDeductionInfo &Info,
6291 SmallVectorImpl<OriginalCallArg> const *OriginalCallArgs = nullptr,
6292 bool PartialOverloading = false);
6294 TemplateDeductionResult
6295 DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
6296 TemplateArgumentListInfo *ExplicitTemplateArgs,
6297 ArrayRef<Expr *> Args,
6298 FunctionDecl *&Specialization,
6299 sema::TemplateDeductionInfo &Info,
6300 bool PartialOverloading = false);
6302 TemplateDeductionResult
6303 DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
6304 TemplateArgumentListInfo *ExplicitTemplateArgs,
6305 QualType ArgFunctionType,
6306 FunctionDecl *&Specialization,
6307 sema::TemplateDeductionInfo &Info,
6308 bool InOverloadResolution = false);
6310 TemplateDeductionResult
6311 DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
6313 CXXConversionDecl *&Specialization,
6314 sema::TemplateDeductionInfo &Info);
6316 TemplateDeductionResult
6317 DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
6318 TemplateArgumentListInfo *ExplicitTemplateArgs,
6319 FunctionDecl *&Specialization,
6320 sema::TemplateDeductionInfo &Info,
6321 bool InOverloadResolution = false);
6323 /// \brief Substitute Replacement for \p auto in \p TypeWithAuto
6324 QualType SubstAutoType(QualType TypeWithAuto, QualType Replacement);
6325 /// \brief Substitute Replacement for auto in TypeWithAuto
6326 TypeSourceInfo* SubstAutoTypeSourceInfo(TypeSourceInfo *TypeWithAuto,
6327 QualType Replacement);
6329 /// \brief Result type of DeduceAutoType.
6330 enum DeduceAutoResult {
6333 DAR_FailedAlreadyDiagnosed
6336 DeduceAutoResult DeduceAutoType(TypeSourceInfo *AutoType, Expr *&Initializer,
6338 DeduceAutoResult DeduceAutoType(TypeLoc AutoTypeLoc, Expr *&Initializer,
6340 void DiagnoseAutoDeductionFailure(VarDecl *VDecl, Expr *Init);
6341 bool DeduceReturnType(FunctionDecl *FD, SourceLocation Loc,
6342 bool Diagnose = true);
6344 TypeLoc getReturnTypeLoc(FunctionDecl *FD) const;
6346 bool DeduceFunctionTypeFromReturnExpr(FunctionDecl *FD,
6347 SourceLocation ReturnLoc,
6348 Expr *&RetExpr, AutoType *AT);
6350 FunctionTemplateDecl *getMoreSpecializedTemplate(FunctionTemplateDecl *FT1,
6351 FunctionTemplateDecl *FT2,
6353 TemplatePartialOrderingContext TPOC,
6354 unsigned NumCallArguments1,
6355 unsigned NumCallArguments2);
6356 UnresolvedSetIterator
6357 getMostSpecialized(UnresolvedSetIterator SBegin, UnresolvedSetIterator SEnd,
6358 TemplateSpecCandidateSet &FailedCandidates,
6360 const PartialDiagnostic &NoneDiag,
6361 const PartialDiagnostic &AmbigDiag,
6362 const PartialDiagnostic &CandidateDiag,
6363 bool Complain = true, QualType TargetType = QualType());
6365 ClassTemplatePartialSpecializationDecl *
6366 getMoreSpecializedPartialSpecialization(
6367 ClassTemplatePartialSpecializationDecl *PS1,
6368 ClassTemplatePartialSpecializationDecl *PS2,
6369 SourceLocation Loc);
6371 VarTemplatePartialSpecializationDecl *getMoreSpecializedPartialSpecialization(
6372 VarTemplatePartialSpecializationDecl *PS1,
6373 VarTemplatePartialSpecializationDecl *PS2, SourceLocation Loc);
6375 void MarkUsedTemplateParameters(const TemplateArgumentList &TemplateArgs,
6378 llvm::SmallBitVector &Used);
6379 void MarkDeducedTemplateParameters(
6380 const FunctionTemplateDecl *FunctionTemplate,
6381 llvm::SmallBitVector &Deduced) {
6382 return MarkDeducedTemplateParameters(Context, FunctionTemplate, Deduced);
6384 static void MarkDeducedTemplateParameters(ASTContext &Ctx,
6385 const FunctionTemplateDecl *FunctionTemplate,
6386 llvm::SmallBitVector &Deduced);
6388 //===--------------------------------------------------------------------===//
6389 // C++ Template Instantiation
6392 MultiLevelTemplateArgumentList
6393 getTemplateInstantiationArgs(NamedDecl *D,
6394 const TemplateArgumentList *Innermost = nullptr,
6395 bool RelativeToPrimary = false,
6396 const FunctionDecl *Pattern = nullptr);
6398 /// \brief A template instantiation that is currently in progress.
6399 struct ActiveTemplateInstantiation {
6400 /// \brief The kind of template instantiation we are performing
6401 enum InstantiationKind {
6402 /// We are instantiating a template declaration. The entity is
6403 /// the declaration we're instantiating (e.g., a CXXRecordDecl).
6404 TemplateInstantiation,
6406 /// We are instantiating a default argument for a template
6407 /// parameter. The Entity is the template, and
6408 /// TemplateArgs/NumTemplateArguments provides the template
6409 /// arguments as specified.
6410 /// FIXME: Use a TemplateArgumentList
6411 DefaultTemplateArgumentInstantiation,
6413 /// We are instantiating a default argument for a function.
6414 /// The Entity is the ParmVarDecl, and TemplateArgs/NumTemplateArgs
6415 /// provides the template arguments as specified.
6416 DefaultFunctionArgumentInstantiation,
6418 /// We are substituting explicit template arguments provided for
6419 /// a function template. The entity is a FunctionTemplateDecl.
6420 ExplicitTemplateArgumentSubstitution,
6422 /// We are substituting template argument determined as part of
6423 /// template argument deduction for either a class template
6424 /// partial specialization or a function template. The
6425 /// Entity is either a ClassTemplatePartialSpecializationDecl or
6426 /// a FunctionTemplateDecl.
6427 DeducedTemplateArgumentSubstitution,
6429 /// We are substituting prior template arguments into a new
6430 /// template parameter. The template parameter itself is either a
6431 /// NonTypeTemplateParmDecl or a TemplateTemplateParmDecl.
6432 PriorTemplateArgumentSubstitution,
6434 /// We are checking the validity of a default template argument that
6435 /// has been used when naming a template-id.
6436 DefaultTemplateArgumentChecking,
6438 /// We are instantiating the exception specification for a function
6439 /// template which was deferred until it was needed.
6440 ExceptionSpecInstantiation
6443 /// \brief The point of instantiation within the source code.
6444 SourceLocation PointOfInstantiation;
6446 /// \brief The template (or partial specialization) in which we are
6447 /// performing the instantiation, for substitutions of prior template
6449 NamedDecl *Template;
6451 /// \brief The entity that is being instantiated.
6454 /// \brief The list of template arguments we are substituting, if they
6455 /// are not part of the entity.
6456 const TemplateArgument *TemplateArgs;
6458 /// \brief The number of template arguments in TemplateArgs.
6459 unsigned NumTemplateArgs;
6461 /// \brief The template deduction info object associated with the
6462 /// substitution or checking of explicit or deduced template arguments.
6463 sema::TemplateDeductionInfo *DeductionInfo;
6465 /// \brief The source range that covers the construct that cause
6466 /// the instantiation, e.g., the template-id that causes a class
6467 /// template instantiation.
6468 SourceRange InstantiationRange;
6470 ActiveTemplateInstantiation()
6471 : Kind(TemplateInstantiation), Template(nullptr), Entity(nullptr),
6472 TemplateArgs(nullptr), NumTemplateArgs(0), DeductionInfo(nullptr) {}
6474 /// \brief Determines whether this template is an actual instantiation
6475 /// that should be counted toward the maximum instantiation depth.
6476 bool isInstantiationRecord() const;
6478 friend bool operator==(const ActiveTemplateInstantiation &X,
6479 const ActiveTemplateInstantiation &Y) {
6480 if (X.Kind != Y.Kind)
6483 if (X.Entity != Y.Entity)
6487 case TemplateInstantiation:
6488 case ExceptionSpecInstantiation:
6491 case PriorTemplateArgumentSubstitution:
6492 case DefaultTemplateArgumentChecking:
6493 return X.Template == Y.Template && X.TemplateArgs == Y.TemplateArgs;
6495 case DefaultTemplateArgumentInstantiation:
6496 case ExplicitTemplateArgumentSubstitution:
6497 case DeducedTemplateArgumentSubstitution:
6498 case DefaultFunctionArgumentInstantiation:
6499 return X.TemplateArgs == Y.TemplateArgs;
6503 llvm_unreachable("Invalid InstantiationKind!");
6506 friend bool operator!=(const ActiveTemplateInstantiation &X,
6507 const ActiveTemplateInstantiation &Y) {
6512 /// \brief List of active template instantiations.
6514 /// This vector is treated as a stack. As one template instantiation
6515 /// requires another template instantiation, additional
6516 /// instantiations are pushed onto the stack up to a
6517 /// user-configurable limit LangOptions::InstantiationDepth.
6518 SmallVector<ActiveTemplateInstantiation, 16>
6519 ActiveTemplateInstantiations;
6521 /// \brief Extra modules inspected when performing a lookup during a template
6522 /// instantiation. Computed lazily.
6523 SmallVector<Module*, 16> ActiveTemplateInstantiationLookupModules;
6525 /// \brief Cache of additional modules that should be used for name lookup
6526 /// within the current template instantiation. Computed lazily; use
6527 /// getLookupModules() to get a complete set.
6528 llvm::DenseSet<Module*> LookupModulesCache;
6530 /// \brief Get the set of additional modules that should be checked during
6531 /// name lookup. A module and its imports become visible when instanting a
6532 /// template defined within it.
6533 llvm::DenseSet<Module*> &getLookupModules();
6535 /// \brief Whether we are in a SFINAE context that is not associated with
6536 /// template instantiation.
6538 /// This is used when setting up a SFINAE trap (\c see SFINAETrap) outside
6539 /// of a template instantiation or template argument deduction.
6540 bool InNonInstantiationSFINAEContext;
6542 /// \brief The number of ActiveTemplateInstantiation entries in
6543 /// \c ActiveTemplateInstantiations that are not actual instantiations and,
6544 /// therefore, should not be counted as part of the instantiation depth.
6545 unsigned NonInstantiationEntries;
6547 /// \brief The last template from which a template instantiation
6548 /// error or warning was produced.
6550 /// This value is used to suppress printing of redundant template
6551 /// instantiation backtraces when there are multiple errors in the
6552 /// same instantiation. FIXME: Does this belong in Sema? It's tough
6553 /// to implement it anywhere else.
6554 ActiveTemplateInstantiation LastTemplateInstantiationErrorContext;
6556 /// \brief The current index into pack expansion arguments that will be
6557 /// used for substitution of parameter packs.
6559 /// The pack expansion index will be -1 to indicate that parameter packs
6560 /// should be instantiated as themselves. Otherwise, the index specifies
6561 /// which argument within the parameter pack will be used for substitution.
6562 int ArgumentPackSubstitutionIndex;
6564 /// \brief RAII object used to change the argument pack substitution index
6565 /// within a \c Sema object.
6567 /// See \c ArgumentPackSubstitutionIndex for more information.
6568 class ArgumentPackSubstitutionIndexRAII {
6570 int OldSubstitutionIndex;
6573 ArgumentPackSubstitutionIndexRAII(Sema &Self, int NewSubstitutionIndex)
6574 : Self(Self), OldSubstitutionIndex(Self.ArgumentPackSubstitutionIndex) {
6575 Self.ArgumentPackSubstitutionIndex = NewSubstitutionIndex;
6578 ~ArgumentPackSubstitutionIndexRAII() {
6579 Self.ArgumentPackSubstitutionIndex = OldSubstitutionIndex;
6583 friend class ArgumentPackSubstitutionRAII;
6585 /// \brief The stack of calls expression undergoing template instantiation.
6587 /// The top of this stack is used by a fixit instantiating unresolved
6588 /// function calls to fix the AST to match the textual change it prints.
6589 SmallVector<CallExpr *, 8> CallsUndergoingInstantiation;
6591 /// \brief For each declaration that involved template argument deduction, the
6592 /// set of diagnostics that were suppressed during that template argument
6595 /// FIXME: Serialize this structure to the AST file.
6596 typedef llvm::DenseMap<Decl *, SmallVector<PartialDiagnosticAt, 1> >
6597 SuppressedDiagnosticsMap;
6598 SuppressedDiagnosticsMap SuppressedDiagnostics;
6600 /// \brief A stack object to be created when performing template
6603 /// Construction of an object of type \c InstantiatingTemplate
6604 /// pushes the current instantiation onto the stack of active
6605 /// instantiations. If the size of this stack exceeds the maximum
6606 /// number of recursive template instantiations, construction
6607 /// produces an error and evaluates true.
6609 /// Destruction of this object will pop the named instantiation off
6611 struct InstantiatingTemplate {
6612 /// \brief Note that we are instantiating a class template,
6613 /// function template, or a member thereof.
6614 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
6616 SourceRange InstantiationRange = SourceRange());
6618 struct ExceptionSpecification {};
6619 /// \brief Note that we are instantiating an exception specification
6620 /// of a function template.
6621 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
6622 FunctionDecl *Entity, ExceptionSpecification,
6623 SourceRange InstantiationRange = SourceRange());
6625 /// \brief Note that we are instantiating a default argument in a
6627 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
6628 TemplateDecl *Template,
6629 ArrayRef<TemplateArgument> TemplateArgs,
6630 SourceRange InstantiationRange = SourceRange());
6632 /// \brief Note that we are instantiating a default argument in a
6634 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
6635 FunctionTemplateDecl *FunctionTemplate,
6636 ArrayRef<TemplateArgument> TemplateArgs,
6637 ActiveTemplateInstantiation::InstantiationKind Kind,
6638 sema::TemplateDeductionInfo &DeductionInfo,
6639 SourceRange InstantiationRange = SourceRange());
6641 /// \brief Note that we are instantiating as part of template
6642 /// argument deduction for a class template partial
6644 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
6645 ClassTemplatePartialSpecializationDecl *PartialSpec,
6646 ArrayRef<TemplateArgument> TemplateArgs,
6647 sema::TemplateDeductionInfo &DeductionInfo,
6648 SourceRange InstantiationRange = SourceRange());
6650 /// \brief Note that we are instantiating as part of template
6651 /// argument deduction for a variable template partial
6653 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
6654 VarTemplatePartialSpecializationDecl *PartialSpec,
6655 ArrayRef<TemplateArgument> TemplateArgs,
6656 sema::TemplateDeductionInfo &DeductionInfo,
6657 SourceRange InstantiationRange = SourceRange());
6659 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
6661 ArrayRef<TemplateArgument> TemplateArgs,
6662 SourceRange InstantiationRange = SourceRange());
6664 /// \brief Note that we are substituting prior template arguments into a
6665 /// non-type parameter.
6666 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
6667 NamedDecl *Template,
6668 NonTypeTemplateParmDecl *Param,
6669 ArrayRef<TemplateArgument> TemplateArgs,
6670 SourceRange InstantiationRange);
6672 /// \brief Note that we are substituting prior template arguments into a
6673 /// template template parameter.
6674 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
6675 NamedDecl *Template,
6676 TemplateTemplateParmDecl *Param,
6677 ArrayRef<TemplateArgument> TemplateArgs,
6678 SourceRange InstantiationRange);
6680 /// \brief Note that we are checking the default template argument
6681 /// against the template parameter for a given template-id.
6682 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
6683 TemplateDecl *Template,
6685 ArrayRef<TemplateArgument> TemplateArgs,
6686 SourceRange InstantiationRange);
6689 /// \brief Note that we have finished instantiating this template.
6692 ~InstantiatingTemplate() { Clear(); }
6694 /// \brief Determines whether we have exceeded the maximum
6695 /// recursive template instantiations.
6696 bool isInvalid() const { return Invalid; }
6701 bool SavedInNonInstantiationSFINAEContext;
6702 bool CheckInstantiationDepth(SourceLocation PointOfInstantiation,
6703 SourceRange InstantiationRange);
6705 InstantiatingTemplate(
6706 Sema &SemaRef, ActiveTemplateInstantiation::InstantiationKind Kind,
6707 SourceLocation PointOfInstantiation, SourceRange InstantiationRange,
6708 Decl *Entity, NamedDecl *Template = nullptr,
6709 ArrayRef<TemplateArgument> TemplateArgs = ArrayRef<TemplateArgument>(),
6710 sema::TemplateDeductionInfo *DeductionInfo = nullptr);
6712 InstantiatingTemplate(const InstantiatingTemplate&) = delete;
6714 InstantiatingTemplate&
6715 operator=(const InstantiatingTemplate&) = delete;
6718 void PrintInstantiationStack();
6720 /// \brief Determines whether we are currently in a context where
6721 /// template argument substitution failures are not considered
6724 /// \returns An empty \c Optional if we're not in a SFINAE context.
6725 /// Otherwise, contains a pointer that, if non-NULL, contains the nearest
6726 /// template-deduction context object, which can be used to capture
6727 /// diagnostics that will be suppressed.
6728 Optional<sema::TemplateDeductionInfo *> isSFINAEContext() const;
6730 /// \brief Determines whether we are currently in a context that
6731 /// is not evaluated as per C++ [expr] p5.
6732 bool isUnevaluatedContext() const {
6733 assert(!ExprEvalContexts.empty() &&
6734 "Must be in an expression evaluation context");
6735 return ExprEvalContexts.back().isUnevaluated();
6738 /// \brief RAII class used to determine whether SFINAE has
6739 /// trapped any errors that occur during template argument
6743 unsigned PrevSFINAEErrors;
6744 bool PrevInNonInstantiationSFINAEContext;
6745 bool PrevAccessCheckingSFINAE;
6748 explicit SFINAETrap(Sema &SemaRef, bool AccessCheckingSFINAE = false)
6749 : SemaRef(SemaRef), PrevSFINAEErrors(SemaRef.NumSFINAEErrors),
6750 PrevInNonInstantiationSFINAEContext(
6751 SemaRef.InNonInstantiationSFINAEContext),
6752 PrevAccessCheckingSFINAE(SemaRef.AccessCheckingSFINAE)
6754 if (!SemaRef.isSFINAEContext())
6755 SemaRef.InNonInstantiationSFINAEContext = true;
6756 SemaRef.AccessCheckingSFINAE = AccessCheckingSFINAE;
6760 SemaRef.NumSFINAEErrors = PrevSFINAEErrors;
6761 SemaRef.InNonInstantiationSFINAEContext
6762 = PrevInNonInstantiationSFINAEContext;
6763 SemaRef.AccessCheckingSFINAE = PrevAccessCheckingSFINAE;
6766 /// \brief Determine whether any SFINAE errors have been trapped.
6767 bool hasErrorOccurred() const {
6768 return SemaRef.NumSFINAEErrors > PrevSFINAEErrors;
6772 /// \brief RAII class used to indicate that we are performing provisional
6773 /// semantic analysis to determine the validity of a construct, so
6774 /// typo-correction and diagnostics in the immediate context (not within
6775 /// implicitly-instantiated templates) should be suppressed.
6776 class TentativeAnalysisScope {
6778 // FIXME: Using a SFINAETrap for this is a hack.
6780 bool PrevDisableTypoCorrection;
6782 explicit TentativeAnalysisScope(Sema &SemaRef)
6783 : SemaRef(SemaRef), Trap(SemaRef, true),
6784 PrevDisableTypoCorrection(SemaRef.DisableTypoCorrection) {
6785 SemaRef.DisableTypoCorrection = true;
6787 ~TentativeAnalysisScope() {
6788 SemaRef.DisableTypoCorrection = PrevDisableTypoCorrection;
6792 /// \brief The current instantiation scope used to store local
6794 LocalInstantiationScope *CurrentInstantiationScope;
6796 /// \brief Tracks whether we are in a context where typo correction is
6798 bool DisableTypoCorrection;
6800 /// \brief The number of typos corrected by CorrectTypo.
6801 unsigned TyposCorrected;
6803 typedef llvm::SmallSet<SourceLocation, 2> SrcLocSet;
6804 typedef llvm::DenseMap<IdentifierInfo *, SrcLocSet> IdentifierSourceLocations;
6806 /// \brief A cache containing identifiers for which typo correction failed and
6807 /// their locations, so that repeated attempts to correct an identifier in a
6808 /// given location are ignored if typo correction already failed for it.
6809 IdentifierSourceLocations TypoCorrectionFailures;
6811 /// \brief Worker object for performing CFG-based warnings.
6812 sema::AnalysisBasedWarnings AnalysisWarnings;
6813 threadSafety::BeforeSet *ThreadSafetyDeclCache;
6815 /// \brief An entity for which implicit template instantiation is required.
6817 /// The source location associated with the declaration is the first place in
6818 /// the source code where the declaration was "used". It is not necessarily
6819 /// the point of instantiation (which will be either before or after the
6820 /// namespace-scope declaration that triggered this implicit instantiation),
6821 /// However, it is the location that diagnostics should generally refer to,
6822 /// because users will need to know what code triggered the instantiation.
6823 typedef std::pair<ValueDecl *, SourceLocation> PendingImplicitInstantiation;
6825 /// \brief The queue of implicit template instantiations that are required
6826 /// but have not yet been performed.
6827 std::deque<PendingImplicitInstantiation> PendingInstantiations;
6829 class SavePendingInstantiationsAndVTableUsesRAII {
6831 SavePendingInstantiationsAndVTableUsesRAII(Sema &S, bool Enabled)
6832 : S(S), Enabled(Enabled) {
6833 if (!Enabled) return;
6835 SavedPendingInstantiations.swap(S.PendingInstantiations);
6836 SavedVTableUses.swap(S.VTableUses);
6839 ~SavePendingInstantiationsAndVTableUsesRAII() {
6840 if (!Enabled) return;
6842 // Restore the set of pending vtables.
6843 assert(S.VTableUses.empty() &&
6844 "VTableUses should be empty before it is discarded.");
6845 S.VTableUses.swap(SavedVTableUses);
6847 // Restore the set of pending implicit instantiations.
6848 assert(S.PendingInstantiations.empty() &&
6849 "PendingInstantiations should be empty before it is discarded.");
6850 S.PendingInstantiations.swap(SavedPendingInstantiations);
6855 SmallVector<VTableUse, 16> SavedVTableUses;
6856 std::deque<PendingImplicitInstantiation> SavedPendingInstantiations;
6860 /// \brief The queue of implicit template instantiations that are required
6861 /// and must be performed within the current local scope.
6863 /// This queue is only used for member functions of local classes in
6864 /// templates, which must be instantiated in the same scope as their
6865 /// enclosing function, so that they can reference function-local
6866 /// types, static variables, enumerators, etc.
6867 std::deque<PendingImplicitInstantiation> PendingLocalImplicitInstantiations;
6869 class SavePendingLocalImplicitInstantiationsRAII {
6871 SavePendingLocalImplicitInstantiationsRAII(Sema &S): S(S) {
6872 SavedPendingLocalImplicitInstantiations.swap(
6873 S.PendingLocalImplicitInstantiations);
6876 ~SavePendingLocalImplicitInstantiationsRAII() {
6877 assert(S.PendingLocalImplicitInstantiations.empty() &&
6878 "there shouldn't be any pending local implicit instantiations");
6879 SavedPendingLocalImplicitInstantiations.swap(
6880 S.PendingLocalImplicitInstantiations);
6885 std::deque<PendingImplicitInstantiation>
6886 SavedPendingLocalImplicitInstantiations;
6889 void PerformPendingInstantiations(bool LocalOnly = false);
6891 TypeSourceInfo *SubstType(TypeSourceInfo *T,
6892 const MultiLevelTemplateArgumentList &TemplateArgs,
6893 SourceLocation Loc, DeclarationName Entity);
6895 QualType SubstType(QualType T,
6896 const MultiLevelTemplateArgumentList &TemplateArgs,
6897 SourceLocation Loc, DeclarationName Entity);
6899 TypeSourceInfo *SubstType(TypeLoc TL,
6900 const MultiLevelTemplateArgumentList &TemplateArgs,
6901 SourceLocation Loc, DeclarationName Entity);
6903 TypeSourceInfo *SubstFunctionDeclType(TypeSourceInfo *T,
6904 const MultiLevelTemplateArgumentList &TemplateArgs,
6906 DeclarationName Entity,
6907 CXXRecordDecl *ThisContext,
6908 unsigned ThisTypeQuals);
6909 void SubstExceptionSpec(FunctionDecl *New, const FunctionProtoType *Proto,
6910 const MultiLevelTemplateArgumentList &Args);
6911 ParmVarDecl *SubstParmVarDecl(ParmVarDecl *D,
6912 const MultiLevelTemplateArgumentList &TemplateArgs,
6913 int indexAdjustment,
6914 Optional<unsigned> NumExpansions,
6915 bool ExpectParameterPack);
6916 bool SubstParmTypes(SourceLocation Loc,
6917 ParmVarDecl **Params, unsigned NumParams,
6918 const MultiLevelTemplateArgumentList &TemplateArgs,
6919 SmallVectorImpl<QualType> &ParamTypes,
6920 SmallVectorImpl<ParmVarDecl *> *OutParams = nullptr);
6921 ExprResult SubstExpr(Expr *E,
6922 const MultiLevelTemplateArgumentList &TemplateArgs);
6924 /// \brief Substitute the given template arguments into a list of
6925 /// expressions, expanding pack expansions if required.
6927 /// \param Exprs The list of expressions to substitute into.
6929 /// \param NumExprs The number of expressions in \p Exprs.
6931 /// \param IsCall Whether this is some form of call, in which case
6932 /// default arguments will be dropped.
6934 /// \param TemplateArgs The set of template arguments to substitute.
6936 /// \param Outputs Will receive all of the substituted arguments.
6938 /// \returns true if an error occurred, false otherwise.
6939 bool SubstExprs(Expr **Exprs, unsigned NumExprs, bool IsCall,
6940 const MultiLevelTemplateArgumentList &TemplateArgs,
6941 SmallVectorImpl<Expr *> &Outputs);
6943 StmtResult SubstStmt(Stmt *S,
6944 const MultiLevelTemplateArgumentList &TemplateArgs);
6946 Decl *SubstDecl(Decl *D, DeclContext *Owner,
6947 const MultiLevelTemplateArgumentList &TemplateArgs);
6949 ExprResult SubstInitializer(Expr *E,
6950 const MultiLevelTemplateArgumentList &TemplateArgs,
6951 bool CXXDirectInit);
6954 SubstBaseSpecifiers(CXXRecordDecl *Instantiation,
6955 CXXRecordDecl *Pattern,
6956 const MultiLevelTemplateArgumentList &TemplateArgs);
6959 InstantiateClass(SourceLocation PointOfInstantiation,
6960 CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern,
6961 const MultiLevelTemplateArgumentList &TemplateArgs,
6962 TemplateSpecializationKind TSK,
6963 bool Complain = true);
6965 bool InstantiateEnum(SourceLocation PointOfInstantiation,
6966 EnumDecl *Instantiation, EnumDecl *Pattern,
6967 const MultiLevelTemplateArgumentList &TemplateArgs,
6968 TemplateSpecializationKind TSK);
6970 bool InstantiateInClassInitializer(
6971 SourceLocation PointOfInstantiation, FieldDecl *Instantiation,
6972 FieldDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs);
6974 struct LateInstantiatedAttribute {
6975 const Attr *TmplAttr;
6976 LocalInstantiationScope *Scope;
6979 LateInstantiatedAttribute(const Attr *A, LocalInstantiationScope *S,
6981 : TmplAttr(A), Scope(S), NewDecl(D)
6984 typedef SmallVector<LateInstantiatedAttribute, 16> LateInstantiatedAttrVec;
6986 void InstantiateAttrs(const MultiLevelTemplateArgumentList &TemplateArgs,
6987 const Decl *Pattern, Decl *Inst,
6988 LateInstantiatedAttrVec *LateAttrs = nullptr,
6989 LocalInstantiationScope *OuterMostScope = nullptr);
6992 InstantiateClassTemplateSpecialization(SourceLocation PointOfInstantiation,
6993 ClassTemplateSpecializationDecl *ClassTemplateSpec,
6994 TemplateSpecializationKind TSK,
6995 bool Complain = true);
6997 void InstantiateClassMembers(SourceLocation PointOfInstantiation,
6998 CXXRecordDecl *Instantiation,
6999 const MultiLevelTemplateArgumentList &TemplateArgs,
7000 TemplateSpecializationKind TSK);
7002 void InstantiateClassTemplateSpecializationMembers(
7003 SourceLocation PointOfInstantiation,
7004 ClassTemplateSpecializationDecl *ClassTemplateSpec,
7005 TemplateSpecializationKind TSK);
7007 NestedNameSpecifierLoc
7008 SubstNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS,
7009 const MultiLevelTemplateArgumentList &TemplateArgs);
7012 SubstDeclarationNameInfo(const DeclarationNameInfo &NameInfo,
7013 const MultiLevelTemplateArgumentList &TemplateArgs);
7015 SubstTemplateName(NestedNameSpecifierLoc QualifierLoc, TemplateName Name,
7017 const MultiLevelTemplateArgumentList &TemplateArgs);
7018 bool Subst(const TemplateArgumentLoc *Args, unsigned NumArgs,
7019 TemplateArgumentListInfo &Result,
7020 const MultiLevelTemplateArgumentList &TemplateArgs);
7022 void InstantiateExceptionSpec(SourceLocation PointOfInstantiation,
7023 FunctionDecl *Function);
7024 void InstantiateFunctionDefinition(SourceLocation PointOfInstantiation,
7025 FunctionDecl *Function,
7026 bool Recursive = false,
7027 bool DefinitionRequired = false);
7028 VarTemplateSpecializationDecl *BuildVarTemplateInstantiation(
7029 VarTemplateDecl *VarTemplate, VarDecl *FromVar,
7030 const TemplateArgumentList &TemplateArgList,
7031 const TemplateArgumentListInfo &TemplateArgsInfo,
7032 SmallVectorImpl<TemplateArgument> &Converted,
7033 SourceLocation PointOfInstantiation, void *InsertPos,
7034 LateInstantiatedAttrVec *LateAttrs = nullptr,
7035 LocalInstantiationScope *StartingScope = nullptr);
7036 VarTemplateSpecializationDecl *CompleteVarTemplateSpecializationDecl(
7037 VarTemplateSpecializationDecl *VarSpec, VarDecl *PatternDecl,
7038 const MultiLevelTemplateArgumentList &TemplateArgs);
7040 BuildVariableInstantiation(VarDecl *NewVar, VarDecl *OldVar,
7041 const MultiLevelTemplateArgumentList &TemplateArgs,
7042 LateInstantiatedAttrVec *LateAttrs,
7044 LocalInstantiationScope *StartingScope,
7045 bool InstantiatingVarTemplate = false);
7046 void InstantiateVariableInitializer(
7047 VarDecl *Var, VarDecl *OldVar,
7048 const MultiLevelTemplateArgumentList &TemplateArgs);
7049 void InstantiateVariableDefinition(SourceLocation PointOfInstantiation,
7050 VarDecl *Var, bool Recursive = false,
7051 bool DefinitionRequired = false);
7052 void InstantiateStaticDataMemberDefinition(
7053 SourceLocation PointOfInstantiation,
7055 bool Recursive = false,
7056 bool DefinitionRequired = false);
7058 void InstantiateMemInitializers(CXXConstructorDecl *New,
7059 const CXXConstructorDecl *Tmpl,
7060 const MultiLevelTemplateArgumentList &TemplateArgs);
7062 NamedDecl *FindInstantiatedDecl(SourceLocation Loc, NamedDecl *D,
7063 const MultiLevelTemplateArgumentList &TemplateArgs);
7064 DeclContext *FindInstantiatedContext(SourceLocation Loc, DeclContext *DC,
7065 const MultiLevelTemplateArgumentList &TemplateArgs);
7067 // Objective-C declarations.
7068 enum ObjCContainerKind {
7075 OCK_CategoryImplementation
7077 ObjCContainerKind getObjCContainerKind() const;
7079 Decl *ActOnStartClassInterface(SourceLocation AtInterfaceLoc,
7080 IdentifierInfo *ClassName,
7081 SourceLocation ClassLoc,
7082 IdentifierInfo *SuperName,
7083 SourceLocation SuperLoc,
7084 Decl * const *ProtoRefs,
7085 unsigned NumProtoRefs,
7086 const SourceLocation *ProtoLocs,
7087 SourceLocation EndProtoLoc,
7088 AttributeList *AttrList);
7090 void ActOnTypedefedProtocols(SmallVectorImpl<Decl *> &ProtocolRefs,
7091 IdentifierInfo *SuperName,
7092 SourceLocation SuperLoc);
7094 Decl *ActOnCompatibilityAlias(
7095 SourceLocation AtCompatibilityAliasLoc,
7096 IdentifierInfo *AliasName, SourceLocation AliasLocation,
7097 IdentifierInfo *ClassName, SourceLocation ClassLocation);
7099 bool CheckForwardProtocolDeclarationForCircularDependency(
7100 IdentifierInfo *PName,
7101 SourceLocation &PLoc, SourceLocation PrevLoc,
7102 const ObjCList<ObjCProtocolDecl> &PList);
7104 Decl *ActOnStartProtocolInterface(
7105 SourceLocation AtProtoInterfaceLoc,
7106 IdentifierInfo *ProtocolName, SourceLocation ProtocolLoc,
7107 Decl * const *ProtoRefNames, unsigned NumProtoRefs,
7108 const SourceLocation *ProtoLocs,
7109 SourceLocation EndProtoLoc,
7110 AttributeList *AttrList);
7112 Decl *ActOnStartCategoryInterface(SourceLocation AtInterfaceLoc,
7113 IdentifierInfo *ClassName,
7114 SourceLocation ClassLoc,
7115 IdentifierInfo *CategoryName,
7116 SourceLocation CategoryLoc,
7117 Decl * const *ProtoRefs,
7118 unsigned NumProtoRefs,
7119 const SourceLocation *ProtoLocs,
7120 SourceLocation EndProtoLoc);
7122 Decl *ActOnStartClassImplementation(
7123 SourceLocation AtClassImplLoc,
7124 IdentifierInfo *ClassName, SourceLocation ClassLoc,
7125 IdentifierInfo *SuperClassname,
7126 SourceLocation SuperClassLoc);
7128 Decl *ActOnStartCategoryImplementation(SourceLocation AtCatImplLoc,
7129 IdentifierInfo *ClassName,
7130 SourceLocation ClassLoc,
7131 IdentifierInfo *CatName,
7132 SourceLocation CatLoc);
7134 DeclGroupPtrTy ActOnFinishObjCImplementation(Decl *ObjCImpDecl,
7135 ArrayRef<Decl *> Decls);
7137 DeclGroupPtrTy ActOnForwardClassDeclaration(SourceLocation Loc,
7138 IdentifierInfo **IdentList,
7139 SourceLocation *IdentLocs,
7142 DeclGroupPtrTy ActOnForwardProtocolDeclaration(SourceLocation AtProtoclLoc,
7143 const IdentifierLocPair *IdentList,
7145 AttributeList *attrList);
7147 void FindProtocolDeclaration(bool WarnOnDeclarations, bool ForObjCContainer,
7148 const IdentifierLocPair *ProtocolId,
7149 unsigned NumProtocols,
7150 SmallVectorImpl<Decl *> &Protocols);
7152 /// Ensure attributes are consistent with type.
7153 /// \param [in, out] Attributes The attributes to check; they will
7154 /// be modified to be consistent with \p PropertyTy.
7155 void CheckObjCPropertyAttributes(Decl *PropertyPtrTy,
7157 unsigned &Attributes,
7158 bool propertyInPrimaryClass);
7160 /// Process the specified property declaration and create decls for the
7161 /// setters and getters as needed.
7162 /// \param property The property declaration being processed
7163 /// \param CD The semantic container for the property
7164 /// \param redeclaredProperty Declaration for property if redeclared
7165 /// in class extension.
7166 /// \param lexicalDC Container for redeclaredProperty.
7167 void ProcessPropertyDecl(ObjCPropertyDecl *property,
7168 ObjCContainerDecl *CD,
7169 ObjCPropertyDecl *redeclaredProperty = nullptr,
7170 ObjCContainerDecl *lexicalDC = nullptr);
7173 void DiagnosePropertyMismatch(ObjCPropertyDecl *Property,
7174 ObjCPropertyDecl *SuperProperty,
7175 const IdentifierInfo *Name,
7176 bool OverridingProtocolProperty);
7178 void DiagnoseClassExtensionDupMethods(ObjCCategoryDecl *CAT,
7179 ObjCInterfaceDecl *ID);
7181 Decl *ActOnAtEnd(Scope *S, SourceRange AtEnd,
7182 ArrayRef<Decl *> allMethods = None,
7183 ArrayRef<DeclGroupPtrTy> allTUVars = None);
7185 Decl *ActOnProperty(Scope *S, SourceLocation AtLoc,
7186 SourceLocation LParenLoc,
7187 FieldDeclarator &FD, ObjCDeclSpec &ODS,
7188 Selector GetterSel, Selector SetterSel,
7189 bool *OverridingProperty,
7190 tok::ObjCKeywordKind MethodImplKind,
7191 DeclContext *lexicalDC = nullptr);
7193 Decl *ActOnPropertyImplDecl(Scope *S,
7194 SourceLocation AtLoc,
7195 SourceLocation PropertyLoc,
7197 IdentifierInfo *PropertyId,
7198 IdentifierInfo *PropertyIvar,
7199 SourceLocation PropertyIvarLoc);
7201 enum ObjCSpecialMethodKind {
7207 OSMK_NonRetainingInit
7210 struct ObjCArgInfo {
7211 IdentifierInfo *Name;
7212 SourceLocation NameLoc;
7213 // The Type is null if no type was specified, and the DeclSpec is invalid
7216 ObjCDeclSpec DeclSpec;
7218 /// ArgAttrs - Attribute list for this argument.
7219 AttributeList *ArgAttrs;
7222 Decl *ActOnMethodDeclaration(
7224 SourceLocation BeginLoc, // location of the + or -.
7225 SourceLocation EndLoc, // location of the ; or {.
7226 tok::TokenKind MethodType,
7227 ObjCDeclSpec &ReturnQT, ParsedType ReturnType,
7228 ArrayRef<SourceLocation> SelectorLocs, Selector Sel,
7229 // optional arguments. The number of types/arguments is obtained
7230 // from the Sel.getNumArgs().
7231 ObjCArgInfo *ArgInfo,
7232 DeclaratorChunk::ParamInfo *CParamInfo, unsigned CNumArgs, // c-style args
7233 AttributeList *AttrList, tok::ObjCKeywordKind MethodImplKind,
7234 bool isVariadic, bool MethodDefinition);
7236 ObjCMethodDecl *LookupMethodInQualifiedType(Selector Sel,
7237 const ObjCObjectPointerType *OPT,
7239 ObjCMethodDecl *LookupMethodInObjectType(Selector Sel, QualType Ty,
7242 bool CheckARCMethodDecl(ObjCMethodDecl *method);
7243 bool inferObjCARCLifetime(ValueDecl *decl);
7246 HandleExprPropertyRefExpr(const ObjCObjectPointerType *OPT,
7248 SourceLocation OpLoc,
7249 DeclarationName MemberName,
7250 SourceLocation MemberLoc,
7251 SourceLocation SuperLoc, QualType SuperType,
7255 ActOnClassPropertyRefExpr(IdentifierInfo &receiverName,
7256 IdentifierInfo &propertyName,
7257 SourceLocation receiverNameLoc,
7258 SourceLocation propertyNameLoc);
7260 ObjCMethodDecl *tryCaptureObjCSelf(SourceLocation Loc);
7262 /// \brief Describes the kind of message expression indicated by a message
7263 /// send that starts with an identifier.
7264 enum ObjCMessageKind {
7265 /// \brief The message is sent to 'super'.
7267 /// \brief The message is an instance message.
7268 ObjCInstanceMessage,
7269 /// \brief The message is a class message, and the identifier is a type
7274 ObjCMessageKind getObjCMessageKind(Scope *S,
7275 IdentifierInfo *Name,
7276 SourceLocation NameLoc,
7278 bool HasTrailingDot,
7279 ParsedType &ReceiverType);
7281 ExprResult ActOnSuperMessage(Scope *S, SourceLocation SuperLoc,
7283 SourceLocation LBracLoc,
7284 ArrayRef<SourceLocation> SelectorLocs,
7285 SourceLocation RBracLoc,
7288 ExprResult BuildClassMessage(TypeSourceInfo *ReceiverTypeInfo,
7289 QualType ReceiverType,
7290 SourceLocation SuperLoc,
7292 ObjCMethodDecl *Method,
7293 SourceLocation LBracLoc,
7294 ArrayRef<SourceLocation> SelectorLocs,
7295 SourceLocation RBracLoc,
7297 bool isImplicit = false);
7299 ExprResult BuildClassMessageImplicit(QualType ReceiverType,
7300 bool isSuperReceiver,
7303 ObjCMethodDecl *Method,
7306 ExprResult ActOnClassMessage(Scope *S,
7307 ParsedType Receiver,
7309 SourceLocation LBracLoc,
7310 ArrayRef<SourceLocation> SelectorLocs,
7311 SourceLocation RBracLoc,
7314 ExprResult BuildInstanceMessage(Expr *Receiver,
7315 QualType ReceiverType,
7316 SourceLocation SuperLoc,
7318 ObjCMethodDecl *Method,
7319 SourceLocation LBracLoc,
7320 ArrayRef<SourceLocation> SelectorLocs,
7321 SourceLocation RBracLoc,
7323 bool isImplicit = false);
7325 ExprResult BuildInstanceMessageImplicit(Expr *Receiver,
7326 QualType ReceiverType,
7329 ObjCMethodDecl *Method,
7332 ExprResult ActOnInstanceMessage(Scope *S,
7335 SourceLocation LBracLoc,
7336 ArrayRef<SourceLocation> SelectorLocs,
7337 SourceLocation RBracLoc,
7340 ExprResult BuildObjCBridgedCast(SourceLocation LParenLoc,
7341 ObjCBridgeCastKind Kind,
7342 SourceLocation BridgeKeywordLoc,
7343 TypeSourceInfo *TSInfo,
7346 ExprResult ActOnObjCBridgedCast(Scope *S,
7347 SourceLocation LParenLoc,
7348 ObjCBridgeCastKind Kind,
7349 SourceLocation BridgeKeywordLoc,
7351 SourceLocation RParenLoc,
7354 void CheckTollFreeBridgeCast(QualType castType, Expr *castExpr);
7356 void CheckObjCBridgeRelatedCast(QualType castType, Expr *castExpr);
7358 bool CheckTollFreeBridgeStaticCast(QualType castType, Expr *castExpr,
7361 bool checkObjCBridgeRelatedComponents(SourceLocation Loc,
7362 QualType DestType, QualType SrcType,
7363 ObjCInterfaceDecl *&RelatedClass,
7364 ObjCMethodDecl *&ClassMethod,
7365 ObjCMethodDecl *&InstanceMethod,
7366 TypedefNameDecl *&TDNDecl,
7369 bool CheckObjCBridgeRelatedConversions(SourceLocation Loc,
7370 QualType DestType, QualType SrcType,
7373 bool ConversionToObjCStringLiteralCheck(QualType DstType, Expr *&SrcExpr);
7375 bool checkInitMethod(ObjCMethodDecl *method, QualType receiverTypeIfCall);
7377 /// \brief Check whether the given new method is a valid override of the
7378 /// given overridden method, and set any properties that should be inherited.
7379 void CheckObjCMethodOverride(ObjCMethodDecl *NewMethod,
7380 const ObjCMethodDecl *Overridden);
7382 /// \brief Describes the compatibility of a result type with its method.
7383 enum ResultTypeCompatibilityKind {
7389 void CheckObjCMethodOverrides(ObjCMethodDecl *ObjCMethod,
7390 ObjCInterfaceDecl *CurrentClass,
7391 ResultTypeCompatibilityKind RTC);
7393 enum PragmaOptionsAlignKind {
7394 POAK_Native, // #pragma options align=native
7395 POAK_Natural, // #pragma options align=natural
7396 POAK_Packed, // #pragma options align=packed
7397 POAK_Power, // #pragma options align=power
7398 POAK_Mac68k, // #pragma options align=mac68k
7399 POAK_Reset // #pragma options align=reset
7402 /// ActOnPragmaOptionsAlign - Called on well formed \#pragma options align.
7403 void ActOnPragmaOptionsAlign(PragmaOptionsAlignKind Kind,
7404 SourceLocation PragmaLoc);
7406 enum PragmaPackKind {
7407 PPK_Default, // #pragma pack([n])
7408 PPK_Show, // #pragma pack(show), only supported by MSVC.
7409 PPK_Push, // #pragma pack(push, [identifier], [n])
7410 PPK_Pop // #pragma pack(pop, [identifier], [n])
7413 enum PragmaMSStructKind {
7414 PMSST_OFF, // #pragms ms_struct off
7415 PMSST_ON // #pragms ms_struct on
7418 enum PragmaMSCommentKind {
7420 PCK_Linker, // #pragma comment(linker, ...)
7421 PCK_Lib, // #pragma comment(lib, ...)
7422 PCK_Compiler, // #pragma comment(compiler, ...)
7423 PCK_ExeStr, // #pragma comment(exestr, ...)
7424 PCK_User // #pragma comment(user, ...)
7427 /// ActOnPragmaPack - Called on well formed \#pragma pack(...).
7428 void ActOnPragmaPack(PragmaPackKind Kind,
7429 IdentifierInfo *Name,
7431 SourceLocation PragmaLoc,
7432 SourceLocation LParenLoc,
7433 SourceLocation RParenLoc);
7435 /// ActOnPragmaMSStruct - Called on well formed \#pragma ms_struct [on|off].
7436 void ActOnPragmaMSStruct(PragmaMSStructKind Kind);
7438 /// ActOnPragmaMSComment - Called on well formed
7439 /// \#pragma comment(kind, "arg").
7440 void ActOnPragmaMSComment(PragmaMSCommentKind Kind, StringRef Arg);
7442 /// ActOnPragmaMSPointersToMembers - called on well formed \#pragma
7443 /// pointers_to_members(representation method[, general purpose
7444 /// representation]).
7445 void ActOnPragmaMSPointersToMembers(
7446 LangOptions::PragmaMSPointersToMembersKind Kind,
7447 SourceLocation PragmaLoc);
7449 /// \brief Called on well formed \#pragma vtordisp().
7450 void ActOnPragmaMSVtorDisp(PragmaVtorDispKind Kind, SourceLocation PragmaLoc,
7451 MSVtorDispAttr::Mode Value);
7453 enum PragmaSectionKind {
7460 bool UnifySection(StringRef SectionName,
7462 DeclaratorDecl *TheDecl);
7463 bool UnifySection(StringRef SectionName,
7465 SourceLocation PragmaSectionLocation);
7467 /// \brief Called on well formed \#pragma bss_seg/data_seg/const_seg/code_seg.
7468 void ActOnPragmaMSSeg(SourceLocation PragmaLocation,
7469 PragmaMsStackAction Action,
7470 llvm::StringRef StackSlotLabel,
7471 StringLiteral *SegmentName,
7472 llvm::StringRef PragmaName);
7474 /// \brief Called on well formed \#pragma section().
7475 void ActOnPragmaMSSection(SourceLocation PragmaLocation,
7476 int SectionFlags, StringLiteral *SegmentName);
7478 /// \brief Called on well-formed \#pragma init_seg().
7479 void ActOnPragmaMSInitSeg(SourceLocation PragmaLocation,
7480 StringLiteral *SegmentName);
7482 /// ActOnPragmaDetectMismatch - Call on well-formed \#pragma detect_mismatch
7483 void ActOnPragmaDetectMismatch(StringRef Name, StringRef Value);
7485 /// ActOnPragmaUnused - Called on well-formed '\#pragma unused'.
7486 void ActOnPragmaUnused(const Token &Identifier,
7488 SourceLocation PragmaLoc);
7490 /// ActOnPragmaVisibility - Called on well formed \#pragma GCC visibility... .
7491 void ActOnPragmaVisibility(const IdentifierInfo* VisType,
7492 SourceLocation PragmaLoc);
7494 NamedDecl *DeclClonePragmaWeak(NamedDecl *ND, IdentifierInfo *II,
7495 SourceLocation Loc);
7496 void DeclApplyPragmaWeak(Scope *S, NamedDecl *ND, WeakInfo &W);
7498 /// ActOnPragmaWeakID - Called on well formed \#pragma weak ident.
7499 void ActOnPragmaWeakID(IdentifierInfo* WeakName,
7500 SourceLocation PragmaLoc,
7501 SourceLocation WeakNameLoc);
7503 /// ActOnPragmaRedefineExtname - Called on well formed
7504 /// \#pragma redefine_extname oldname newname.
7505 void ActOnPragmaRedefineExtname(IdentifierInfo* WeakName,
7506 IdentifierInfo* AliasName,
7507 SourceLocation PragmaLoc,
7508 SourceLocation WeakNameLoc,
7509 SourceLocation AliasNameLoc);
7511 /// ActOnPragmaWeakAlias - Called on well formed \#pragma weak ident = ident.
7512 void ActOnPragmaWeakAlias(IdentifierInfo* WeakName,
7513 IdentifierInfo* AliasName,
7514 SourceLocation PragmaLoc,
7515 SourceLocation WeakNameLoc,
7516 SourceLocation AliasNameLoc);
7518 /// ActOnPragmaFPContract - Called on well formed
7519 /// \#pragma {STDC,OPENCL} FP_CONTRACT
7520 void ActOnPragmaFPContract(tok::OnOffSwitch OOS);
7522 /// AddAlignmentAttributesForRecord - Adds any needed alignment attributes to
7523 /// a the record decl, to handle '\#pragma pack' and '\#pragma options align'.
7524 void AddAlignmentAttributesForRecord(RecordDecl *RD);
7526 /// AddMsStructLayoutForRecord - Adds ms_struct layout attribute to record.
7527 void AddMsStructLayoutForRecord(RecordDecl *RD);
7529 /// FreePackedContext - Deallocate and null out PackContext.
7530 void FreePackedContext();
7532 /// PushNamespaceVisibilityAttr - Note that we've entered a
7533 /// namespace with a visibility attribute.
7534 void PushNamespaceVisibilityAttr(const VisibilityAttr *Attr,
7535 SourceLocation Loc);
7537 /// AddPushedVisibilityAttribute - If '\#pragma GCC visibility' was used,
7538 /// add an appropriate visibility attribute.
7539 void AddPushedVisibilityAttribute(Decl *RD);
7541 /// PopPragmaVisibility - Pop the top element of the visibility stack; used
7542 /// for '\#pragma GCC visibility' and visibility attributes on namespaces.
7543 void PopPragmaVisibility(bool IsNamespaceEnd, SourceLocation EndLoc);
7545 /// FreeVisContext - Deallocate and null out VisContext.
7546 void FreeVisContext();
7548 /// AddCFAuditedAttribute - Check whether we're currently within
7549 /// '\#pragma clang arc_cf_code_audited' and, if so, consider adding
7550 /// the appropriate attribute.
7551 void AddCFAuditedAttribute(Decl *D);
7553 /// \brief Called on well formed \#pragma clang optimize.
7554 void ActOnPragmaOptimize(bool On, SourceLocation PragmaLoc);
7556 /// \brief Get the location for the currently active "\#pragma clang optimize
7557 /// off". If this location is invalid, then the state of the pragma is "on".
7558 SourceLocation getOptimizeOffPragmaLocation() const {
7559 return OptimizeOffPragmaLocation;
7562 /// \brief Only called on function definitions; if there is a pragma in scope
7563 /// with the effect of a range-based optnone, consider marking the function
7564 /// with attribute optnone.
7565 void AddRangeBasedOptnone(FunctionDecl *FD);
7567 /// \brief Adds the 'optnone' attribute to the function declaration if there
7568 /// are no conflicts; Loc represents the location causing the 'optnone'
7569 /// attribute to be added (usually because of a pragma).
7570 void AddOptnoneAttributeIfNoConflicts(FunctionDecl *FD, SourceLocation Loc);
7572 /// AddAlignedAttr - Adds an aligned attribute to a particular declaration.
7573 void AddAlignedAttr(SourceRange AttrRange, Decl *D, Expr *E,
7574 unsigned SpellingListIndex, bool IsPackExpansion);
7575 void AddAlignedAttr(SourceRange AttrRange, Decl *D, TypeSourceInfo *T,
7576 unsigned SpellingListIndex, bool IsPackExpansion);
7578 /// AddAssumeAlignedAttr - Adds an assume_aligned attribute to a particular
7580 void AddAssumeAlignedAttr(SourceRange AttrRange, Decl *D, Expr *E, Expr *OE,
7581 unsigned SpellingListIndex);
7583 /// AddAlignValueAttr - Adds an align_value attribute to a particular
7585 void AddAlignValueAttr(SourceRange AttrRange, Decl *D, Expr *E,
7586 unsigned SpellingListIndex);
7588 /// AddLaunchBoundsAttr - Adds a launch_bounds attribute to a particular
7590 void AddLaunchBoundsAttr(SourceRange AttrRange, Decl *D, Expr *MaxThreads,
7591 Expr *MinBlocks, unsigned SpellingListIndex);
7593 // OpenMP directives and clauses.
7595 void *VarDataSharingAttributesStack;
7596 /// \brief Initialization of data-sharing attributes stack.
7597 void InitDataSharingAttributesStack();
7598 void DestroyDataSharingAttributesStack();
7599 ExprResult VerifyPositiveIntegerConstantInClause(Expr *Op,
7600 OpenMPClauseKind CKind);
7601 /// \brief Checks if the specified variable is used in one of the private
7602 /// clauses in OpenMP constructs.
7603 bool IsOpenMPCapturedVar(VarDecl *VD);
7606 ExprResult PerformOpenMPImplicitIntegerConversion(SourceLocation OpLoc,
7608 /// \brief Called on start of new data sharing attribute block.
7609 void StartOpenMPDSABlock(OpenMPDirectiveKind K,
7610 const DeclarationNameInfo &DirName, Scope *CurScope,
7611 SourceLocation Loc);
7612 /// \brief Start analysis of clauses.
7613 void StartOpenMPClauses();
7614 /// \brief End analysis of clauses.
7615 void EndOpenMPClauses();
7616 /// \brief Called on end of data sharing attribute block.
7617 void EndOpenMPDSABlock(Stmt *CurDirective);
7619 /// \brief Check if the current region is an OpenMP loop region and if it is,
7620 /// mark loop control variable, used in \p Init for loop initialization, as
7621 /// private by default.
7622 /// \param Init First part of the for loop.
7623 void ActOnOpenMPLoopInitialization(SourceLocation ForLoc, Stmt *Init);
7625 // OpenMP directives and clauses.
7626 /// \brief Called on correct id-expression from the '#pragma omp
7628 ExprResult ActOnOpenMPIdExpression(Scope *CurScope,
7629 CXXScopeSpec &ScopeSpec,
7630 const DeclarationNameInfo &Id);
7631 /// \brief Called on well-formed '#pragma omp threadprivate'.
7632 DeclGroupPtrTy ActOnOpenMPThreadprivateDirective(
7634 ArrayRef<Expr *> VarList);
7635 /// \brief Builds a new OpenMPThreadPrivateDecl and checks its correctness.
7636 OMPThreadPrivateDecl *CheckOMPThreadPrivateDecl(
7638 ArrayRef<Expr *> VarList);
7640 /// \brief Initialization of captured region for OpenMP region.
7641 void ActOnOpenMPRegionStart(OpenMPDirectiveKind DKind, Scope *CurScope);
7642 /// \brief End of OpenMP region.
7644 /// \param S Statement associated with the current OpenMP region.
7645 /// \param Clauses List of clauses for the current OpenMP region.
7647 /// \returns Statement for finished OpenMP region.
7648 StmtResult ActOnOpenMPRegionEnd(StmtResult S, ArrayRef<OMPClause *> Clauses);
7649 StmtResult ActOnOpenMPExecutableDirective(OpenMPDirectiveKind Kind,
7650 const DeclarationNameInfo &DirName,
7651 ArrayRef<OMPClause *> Clauses,
7653 SourceLocation StartLoc,
7654 SourceLocation EndLoc);
7655 /// \brief Called on well-formed '\#pragma omp parallel' after parsing
7656 /// of the associated statement.
7657 StmtResult ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses,
7659 SourceLocation StartLoc,
7660 SourceLocation EndLoc);
7661 /// \brief Called on well-formed '\#pragma omp simd' after parsing
7662 /// of the associated statement.
7663 StmtResult ActOnOpenMPSimdDirective(
7664 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7665 SourceLocation EndLoc,
7666 llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA);
7667 /// \brief Called on well-formed '\#pragma omp for' after parsing
7668 /// of the associated statement.
7669 StmtResult ActOnOpenMPForDirective(
7670 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7671 SourceLocation EndLoc,
7672 llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA);
7673 /// \brief Called on well-formed '\#pragma omp for simd' after parsing
7674 /// of the associated statement.
7675 StmtResult ActOnOpenMPForSimdDirective(
7676 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7677 SourceLocation EndLoc,
7678 llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA);
7679 /// \brief Called on well-formed '\#pragma omp sections' after parsing
7680 /// of the associated statement.
7681 StmtResult ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses,
7682 Stmt *AStmt, SourceLocation StartLoc,
7683 SourceLocation EndLoc);
7684 /// \brief Called on well-formed '\#pragma omp section' after parsing of the
7685 /// associated statement.
7686 StmtResult ActOnOpenMPSectionDirective(Stmt *AStmt, SourceLocation StartLoc,
7687 SourceLocation EndLoc);
7688 /// \brief Called on well-formed '\#pragma omp single' after parsing of the
7689 /// associated statement.
7690 StmtResult ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses,
7691 Stmt *AStmt, SourceLocation StartLoc,
7692 SourceLocation EndLoc);
7693 /// \brief Called on well-formed '\#pragma omp master' after parsing of the
7694 /// associated statement.
7695 StmtResult ActOnOpenMPMasterDirective(Stmt *AStmt, SourceLocation StartLoc,
7696 SourceLocation EndLoc);
7697 /// \brief Called on well-formed '\#pragma omp critical' after parsing of the
7698 /// associated statement.
7699 StmtResult ActOnOpenMPCriticalDirective(const DeclarationNameInfo &DirName,
7700 Stmt *AStmt, SourceLocation StartLoc,
7701 SourceLocation EndLoc);
7702 /// \brief Called on well-formed '\#pragma omp parallel for' after parsing
7703 /// of the associated statement.
7704 StmtResult ActOnOpenMPParallelForDirective(
7705 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7706 SourceLocation EndLoc,
7707 llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA);
7708 /// \brief Called on well-formed '\#pragma omp parallel for simd' after
7709 /// parsing of the associated statement.
7710 StmtResult ActOnOpenMPParallelForSimdDirective(
7711 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7712 SourceLocation EndLoc,
7713 llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA);
7714 /// \brief Called on well-formed '\#pragma omp parallel sections' after
7715 /// parsing of the associated statement.
7716 StmtResult ActOnOpenMPParallelSectionsDirective(ArrayRef<OMPClause *> Clauses,
7718 SourceLocation StartLoc,
7719 SourceLocation EndLoc);
7720 /// \brief Called on well-formed '\#pragma omp task' after parsing of the
7721 /// associated statement.
7722 StmtResult ActOnOpenMPTaskDirective(ArrayRef<OMPClause *> Clauses,
7723 Stmt *AStmt, SourceLocation StartLoc,
7724 SourceLocation EndLoc);
7725 /// \brief Called on well-formed '\#pragma omp taskyield'.
7726 StmtResult ActOnOpenMPTaskyieldDirective(SourceLocation StartLoc,
7727 SourceLocation EndLoc);
7728 /// \brief Called on well-formed '\#pragma omp barrier'.
7729 StmtResult ActOnOpenMPBarrierDirective(SourceLocation StartLoc,
7730 SourceLocation EndLoc);
7731 /// \brief Called on well-formed '\#pragma omp taskwait'.
7732 StmtResult ActOnOpenMPTaskwaitDirective(SourceLocation StartLoc,
7733 SourceLocation EndLoc);
7734 /// \brief Called on well-formed '\#pragma omp taskgroup'.
7735 StmtResult ActOnOpenMPTaskgroupDirective(Stmt *AStmt, SourceLocation StartLoc,
7736 SourceLocation EndLoc);
7737 /// \brief Called on well-formed '\#pragma omp flush'.
7738 StmtResult ActOnOpenMPFlushDirective(ArrayRef<OMPClause *> Clauses,
7739 SourceLocation StartLoc,
7740 SourceLocation EndLoc);
7741 /// \brief Called on well-formed '\#pragma omp ordered' after parsing of the
7742 /// associated statement.
7743 StmtResult ActOnOpenMPOrderedDirective(Stmt *AStmt, SourceLocation StartLoc,
7744 SourceLocation EndLoc);
7745 /// \brief Called on well-formed '\#pragma omp atomic' after parsing of the
7746 /// associated statement.
7747 StmtResult ActOnOpenMPAtomicDirective(ArrayRef<OMPClause *> Clauses,
7748 Stmt *AStmt, SourceLocation StartLoc,
7749 SourceLocation EndLoc);
7750 /// \brief Called on well-formed '\#pragma omp target' after parsing of the
7751 /// associated statement.
7752 StmtResult ActOnOpenMPTargetDirective(ArrayRef<OMPClause *> Clauses,
7753 Stmt *AStmt, SourceLocation StartLoc,
7754 SourceLocation EndLoc);
7755 /// \brief Called on well-formed '\#pragma omp teams' after parsing of the
7756 /// associated statement.
7757 StmtResult ActOnOpenMPTeamsDirective(ArrayRef<OMPClause *> Clauses,
7758 Stmt *AStmt, SourceLocation StartLoc,
7759 SourceLocation EndLoc);
7761 OMPClause *ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind,
7763 SourceLocation StartLoc,
7764 SourceLocation LParenLoc,
7765 SourceLocation EndLoc);
7766 /// \brief Called on well-formed 'if' clause.
7767 OMPClause *ActOnOpenMPIfClause(Expr *Condition, SourceLocation StartLoc,
7768 SourceLocation LParenLoc,
7769 SourceLocation EndLoc);
7770 /// \brief Called on well-formed 'final' clause.
7771 OMPClause *ActOnOpenMPFinalClause(Expr *Condition, SourceLocation StartLoc,
7772 SourceLocation LParenLoc,
7773 SourceLocation EndLoc);
7774 /// \brief Called on well-formed 'num_threads' clause.
7775 OMPClause *ActOnOpenMPNumThreadsClause(Expr *NumThreads,
7776 SourceLocation StartLoc,
7777 SourceLocation LParenLoc,
7778 SourceLocation EndLoc);
7779 /// \brief Called on well-formed 'safelen' clause.
7780 OMPClause *ActOnOpenMPSafelenClause(Expr *Length,
7781 SourceLocation StartLoc,
7782 SourceLocation LParenLoc,
7783 SourceLocation EndLoc);
7784 /// \brief Called on well-formed 'collapse' clause.
7785 OMPClause *ActOnOpenMPCollapseClause(Expr *NumForLoops,
7786 SourceLocation StartLoc,
7787 SourceLocation LParenLoc,
7788 SourceLocation EndLoc);
7790 OMPClause *ActOnOpenMPSimpleClause(OpenMPClauseKind Kind,
7792 SourceLocation ArgumentLoc,
7793 SourceLocation StartLoc,
7794 SourceLocation LParenLoc,
7795 SourceLocation EndLoc);
7796 /// \brief Called on well-formed 'default' clause.
7797 OMPClause *ActOnOpenMPDefaultClause(OpenMPDefaultClauseKind Kind,
7798 SourceLocation KindLoc,
7799 SourceLocation StartLoc,
7800 SourceLocation LParenLoc,
7801 SourceLocation EndLoc);
7802 /// \brief Called on well-formed 'proc_bind' clause.
7803 OMPClause *ActOnOpenMPProcBindClause(OpenMPProcBindClauseKind Kind,
7804 SourceLocation KindLoc,
7805 SourceLocation StartLoc,
7806 SourceLocation LParenLoc,
7807 SourceLocation EndLoc);
7809 OMPClause *ActOnOpenMPSingleExprWithArgClause(OpenMPClauseKind Kind,
7810 unsigned Argument, Expr *Expr,
7811 SourceLocation StartLoc,
7812 SourceLocation LParenLoc,
7813 SourceLocation ArgumentLoc,
7814 SourceLocation CommaLoc,
7815 SourceLocation EndLoc);
7816 /// \brief Called on well-formed 'schedule' clause.
7817 OMPClause *ActOnOpenMPScheduleClause(OpenMPScheduleClauseKind Kind,
7818 Expr *ChunkSize, SourceLocation StartLoc,
7819 SourceLocation LParenLoc,
7820 SourceLocation KindLoc,
7821 SourceLocation CommaLoc,
7822 SourceLocation EndLoc);
7824 OMPClause *ActOnOpenMPClause(OpenMPClauseKind Kind, SourceLocation StartLoc,
7825 SourceLocation EndLoc);
7826 /// \brief Called on well-formed 'ordered' clause.
7827 OMPClause *ActOnOpenMPOrderedClause(SourceLocation StartLoc,
7828 SourceLocation EndLoc);
7829 /// \brief Called on well-formed 'nowait' clause.
7830 OMPClause *ActOnOpenMPNowaitClause(SourceLocation StartLoc,
7831 SourceLocation EndLoc);
7832 /// \brief Called on well-formed 'untied' clause.
7833 OMPClause *ActOnOpenMPUntiedClause(SourceLocation StartLoc,
7834 SourceLocation EndLoc);
7835 /// \brief Called on well-formed 'mergeable' clause.
7836 OMPClause *ActOnOpenMPMergeableClause(SourceLocation StartLoc,
7837 SourceLocation EndLoc);
7838 /// \brief Called on well-formed 'read' clause.
7839 OMPClause *ActOnOpenMPReadClause(SourceLocation StartLoc,
7840 SourceLocation EndLoc);
7841 /// \brief Called on well-formed 'write' clause.
7842 OMPClause *ActOnOpenMPWriteClause(SourceLocation StartLoc,
7843 SourceLocation EndLoc);
7844 /// \brief Called on well-formed 'update' clause.
7845 OMPClause *ActOnOpenMPUpdateClause(SourceLocation StartLoc,
7846 SourceLocation EndLoc);
7847 /// \brief Called on well-formed 'capture' clause.
7848 OMPClause *ActOnOpenMPCaptureClause(SourceLocation StartLoc,
7849 SourceLocation EndLoc);
7850 /// \brief Called on well-formed 'seq_cst' clause.
7851 OMPClause *ActOnOpenMPSeqCstClause(SourceLocation StartLoc,
7852 SourceLocation EndLoc);
7855 ActOnOpenMPVarListClause(OpenMPClauseKind Kind, ArrayRef<Expr *> Vars,
7856 Expr *TailExpr, SourceLocation StartLoc,
7857 SourceLocation LParenLoc, SourceLocation ColonLoc,
7858 SourceLocation EndLoc,
7859 CXXScopeSpec &ReductionIdScopeSpec,
7860 const DeclarationNameInfo &ReductionId);
7861 /// \brief Called on well-formed 'private' clause.
7862 OMPClause *ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList,
7863 SourceLocation StartLoc,
7864 SourceLocation LParenLoc,
7865 SourceLocation EndLoc);
7866 /// \brief Called on well-formed 'firstprivate' clause.
7867 OMPClause *ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList,
7868 SourceLocation StartLoc,
7869 SourceLocation LParenLoc,
7870 SourceLocation EndLoc);
7871 /// \brief Called on well-formed 'lastprivate' clause.
7872 OMPClause *ActOnOpenMPLastprivateClause(ArrayRef<Expr *> VarList,
7873 SourceLocation StartLoc,
7874 SourceLocation LParenLoc,
7875 SourceLocation EndLoc);
7876 /// \brief Called on well-formed 'shared' clause.
7877 OMPClause *ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList,
7878 SourceLocation StartLoc,
7879 SourceLocation LParenLoc,
7880 SourceLocation EndLoc);
7881 /// \brief Called on well-formed 'reduction' clause.
7883 ActOnOpenMPReductionClause(ArrayRef<Expr *> VarList, SourceLocation StartLoc,
7884 SourceLocation LParenLoc, SourceLocation ColonLoc,
7885 SourceLocation EndLoc,
7886 CXXScopeSpec &ReductionIdScopeSpec,
7887 const DeclarationNameInfo &ReductionId);
7888 /// \brief Called on well-formed 'linear' clause.
7889 OMPClause *ActOnOpenMPLinearClause(ArrayRef<Expr *> VarList,
7891 SourceLocation StartLoc,
7892 SourceLocation LParenLoc,
7893 SourceLocation ColonLoc,
7894 SourceLocation EndLoc);
7895 /// \brief Called on well-formed 'aligned' clause.
7896 OMPClause *ActOnOpenMPAlignedClause(ArrayRef<Expr *> VarList,
7898 SourceLocation StartLoc,
7899 SourceLocation LParenLoc,
7900 SourceLocation ColonLoc,
7901 SourceLocation EndLoc);
7902 /// \brief Called on well-formed 'copyin' clause.
7903 OMPClause *ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList,
7904 SourceLocation StartLoc,
7905 SourceLocation LParenLoc,
7906 SourceLocation EndLoc);
7907 /// \brief Called on well-formed 'copyprivate' clause.
7908 OMPClause *ActOnOpenMPCopyprivateClause(ArrayRef<Expr *> VarList,
7909 SourceLocation StartLoc,
7910 SourceLocation LParenLoc,
7911 SourceLocation EndLoc);
7912 /// \brief Called on well-formed 'flush' pseudo clause.
7913 OMPClause *ActOnOpenMPFlushClause(ArrayRef<Expr *> VarList,
7914 SourceLocation StartLoc,
7915 SourceLocation LParenLoc,
7916 SourceLocation EndLoc);
7918 /// \brief The kind of conversion being performed.
7919 enum CheckedConversionKind {
7920 /// \brief An implicit conversion.
7921 CCK_ImplicitConversion,
7922 /// \brief A C-style cast.
7924 /// \brief A functional-style cast.
7926 /// \brief A cast other than a C-style cast.
7930 /// ImpCastExprToType - If Expr is not of type 'Type', insert an implicit
7931 /// cast. If there is already an implicit cast, merge into the existing one.
7932 /// If isLvalue, the result of the cast is an lvalue.
7933 ExprResult ImpCastExprToType(Expr *E, QualType Type, CastKind CK,
7934 ExprValueKind VK = VK_RValue,
7935 const CXXCastPath *BasePath = nullptr,
7936 CheckedConversionKind CCK
7937 = CCK_ImplicitConversion);
7939 /// ScalarTypeToBooleanCastKind - Returns the cast kind corresponding
7940 /// to the conversion from scalar type ScalarTy to the Boolean type.
7941 static CastKind ScalarTypeToBooleanCastKind(QualType ScalarTy);
7943 /// IgnoredValueConversions - Given that an expression's result is
7944 /// syntactically ignored, perform any conversions that are
7946 ExprResult IgnoredValueConversions(Expr *E);
7948 // UsualUnaryConversions - promotes integers (C99 6.3.1.1p2) and converts
7949 // functions and arrays to their respective pointers (C99 6.3.2.1).
7950 ExprResult UsualUnaryConversions(Expr *E);
7952 /// CallExprUnaryConversions - a special case of an unary conversion
7953 /// performed on a function designator of a call expression.
7954 ExprResult CallExprUnaryConversions(Expr *E);
7956 // DefaultFunctionArrayConversion - converts functions and arrays
7957 // to their respective pointers (C99 6.3.2.1).
7958 ExprResult DefaultFunctionArrayConversion(Expr *E);
7960 // DefaultFunctionArrayLvalueConversion - converts functions and
7961 // arrays to their respective pointers and performs the
7962 // lvalue-to-rvalue conversion.
7963 ExprResult DefaultFunctionArrayLvalueConversion(Expr *E);
7965 // DefaultLvalueConversion - performs lvalue-to-rvalue conversion on
7966 // the operand. This is DefaultFunctionArrayLvalueConversion,
7967 // except that it assumes the operand isn't of function or array
7969 ExprResult DefaultLvalueConversion(Expr *E);
7971 // DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
7972 // do not have a prototype. Integer promotions are performed on each
7973 // argument, and arguments that have type float are promoted to double.
7974 ExprResult DefaultArgumentPromotion(Expr *E);
7976 // Used for emitting the right warning by DefaultVariadicArgumentPromotion
7977 enum VariadicCallType {
7981 VariadicConstructor,
7982 VariadicDoesNotApply
7985 VariadicCallType getVariadicCallType(FunctionDecl *FDecl,
7986 const FunctionProtoType *Proto,
7989 // Used for determining in which context a type is allowed to be passed to a
7999 // Determines which VarArgKind fits an expression.
8000 VarArgKind isValidVarArgType(const QualType &Ty);
8002 /// Check to see if the given expression is a valid argument to a variadic
8003 /// function, issuing a diagnostic if not.
8004 void checkVariadicArgument(const Expr *E, VariadicCallType CT);
8006 /// Check to see if a given expression could have '.c_str()' called on it.
8007 bool hasCStrMethod(const Expr *E);
8009 /// GatherArgumentsForCall - Collector argument expressions for various
8010 /// form of call prototypes.
8011 bool GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl,
8012 const FunctionProtoType *Proto,
8013 unsigned FirstParam, ArrayRef<Expr *> Args,
8014 SmallVectorImpl<Expr *> &AllArgs,
8015 VariadicCallType CallType = VariadicDoesNotApply,
8016 bool AllowExplicit = false,
8017 bool IsListInitialization = false);
8019 // DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
8020 // will create a runtime trap if the resulting type is not a POD type.
8021 ExprResult DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
8022 FunctionDecl *FDecl);
8024 // UsualArithmeticConversions - performs the UsualUnaryConversions on it's
8025 // operands and then handles various conversions that are common to binary
8026 // operators (C99 6.3.1.8). If both operands aren't arithmetic, this
8027 // routine returns the first non-arithmetic type found. The client is
8028 // responsible for emitting appropriate error diagnostics.
8029 QualType UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
8030 bool IsCompAssign = false);
8032 /// AssignConvertType - All of the 'assignment' semantic checks return this
8033 /// enum to indicate whether the assignment was allowed. These checks are
8034 /// done for simple assignments, as well as initialization, return from
8035 /// function, argument passing, etc. The query is phrased in terms of a
8036 /// source and destination type.
8037 enum AssignConvertType {
8038 /// Compatible - the types are compatible according to the standard.
8041 /// PointerToInt - The assignment converts a pointer to an int, which we
8042 /// accept as an extension.
8045 /// IntToPointer - The assignment converts an int to a pointer, which we
8046 /// accept as an extension.
8049 /// FunctionVoidPointer - The assignment is between a function pointer and
8050 /// void*, which the standard doesn't allow, but we accept as an extension.
8051 FunctionVoidPointer,
8053 /// IncompatiblePointer - The assignment is between two pointers types that
8054 /// are not compatible, but we accept them as an extension.
8055 IncompatiblePointer,
8057 /// IncompatiblePointer - The assignment is between two pointers types which
8058 /// point to integers which have a different sign, but are otherwise
8059 /// identical. This is a subset of the above, but broken out because it's by
8060 /// far the most common case of incompatible pointers.
8061 IncompatiblePointerSign,
8063 /// CompatiblePointerDiscardsQualifiers - The assignment discards
8064 /// c/v/r qualifiers, which we accept as an extension.
8065 CompatiblePointerDiscardsQualifiers,
8067 /// IncompatiblePointerDiscardsQualifiers - The assignment
8068 /// discards qualifiers that we don't permit to be discarded,
8069 /// like address spaces.
8070 IncompatiblePointerDiscardsQualifiers,
8072 /// IncompatibleNestedPointerQualifiers - The assignment is between two
8073 /// nested pointer types, and the qualifiers other than the first two
8074 /// levels differ e.g. char ** -> const char **, but we accept them as an
8076 IncompatibleNestedPointerQualifiers,
8078 /// IncompatibleVectors - The assignment is between two vector types that
8079 /// have the same size, which we accept as an extension.
8080 IncompatibleVectors,
8082 /// IntToBlockPointer - The assignment converts an int to a block
8083 /// pointer. We disallow this.
8086 /// IncompatibleBlockPointer - The assignment is between two block
8087 /// pointers types that are not compatible.
8088 IncompatibleBlockPointer,
8090 /// IncompatibleObjCQualifiedId - The assignment is between a qualified
8091 /// id type and something else (that is incompatible with it). For example,
8092 /// "id <XXX>" = "Foo *", where "Foo *" doesn't implement the XXX protocol.
8093 IncompatibleObjCQualifiedId,
8095 /// IncompatibleObjCWeakRef - Assigning a weak-unavailable object to an
8096 /// object with __weak qualifier.
8097 IncompatibleObjCWeakRef,
8099 /// Incompatible - We reject this conversion outright, it is invalid to
8100 /// represent it in the AST.
8104 /// DiagnoseAssignmentResult - Emit a diagnostic, if required, for the
8105 /// assignment conversion type specified by ConvTy. This returns true if the
8106 /// conversion was invalid or false if the conversion was accepted.
8107 bool DiagnoseAssignmentResult(AssignConvertType ConvTy,
8109 QualType DstType, QualType SrcType,
8110 Expr *SrcExpr, AssignmentAction Action,
8111 bool *Complained = nullptr);
8113 /// IsValueInFlagEnum - Determine if a value is allowed as part of a flag
8114 /// enum. If AllowMask is true, then we also allow the complement of a valid
8115 /// value, to be used as a mask.
8116 bool IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
8117 bool AllowMask) const;
8119 /// DiagnoseAssignmentEnum - Warn if assignment to enum is a constant
8120 /// integer not in the range of enum values.
8121 void DiagnoseAssignmentEnum(QualType DstType, QualType SrcType,
8124 /// CheckAssignmentConstraints - Perform type checking for assignment,
8125 /// argument passing, variable initialization, and function return values.
8127 AssignConvertType CheckAssignmentConstraints(SourceLocation Loc,
8131 /// Check assignment constraints and prepare for a conversion of the
8132 /// RHS to the LHS type.
8133 AssignConvertType CheckAssignmentConstraints(QualType LHSType,
8137 // CheckSingleAssignmentConstraints - Currently used by
8138 // CheckAssignmentOperands, and ActOnReturnStmt. Prior to type checking,
8139 // this routine performs the default function/array converions.
8140 AssignConvertType CheckSingleAssignmentConstraints(QualType LHSType,
8142 bool Diagnose = true,
8143 bool DiagnoseCFAudited = false);
8145 // \brief If the lhs type is a transparent union, check whether we
8146 // can initialize the transparent union with the given expression.
8147 AssignConvertType CheckTransparentUnionArgumentConstraints(QualType ArgType,
8150 bool IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType);
8152 bool CheckExceptionSpecCompatibility(Expr *From, QualType ToType);
8154 ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
8155 AssignmentAction Action,
8156 bool AllowExplicit = false);
8157 ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
8158 AssignmentAction Action,
8160 ImplicitConversionSequence& ICS);
8161 ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
8162 const ImplicitConversionSequence& ICS,
8163 AssignmentAction Action,
8164 CheckedConversionKind CCK
8165 = CCK_ImplicitConversion);
8166 ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
8167 const StandardConversionSequence& SCS,
8168 AssignmentAction Action,
8169 CheckedConversionKind CCK);
8171 /// the following "Check" methods will return a valid/converted QualType
8172 /// or a null QualType (indicating an error diagnostic was issued).
8174 /// type checking binary operators (subroutines of CreateBuiltinBinOp).
8175 QualType InvalidOperands(SourceLocation Loc, ExprResult &LHS,
8177 QualType CheckPointerToMemberOperands( // C++ 5.5
8178 ExprResult &LHS, ExprResult &RHS, ExprValueKind &VK,
8179 SourceLocation OpLoc, bool isIndirect);
8180 QualType CheckMultiplyDivideOperands( // C99 6.5.5
8181 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign,
8183 QualType CheckRemainderOperands( // C99 6.5.5
8184 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
8185 bool IsCompAssign = false);
8186 QualType CheckAdditionOperands( // C99 6.5.6
8187 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc,
8188 QualType* CompLHSTy = nullptr);
8189 QualType CheckSubtractionOperands( // C99 6.5.6
8190 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
8191 QualType* CompLHSTy = nullptr);
8192 QualType CheckShiftOperands( // C99 6.5.7
8193 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc,
8194 bool IsCompAssign = false);
8195 QualType CheckCompareOperands( // C99 6.5.8/9
8196 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned OpaqueOpc,
8198 QualType CheckBitwiseOperands( // C99 6.5.[10...12]
8199 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
8200 bool IsCompAssign = false);
8201 QualType CheckLogicalOperands( // C99 6.5.[13,14]
8202 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc);
8203 // CheckAssignmentOperands is used for both simple and compound assignment.
8204 // For simple assignment, pass both expressions and a null converted type.
8205 // For compound assignment, pass both expressions and the converted type.
8206 QualType CheckAssignmentOperands( // C99 6.5.16.[1,2]
8207 Expr *LHSExpr, ExprResult &RHS, SourceLocation Loc, QualType CompoundType);
8209 ExprResult checkPseudoObjectIncDec(Scope *S, SourceLocation OpLoc,
8210 UnaryOperatorKind Opcode, Expr *Op);
8211 ExprResult checkPseudoObjectAssignment(Scope *S, SourceLocation OpLoc,
8212 BinaryOperatorKind Opcode,
8213 Expr *LHS, Expr *RHS);
8214 ExprResult checkPseudoObjectRValue(Expr *E);
8215 Expr *recreateSyntacticForm(PseudoObjectExpr *E);
8217 QualType CheckConditionalOperands( // C99 6.5.15
8218 ExprResult &Cond, ExprResult &LHS, ExprResult &RHS,
8219 ExprValueKind &VK, ExprObjectKind &OK, SourceLocation QuestionLoc);
8220 QualType CXXCheckConditionalOperands( // C++ 5.16
8221 ExprResult &cond, ExprResult &lhs, ExprResult &rhs,
8222 ExprValueKind &VK, ExprObjectKind &OK, SourceLocation questionLoc);
8223 QualType FindCompositePointerType(SourceLocation Loc, Expr *&E1, Expr *&E2,
8224 bool *NonStandardCompositeType = nullptr);
8225 QualType FindCompositePointerType(SourceLocation Loc,
8226 ExprResult &E1, ExprResult &E2,
8227 bool *NonStandardCompositeType = nullptr) {
8228 Expr *E1Tmp = E1.get(), *E2Tmp = E2.get();
8229 QualType Composite = FindCompositePointerType(Loc, E1Tmp, E2Tmp,
8230 NonStandardCompositeType);
8236 QualType FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
8237 SourceLocation QuestionLoc);
8239 bool DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
8240 SourceLocation QuestionLoc);
8242 void DiagnoseAlwaysNonNullPointer(Expr *E,
8243 Expr::NullPointerConstantKind NullType,
8244 bool IsEqual, SourceRange Range);
8246 /// type checking for vector binary operators.
8247 QualType CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
8248 SourceLocation Loc, bool IsCompAssign);
8249 QualType GetSignedVectorType(QualType V);
8250 QualType CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
8251 SourceLocation Loc, bool isRelational);
8252 QualType CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
8253 SourceLocation Loc);
8255 bool isLaxVectorConversion(QualType srcType, QualType destType);
8257 /// type checking declaration initializers (C99 6.7.8)
8258 bool CheckForConstantInitializer(Expr *e, QualType t);
8260 // type checking C++ declaration initializers (C++ [dcl.init]).
8262 /// ReferenceCompareResult - Expresses the result of comparing two
8263 /// types (cv1 T1 and cv2 T2) to determine their compatibility for the
8264 /// purposes of initialization by reference (C++ [dcl.init.ref]p4).
8265 enum ReferenceCompareResult {
8266 /// Ref_Incompatible - The two types are incompatible, so direct
8267 /// reference binding is not possible.
8268 Ref_Incompatible = 0,
8269 /// Ref_Related - The two types are reference-related, which means
8270 /// that their unqualified forms (T1 and T2) are either the same
8271 /// or T1 is a base class of T2.
8273 /// Ref_Compatible_With_Added_Qualification - The two types are
8274 /// reference-compatible with added qualification, meaning that
8275 /// they are reference-compatible and the qualifiers on T1 (cv1)
8276 /// are greater than the qualifiers on T2 (cv2).
8277 Ref_Compatible_With_Added_Qualification,
8278 /// Ref_Compatible - The two types are reference-compatible and
8279 /// have equivalent qualifiers (cv1 == cv2).
8283 ReferenceCompareResult CompareReferenceRelationship(SourceLocation Loc,
8284 QualType T1, QualType T2,
8285 bool &DerivedToBase,
8286 bool &ObjCConversion,
8287 bool &ObjCLifetimeConversion);
8289 ExprResult checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
8290 Expr *CastExpr, CastKind &CastKind,
8291 ExprValueKind &VK, CXXCastPath &Path);
8293 /// \brief Force an expression with unknown-type to an expression of the
8295 ExprResult forceUnknownAnyToType(Expr *E, QualType ToType);
8297 /// \brief Type-check an expression that's being passed to an
8298 /// __unknown_anytype parameter.
8299 ExprResult checkUnknownAnyArg(SourceLocation callLoc,
8300 Expr *result, QualType ¶mType);
8302 // CheckVectorCast - check type constraints for vectors.
8303 // Since vectors are an extension, there are no C standard reference for this.
8304 // We allow casting between vectors and integer datatypes of the same size.
8305 // returns true if the cast is invalid
8306 bool CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
8309 // CheckExtVectorCast - check type constraints for extended vectors.
8310 // Since vectors are an extension, there are no C standard reference for this.
8311 // We allow casting between vectors and integer datatypes of the same size,
8312 // or vectors and the element type of that vector.
8313 // returns the cast expr
8314 ExprResult CheckExtVectorCast(SourceRange R, QualType DestTy, Expr *CastExpr,
8317 ExprResult BuildCXXFunctionalCastExpr(TypeSourceInfo *TInfo,
8318 SourceLocation LParenLoc,
8320 SourceLocation RParenLoc);
8322 enum ARCConversionResult { ACR_okay, ACR_unbridged };
8324 /// \brief Checks for invalid conversions and casts between
8325 /// retainable pointers and other pointer kinds.
8326 ARCConversionResult CheckObjCARCConversion(SourceRange castRange,
8327 QualType castType, Expr *&op,
8328 CheckedConversionKind CCK,
8329 bool DiagnoseCFAudited = false,
8330 BinaryOperatorKind Opc = BO_PtrMemD
8333 Expr *stripARCUnbridgedCast(Expr *e);
8334 void diagnoseARCUnbridgedCast(Expr *e);
8336 bool CheckObjCARCUnavailableWeakConversion(QualType castType,
8339 /// checkRetainCycles - Check whether an Objective-C message send
8340 /// might create an obvious retain cycle.
8341 void checkRetainCycles(ObjCMessageExpr *msg);
8342 void checkRetainCycles(Expr *receiver, Expr *argument);
8343 void checkRetainCycles(VarDecl *Var, Expr *Init);
8345 /// checkUnsafeAssigns - Check whether +1 expr is being assigned
8346 /// to weak/__unsafe_unretained type.
8347 bool checkUnsafeAssigns(SourceLocation Loc, QualType LHS, Expr *RHS);
8349 /// checkUnsafeExprAssigns - Check whether +1 expr is being assigned
8350 /// to weak/__unsafe_unretained expression.
8351 void checkUnsafeExprAssigns(SourceLocation Loc, Expr *LHS, Expr *RHS);
8353 /// CheckMessageArgumentTypes - Check types in an Obj-C message send.
8354 /// \param Method - May be null.
8355 /// \param [out] ReturnType - The return type of the send.
8356 /// \return true iff there were any incompatible types.
8357 bool CheckMessageArgumentTypes(QualType ReceiverType,
8358 MultiExprArg Args, Selector Sel,
8359 ArrayRef<SourceLocation> SelectorLocs,
8360 ObjCMethodDecl *Method, bool isClassMessage,
8361 bool isSuperMessage,
8362 SourceLocation lbrac, SourceLocation rbrac,
8363 SourceRange RecRange,
8364 QualType &ReturnType, ExprValueKind &VK);
8366 /// \brief Determine the result of a message send expression based on
8367 /// the type of the receiver, the method expected to receive the message,
8368 /// and the form of the message send.
8369 QualType getMessageSendResultType(QualType ReceiverType,
8370 ObjCMethodDecl *Method,
8371 bool isClassMessage, bool isSuperMessage);
8373 /// \brief If the given expression involves a message send to a method
8374 /// with a related result type, emit a note describing what happened.
8375 void EmitRelatedResultTypeNote(const Expr *E);
8377 /// \brief Given that we had incompatible pointer types in a return
8378 /// statement, check whether we're in a method with a related result
8379 /// type, and if so, emit a note describing what happened.
8380 void EmitRelatedResultTypeNoteForReturn(QualType destType);
8382 /// CheckBooleanCondition - Diagnose problems involving the use of
8383 /// the given expression as a boolean condition (e.g. in an if
8384 /// statement). Also performs the standard function and array
8385 /// decays, possibly changing the input variable.
8387 /// \param Loc - A location associated with the condition, e.g. the
8389 /// \return true iff there were any errors
8390 ExprResult CheckBooleanCondition(Expr *E, SourceLocation Loc);
8392 ExprResult ActOnBooleanCondition(Scope *S, SourceLocation Loc,
8395 /// DiagnoseAssignmentAsCondition - Given that an expression is
8396 /// being used as a boolean condition, warn if it's an assignment.
8397 void DiagnoseAssignmentAsCondition(Expr *E);
8399 /// \brief Redundant parentheses over an equality comparison can indicate
8400 /// that the user intended an assignment used as condition.
8401 void DiagnoseEqualityWithExtraParens(ParenExpr *ParenE);
8403 /// CheckCXXBooleanCondition - Returns true if conversion to bool is invalid.
8404 ExprResult CheckCXXBooleanCondition(Expr *CondExpr);
8406 /// ConvertIntegerToTypeWarnOnOverflow - Convert the specified APInt to have
8407 /// the specified width and sign. If an overflow occurs, detect it and emit
8408 /// the specified diagnostic.
8409 void ConvertIntegerToTypeWarnOnOverflow(llvm::APSInt &OldVal,
8410 unsigned NewWidth, bool NewSign,
8411 SourceLocation Loc, unsigned DiagID);
8413 /// Checks that the Objective-C declaration is declared in the global scope.
8414 /// Emits an error and marks the declaration as invalid if it's not declared
8415 /// in the global scope.
8416 bool CheckObjCDeclScope(Decl *D);
8418 /// \brief Abstract base class used for diagnosing integer constant
8419 /// expression violations.
8420 class VerifyICEDiagnoser {
8424 VerifyICEDiagnoser(bool Suppress = false) : Suppress(Suppress) { }
8426 virtual void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) =0;
8427 virtual void diagnoseFold(Sema &S, SourceLocation Loc, SourceRange SR);
8428 virtual ~VerifyICEDiagnoser() { }
8431 /// VerifyIntegerConstantExpression - Verifies that an expression is an ICE,
8432 /// and reports the appropriate diagnostics. Returns false on success.
8433 /// Can optionally return the value of the expression.
8434 ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
8435 VerifyICEDiagnoser &Diagnoser,
8436 bool AllowFold = true);
8437 ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
8439 bool AllowFold = true);
8440 ExprResult VerifyIntegerConstantExpression(Expr *E,
8441 llvm::APSInt *Result = nullptr);
8443 /// VerifyBitField - verifies that a bit field expression is an ICE and has
8444 /// the correct width, and that the field type is valid.
8445 /// Returns false on success.
8446 /// Can optionally return whether the bit-field is of width 0
8447 ExprResult VerifyBitField(SourceLocation FieldLoc, IdentifierInfo *FieldName,
8448 QualType FieldTy, bool IsMsStruct,
8449 Expr *BitWidth, bool *ZeroWidth = nullptr);
8451 enum CUDAFunctionTarget {
8459 CUDAFunctionTarget IdentifyCUDATarget(const FunctionDecl *D);
8461 bool CheckCUDATarget(const FunctionDecl *Caller, const FunctionDecl *Callee);
8463 /// Given a implicit special member, infer its CUDA target from the
8464 /// calls it needs to make to underlying base/field special members.
8465 /// \param ClassDecl the class for which the member is being created.
8466 /// \param CSM the kind of special member.
8467 /// \param MemberDecl the special member itself.
8468 /// \param ConstRHS true if this is a copy operation with a const object on
8470 /// \param Diagnose true if this call should emit diagnostics.
8471 /// \return true if there was an error inferring.
8472 /// The result of this call is implicit CUDA target attribute(s) attached to
8473 /// the member declaration.
8474 bool inferCUDATargetForImplicitSpecialMember(CXXRecordDecl *ClassDecl,
8475 CXXSpecialMember CSM,
8476 CXXMethodDecl *MemberDecl,
8480 /// \name Code completion
8482 /// \brief Describes the context in which code completion occurs.
8483 enum ParserCompletionContext {
8484 /// \brief Code completion occurs at top-level or namespace context.
8486 /// \brief Code completion occurs within a class, struct, or union.
8488 /// \brief Code completion occurs within an Objective-C interface, protocol,
8491 /// \brief Code completion occurs within an Objective-C implementation or
8492 /// category implementation
8493 PCC_ObjCImplementation,
8494 /// \brief Code completion occurs within the list of instance variables
8495 /// in an Objective-C interface, protocol, category, or implementation.
8496 PCC_ObjCInstanceVariableList,
8497 /// \brief Code completion occurs following one or more template
8500 /// \brief Code completion occurs following one or more template
8501 /// headers within a class.
8503 /// \brief Code completion occurs within an expression.
8505 /// \brief Code completion occurs within a statement, which may
8506 /// also be an expression or a declaration.
8508 /// \brief Code completion occurs at the beginning of the
8509 /// initialization statement (or expression) in a for loop.
8511 /// \brief Code completion occurs within the condition of an if,
8512 /// while, switch, or for statement.
8514 /// \brief Code completion occurs within the body of a function on a
8515 /// recovery path, where we do not have a specific handle on our position
8517 PCC_RecoveryInFunction,
8518 /// \brief Code completion occurs where only a type is permitted.
8520 /// \brief Code completion occurs in a parenthesized expression, which
8521 /// might also be a type cast.
8522 PCC_ParenthesizedExpression,
8523 /// \brief Code completion occurs within a sequence of declaration
8524 /// specifiers within a function, method, or block.
8525 PCC_LocalDeclarationSpecifiers
8528 void CodeCompleteModuleImport(SourceLocation ImportLoc, ModuleIdPath Path);
8529 void CodeCompleteOrdinaryName(Scope *S,
8530 ParserCompletionContext CompletionContext);
8531 void CodeCompleteDeclSpec(Scope *S, DeclSpec &DS,
8532 bool AllowNonIdentifiers,
8533 bool AllowNestedNameSpecifiers);
8535 struct CodeCompleteExpressionData;
8536 void CodeCompleteExpression(Scope *S,
8537 const CodeCompleteExpressionData &Data);
8538 void CodeCompleteMemberReferenceExpr(Scope *S, Expr *Base,
8539 SourceLocation OpLoc,
8541 void CodeCompletePostfixExpression(Scope *S, ExprResult LHS);
8542 void CodeCompleteTag(Scope *S, unsigned TagSpec);
8543 void CodeCompleteTypeQualifiers(DeclSpec &DS);
8544 void CodeCompleteCase(Scope *S);
8545 void CodeCompleteCall(Scope *S, Expr *Fn, ArrayRef<Expr *> Args);
8546 void CodeCompleteConstructor(Scope *S, QualType Type, SourceLocation Loc,
8547 ArrayRef<Expr *> Args);
8548 void CodeCompleteInitializer(Scope *S, Decl *D);
8549 void CodeCompleteReturn(Scope *S);
8550 void CodeCompleteAfterIf(Scope *S);
8551 void CodeCompleteAssignmentRHS(Scope *S, Expr *LHS);
8553 void CodeCompleteQualifiedId(Scope *S, CXXScopeSpec &SS,
8554 bool EnteringContext);
8555 void CodeCompleteUsing(Scope *S);
8556 void CodeCompleteUsingDirective(Scope *S);
8557 void CodeCompleteNamespaceDecl(Scope *S);
8558 void CodeCompleteNamespaceAliasDecl(Scope *S);
8559 void CodeCompleteOperatorName(Scope *S);
8560 void CodeCompleteConstructorInitializer(
8562 ArrayRef<CXXCtorInitializer *> Initializers);
8564 void CodeCompleteLambdaIntroducer(Scope *S, LambdaIntroducer &Intro,
8565 bool AfterAmpersand);
8567 void CodeCompleteObjCAtDirective(Scope *S);
8568 void CodeCompleteObjCAtVisibility(Scope *S);
8569 void CodeCompleteObjCAtStatement(Scope *S);
8570 void CodeCompleteObjCAtExpression(Scope *S);
8571 void CodeCompleteObjCPropertyFlags(Scope *S, ObjCDeclSpec &ODS);
8572 void CodeCompleteObjCPropertyGetter(Scope *S);
8573 void CodeCompleteObjCPropertySetter(Scope *S);
8574 void CodeCompleteObjCPassingType(Scope *S, ObjCDeclSpec &DS,
8576 void CodeCompleteObjCMessageReceiver(Scope *S);
8577 void CodeCompleteObjCSuperMessage(Scope *S, SourceLocation SuperLoc,
8578 ArrayRef<IdentifierInfo *> SelIdents,
8579 bool AtArgumentExpression);
8580 void CodeCompleteObjCClassMessage(Scope *S, ParsedType Receiver,
8581 ArrayRef<IdentifierInfo *> SelIdents,
8582 bool AtArgumentExpression,
8583 bool IsSuper = false);
8584 void CodeCompleteObjCInstanceMessage(Scope *S, Expr *Receiver,
8585 ArrayRef<IdentifierInfo *> SelIdents,
8586 bool AtArgumentExpression,
8587 ObjCInterfaceDecl *Super = nullptr);
8588 void CodeCompleteObjCForCollection(Scope *S,
8589 DeclGroupPtrTy IterationVar);
8590 void CodeCompleteObjCSelector(Scope *S,
8591 ArrayRef<IdentifierInfo *> SelIdents);
8592 void CodeCompleteObjCProtocolReferences(IdentifierLocPair *Protocols,
8593 unsigned NumProtocols);
8594 void CodeCompleteObjCProtocolDecl(Scope *S);
8595 void CodeCompleteObjCInterfaceDecl(Scope *S);
8596 void CodeCompleteObjCSuperclass(Scope *S,
8597 IdentifierInfo *ClassName,
8598 SourceLocation ClassNameLoc);
8599 void CodeCompleteObjCImplementationDecl(Scope *S);
8600 void CodeCompleteObjCInterfaceCategory(Scope *S,
8601 IdentifierInfo *ClassName,
8602 SourceLocation ClassNameLoc);
8603 void CodeCompleteObjCImplementationCategory(Scope *S,
8604 IdentifierInfo *ClassName,
8605 SourceLocation ClassNameLoc);
8606 void CodeCompleteObjCPropertyDefinition(Scope *S);
8607 void CodeCompleteObjCPropertySynthesizeIvar(Scope *S,
8608 IdentifierInfo *PropertyName);
8609 void CodeCompleteObjCMethodDecl(Scope *S,
8610 bool IsInstanceMethod,
8611 ParsedType ReturnType);
8612 void CodeCompleteObjCMethodDeclSelector(Scope *S,
8613 bool IsInstanceMethod,
8614 bool AtParameterName,
8615 ParsedType ReturnType,
8616 ArrayRef<IdentifierInfo *> SelIdents);
8617 void CodeCompletePreprocessorDirective(bool InConditional);
8618 void CodeCompleteInPreprocessorConditionalExclusion(Scope *S);
8619 void CodeCompletePreprocessorMacroName(bool IsDefinition);
8620 void CodeCompletePreprocessorExpression();
8621 void CodeCompletePreprocessorMacroArgument(Scope *S,
8622 IdentifierInfo *Macro,
8623 MacroInfo *MacroInfo,
8625 void CodeCompleteNaturalLanguage();
8626 void GatherGlobalCodeCompletions(CodeCompletionAllocator &Allocator,
8627 CodeCompletionTUInfo &CCTUInfo,
8628 SmallVectorImpl<CodeCompletionResult> &Results);
8631 //===--------------------------------------------------------------------===//
8632 // Extra semantic analysis beyond the C type system
8635 SourceLocation getLocationOfStringLiteralByte(const StringLiteral *SL,
8636 unsigned ByteNo) const;
8639 void CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
8640 const ArraySubscriptExpr *ASE=nullptr,
8641 bool AllowOnePastEnd=true, bool IndexNegated=false);
8642 void CheckArrayAccess(const Expr *E);
8643 // Used to grab the relevant information from a FormatAttr and a
8644 // FunctionDeclaration.
8645 struct FormatStringInfo {
8647 unsigned FirstDataArg;
8651 bool getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
8652 FormatStringInfo *FSI);
8653 bool CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
8654 const FunctionProtoType *Proto);
8655 bool CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation loc,
8656 ArrayRef<const Expr *> Args);
8657 bool CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
8658 const FunctionProtoType *Proto);
8659 bool CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto);
8660 void CheckConstructorCall(FunctionDecl *FDecl,
8661 ArrayRef<const Expr *> Args,
8662 const FunctionProtoType *Proto,
8663 SourceLocation Loc);
8665 void checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
8666 ArrayRef<const Expr *> Args, bool IsMemberFunction,
8667 SourceLocation Loc, SourceRange Range,
8668 VariadicCallType CallType);
8670 bool CheckObjCString(Expr *Arg);
8672 ExprResult CheckBuiltinFunctionCall(FunctionDecl *FDecl,
8673 unsigned BuiltinID, CallExpr *TheCall);
8675 bool CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
8677 bool CheckNeonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
8678 bool CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
8680 bool CheckAArch64BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
8681 bool CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
8682 bool CheckSystemZBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
8683 bool CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
8684 bool CheckPPCBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
8686 bool SemaBuiltinVAStart(CallExpr *TheCall);
8687 bool SemaBuiltinVAStartARM(CallExpr *Call);
8688 bool SemaBuiltinUnorderedCompare(CallExpr *TheCall);
8689 bool SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs);
8692 // Used by C++ template instantiation.
8693 ExprResult SemaBuiltinShuffleVector(CallExpr *TheCall);
8694 ExprResult SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
8695 SourceLocation BuiltinLoc,
8696 SourceLocation RParenLoc);
8699 bool SemaBuiltinPrefetch(CallExpr *TheCall);
8700 bool SemaBuiltinAssume(CallExpr *TheCall);
8701 bool SemaBuiltinAssumeAligned(CallExpr *TheCall);
8702 bool SemaBuiltinLongjmp(CallExpr *TheCall);
8703 bool SemaBuiltinSetjmp(CallExpr *TheCall);
8704 ExprResult SemaBuiltinAtomicOverloaded(ExprResult TheCallResult);
8705 ExprResult SemaAtomicOpsOverloaded(ExprResult TheCallResult,
8706 AtomicExpr::AtomicOp Op);
8707 bool SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
8708 llvm::APSInt &Result);
8709 bool SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
8711 bool SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall,
8712 int ArgNum, unsigned ExpectedFieldNum,
8715 enum FormatStringType {
8726 static FormatStringType GetFormatStringType(const FormatAttr *Format);
8728 void CheckFormatString(const StringLiteral *FExpr, const Expr *OrigFormatExpr,
8729 ArrayRef<const Expr *> Args, bool HasVAListArg,
8730 unsigned format_idx, unsigned firstDataArg,
8731 FormatStringType Type, bool inFunctionCall,
8732 VariadicCallType CallType,
8733 llvm::SmallBitVector &CheckedVarArgs);
8735 bool FormatStringHasSArg(const StringLiteral *FExpr);
8737 bool GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx);
8740 bool CheckFormatArguments(const FormatAttr *Format,
8741 ArrayRef<const Expr *> Args,
8743 VariadicCallType CallType,
8744 SourceLocation Loc, SourceRange Range,
8745 llvm::SmallBitVector &CheckedVarArgs);
8746 bool CheckFormatArguments(ArrayRef<const Expr *> Args,
8747 bool HasVAListArg, unsigned format_idx,
8748 unsigned firstDataArg, FormatStringType Type,
8749 VariadicCallType CallType,
8750 SourceLocation Loc, SourceRange range,
8751 llvm::SmallBitVector &CheckedVarArgs);
8753 void CheckAbsoluteValueFunction(const CallExpr *Call,
8754 const FunctionDecl *FDecl,
8755 IdentifierInfo *FnInfo);
8757 void CheckMemaccessArguments(const CallExpr *Call,
8759 IdentifierInfo *FnName);
8761 void CheckStrlcpycatArguments(const CallExpr *Call,
8762 IdentifierInfo *FnName);
8764 void CheckStrncatArguments(const CallExpr *Call,
8765 IdentifierInfo *FnName);
8767 void CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
8768 SourceLocation ReturnLoc,
8769 bool isObjCMethod = false,
8770 const AttrVec *Attrs = nullptr,
8771 const FunctionDecl *FD = nullptr);
8773 void CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr* RHS);
8774 void CheckImplicitConversions(Expr *E, SourceLocation CC = SourceLocation());
8775 void CheckBoolLikeConversion(Expr *E, SourceLocation CC);
8776 void CheckForIntOverflow(Expr *E);
8777 void CheckUnsequencedOperations(Expr *E);
8779 /// \brief Perform semantic checks on a completed expression. This will either
8780 /// be a full-expression or a default argument expression.
8781 void CheckCompletedExpr(Expr *E, SourceLocation CheckLoc = SourceLocation(),
8782 bool IsConstexpr = false);
8784 void CheckBitFieldInitialization(SourceLocation InitLoc, FieldDecl *Field,
8787 /// \brief Check if the given expression contains 'break' or 'continue'
8788 /// statement that produces control flow different from GCC.
8789 void CheckBreakContinueBinding(Expr *E);
8791 /// \brief Check whether receiver is mutable ObjC container which
8792 /// attempts to add itself into the container
8793 void CheckObjCCircularContainer(ObjCMessageExpr *Message);
8795 void AnalyzeDeleteExprMismatch(const CXXDeleteExpr *DE);
8796 void AnalyzeDeleteExprMismatch(FieldDecl *Field, SourceLocation DeleteLoc,
8797 bool DeleteWasArrayForm);
8799 /// \brief Register a magic integral constant to be used as a type tag.
8800 void RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
8801 uint64_t MagicValue, QualType Type,
8802 bool LayoutCompatible, bool MustBeNull);
8804 struct TypeTagData {
8807 TypeTagData(QualType Type, bool LayoutCompatible, bool MustBeNull) :
8808 Type(Type), LayoutCompatible(LayoutCompatible),
8809 MustBeNull(MustBeNull)
8814 /// If true, \c Type should be compared with other expression's types for
8815 /// layout-compatibility.
8816 unsigned LayoutCompatible : 1;
8817 unsigned MustBeNull : 1;
8820 /// A pair of ArgumentKind identifier and magic value. This uniquely
8821 /// identifies the magic value.
8822 typedef std::pair<const IdentifierInfo *, uint64_t> TypeTagMagicValue;
8825 /// \brief A map from magic value to type information.
8826 std::unique_ptr<llvm::DenseMap<TypeTagMagicValue, TypeTagData>>
8827 TypeTagForDatatypeMagicValues;
8829 /// \brief Peform checks on a call of a function with argument_with_type_tag
8830 /// or pointer_with_type_tag attributes.
8831 void CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
8832 const Expr * const *ExprArgs);
8834 /// \brief The parser's current scope.
8836 /// The parser maintains this state here.
8839 mutable IdentifierInfo *Ident_super;
8840 mutable IdentifierInfo *Ident___float128;
8842 /// Nullability type specifiers.
8843 IdentifierInfo *Ident___nonnull = nullptr;
8844 IdentifierInfo *Ident___nullable = nullptr;
8845 IdentifierInfo *Ident___null_unspecified = nullptr;
8847 IdentifierInfo *Ident_NSError = nullptr;
8850 friend class Parser;
8851 friend class InitializationSequence;
8852 friend class ASTReader;
8853 friend class ASTDeclReader;
8854 friend class ASTWriter;
8857 /// Retrieve the keyword associated
8858 IdentifierInfo *getNullabilityKeyword(NullabilityKind nullability);
8860 /// The struct behind the CFErrorRef pointer.
8861 RecordDecl *CFError = nullptr;
8863 /// Retrieve the identifier "NSError".
8864 IdentifierInfo *getNSErrorIdent();
8866 /// \brief Retrieve the parser's current scope.
8868 /// This routine must only be used when it is certain that semantic analysis
8869 /// and the parser are in precisely the same context, which is not the case
8870 /// when, e.g., we are performing any kind of template instantiation.
8871 /// Therefore, the only safe places to use this scope are in the parser
8872 /// itself and in routines directly invoked from the parser and *never* from
8873 /// template substitution or instantiation.
8874 Scope *getCurScope() const { return CurScope; }
8876 void incrementMSManglingNumber() const {
8877 return CurScope->incrementMSManglingNumber();
8880 IdentifierInfo *getSuperIdentifier() const;
8881 IdentifierInfo *getFloat128Identifier() const;
8883 Decl *getObjCDeclContext() const;
8885 DeclContext *getCurLexicalContext() const {
8886 return OriginalLexicalContext ? OriginalLexicalContext : CurContext;
8889 AvailabilityResult getCurContextAvailability() const;
8891 const DeclContext *getCurObjCLexicalContext() const {
8892 const DeclContext *DC = getCurLexicalContext();
8893 // A category implicitly has the attribute of the interface.
8894 if (const ObjCCategoryDecl *CatD = dyn_cast<ObjCCategoryDecl>(DC))
8895 DC = CatD->getClassInterface();
8899 /// \brief To be used for checking whether the arguments being passed to
8900 /// function exceeds the number of parameters expected for it.
8901 static bool TooManyArguments(size_t NumParams, size_t NumArgs,
8902 bool PartialOverloading = false) {
8903 // We check whether we're just after a comma in code-completion.
8904 if (NumArgs > 0 && PartialOverloading)
8905 return NumArgs + 1 > NumParams; // If so, we view as an extra argument.
8906 return NumArgs > NumParams;
8910 /// \brief RAII object that enters a new expression evaluation context.
8911 class EnterExpressionEvaluationContext {
8915 EnterExpressionEvaluationContext(Sema &Actions,
8916 Sema::ExpressionEvaluationContext NewContext,
8917 Decl *LambdaContextDecl = nullptr,
8918 bool IsDecltype = false)
8919 : Actions(Actions) {
8920 Actions.PushExpressionEvaluationContext(NewContext, LambdaContextDecl,
8923 EnterExpressionEvaluationContext(Sema &Actions,
8924 Sema::ExpressionEvaluationContext NewContext,
8925 Sema::ReuseLambdaContextDecl_t,
8926 bool IsDecltype = false)
8927 : Actions(Actions) {
8928 Actions.PushExpressionEvaluationContext(NewContext,
8929 Sema::ReuseLambdaContextDecl,
8933 ~EnterExpressionEvaluationContext() {
8934 Actions.PopExpressionEvaluationContext();
8938 DeductionFailureInfo
8939 MakeDeductionFailureInfo(ASTContext &Context, Sema::TemplateDeductionResult TDK,
8940 sema::TemplateDeductionInfo &Info);
8942 /// \brief Contains a late templated function.
8943 /// Will be parsed at the end of the translation unit, used by Sema & Parser.
8944 struct LateParsedTemplate {
8946 /// \brief The template function declaration to be late parsed.
8950 } // end namespace clang