1 //===--- Sema.h - Semantic Analysis & AST Building --------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the Sema class, which performs semantic analysis and
13 //===----------------------------------------------------------------------===//
15 #ifndef LLVM_CLANG_SEMA_SEMA_H
16 #define LLVM_CLANG_SEMA_SEMA_H
18 #include "clang/AST/Attr.h"
19 #include "clang/AST/DeclarationName.h"
20 #include "clang/AST/Expr.h"
21 #include "clang/AST/ExprObjC.h"
22 #include "clang/AST/ExternalASTSource.h"
23 #include "clang/AST/MangleNumberingContext.h"
24 #include "clang/AST/NSAPI.h"
25 #include "clang/AST/PrettyPrinter.h"
26 #include "clang/AST/TypeLoc.h"
27 #include "clang/Basic/ExpressionTraits.h"
28 #include "clang/Basic/LangOptions.h"
29 #include "clang/Basic/Module.h"
30 #include "clang/Basic/OpenMPKinds.h"
31 #include "clang/Basic/Specifiers.h"
32 #include "clang/Basic/TemplateKinds.h"
33 #include "clang/Basic/TypeTraits.h"
34 #include "clang/Sema/AnalysisBasedWarnings.h"
35 #include "clang/Sema/DeclSpec.h"
36 #include "clang/Sema/ExternalSemaSource.h"
37 #include "clang/Sema/IdentifierResolver.h"
38 #include "clang/Sema/LocInfoType.h"
39 #include "clang/Sema/ObjCMethodList.h"
40 #include "clang/Sema/Ownership.h"
41 #include "clang/Sema/Scope.h"
42 #include "clang/Sema/ScopeInfo.h"
43 #include "clang/Sema/TypoCorrection.h"
44 #include "clang/Sema/Weak.h"
45 #include "llvm/ADT/ArrayRef.h"
46 #include "llvm/ADT/Optional.h"
47 #include "llvm/ADT/SetVector.h"
48 #include "llvm/ADT/SmallPtrSet.h"
49 #include "llvm/ADT/SmallVector.h"
50 #include "llvm/ADT/TinyPtrVector.h"
58 template <typename ValueT> struct DenseMapInfo;
59 template <typename ValueT, typename ValueInfoT> class DenseSet;
61 class InlineAsmIdentifierInfo;
68 class ASTMutationListener;
77 class CXXBindTemporaryExpr;
78 typedef SmallVector<CXXBaseSpecifier*, 4> CXXCastPath;
79 class CXXConstructorDecl;
80 class CXXConversionDecl;
82 class CXXDestructorDecl;
83 class CXXFieldCollector;
84 class CXXMemberCallExpr;
90 class ClassTemplateDecl;
91 class ClassTemplatePartialSpecializationDecl;
92 class ClassTemplateSpecializationDecl;
93 class VarTemplatePartialSpecializationDecl;
94 class CodeCompleteConsumer;
95 class CodeCompletionAllocator;
96 class CodeCompletionTUInfo;
97 class CodeCompletionResult;
102 class DeclaratorDecl;
103 class DeducedTemplateArgument;
104 class DependentDiagnostic;
105 class DesignatedInitExpr;
108 class EnumConstantDecl;
111 class ExternalSemaSource;
115 class FunctionProtoType;
116 class FunctionTemplateDecl;
117 class ImplicitConversionSequence;
119 class InitializationKind;
120 class InitializationSequence;
121 class InitializedEntity;
122 class IntegerLiteral;
126 class LocalInstantiationScope;
129 typedef ArrayRef<std::pair<IdentifierInfo *, SourceLocation>> ModuleIdPath;
131 class MultiLevelTemplateArgumentList;
133 class ObjCCategoryDecl;
134 class ObjCCategoryImplDecl;
135 class ObjCCompatibleAliasDecl;
136 class ObjCContainerDecl;
138 class ObjCImplementationDecl;
139 class ObjCInterfaceDecl;
141 template <class T> class ObjCList;
142 class ObjCMessageExpr;
143 class ObjCMethodDecl;
144 class ObjCPropertyDecl;
145 class ObjCProtocolDecl;
146 class OMPThreadPrivateDecl;
148 class OverloadCandidateSet;
153 class PseudoDestructorTypeStorage;
154 class PseudoObjectExpr;
156 class StandardConversionSequence;
160 class TemplateArgument;
161 class TemplateArgumentList;
162 class TemplateArgumentLoc;
164 class TemplateParameterList;
165 class TemplatePartialOrderingContext;
166 class TemplateTemplateParmDecl;
170 class TypedefNameDecl;
172 class TypoCorrectionConsumer;
174 class UnresolvedLookupExpr;
175 class UnresolvedMemberExpr;
176 class UnresolvedSetImpl;
177 class UnresolvedSetIterator;
179 class UsingShadowDecl;
182 class VarTemplateSpecializationDecl;
183 class VisibilityAttr;
184 class VisibleDeclConsumer;
185 class IndirectFieldDecl;
186 struct DeductionFailureInfo;
187 class TemplateSpecCandidateSet;
190 class AccessedEntity;
191 class BlockScopeInfo;
192 class CapturedRegionScopeInfo;
193 class CapturingScopeInfo;
194 class CompoundScopeInfo;
195 class DelayedDiagnostic;
196 class DelayedDiagnosticPool;
197 class FunctionScopeInfo;
198 class LambdaScopeInfo;
199 class PossiblyUnreachableDiag;
200 class TemplateDeductionInfo;
203 namespace threadSafety {
205 void threadSafetyCleanup(BeforeSet* Cache);
208 // FIXME: No way to easily map from TemplateTypeParmTypes to
209 // TemplateTypeParmDecls, so we have this horrible PointerUnion.
210 typedef std::pair<llvm::PointerUnion<const TemplateTypeParmType*, NamedDecl*>,
211 SourceLocation> UnexpandedParameterPack;
213 /// Describes whether we've seen any nullability information for the given
215 struct FileNullability {
216 /// The first pointer declarator (of any pointer kind) in the file that does
217 /// not have a corresponding nullability annotation.
218 SourceLocation PointerLoc;
220 /// Which kind of pointer declarator we saw.
223 /// Whether we saw any type nullability annotations in the given file.
224 bool SawTypeNullability = false;
227 /// A mapping from file IDs to a record of whether we've seen nullability
228 /// information in that file.
229 class FileNullabilityMap {
230 /// A mapping from file IDs to the nullability information for each file ID.
231 llvm::DenseMap<FileID, FileNullability> Map;
233 /// A single-element cache based on the file ID.
236 FileNullability Nullability;
240 FileNullability &operator[](FileID file) {
241 // Check the single-element cache.
242 if (file == Cache.File)
243 return Cache.Nullability;
245 // It's not in the single-element cache; flush the cache if we have one.
246 if (!Cache.File.isInvalid()) {
247 Map[Cache.File] = Cache.Nullability;
250 // Pull this entry into the cache.
252 Cache.Nullability = Map[file];
253 return Cache.Nullability;
257 /// Sema - This implements semantic analysis and AST building for C.
259 Sema(const Sema &) = delete;
260 void operator=(const Sema &) = delete;
262 ///\brief Source of additional semantic information.
263 ExternalSemaSource *ExternalSource;
265 ///\brief Whether Sema has generated a multiplexer and has to delete it.
266 bool isMultiplexExternalSource;
268 static bool mightHaveNonExternalLinkage(const DeclaratorDecl *FD);
270 bool isVisibleSlow(const NamedDecl *D);
272 bool shouldLinkPossiblyHiddenDecl(const NamedDecl *Old,
273 const NamedDecl *New) {
274 // We are about to link these. It is now safe to compute the linkage of
275 // the new decl. If the new decl has external linkage, we will
276 // link it with the hidden decl (which also has external linkage) and
277 // it will keep having external linkage. If it has internal linkage, we
278 // will not link it. Since it has no previous decls, it will remain
279 // with internal linkage.
280 if (getLangOpts().ModulesHideInternalLinkage)
281 return isVisible(Old) || New->isExternallyVisible();
286 typedef OpaquePtr<DeclGroupRef> DeclGroupPtrTy;
287 typedef OpaquePtr<TemplateName> TemplateTy;
288 typedef OpaquePtr<QualType> TypeTy;
290 OpenCLOptions OpenCLFeatures;
291 FPOptions FPFeatures;
293 const LangOptions &LangOpts;
296 ASTConsumer &Consumer;
297 DiagnosticsEngine &Diags;
298 SourceManager &SourceMgr;
300 /// \brief Flag indicating whether or not to collect detailed statistics.
303 /// \brief Code-completion consumer.
304 CodeCompleteConsumer *CodeCompleter;
306 /// CurContext - This is the current declaration context of parsing.
307 DeclContext *CurContext;
309 /// \brief Generally null except when we temporarily switch decl contexts,
310 /// like in \see ActOnObjCTemporaryExitContainerContext.
311 DeclContext *OriginalLexicalContext;
313 /// VAListTagName - The declaration name corresponding to __va_list_tag.
314 /// This is used as part of a hack to omit that class from ADL results.
315 DeclarationName VAListTagName;
317 /// PackContext - Manages the stack for \#pragma pack. An alignment
318 /// of 0 indicates default alignment.
319 void *PackContext; // Really a "PragmaPackStack*"
321 bool MSStructPragmaOn; // True when \#pragma ms_struct on
323 /// \brief Controls member pointer representation format under the MS ABI.
324 LangOptions::PragmaMSPointersToMembersKind
325 MSPointerToMemberRepresentationMethod;
327 enum PragmaVtorDispKind {
328 PVDK_Push, ///< #pragma vtordisp(push, mode)
329 PVDK_Set, ///< #pragma vtordisp(mode)
330 PVDK_Pop, ///< #pragma vtordisp(pop)
331 PVDK_Reset ///< #pragma vtordisp()
334 enum PragmaMsStackAction {
335 PSK_Reset, // #pragma ()
336 PSK_Set, // #pragma ("name")
337 PSK_Push, // #pragma (push[, id])
338 PSK_Push_Set, // #pragma (push[, id], "name")
339 PSK_Pop, // #pragma (pop[, id])
340 PSK_Pop_Set, // #pragma (pop[, id], "name")
343 /// \brief Whether to insert vtordisps prior to virtual bases in the Microsoft
344 /// C++ ABI. Possible values are 0, 1, and 2, which mean:
346 /// 0: Suppress all vtordisps
347 /// 1: Insert vtordisps in the presence of vbase overrides and non-trivial
349 /// 2: Always insert vtordisps to support RTTI on partially constructed
352 /// The stack always has at least one element in it.
353 SmallVector<MSVtorDispAttr::Mode, 2> VtorDispModeStack;
355 /// Stack of active SEH __finally scopes. Can be empty.
356 SmallVector<Scope*, 2> CurrentSEHFinally;
358 /// \brief Source location for newly created implicit MSInheritanceAttrs
359 SourceLocation ImplicitMSInheritanceAttrLoc;
361 template<typename ValueType>
364 llvm::StringRef StackSlotLabel;
366 SourceLocation PragmaLocation;
367 Slot(llvm::StringRef StackSlotLabel,
369 SourceLocation PragmaLocation)
370 : StackSlotLabel(StackSlotLabel), Value(Value),
371 PragmaLocation(PragmaLocation) {}
373 void Act(SourceLocation PragmaLocation,
374 PragmaMsStackAction Action,
375 llvm::StringRef StackSlotLabel,
377 explicit PragmaStack(const ValueType &Value)
378 : CurrentValue(Value) {}
379 SmallVector<Slot, 2> Stack;
380 ValueType CurrentValue;
381 SourceLocation CurrentPragmaLocation;
383 // FIXME: We should serialize / deserialize these if they occur in a PCH (but
384 // we shouldn't do so if they're in a module).
385 PragmaStack<StringLiteral *> DataSegStack;
386 PragmaStack<StringLiteral *> BSSSegStack;
387 PragmaStack<StringLiteral *> ConstSegStack;
388 PragmaStack<StringLiteral *> CodeSegStack;
390 /// A mapping that describes the nullability we've seen in each header file.
391 FileNullabilityMap NullabilityMap;
393 /// Last section used with #pragma init_seg.
394 StringLiteral *CurInitSeg;
395 SourceLocation CurInitSegLoc;
397 /// VisContext - Manages the stack for \#pragma GCC visibility.
398 void *VisContext; // Really a "PragmaVisStack*"
400 /// \brief This represents the last location of a "#pragma clang optimize off"
401 /// directive if such a directive has not been closed by an "on" yet. If
402 /// optimizations are currently "on", this is set to an invalid location.
403 SourceLocation OptimizeOffPragmaLocation;
405 /// \brief Flag indicating if Sema is building a recovery call expression.
407 /// This flag is used to avoid building recovery call expressions
408 /// if Sema is already doing so, which would cause infinite recursions.
409 bool IsBuildingRecoveryCallExpr;
411 /// ExprNeedsCleanups - True if the current evaluation context
412 /// requires cleanups to be run at its conclusion.
413 bool ExprNeedsCleanups;
415 /// ExprCleanupObjects - This is the stack of objects requiring
416 /// cleanup that are created by the current full expression. The
417 /// element type here is ExprWithCleanups::Object.
418 SmallVector<BlockDecl*, 8> ExprCleanupObjects;
420 /// \brief Store a list of either DeclRefExprs or MemberExprs
421 /// that contain a reference to a variable (constant) that may or may not
422 /// be odr-used in this Expr, and we won't know until all lvalue-to-rvalue
423 /// and discarded value conversions have been applied to all subexpressions
424 /// of the enclosing full expression. This is cleared at the end of each
426 llvm::SmallPtrSet<Expr*, 2> MaybeODRUseExprs;
428 /// \brief Stack containing information about each of the nested
429 /// function, block, and method scopes that are currently active.
431 /// This array is never empty. Clients should ignore the first
432 /// element, which is used to cache a single FunctionScopeInfo
433 /// that's used to parse every top-level function.
434 SmallVector<sema::FunctionScopeInfo *, 4> FunctionScopes;
436 typedef LazyVector<TypedefNameDecl *, ExternalSemaSource,
437 &ExternalSemaSource::ReadExtVectorDecls, 2, 2>
440 /// ExtVectorDecls - This is a list all the extended vector types. This allows
441 /// us to associate a raw vector type with one of the ext_vector type names.
442 /// This is only necessary for issuing pretty diagnostics.
443 ExtVectorDeclsType ExtVectorDecls;
445 /// FieldCollector - Collects CXXFieldDecls during parsing of C++ classes.
446 std::unique_ptr<CXXFieldCollector> FieldCollector;
448 typedef llvm::SmallSetVector<const NamedDecl*, 16> NamedDeclSetType;
450 /// \brief Set containing all declared private fields that are not used.
451 NamedDeclSetType UnusedPrivateFields;
453 /// \brief Set containing all typedefs that are likely unused.
454 llvm::SmallSetVector<const TypedefNameDecl *, 4>
455 UnusedLocalTypedefNameCandidates;
457 /// \brief Delete-expressions to be analyzed at the end of translation unit
459 /// This list contains class members, and locations of delete-expressions
460 /// that could not be proven as to whether they mismatch with new-expression
461 /// used in initializer of the field.
462 typedef std::pair<SourceLocation, bool> DeleteExprLoc;
463 typedef llvm::SmallVector<DeleteExprLoc, 4> DeleteLocs;
464 llvm::MapVector<FieldDecl *, DeleteLocs> DeleteExprs;
466 typedef llvm::SmallPtrSet<const CXXRecordDecl*, 8> RecordDeclSetTy;
468 /// PureVirtualClassDiagSet - a set of class declarations which we have
469 /// emitted a list of pure virtual functions. Used to prevent emitting the
470 /// same list more than once.
471 std::unique_ptr<RecordDeclSetTy> PureVirtualClassDiagSet;
473 /// ParsingInitForAutoVars - a set of declarations with auto types for which
474 /// we are currently parsing the initializer.
475 llvm::SmallPtrSet<const Decl*, 4> ParsingInitForAutoVars;
477 /// \brief Look for a locally scoped extern "C" declaration by the given name.
478 NamedDecl *findLocallyScopedExternCDecl(DeclarationName Name);
480 typedef LazyVector<VarDecl *, ExternalSemaSource,
481 &ExternalSemaSource::ReadTentativeDefinitions, 2, 2>
482 TentativeDefinitionsType;
484 /// \brief All the tentative definitions encountered in the TU.
485 TentativeDefinitionsType TentativeDefinitions;
487 typedef LazyVector<const DeclaratorDecl *, ExternalSemaSource,
488 &ExternalSemaSource::ReadUnusedFileScopedDecls, 2, 2>
489 UnusedFileScopedDeclsType;
491 /// \brief The set of file scoped decls seen so far that have not been used
492 /// and must warn if not used. Only contains the first declaration.
493 UnusedFileScopedDeclsType UnusedFileScopedDecls;
495 typedef LazyVector<CXXConstructorDecl *, ExternalSemaSource,
496 &ExternalSemaSource::ReadDelegatingConstructors, 2, 2>
497 DelegatingCtorDeclsType;
499 /// \brief All the delegating constructors seen so far in the file, used for
500 /// cycle detection at the end of the TU.
501 DelegatingCtorDeclsType DelegatingCtorDecls;
503 /// \brief All the overriding functions seen during a class definition
504 /// that had their exception spec checks delayed, plus the overridden
506 SmallVector<std::pair<const CXXMethodDecl*, const CXXMethodDecl*>, 2>
507 DelayedExceptionSpecChecks;
509 /// \brief All the members seen during a class definition which were both
510 /// explicitly defaulted and had explicitly-specified exception
511 /// specifications, along with the function type containing their
512 /// user-specified exception specification. Those exception specifications
513 /// were overridden with the default specifications, but we still need to
514 /// check whether they are compatible with the default specification, and
515 /// we can't do that until the nesting set of class definitions is complete.
516 SmallVector<std::pair<CXXMethodDecl*, const FunctionProtoType*>, 2>
517 DelayedDefaultedMemberExceptionSpecs;
519 typedef llvm::MapVector<const FunctionDecl *, LateParsedTemplate *>
520 LateParsedTemplateMapT;
521 LateParsedTemplateMapT LateParsedTemplateMap;
523 /// \brief Callback to the parser to parse templated functions when needed.
524 typedef void LateTemplateParserCB(void *P, LateParsedTemplate &LPT);
525 typedef void LateTemplateParserCleanupCB(void *P);
526 LateTemplateParserCB *LateTemplateParser;
527 LateTemplateParserCleanupCB *LateTemplateParserCleanup;
530 void SetLateTemplateParser(LateTemplateParserCB *LTP,
531 LateTemplateParserCleanupCB *LTPCleanup,
533 LateTemplateParser = LTP;
534 LateTemplateParserCleanup = LTPCleanup;
538 class DelayedDiagnostics;
540 class DelayedDiagnosticsState {
541 sema::DelayedDiagnosticPool *SavedPool;
542 friend class Sema::DelayedDiagnostics;
544 typedef DelayedDiagnosticsState ParsingDeclState;
545 typedef DelayedDiagnosticsState ProcessingContextState;
547 /// A class which encapsulates the logic for delaying diagnostics
548 /// during parsing and other processing.
549 class DelayedDiagnostics {
550 /// \brief The current pool of diagnostics into which delayed
551 /// diagnostics should go.
552 sema::DelayedDiagnosticPool *CurPool;
555 DelayedDiagnostics() : CurPool(nullptr) {}
557 /// Adds a delayed diagnostic.
558 void add(const sema::DelayedDiagnostic &diag); // in DelayedDiagnostic.h
560 /// Determines whether diagnostics should be delayed.
561 bool shouldDelayDiagnostics() { return CurPool != nullptr; }
563 /// Returns the current delayed-diagnostics pool.
564 sema::DelayedDiagnosticPool *getCurrentPool() const {
568 /// Enter a new scope. Access and deprecation diagnostics will be
569 /// collected in this pool.
570 DelayedDiagnosticsState push(sema::DelayedDiagnosticPool &pool) {
571 DelayedDiagnosticsState state;
572 state.SavedPool = CurPool;
577 /// Leave a delayed-diagnostic state that was previously pushed.
578 /// Do not emit any of the diagnostics. This is performed as part
579 /// of the bookkeeping of popping a pool "properly".
580 void popWithoutEmitting(DelayedDiagnosticsState state) {
581 CurPool = state.SavedPool;
584 /// Enter a new scope where access and deprecation diagnostics are
586 DelayedDiagnosticsState pushUndelayed() {
587 DelayedDiagnosticsState state;
588 state.SavedPool = CurPool;
593 /// Undo a previous pushUndelayed().
594 void popUndelayed(DelayedDiagnosticsState state) {
595 assert(CurPool == nullptr);
596 CurPool = state.SavedPool;
598 } DelayedDiagnostics;
600 /// A RAII object to temporarily push a declaration context.
604 DeclContext *SavedContext;
605 ProcessingContextState SavedContextState;
606 QualType SavedCXXThisTypeOverride;
609 ContextRAII(Sema &S, DeclContext *ContextToPush, bool NewThisContext = true)
610 : S(S), SavedContext(S.CurContext),
611 SavedContextState(S.DelayedDiagnostics.pushUndelayed()),
612 SavedCXXThisTypeOverride(S.CXXThisTypeOverride)
614 assert(ContextToPush && "pushing null context");
615 S.CurContext = ContextToPush;
617 S.CXXThisTypeOverride = QualType();
621 if (!SavedContext) return;
622 S.CurContext = SavedContext;
623 S.DelayedDiagnostics.popUndelayed(SavedContextState);
624 S.CXXThisTypeOverride = SavedCXXThisTypeOverride;
625 SavedContext = nullptr;
633 /// \brief RAII object to handle the state changes required to synthesize
635 class SynthesizedFunctionScope {
637 Sema::ContextRAII SavedContext;
640 SynthesizedFunctionScope(Sema &S, DeclContext *DC)
641 : S(S), SavedContext(S, DC)
643 S.PushFunctionScope();
644 S.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated);
647 ~SynthesizedFunctionScope() {
648 S.PopExpressionEvaluationContext();
649 S.PopFunctionScopeInfo();
653 /// WeakUndeclaredIdentifiers - Identifiers contained in
654 /// \#pragma weak before declared. rare. may alias another
655 /// identifier, declared or undeclared
656 llvm::MapVector<IdentifierInfo *, WeakInfo> WeakUndeclaredIdentifiers;
658 /// ExtnameUndeclaredIdentifiers - Identifiers contained in
659 /// \#pragma redefine_extname before declared. Used in Solaris system headers
660 /// to define functions that occur in multiple standards to call the version
661 /// in the currently selected standard.
662 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*> ExtnameUndeclaredIdentifiers;
665 /// \brief Load weak undeclared identifiers from the external source.
666 void LoadExternalWeakUndeclaredIdentifiers();
668 /// WeakTopLevelDecl - Translation-unit scoped declarations generated by
669 /// \#pragma weak during processing of other Decls.
670 /// I couldn't figure out a clean way to generate these in-line, so
671 /// we store them here and handle separately -- which is a hack.
672 /// It would be best to refactor this.
673 SmallVector<Decl*,2> WeakTopLevelDecl;
675 IdentifierResolver IdResolver;
677 /// Translation Unit Scope - useful to Objective-C actions that need
678 /// to lookup file scope declarations in the "ordinary" C decl namespace.
679 /// For example, user-defined classes, built-in "id" type, etc.
682 /// \brief The C++ "std" namespace, where the standard library resides.
683 LazyDeclPtr StdNamespace;
685 /// \brief The C++ "std::bad_alloc" class, which is defined by the C++
686 /// standard library.
687 LazyDeclPtr StdBadAlloc;
689 /// \brief The C++ "std::initializer_list" template, which is defined in
690 /// \<initializer_list>.
691 ClassTemplateDecl *StdInitializerList;
693 /// \brief The C++ "type_info" declaration, which is defined in \<typeinfo>.
694 RecordDecl *CXXTypeInfoDecl;
696 /// \brief The MSVC "_GUID" struct, which is defined in MSVC header files.
697 RecordDecl *MSVCGuidDecl;
699 /// \brief Caches identifiers/selectors for NSFoundation APIs.
700 std::unique_ptr<NSAPI> NSAPIObj;
702 /// \brief The declaration of the Objective-C NSNumber class.
703 ObjCInterfaceDecl *NSNumberDecl;
705 /// \brief The declaration of the Objective-C NSValue class.
706 ObjCInterfaceDecl *NSValueDecl;
708 /// \brief Pointer to NSNumber type (NSNumber *).
709 QualType NSNumberPointer;
711 /// \brief Pointer to NSValue type (NSValue *).
712 QualType NSValuePointer;
714 /// \brief The Objective-C NSNumber methods used to create NSNumber literals.
715 ObjCMethodDecl *NSNumberLiteralMethods[NSAPI::NumNSNumberLiteralMethods];
717 /// \brief The declaration of the Objective-C NSString class.
718 ObjCInterfaceDecl *NSStringDecl;
720 /// \brief Pointer to NSString type (NSString *).
721 QualType NSStringPointer;
723 /// \brief The declaration of the stringWithUTF8String: method.
724 ObjCMethodDecl *StringWithUTF8StringMethod;
726 /// \brief The declaration of the valueWithBytes:objCType: method.
727 ObjCMethodDecl *ValueWithBytesObjCTypeMethod;
729 /// \brief The declaration of the Objective-C NSArray class.
730 ObjCInterfaceDecl *NSArrayDecl;
732 /// \brief Pointer to NSMutableArray type (NSMutableArray *).
733 QualType NSMutableArrayPointer;
735 /// \brief The declaration of the arrayWithObjects:count: method.
736 ObjCMethodDecl *ArrayWithObjectsMethod;
738 /// \brief The declaration of the Objective-C NSDictionary class.
739 ObjCInterfaceDecl *NSDictionaryDecl;
741 /// \brief Pointer to NSMutableDictionary type (NSMutableDictionary *).
742 QualType NSMutableDictionaryPointer;
744 /// \brief Pointer to NSMutableSet type (NSMutableSet *).
745 QualType NSMutableSetPointer;
747 /// \brief Pointer to NSCountedSet type (NSCountedSet *).
748 QualType NSCountedSetPointer;
750 /// \brief Pointer to NSMutableOrderedSet type (NSMutableOrderedSet *).
751 QualType NSMutableOrderedSetPointer;
753 /// \brief The declaration of the dictionaryWithObjects:forKeys:count: method.
754 ObjCMethodDecl *DictionaryWithObjectsMethod;
756 /// \brief id<NSCopying> type.
757 QualType QIDNSCopying;
759 /// \brief will hold 'respondsToSelector:'
760 Selector RespondsToSelectorSel;
762 /// \brief counter for internal MS Asm label names.
763 unsigned MSAsmLabelNameCounter;
765 /// A flag to remember whether the implicit forms of operator new and delete
766 /// have been declared.
767 bool GlobalNewDeleteDeclared;
769 /// A flag to indicate that we're in a context that permits abstract
770 /// references to fields. This is really a
771 bool AllowAbstractFieldReference;
773 /// \brief Describes how the expressions currently being parsed are
774 /// evaluated at run-time, if at all.
775 enum ExpressionEvaluationContext {
776 /// \brief The current expression and its subexpressions occur within an
777 /// unevaluated operand (C++11 [expr]p7), such as the subexpression of
778 /// \c sizeof, where the type of the expression may be significant but
779 /// no code will be generated to evaluate the value of the expression at
783 /// \brief The current expression occurs within an unevaluated
784 /// operand that unconditionally permits abstract references to
785 /// fields, such as a SIZE operator in MS-style inline assembly.
788 /// \brief The current context is "potentially evaluated" in C++11 terms,
789 /// but the expression is evaluated at compile-time (like the values of
790 /// cases in a switch statement).
793 /// \brief The current expression is potentially evaluated at run time,
794 /// which means that code may be generated to evaluate the value of the
795 /// expression at run time.
796 PotentiallyEvaluated,
798 /// \brief The current expression is potentially evaluated, but any
799 /// declarations referenced inside that expression are only used if
800 /// in fact the current expression is used.
802 /// This value is used when parsing default function arguments, for which
803 /// we would like to provide diagnostics (e.g., passing non-POD arguments
804 /// through varargs) but do not want to mark declarations as "referenced"
805 /// until the default argument is used.
806 PotentiallyEvaluatedIfUsed
809 /// \brief Data structure used to record current or nested
810 /// expression evaluation contexts.
811 struct ExpressionEvaluationContextRecord {
812 /// \brief The expression evaluation context.
813 ExpressionEvaluationContext Context;
815 /// \brief Whether the enclosing context needed a cleanup.
816 bool ParentNeedsCleanups;
818 /// \brief Whether we are in a decltype expression.
821 /// \brief The number of active cleanup objects when we entered
822 /// this expression evaluation context.
823 unsigned NumCleanupObjects;
825 /// \brief The number of typos encountered during this expression evaluation
826 /// context (i.e. the number of TypoExprs created).
829 llvm::SmallPtrSet<Expr*, 2> SavedMaybeODRUseExprs;
831 /// \brief The lambdas that are present within this context, if it
832 /// is indeed an unevaluated context.
833 SmallVector<LambdaExpr *, 2> Lambdas;
835 /// \brief The declaration that provides context for lambda expressions
836 /// and block literals if the normal declaration context does not
837 /// suffice, e.g., in a default function argument.
838 Decl *ManglingContextDecl;
840 /// \brief The context information used to mangle lambda expressions
841 /// and block literals within this context.
843 /// This mangling information is allocated lazily, since most contexts
844 /// do not have lambda expressions or block literals.
845 IntrusiveRefCntPtr<MangleNumberingContext> MangleNumbering;
847 /// \brief If we are processing a decltype type, a set of call expressions
848 /// for which we have deferred checking the completeness of the return type.
849 SmallVector<CallExpr *, 8> DelayedDecltypeCalls;
851 /// \brief If we are processing a decltype type, a set of temporary binding
852 /// expressions for which we have deferred checking the destructor.
853 SmallVector<CXXBindTemporaryExpr *, 8> DelayedDecltypeBinds;
855 ExpressionEvaluationContextRecord(ExpressionEvaluationContext Context,
856 unsigned NumCleanupObjects,
857 bool ParentNeedsCleanups,
858 Decl *ManglingContextDecl,
860 : Context(Context), ParentNeedsCleanups(ParentNeedsCleanups),
861 IsDecltype(IsDecltype), NumCleanupObjects(NumCleanupObjects),
863 ManglingContextDecl(ManglingContextDecl), MangleNumbering() { }
865 /// \brief Retrieve the mangling numbering context, used to consistently
866 /// number constructs like lambdas for mangling.
867 MangleNumberingContext &getMangleNumberingContext(ASTContext &Ctx);
869 bool isUnevaluated() const {
870 return Context == Unevaluated || Context == UnevaluatedAbstract;
874 /// A stack of expression evaluation contexts.
875 SmallVector<ExpressionEvaluationContextRecord, 8> ExprEvalContexts;
877 /// \brief Compute the mangling number context for a lambda expression or
880 /// \param DC - The DeclContext containing the lambda expression or
882 /// \param[out] ManglingContextDecl - Returns the ManglingContextDecl
883 /// associated with the context, if relevant.
884 MangleNumberingContext *getCurrentMangleNumberContext(
885 const DeclContext *DC,
886 Decl *&ManglingContextDecl);
889 /// SpecialMemberOverloadResult - The overloading result for a special member
892 /// This is basically a wrapper around PointerIntPair. The lowest bits of the
893 /// integer are used to determine whether overload resolution succeeded.
894 class SpecialMemberOverloadResult : public llvm::FastFoldingSetNode {
903 llvm::PointerIntPair<CXXMethodDecl*, 2> Pair;
906 SpecialMemberOverloadResult(const llvm::FoldingSetNodeID &ID)
907 : FastFoldingSetNode(ID)
910 CXXMethodDecl *getMethod() const { return Pair.getPointer(); }
911 void setMethod(CXXMethodDecl *MD) { Pair.setPointer(MD); }
913 Kind getKind() const { return static_cast<Kind>(Pair.getInt()); }
914 void setKind(Kind K) { Pair.setInt(K); }
917 /// \brief A cache of special member function overload resolution results
919 llvm::FoldingSet<SpecialMemberOverloadResult> SpecialMemberCache;
921 /// \brief The kind of translation unit we are processing.
923 /// When we're processing a complete translation unit, Sema will perform
924 /// end-of-translation-unit semantic tasks (such as creating
925 /// initializers for tentative definitions in C) once parsing has
926 /// completed. Modules and precompiled headers perform different kinds of
928 TranslationUnitKind TUKind;
930 llvm::BumpPtrAllocator BumpAlloc;
932 /// \brief The number of SFINAE diagnostics that have been trapped.
933 unsigned NumSFINAEErrors;
935 typedef llvm::DenseMap<ParmVarDecl *, llvm::TinyPtrVector<ParmVarDecl *>>
936 UnparsedDefaultArgInstantiationsMap;
938 /// \brief A mapping from parameters with unparsed default arguments to the
939 /// set of instantiations of each parameter.
941 /// This mapping is a temporary data structure used when parsing
942 /// nested class templates or nested classes of class templates,
943 /// where we might end up instantiating an inner class before the
944 /// default arguments of its methods have been parsed.
945 UnparsedDefaultArgInstantiationsMap UnparsedDefaultArgInstantiations;
947 // Contains the locations of the beginning of unparsed default
948 // argument locations.
949 llvm::DenseMap<ParmVarDecl *, SourceLocation> UnparsedDefaultArgLocs;
951 /// UndefinedInternals - all the used, undefined objects which require a
952 /// definition in this translation unit.
953 llvm::DenseMap<NamedDecl *, SourceLocation> UndefinedButUsed;
955 /// Obtain a sorted list of functions that are undefined but ODR-used.
956 void getUndefinedButUsed(
957 SmallVectorImpl<std::pair<NamedDecl *, SourceLocation> > &Undefined);
959 /// Retrieves list of suspicious delete-expressions that will be checked at
960 /// the end of translation unit.
961 const llvm::MapVector<FieldDecl *, DeleteLocs> &
962 getMismatchingDeleteExpressions() const;
964 typedef std::pair<ObjCMethodList, ObjCMethodList> GlobalMethods;
965 typedef llvm::DenseMap<Selector, GlobalMethods> GlobalMethodPool;
967 /// Method Pool - allows efficient lookup when typechecking messages to "id".
968 /// We need to maintain a list, since selectors can have differing signatures
969 /// across classes. In Cocoa, this happens to be extremely uncommon (only 1%
970 /// of selectors are "overloaded").
971 /// At the head of the list it is recorded whether there were 0, 1, or >= 2
972 /// methods inside categories with a particular selector.
973 GlobalMethodPool MethodPool;
975 /// Method selectors used in a \@selector expression. Used for implementation
977 llvm::MapVector<Selector, SourceLocation> ReferencedSelectors;
979 /// Kinds of C++ special members.
980 enum CXXSpecialMember {
981 CXXDefaultConstructor,
990 typedef std::pair<CXXRecordDecl*, CXXSpecialMember> SpecialMemberDecl;
992 /// The C++ special members which we are currently in the process of
993 /// declaring. If this process recursively triggers the declaration of the
994 /// same special member, we should act as if it is not yet declared.
995 llvm::SmallSet<SpecialMemberDecl, 4> SpecialMembersBeingDeclared;
997 void ReadMethodPool(Selector Sel);
999 /// Private Helper predicate to check for 'self'.
1000 bool isSelfExpr(Expr *RExpr);
1001 bool isSelfExpr(Expr *RExpr, const ObjCMethodDecl *Method);
1003 /// \brief Cause the active diagnostic on the DiagosticsEngine to be
1004 /// emitted. This is closely coupled to the SemaDiagnosticBuilder class and
1005 /// should not be used elsewhere.
1006 void EmitCurrentDiagnostic(unsigned DiagID);
1008 /// Records and restores the FP_CONTRACT state on entry/exit of compound
1010 class FPContractStateRAII {
1012 FPContractStateRAII(Sema& S)
1013 : S(S), OldFPContractState(S.FPFeatures.fp_contract) {}
1014 ~FPContractStateRAII() {
1015 S.FPFeatures.fp_contract = OldFPContractState;
1019 bool OldFPContractState : 1;
1022 void addImplicitTypedef(StringRef Name, QualType T);
1025 Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer,
1026 TranslationUnitKind TUKind = TU_Complete,
1027 CodeCompleteConsumer *CompletionConsumer = nullptr);
1030 /// \brief Perform initialization that occurs after the parser has been
1031 /// initialized but before it parses anything.
1034 const LangOptions &getLangOpts() const { return LangOpts; }
1035 OpenCLOptions &getOpenCLOptions() { return OpenCLFeatures; }
1036 FPOptions &getFPOptions() { return FPFeatures; }
1038 DiagnosticsEngine &getDiagnostics() const { return Diags; }
1039 SourceManager &getSourceManager() const { return SourceMgr; }
1040 Preprocessor &getPreprocessor() const { return PP; }
1041 ASTContext &getASTContext() const { return Context; }
1042 ASTConsumer &getASTConsumer() const { return Consumer; }
1043 ASTMutationListener *getASTMutationListener() const;
1044 ExternalSemaSource* getExternalSource() const { return ExternalSource; }
1046 ///\brief Registers an external source. If an external source already exists,
1047 /// creates a multiplex external source and appends to it.
1049 ///\param[in] E - A non-null external sema source.
1051 void addExternalSource(ExternalSemaSource *E);
1053 void PrintStats() const;
1055 /// \brief Helper class that creates diagnostics with optional
1056 /// template instantiation stacks.
1058 /// This class provides a wrapper around the basic DiagnosticBuilder
1059 /// class that emits diagnostics. SemaDiagnosticBuilder is
1060 /// responsible for emitting the diagnostic (as DiagnosticBuilder
1061 /// does) and, if the diagnostic comes from inside a template
1062 /// instantiation, printing the template instantiation stack as
1064 class SemaDiagnosticBuilder : public DiagnosticBuilder {
1069 SemaDiagnosticBuilder(DiagnosticBuilder &DB, Sema &SemaRef, unsigned DiagID)
1070 : DiagnosticBuilder(DB), SemaRef(SemaRef), DiagID(DiagID) { }
1072 ~SemaDiagnosticBuilder() {
1073 // If we aren't active, there is nothing to do.
1074 if (!isActive()) return;
1076 // Otherwise, we need to emit the diagnostic. First flush the underlying
1077 // DiagnosticBuilder data, and clear the diagnostic builder itself so it
1078 // won't emit the diagnostic in its own destructor.
1080 // This seems wasteful, in that as written the DiagnosticBuilder dtor will
1081 // do its own needless checks to see if the diagnostic needs to be
1082 // emitted. However, because we take care to ensure that the builder
1083 // objects never escape, a sufficiently smart compiler will be able to
1084 // eliminate that code.
1088 // Dispatch to Sema to emit the diagnostic.
1089 SemaRef.EmitCurrentDiagnostic(DiagID);
1092 /// Teach operator<< to produce an object of the correct type.
1093 template<typename T>
1094 friend const SemaDiagnosticBuilder &operator<<(
1095 const SemaDiagnosticBuilder &Diag, const T &Value) {
1096 const DiagnosticBuilder &BaseDiag = Diag;
1102 /// \brief Emit a diagnostic.
1103 SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID) {
1104 DiagnosticBuilder DB = Diags.Report(Loc, DiagID);
1105 return SemaDiagnosticBuilder(DB, *this, DiagID);
1108 /// \brief Emit a partial diagnostic.
1109 SemaDiagnosticBuilder Diag(SourceLocation Loc, const PartialDiagnostic& PD);
1111 /// \brief Build a partial diagnostic.
1112 PartialDiagnostic PDiag(unsigned DiagID = 0); // in SemaInternal.h
1114 bool findMacroSpelling(SourceLocation &loc, StringRef name);
1116 /// \brief Get a string to suggest for zero-initialization of a type.
1118 getFixItZeroInitializerForType(QualType T, SourceLocation Loc) const;
1119 std::string getFixItZeroLiteralForType(QualType T, SourceLocation Loc) const;
1121 /// \brief Calls \c Lexer::getLocForEndOfToken()
1122 SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset = 0);
1124 /// \brief Retrieve the module loader associated with the preprocessor.
1125 ModuleLoader &getModuleLoader() const;
1127 void emitAndClearUnusedLocalTypedefWarnings();
1129 void ActOnEndOfTranslationUnit();
1131 void CheckDelegatingCtorCycles();
1133 Scope *getScopeForContext(DeclContext *Ctx);
1135 void PushFunctionScope();
1136 void PushBlockScope(Scope *BlockScope, BlockDecl *Block);
1137 sema::LambdaScopeInfo *PushLambdaScope();
1139 /// \brief This is used to inform Sema what the current TemplateParameterDepth
1140 /// is during Parsing. Currently it is used to pass on the depth
1141 /// when parsing generic lambda 'auto' parameters.
1142 void RecordParsingTemplateParameterDepth(unsigned Depth);
1144 void PushCapturedRegionScope(Scope *RegionScope, CapturedDecl *CD,
1146 CapturedRegionKind K);
1148 PopFunctionScopeInfo(const sema::AnalysisBasedWarnings::Policy *WP = nullptr,
1149 const Decl *D = nullptr,
1150 const BlockExpr *blkExpr = nullptr);
1152 sema::FunctionScopeInfo *getCurFunction() const {
1153 return FunctionScopes.back();
1156 sema::FunctionScopeInfo *getEnclosingFunction() const {
1157 if (FunctionScopes.empty())
1160 for (int e = FunctionScopes.size()-1; e >= 0; --e) {
1161 if (isa<sema::BlockScopeInfo>(FunctionScopes[e]))
1163 return FunctionScopes[e];
1168 template <typename ExprT>
1169 void recordUseOfEvaluatedWeak(const ExprT *E, bool IsRead=true) {
1170 if (!isUnevaluatedContext())
1171 getCurFunction()->recordUseOfWeak(E, IsRead);
1174 void PushCompoundScope();
1175 void PopCompoundScope();
1177 sema::CompoundScopeInfo &getCurCompoundScope() const;
1179 bool hasAnyUnrecoverableErrorsInThisFunction() const;
1181 /// \brief Retrieve the current block, if any.
1182 sema::BlockScopeInfo *getCurBlock();
1184 /// \brief Retrieve the current lambda scope info, if any.
1185 sema::LambdaScopeInfo *getCurLambda();
1187 /// \brief Retrieve the current generic lambda info, if any.
1188 sema::LambdaScopeInfo *getCurGenericLambda();
1190 /// \brief Retrieve the current captured region, if any.
1191 sema::CapturedRegionScopeInfo *getCurCapturedRegion();
1193 /// WeakTopLevelDeclDecls - access to \#pragma weak-generated Decls
1194 SmallVectorImpl<Decl *> &WeakTopLevelDecls() { return WeakTopLevelDecl; }
1196 void ActOnComment(SourceRange Comment);
1198 //===--------------------------------------------------------------------===//
1199 // Type Analysis / Processing: SemaType.cpp.
1202 QualType BuildQualifiedType(QualType T, SourceLocation Loc, Qualifiers Qs,
1203 const DeclSpec *DS = nullptr);
1204 QualType BuildQualifiedType(QualType T, SourceLocation Loc, unsigned CVRA,
1205 const DeclSpec *DS = nullptr);
1206 QualType BuildPointerType(QualType T,
1207 SourceLocation Loc, DeclarationName Entity);
1208 QualType BuildReferenceType(QualType T, bool LValueRef,
1209 SourceLocation Loc, DeclarationName Entity);
1210 QualType BuildArrayType(QualType T, ArrayType::ArraySizeModifier ASM,
1211 Expr *ArraySize, unsigned Quals,
1212 SourceRange Brackets, DeclarationName Entity);
1213 QualType BuildExtVectorType(QualType T, Expr *ArraySize,
1214 SourceLocation AttrLoc);
1216 bool CheckFunctionReturnType(QualType T, SourceLocation Loc);
1218 unsigned deduceWeakPropertyFromType(QualType T) {
1219 if ((getLangOpts().getGC() != LangOptions::NonGC &&
1220 T.isObjCGCWeak()) ||
1221 (getLangOpts().ObjCAutoRefCount &&
1222 T.getObjCLifetime() == Qualifiers::OCL_Weak))
1223 return ObjCDeclSpec::DQ_PR_weak;
1228 /// \brief Build a function type.
1230 /// This routine checks the function type according to C++ rules and
1231 /// under the assumption that the result type and parameter types have
1232 /// just been instantiated from a template. It therefore duplicates
1233 /// some of the behavior of GetTypeForDeclarator, but in a much
1234 /// simpler form that is only suitable for this narrow use case.
1236 /// \param T The return type of the function.
1238 /// \param ParamTypes The parameter types of the function. This array
1239 /// will be modified to account for adjustments to the types of the
1240 /// function parameters.
1242 /// \param Loc The location of the entity whose type involves this
1243 /// function type or, if there is no such entity, the location of the
1244 /// type that will have function type.
1246 /// \param Entity The name of the entity that involves the function
1249 /// \param EPI Extra information about the function type. Usually this will
1250 /// be taken from an existing function with the same prototype.
1252 /// \returns A suitable function type, if there are no errors. The
1253 /// unqualified type will always be a FunctionProtoType.
1254 /// Otherwise, returns a NULL type.
1255 QualType BuildFunctionType(QualType T,
1256 MutableArrayRef<QualType> ParamTypes,
1257 SourceLocation Loc, DeclarationName Entity,
1258 const FunctionProtoType::ExtProtoInfo &EPI);
1260 QualType BuildMemberPointerType(QualType T, QualType Class,
1262 DeclarationName Entity);
1263 QualType BuildBlockPointerType(QualType T,
1264 SourceLocation Loc, DeclarationName Entity);
1265 QualType BuildParenType(QualType T);
1266 QualType BuildAtomicType(QualType T, SourceLocation Loc);
1268 TypeSourceInfo *GetTypeForDeclarator(Declarator &D, Scope *S);
1269 TypeSourceInfo *GetTypeForDeclaratorCast(Declarator &D, QualType FromTy);
1270 TypeSourceInfo *GetTypeSourceInfoForDeclarator(Declarator &D, QualType T,
1271 TypeSourceInfo *ReturnTypeInfo);
1273 /// \brief Package the given type and TSI into a ParsedType.
1274 ParsedType CreateParsedType(QualType T, TypeSourceInfo *TInfo);
1275 DeclarationNameInfo GetNameForDeclarator(Declarator &D);
1276 DeclarationNameInfo GetNameFromUnqualifiedId(const UnqualifiedId &Name);
1277 static QualType GetTypeFromParser(ParsedType Ty,
1278 TypeSourceInfo **TInfo = nullptr);
1279 CanThrowResult canThrow(const Expr *E);
1280 const FunctionProtoType *ResolveExceptionSpec(SourceLocation Loc,
1281 const FunctionProtoType *FPT);
1282 void UpdateExceptionSpec(FunctionDecl *FD,
1283 const FunctionProtoType::ExceptionSpecInfo &ESI);
1284 bool CheckSpecifiedExceptionType(QualType &T, const SourceRange &Range);
1285 bool CheckDistantExceptionSpec(QualType T);
1286 bool CheckEquivalentExceptionSpec(FunctionDecl *Old, FunctionDecl *New);
1287 bool CheckEquivalentExceptionSpec(
1288 const FunctionProtoType *Old, SourceLocation OldLoc,
1289 const FunctionProtoType *New, SourceLocation NewLoc);
1290 bool CheckEquivalentExceptionSpec(
1291 const PartialDiagnostic &DiagID, const PartialDiagnostic & NoteID,
1292 const FunctionProtoType *Old, SourceLocation OldLoc,
1293 const FunctionProtoType *New, SourceLocation NewLoc,
1294 bool *MissingExceptionSpecification = nullptr,
1295 bool *MissingEmptyExceptionSpecification = nullptr,
1296 bool AllowNoexceptAllMatchWithNoSpec = false,
1297 bool IsOperatorNew = false);
1298 bool CheckExceptionSpecSubset(
1299 const PartialDiagnostic &DiagID, const PartialDiagnostic & NoteID,
1300 const FunctionProtoType *Superset, SourceLocation SuperLoc,
1301 const FunctionProtoType *Subset, SourceLocation SubLoc);
1302 bool CheckParamExceptionSpec(const PartialDiagnostic & NoteID,
1303 const FunctionProtoType *Target, SourceLocation TargetLoc,
1304 const FunctionProtoType *Source, SourceLocation SourceLoc);
1306 TypeResult ActOnTypeName(Scope *S, Declarator &D);
1308 /// \brief The parser has parsed the context-sensitive type 'instancetype'
1309 /// in an Objective-C message declaration. Return the appropriate type.
1310 ParsedType ActOnObjCInstanceType(SourceLocation Loc);
1312 /// \brief Abstract class used to diagnose incomplete types.
1313 struct TypeDiagnoser {
1316 TypeDiagnoser(bool Suppressed = false) : Suppressed(Suppressed) { }
1318 virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) = 0;
1319 virtual ~TypeDiagnoser() {}
1322 static int getPrintable(int I) { return I; }
1323 static unsigned getPrintable(unsigned I) { return I; }
1324 static bool getPrintable(bool B) { return B; }
1325 static const char * getPrintable(const char *S) { return S; }
1326 static StringRef getPrintable(StringRef S) { return S; }
1327 static const std::string &getPrintable(const std::string &S) { return S; }
1328 static const IdentifierInfo *getPrintable(const IdentifierInfo *II) {
1331 static DeclarationName getPrintable(DeclarationName N) { return N; }
1332 static QualType getPrintable(QualType T) { return T; }
1333 static SourceRange getPrintable(SourceRange R) { return R; }
1334 static SourceRange getPrintable(SourceLocation L) { return L; }
1335 static SourceRange getPrintable(const Expr *E) { return E->getSourceRange(); }
1336 static SourceRange getPrintable(TypeLoc TL) { return TL.getSourceRange();}
1338 template <typename... Ts> class BoundTypeDiagnoser : public TypeDiagnoser {
1340 std::tuple<const Ts &...> Args;
1342 template <std::size_t... Is>
1343 void emit(const SemaDiagnosticBuilder &DB,
1344 llvm::index_sequence<Is...>) const {
1345 // Apply all tuple elements to the builder in order.
1346 bool Dummy[] = {(DB << getPrintable(std::get<Is>(Args)))...};
1351 BoundTypeDiagnoser(unsigned DiagID, const Ts &...Args)
1352 : TypeDiagnoser(DiagID == 0), DiagID(DiagID), Args(Args...) {}
1354 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
1357 const SemaDiagnosticBuilder &DB = S.Diag(Loc, DiagID);
1358 emit(DB, llvm::index_sequence_for<Ts...>());
1364 bool RequireCompleteTypeImpl(SourceLocation Loc, QualType T,
1365 TypeDiagnoser &Diagnoser);
1367 VisibleModuleSet VisibleModules;
1368 llvm::SmallVector<VisibleModuleSet, 16> VisibleModulesStack;
1370 Module *CachedFakeTopLevelModule;
1373 /// \brief Get the module owning an entity.
1374 Module *getOwningModule(Decl *Entity);
1376 /// \brief Make a merged definition of an existing hidden definition \p ND
1377 /// visible at the specified location.
1378 void makeMergedDefinitionVisible(NamedDecl *ND, SourceLocation Loc);
1380 bool isModuleVisible(Module *M) { return VisibleModules.isVisible(M); }
1382 /// Determine whether a declaration is visible to name lookup.
1383 bool isVisible(const NamedDecl *D) {
1384 return !D->isHidden() || isVisibleSlow(D);
1386 bool hasVisibleMergedDefinition(NamedDecl *Def);
1388 /// Determine if \p D has a visible definition. If not, suggest a declaration
1389 /// that should be made visible to expose the definition.
1390 bool hasVisibleDefinition(NamedDecl *D, NamedDecl **Suggested);
1391 bool hasVisibleDefinition(const NamedDecl *D) {
1393 return hasVisibleDefinition(const_cast<NamedDecl*>(D), &Hidden);
1396 /// Determine if the template parameter \p D has a visible default argument.
1398 hasVisibleDefaultArgument(const NamedDecl *D,
1399 llvm::SmallVectorImpl<Module *> *Modules = nullptr);
1401 bool RequireCompleteType(SourceLocation Loc, QualType T,
1402 TypeDiagnoser &Diagnoser);
1403 bool RequireCompleteType(SourceLocation Loc, QualType T,
1406 template <typename... Ts>
1407 bool RequireCompleteType(SourceLocation Loc, QualType T, unsigned DiagID,
1408 const Ts &...Args) {
1409 BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
1410 return RequireCompleteType(Loc, T, Diagnoser);
1413 bool RequireCompleteExprType(Expr *E, TypeDiagnoser &Diagnoser);
1414 bool RequireCompleteExprType(Expr *E, unsigned DiagID);
1416 template <typename... Ts>
1417 bool RequireCompleteExprType(Expr *E, unsigned DiagID, const Ts &...Args) {
1418 BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
1419 return RequireCompleteExprType(E, Diagnoser);
1422 bool RequireLiteralType(SourceLocation Loc, QualType T,
1423 TypeDiagnoser &Diagnoser);
1424 bool RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID);
1426 template <typename... Ts>
1427 bool RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID,
1428 const Ts &...Args) {
1429 BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
1430 return RequireLiteralType(Loc, T, Diagnoser);
1433 QualType getElaboratedType(ElaboratedTypeKeyword Keyword,
1434 const CXXScopeSpec &SS, QualType T);
1436 QualType BuildTypeofExprType(Expr *E, SourceLocation Loc);
1437 /// If AsUnevaluated is false, E is treated as though it were an evaluated
1438 /// context, such as when building a type for decltype(auto).
1439 QualType BuildDecltypeType(Expr *E, SourceLocation Loc,
1440 bool AsUnevaluated = true);
1441 QualType BuildUnaryTransformType(QualType BaseType,
1442 UnaryTransformType::UTTKind UKind,
1443 SourceLocation Loc);
1445 //===--------------------------------------------------------------------===//
1446 // Symbol table / Decl tracking callbacks: SemaDecl.cpp.
1449 /// List of decls defined in a function prototype. This contains EnumConstants
1450 /// that incorrectly end up in translation unit scope because there is no
1451 /// function to pin them on. ActOnFunctionDeclarator reads this list and patches
1452 /// them into the FunctionDecl.
1453 std::vector<NamedDecl*> DeclsInPrototypeScope;
1455 DeclGroupPtrTy ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType = nullptr);
1457 void DiagnoseUseOfUnimplementedSelectors();
1459 bool isSimpleTypeSpecifier(tok::TokenKind Kind) const;
1461 ParsedType getTypeName(const IdentifierInfo &II, SourceLocation NameLoc,
1462 Scope *S, CXXScopeSpec *SS = nullptr,
1463 bool isClassName = false,
1464 bool HasTrailingDot = false,
1465 ParsedType ObjectType = ParsedType(),
1466 bool IsCtorOrDtorName = false,
1467 bool WantNontrivialTypeSourceInfo = false,
1468 IdentifierInfo **CorrectedII = nullptr);
1469 TypeSpecifierType isTagName(IdentifierInfo &II, Scope *S);
1470 bool isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S);
1471 void DiagnoseUnknownTypeName(IdentifierInfo *&II,
1472 SourceLocation IILoc,
1475 ParsedType &SuggestedType,
1476 bool AllowClassTemplates = false);
1478 /// \brief For compatibility with MSVC, we delay parsing of some default
1479 /// template type arguments until instantiation time. Emits a warning and
1480 /// returns a synthesized DependentNameType that isn't really dependent on any
1481 /// other template arguments.
1482 ParsedType ActOnDelayedDefaultTemplateArg(const IdentifierInfo &II,
1483 SourceLocation NameLoc);
1485 /// \brief Describes the result of the name lookup and resolution performed
1486 /// by \c ClassifyName().
1487 enum NameClassificationKind {
1493 NC_NestedNameSpecifier,
1499 class NameClassification {
1500 NameClassificationKind Kind;
1502 TemplateName Template;
1504 const IdentifierInfo *Keyword;
1506 explicit NameClassification(NameClassificationKind Kind) : Kind(Kind) {}
1509 NameClassification(ExprResult Expr) : Kind(NC_Expression), Expr(Expr) {}
1511 NameClassification(ParsedType Type) : Kind(NC_Type), Type(Type) {}
1513 NameClassification(const IdentifierInfo *Keyword)
1514 : Kind(NC_Keyword), Keyword(Keyword) { }
1516 static NameClassification Error() {
1517 return NameClassification(NC_Error);
1520 static NameClassification Unknown() {
1521 return NameClassification(NC_Unknown);
1524 static NameClassification NestedNameSpecifier() {
1525 return NameClassification(NC_NestedNameSpecifier);
1528 static NameClassification TypeTemplate(TemplateName Name) {
1529 NameClassification Result(NC_TypeTemplate);
1530 Result.Template = Name;
1534 static NameClassification VarTemplate(TemplateName Name) {
1535 NameClassification Result(NC_VarTemplate);
1536 Result.Template = Name;
1540 static NameClassification FunctionTemplate(TemplateName Name) {
1541 NameClassification Result(NC_FunctionTemplate);
1542 Result.Template = Name;
1546 NameClassificationKind getKind() const { return Kind; }
1548 ParsedType getType() const {
1549 assert(Kind == NC_Type);
1553 ExprResult getExpression() const {
1554 assert(Kind == NC_Expression);
1558 TemplateName getTemplateName() const {
1559 assert(Kind == NC_TypeTemplate || Kind == NC_FunctionTemplate ||
1560 Kind == NC_VarTemplate);
1564 TemplateNameKind getTemplateNameKind() const {
1566 case NC_TypeTemplate:
1567 return TNK_Type_template;
1568 case NC_FunctionTemplate:
1569 return TNK_Function_template;
1570 case NC_VarTemplate:
1571 return TNK_Var_template;
1573 llvm_unreachable("unsupported name classification.");
1578 /// \brief Perform name lookup on the given name, classifying it based on
1579 /// the results of name lookup and the following token.
1581 /// This routine is used by the parser to resolve identifiers and help direct
1582 /// parsing. When the identifier cannot be found, this routine will attempt
1583 /// to correct the typo and classify based on the resulting name.
1585 /// \param S The scope in which we're performing name lookup.
1587 /// \param SS The nested-name-specifier that precedes the name.
1589 /// \param Name The identifier. If typo correction finds an alternative name,
1590 /// this pointer parameter will be updated accordingly.
1592 /// \param NameLoc The location of the identifier.
1594 /// \param NextToken The token following the identifier. Used to help
1595 /// disambiguate the name.
1597 /// \param IsAddressOfOperand True if this name is the operand of a unary
1598 /// address of ('&') expression, assuming it is classified as an
1601 /// \param CCC The correction callback, if typo correction is desired.
1603 ClassifyName(Scope *S, CXXScopeSpec &SS, IdentifierInfo *&Name,
1604 SourceLocation NameLoc, const Token &NextToken,
1605 bool IsAddressOfOperand,
1606 std::unique_ptr<CorrectionCandidateCallback> CCC = nullptr);
1608 Decl *ActOnDeclarator(Scope *S, Declarator &D);
1610 NamedDecl *HandleDeclarator(Scope *S, Declarator &D,
1611 MultiTemplateParamsArg TemplateParameterLists);
1612 void RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S);
1613 bool DiagnoseClassNameShadow(DeclContext *DC, DeclarationNameInfo Info);
1614 bool diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
1615 DeclarationName Name,
1616 SourceLocation Loc);
1618 diagnoseIgnoredQualifiers(unsigned DiagID, unsigned Quals,
1619 SourceLocation FallbackLoc,
1620 SourceLocation ConstQualLoc = SourceLocation(),
1621 SourceLocation VolatileQualLoc = SourceLocation(),
1622 SourceLocation RestrictQualLoc = SourceLocation(),
1623 SourceLocation AtomicQualLoc = SourceLocation());
1625 static bool adjustContextForLocalExternDecl(DeclContext *&DC);
1626 void DiagnoseFunctionSpecifiers(const DeclSpec &DS);
1627 void CheckShadow(Scope *S, VarDecl *D, const LookupResult& R);
1628 void CheckShadow(Scope *S, VarDecl *D);
1629 void CheckCastAlign(Expr *Op, QualType T, SourceRange TRange);
1630 void handleTagNumbering(const TagDecl *Tag, Scope *TagScope);
1631 void setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
1632 TypedefNameDecl *NewTD);
1633 void CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *D);
1634 NamedDecl* ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
1635 TypeSourceInfo *TInfo,
1636 LookupResult &Previous);
1637 NamedDecl* ActOnTypedefNameDecl(Scope* S, DeclContext* DC, TypedefNameDecl *D,
1638 LookupResult &Previous, bool &Redeclaration);
1639 NamedDecl *ActOnVariableDeclarator(Scope *S, Declarator &D, DeclContext *DC,
1640 TypeSourceInfo *TInfo,
1641 LookupResult &Previous,
1642 MultiTemplateParamsArg TemplateParamLists,
1644 // Returns true if the variable declaration is a redeclaration
1645 bool CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous);
1646 void CheckVariableDeclarationType(VarDecl *NewVD);
1647 void CheckCompleteVariableDeclaration(VarDecl *var);
1648 void MaybeSuggestAddingStaticToDecl(const FunctionDecl *D);
1650 NamedDecl* ActOnFunctionDeclarator(Scope* S, Declarator& D, DeclContext* DC,
1651 TypeSourceInfo *TInfo,
1652 LookupResult &Previous,
1653 MultiTemplateParamsArg TemplateParamLists,
1655 bool AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD);
1657 bool CheckConstexprFunctionDecl(const FunctionDecl *FD);
1658 bool CheckConstexprFunctionBody(const FunctionDecl *FD, Stmt *Body);
1660 void DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD);
1661 void FindHiddenVirtualMethods(CXXMethodDecl *MD,
1662 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods);
1663 void NoteHiddenVirtualMethods(CXXMethodDecl *MD,
1664 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods);
1665 // Returns true if the function declaration is a redeclaration
1666 bool CheckFunctionDeclaration(Scope *S,
1667 FunctionDecl *NewFD, LookupResult &Previous,
1668 bool IsExplicitSpecialization);
1669 void CheckMain(FunctionDecl *FD, const DeclSpec &D);
1670 void CheckMSVCRTEntryPoint(FunctionDecl *FD);
1671 Decl *ActOnParamDeclarator(Scope *S, Declarator &D);
1672 ParmVarDecl *BuildParmVarDeclForTypedef(DeclContext *DC,
1675 ParmVarDecl *CheckParameter(DeclContext *DC, SourceLocation StartLoc,
1676 SourceLocation NameLoc, IdentifierInfo *Name,
1677 QualType T, TypeSourceInfo *TSInfo,
1679 void ActOnParamDefaultArgument(Decl *param,
1680 SourceLocation EqualLoc,
1682 void ActOnParamUnparsedDefaultArgument(Decl *param,
1683 SourceLocation EqualLoc,
1684 SourceLocation ArgLoc);
1685 void ActOnParamDefaultArgumentError(Decl *param, SourceLocation EqualLoc);
1686 bool SetParamDefaultArgument(ParmVarDecl *Param, Expr *DefaultArg,
1687 SourceLocation EqualLoc);
1689 void AddInitializerToDecl(Decl *dcl, Expr *init, bool DirectInit,
1690 bool TypeMayContainAuto);
1691 void ActOnUninitializedDecl(Decl *dcl, bool TypeMayContainAuto);
1692 void ActOnInitializerError(Decl *Dcl);
1693 void ActOnPureSpecifier(Decl *D, SourceLocation PureSpecLoc);
1694 void ActOnCXXForRangeDecl(Decl *D);
1695 StmtResult ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc,
1696 IdentifierInfo *Ident,
1697 ParsedAttributes &Attrs,
1698 SourceLocation AttrEnd);
1699 void SetDeclDeleted(Decl *dcl, SourceLocation DelLoc);
1700 void SetDeclDefaulted(Decl *dcl, SourceLocation DefaultLoc);
1701 void FinalizeDeclaration(Decl *D);
1702 DeclGroupPtrTy FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
1703 ArrayRef<Decl *> Group);
1704 DeclGroupPtrTy BuildDeclaratorGroup(MutableArrayRef<Decl *> Group,
1705 bool TypeMayContainAuto = true);
1707 /// Should be called on all declarations that might have attached
1708 /// documentation comments.
1709 void ActOnDocumentableDecl(Decl *D);
1710 void ActOnDocumentableDecls(ArrayRef<Decl *> Group);
1712 void ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
1713 SourceLocation LocAfterDecls);
1714 void CheckForFunctionRedefinition(FunctionDecl *FD,
1715 const FunctionDecl *EffectiveDefinition =
1717 Decl *ActOnStartOfFunctionDef(Scope *S, Declarator &D);
1718 Decl *ActOnStartOfFunctionDef(Scope *S, Decl *D);
1719 void ActOnStartOfObjCMethodDef(Scope *S, Decl *D);
1720 bool isObjCMethodDecl(Decl *D) {
1721 return D && isa<ObjCMethodDecl>(D);
1724 /// \brief Determine whether we can delay parsing the body of a function or
1725 /// function template until it is used, assuming we don't care about emitting
1726 /// code for that function.
1728 /// This will be \c false if we may need the body of the function in the
1729 /// middle of parsing an expression (where it's impractical to switch to
1730 /// parsing a different function), for instance, if it's constexpr in C++11
1731 /// or has an 'auto' return type in C++14. These cases are essentially bugs.
1732 bool canDelayFunctionBody(const Declarator &D);
1734 /// \brief Determine whether we can skip parsing the body of a function
1735 /// definition, assuming we don't care about analyzing its body or emitting
1736 /// code for that function.
1738 /// This will be \c false only if we may need the body of the function in
1739 /// order to parse the rest of the program (for instance, if it is
1740 /// \c constexpr in C++11 or has an 'auto' return type in C++14).
1741 bool canSkipFunctionBody(Decl *D);
1743 void computeNRVO(Stmt *Body, sema::FunctionScopeInfo *Scope);
1744 Decl *ActOnFinishFunctionBody(Decl *Decl, Stmt *Body);
1745 Decl *ActOnFinishFunctionBody(Decl *Decl, Stmt *Body, bool IsInstantiation);
1746 Decl *ActOnSkippedFunctionBody(Decl *Decl);
1747 void ActOnFinishInlineMethodDef(CXXMethodDecl *D);
1749 /// ActOnFinishDelayedAttribute - Invoked when we have finished parsing an
1750 /// attribute for which parsing is delayed.
1751 void ActOnFinishDelayedAttribute(Scope *S, Decl *D, ParsedAttributes &Attrs);
1753 /// \brief Diagnose any unused parameters in the given sequence of
1754 /// ParmVarDecl pointers.
1755 void DiagnoseUnusedParameters(ParmVarDecl * const *Begin,
1756 ParmVarDecl * const *End);
1758 /// \brief Diagnose whether the size of parameters or return value of a
1759 /// function or obj-c method definition is pass-by-value and larger than a
1760 /// specified threshold.
1761 void DiagnoseSizeOfParametersAndReturnValue(ParmVarDecl * const *Begin,
1762 ParmVarDecl * const *End,
1766 void DiagnoseInvalidJumps(Stmt *Body);
1767 Decl *ActOnFileScopeAsmDecl(Expr *expr,
1768 SourceLocation AsmLoc,
1769 SourceLocation RParenLoc);
1771 /// \brief Handle a C++11 empty-declaration and attribute-declaration.
1772 Decl *ActOnEmptyDeclaration(Scope *S,
1773 AttributeList *AttrList,
1774 SourceLocation SemiLoc);
1776 /// \brief The parser has processed a module import declaration.
1778 /// \param AtLoc The location of the '@' symbol, if any.
1780 /// \param ImportLoc The location of the 'import' keyword.
1782 /// \param Path The module access path.
1783 DeclResult ActOnModuleImport(SourceLocation AtLoc, SourceLocation ImportLoc,
1786 /// \brief The parser has processed a module import translated from a
1787 /// #include or similar preprocessing directive.
1788 void ActOnModuleInclude(SourceLocation DirectiveLoc, Module *Mod);
1790 /// \brief The parsed has entered a submodule.
1791 void ActOnModuleBegin(SourceLocation DirectiveLoc, Module *Mod);
1792 /// \brief The parser has left a submodule.
1793 void ActOnModuleEnd(SourceLocation DirectiveLoc, Module *Mod);
1795 /// \brief Create an implicit import of the given module at the given
1796 /// source location, for error recovery, if possible.
1798 /// This routine is typically used when an entity found by name lookup
1799 /// is actually hidden within a module that we know about but the user
1800 /// has forgotten to import.
1801 void createImplicitModuleImportForErrorRecovery(SourceLocation Loc,
1804 /// Kinds of missing import. Note, the values of these enumerators correspond
1805 /// to %select values in diagnostics.
1806 enum class MissingImportKind {
1812 /// \brief Diagnose that the specified declaration needs to be visible but
1813 /// isn't, and suggest a module import that would resolve the problem.
1814 void diagnoseMissingImport(SourceLocation Loc, NamedDecl *Decl,
1815 bool NeedDefinition, bool Recover = true);
1816 void diagnoseMissingImport(SourceLocation Loc, NamedDecl *Decl,
1817 SourceLocation DeclLoc, ArrayRef<Module *> Modules,
1818 MissingImportKind MIK, bool Recover);
1820 /// \brief Retrieve a suitable printing policy.
1821 PrintingPolicy getPrintingPolicy() const {
1822 return getPrintingPolicy(Context, PP);
1825 /// \brief Retrieve a suitable printing policy.
1826 static PrintingPolicy getPrintingPolicy(const ASTContext &Ctx,
1827 const Preprocessor &PP);
1830 void ActOnPopScope(SourceLocation Loc, Scope *S);
1831 void ActOnTranslationUnitScope(Scope *S);
1833 Decl *ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS,
1835 Decl *ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS,
1837 MultiTemplateParamsArg TemplateParams,
1838 bool IsExplicitInstantiation = false);
1840 Decl *BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
1843 const PrintingPolicy &Policy);
1845 Decl *BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
1846 RecordDecl *Record);
1848 bool isAcceptableTagRedeclaration(const TagDecl *Previous,
1849 TagTypeKind NewTag, bool isDefinition,
1850 SourceLocation NewTagLoc,
1851 const IdentifierInfo &Name);
1854 TUK_Reference, // Reference to a tag: 'struct foo *X;'
1855 TUK_Declaration, // Fwd decl of a tag: 'struct foo;'
1856 TUK_Definition, // Definition of a tag: 'struct foo { int X; } Y;'
1857 TUK_Friend // Friend declaration: 'friend struct foo;'
1860 struct SkipBodyInfo {
1861 SkipBodyInfo() : ShouldSkip(false), Previous(nullptr) {}
1863 NamedDecl *Previous;
1866 Decl *ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
1867 SourceLocation KWLoc, CXXScopeSpec &SS,
1868 IdentifierInfo *Name, SourceLocation NameLoc,
1869 AttributeList *Attr, AccessSpecifier AS,
1870 SourceLocation ModulePrivateLoc,
1871 MultiTemplateParamsArg TemplateParameterLists,
1872 bool &OwnedDecl, bool &IsDependent,
1873 SourceLocation ScopedEnumKWLoc,
1874 bool ScopedEnumUsesClassTag, TypeResult UnderlyingType,
1875 bool IsTypeSpecifier, SkipBodyInfo *SkipBody = nullptr);
1877 Decl *ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
1878 unsigned TagSpec, SourceLocation TagLoc,
1880 IdentifierInfo *Name, SourceLocation NameLoc,
1881 AttributeList *Attr,
1882 MultiTemplateParamsArg TempParamLists);
1884 TypeResult ActOnDependentTag(Scope *S,
1887 const CXXScopeSpec &SS,
1888 IdentifierInfo *Name,
1889 SourceLocation TagLoc,
1890 SourceLocation NameLoc);
1892 void ActOnDefs(Scope *S, Decl *TagD, SourceLocation DeclStart,
1893 IdentifierInfo *ClassName,
1894 SmallVectorImpl<Decl *> &Decls);
1895 Decl *ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
1896 Declarator &D, Expr *BitfieldWidth);
1898 FieldDecl *HandleField(Scope *S, RecordDecl *TagD, SourceLocation DeclStart,
1899 Declarator &D, Expr *BitfieldWidth,
1900 InClassInitStyle InitStyle,
1901 AccessSpecifier AS);
1902 MSPropertyDecl *HandleMSProperty(Scope *S, RecordDecl *TagD,
1903 SourceLocation DeclStart,
1904 Declarator &D, Expr *BitfieldWidth,
1905 InClassInitStyle InitStyle,
1907 AttributeList *MSPropertyAttr);
1909 FieldDecl *CheckFieldDecl(DeclarationName Name, QualType T,
1910 TypeSourceInfo *TInfo,
1911 RecordDecl *Record, SourceLocation Loc,
1912 bool Mutable, Expr *BitfieldWidth,
1913 InClassInitStyle InitStyle,
1914 SourceLocation TSSL,
1915 AccessSpecifier AS, NamedDecl *PrevDecl,
1916 Declarator *D = nullptr);
1918 bool CheckNontrivialField(FieldDecl *FD);
1919 void DiagnoseNontrivial(const CXXRecordDecl *Record, CXXSpecialMember CSM);
1920 bool SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
1921 bool Diagnose = false);
1922 CXXSpecialMember getSpecialMember(const CXXMethodDecl *MD);
1923 void ActOnLastBitfield(SourceLocation DeclStart,
1924 SmallVectorImpl<Decl *> &AllIvarDecls);
1925 Decl *ActOnIvar(Scope *S, SourceLocation DeclStart,
1926 Declarator &D, Expr *BitfieldWidth,
1927 tok::ObjCKeywordKind visibility);
1929 // This is used for both record definitions and ObjC interface declarations.
1930 void ActOnFields(Scope* S, SourceLocation RecLoc, Decl *TagDecl,
1931 ArrayRef<Decl *> Fields,
1932 SourceLocation LBrac, SourceLocation RBrac,
1933 AttributeList *AttrList);
1935 /// ActOnTagStartDefinition - Invoked when we have entered the
1936 /// scope of a tag's definition (e.g., for an enumeration, class,
1937 /// struct, or union).
1938 void ActOnTagStartDefinition(Scope *S, Decl *TagDecl);
1940 typedef void *SkippedDefinitionContext;
1942 /// \brief Invoked when we enter a tag definition that we're skipping.
1943 SkippedDefinitionContext ActOnTagStartSkippedDefinition(Scope *S, Decl *TD);
1945 Decl *ActOnObjCContainerStartDefinition(Decl *IDecl);
1947 /// ActOnStartCXXMemberDeclarations - Invoked when we have parsed a
1948 /// C++ record definition's base-specifiers clause and are starting its
1949 /// member declarations.
1950 void ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagDecl,
1951 SourceLocation FinalLoc,
1952 bool IsFinalSpelledSealed,
1953 SourceLocation LBraceLoc);
1955 /// ActOnTagFinishDefinition - Invoked once we have finished parsing
1956 /// the definition of a tag (enumeration, class, struct, or union).
1957 void ActOnTagFinishDefinition(Scope *S, Decl *TagDecl,
1958 SourceLocation RBraceLoc);
1960 void ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context);
1962 void ActOnObjCContainerFinishDefinition();
1964 /// \brief Invoked when we must temporarily exit the objective-c container
1965 /// scope for parsing/looking-up C constructs.
1967 /// Must be followed by a call to \see ActOnObjCReenterContainerContext
1968 void ActOnObjCTemporaryExitContainerContext(DeclContext *DC);
1969 void ActOnObjCReenterContainerContext(DeclContext *DC);
1971 /// ActOnTagDefinitionError - Invoked when there was an unrecoverable
1972 /// error parsing the definition of a tag.
1973 void ActOnTagDefinitionError(Scope *S, Decl *TagDecl);
1975 EnumConstantDecl *CheckEnumConstant(EnumDecl *Enum,
1976 EnumConstantDecl *LastEnumConst,
1977 SourceLocation IdLoc,
1980 bool CheckEnumUnderlyingType(TypeSourceInfo *TI);
1981 bool CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
1982 QualType EnumUnderlyingTy, const EnumDecl *Prev);
1984 /// Determine whether the body of an anonymous enumeration should be skipped.
1985 /// \param II The name of the first enumerator.
1986 SkipBodyInfo shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II,
1987 SourceLocation IILoc);
1989 Decl *ActOnEnumConstant(Scope *S, Decl *EnumDecl, Decl *LastEnumConstant,
1990 SourceLocation IdLoc, IdentifierInfo *Id,
1991 AttributeList *Attrs,
1992 SourceLocation EqualLoc, Expr *Val);
1993 void ActOnEnumBody(SourceLocation EnumLoc, SourceLocation LBraceLoc,
1994 SourceLocation RBraceLoc, Decl *EnumDecl,
1995 ArrayRef<Decl *> Elements,
1996 Scope *S, AttributeList *Attr);
1998 DeclContext *getContainingDC(DeclContext *DC);
2000 /// Set the current declaration context until it gets popped.
2001 void PushDeclContext(Scope *S, DeclContext *DC);
2002 void PopDeclContext();
2004 /// EnterDeclaratorContext - Used when we must lookup names in the context
2005 /// of a declarator's nested name specifier.
2006 void EnterDeclaratorContext(Scope *S, DeclContext *DC);
2007 void ExitDeclaratorContext(Scope *S);
2009 /// Push the parameters of D, which must be a function, into scope.
2010 void ActOnReenterFunctionContext(Scope* S, Decl* D);
2011 void ActOnExitFunctionContext();
2013 DeclContext *getFunctionLevelDeclContext();
2015 /// getCurFunctionDecl - If inside of a function body, this returns a pointer
2016 /// to the function decl for the function being parsed. If we're currently
2017 /// in a 'block', this returns the containing context.
2018 FunctionDecl *getCurFunctionDecl();
2020 /// getCurMethodDecl - If inside of a method body, this returns a pointer to
2021 /// the method decl for the method being parsed. If we're currently
2022 /// in a 'block', this returns the containing context.
2023 ObjCMethodDecl *getCurMethodDecl();
2025 /// getCurFunctionOrMethodDecl - Return the Decl for the current ObjC method
2026 /// or C function we're in, otherwise return null. If we're currently
2027 /// in a 'block', this returns the containing context.
2028 NamedDecl *getCurFunctionOrMethodDecl();
2030 /// Add this decl to the scope shadowed decl chains.
2031 void PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext = true);
2033 /// \brief Make the given externally-produced declaration visible at the
2034 /// top level scope.
2036 /// \param D The externally-produced declaration to push.
2038 /// \param Name The name of the externally-produced declaration.
2039 void pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name);
2041 /// isDeclInScope - If 'Ctx' is a function/method, isDeclInScope returns true
2042 /// if 'D' is in Scope 'S', otherwise 'S' is ignored and isDeclInScope returns
2043 /// true if 'D' belongs to the given declaration context.
2045 /// \param AllowInlineNamespace If \c true, allow the declaration to be in the
2046 /// enclosing namespace set of the context, rather than contained
2047 /// directly within it.
2048 bool isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S = nullptr,
2049 bool AllowInlineNamespace = false);
2051 /// Finds the scope corresponding to the given decl context, if it
2052 /// happens to be an enclosing scope. Otherwise return NULL.
2053 static Scope *getScopeForDeclContext(Scope *S, DeclContext *DC);
2055 /// Subroutines of ActOnDeclarator().
2056 TypedefDecl *ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
2057 TypeSourceInfo *TInfo);
2058 bool isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New);
2060 /// Attribute merging methods. Return true if a new attribute was added.
2061 AvailabilityAttr *mergeAvailabilityAttr(NamedDecl *D, SourceRange Range,
2062 IdentifierInfo *Platform,
2063 VersionTuple Introduced,
2064 VersionTuple Deprecated,
2065 VersionTuple Obsoleted,
2069 unsigned AttrSpellingListIndex);
2070 TypeVisibilityAttr *mergeTypeVisibilityAttr(Decl *D, SourceRange Range,
2071 TypeVisibilityAttr::VisibilityType Vis,
2072 unsigned AttrSpellingListIndex);
2073 VisibilityAttr *mergeVisibilityAttr(Decl *D, SourceRange Range,
2074 VisibilityAttr::VisibilityType Vis,
2075 unsigned AttrSpellingListIndex);
2076 DLLImportAttr *mergeDLLImportAttr(Decl *D, SourceRange Range,
2077 unsigned AttrSpellingListIndex);
2078 DLLExportAttr *mergeDLLExportAttr(Decl *D, SourceRange Range,
2079 unsigned AttrSpellingListIndex);
2081 mergeMSInheritanceAttr(Decl *D, SourceRange Range, bool BestCase,
2082 unsigned AttrSpellingListIndex,
2083 MSInheritanceAttr::Spelling SemanticSpelling);
2084 FormatAttr *mergeFormatAttr(Decl *D, SourceRange Range,
2085 IdentifierInfo *Format, int FormatIdx,
2086 int FirstArg, unsigned AttrSpellingListIndex);
2087 SectionAttr *mergeSectionAttr(Decl *D, SourceRange Range, StringRef Name,
2088 unsigned AttrSpellingListIndex);
2089 AlwaysInlineAttr *mergeAlwaysInlineAttr(Decl *D, SourceRange Range,
2090 IdentifierInfo *Ident,
2091 unsigned AttrSpellingListIndex);
2092 MinSizeAttr *mergeMinSizeAttr(Decl *D, SourceRange Range,
2093 unsigned AttrSpellingListIndex);
2094 OptimizeNoneAttr *mergeOptimizeNoneAttr(Decl *D, SourceRange Range,
2095 unsigned AttrSpellingListIndex);
2097 /// \brief Describes the kind of merge to perform for availability
2098 /// attributes (including "deprecated", "unavailable", and "availability").
2099 enum AvailabilityMergeKind {
2100 /// \brief Don't merge availability attributes at all.
2102 /// \brief Merge availability attributes for a redeclaration, which requires
2105 /// \brief Merge availability attributes for an override, which requires
2106 /// an exact match or a weakening of constraints.
2110 void mergeDeclAttributes(NamedDecl *New, Decl *Old,
2111 AvailabilityMergeKind AMK = AMK_Redeclaration);
2112 void MergeTypedefNameDecl(TypedefNameDecl *New, LookupResult &OldDecls);
2113 bool MergeFunctionDecl(FunctionDecl *New, NamedDecl *&Old, Scope *S,
2114 bool MergeTypeWithOld);
2115 bool MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
2116 Scope *S, bool MergeTypeWithOld);
2117 void mergeObjCMethodDecls(ObjCMethodDecl *New, ObjCMethodDecl *Old);
2118 void MergeVarDecl(VarDecl *New, LookupResult &Previous);
2119 void MergeVarDeclTypes(VarDecl *New, VarDecl *Old, bool MergeTypeWithOld);
2120 void MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old);
2121 bool MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old, Scope *S);
2123 // AssignmentAction - This is used by all the assignment diagnostic functions
2124 // to represent what is actually causing the operation
2125 enum AssignmentAction {
2133 AA_Passing_CFAudited
2136 /// C++ Overloading.
2138 /// This is a legitimate overload: the existing declarations are
2139 /// functions or function templates with different signatures.
2142 /// This is not an overload because the signature exactly matches
2143 /// an existing declaration.
2146 /// This is not an overload because the lookup results contain a
2150 OverloadKind CheckOverload(Scope *S,
2152 const LookupResult &OldDecls,
2153 NamedDecl *&OldDecl,
2154 bool IsForUsingDecl);
2155 bool IsOverload(FunctionDecl *New, FunctionDecl *Old, bool IsForUsingDecl);
2157 /// \brief Checks availability of the function depending on the current
2158 /// function context.Inside an unavailable function,unavailability is ignored.
2160 /// \returns true if \p FD is unavailable and current context is inside
2161 /// an available function, false otherwise.
2162 bool isFunctionConsideredUnavailable(FunctionDecl *FD);
2164 ImplicitConversionSequence
2165 TryImplicitConversion(Expr *From, QualType ToType,
2166 bool SuppressUserConversions,
2168 bool InOverloadResolution,
2170 bool AllowObjCWritebackConversion);
2172 bool IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType);
2173 bool IsFloatingPointPromotion(QualType FromType, QualType ToType);
2174 bool IsComplexPromotion(QualType FromType, QualType ToType);
2175 bool IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
2176 bool InOverloadResolution,
2177 QualType& ConvertedType, bool &IncompatibleObjC);
2178 bool isObjCPointerConversion(QualType FromType, QualType ToType,
2179 QualType& ConvertedType, bool &IncompatibleObjC);
2180 bool isObjCWritebackConversion(QualType FromType, QualType ToType,
2181 QualType &ConvertedType);
2182 bool IsBlockPointerConversion(QualType FromType, QualType ToType,
2183 QualType& ConvertedType);
2184 bool FunctionParamTypesAreEqual(const FunctionProtoType *OldType,
2185 const FunctionProtoType *NewType,
2186 unsigned *ArgPos = nullptr);
2187 void HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
2188 QualType FromType, QualType ToType);
2190 CastKind PrepareCastToObjCObjectPointer(ExprResult &E);
2191 bool CheckPointerConversion(Expr *From, QualType ToType,
2193 CXXCastPath& BasePath,
2194 bool IgnoreBaseAccess);
2195 bool IsMemberPointerConversion(Expr *From, QualType FromType, QualType ToType,
2196 bool InOverloadResolution,
2197 QualType &ConvertedType);
2198 bool CheckMemberPointerConversion(Expr *From, QualType ToType,
2200 CXXCastPath &BasePath,
2201 bool IgnoreBaseAccess);
2202 bool IsQualificationConversion(QualType FromType, QualType ToType,
2203 bool CStyle, bool &ObjCLifetimeConversion);
2204 bool IsNoReturnConversion(QualType FromType, QualType ToType,
2205 QualType &ResultTy);
2206 bool DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType);
2207 bool isSameOrCompatibleFunctionType(CanQualType Param, CanQualType Arg);
2209 ExprResult PerformMoveOrCopyInitialization(const InitializedEntity &Entity,
2210 const VarDecl *NRVOCandidate,
2211 QualType ResultType,
2213 bool AllowNRVO = true);
2215 bool CanPerformCopyInitialization(const InitializedEntity &Entity,
2217 ExprResult PerformCopyInitialization(const InitializedEntity &Entity,
2218 SourceLocation EqualLoc,
2220 bool TopLevelOfInitList = false,
2221 bool AllowExplicit = false);
2222 ExprResult PerformObjectArgumentInitialization(Expr *From,
2223 NestedNameSpecifier *Qualifier,
2224 NamedDecl *FoundDecl,
2225 CXXMethodDecl *Method);
2227 ExprResult PerformContextuallyConvertToBool(Expr *From);
2228 ExprResult PerformContextuallyConvertToObjCPointer(Expr *From);
2230 /// Contexts in which a converted constant expression is required.
2232 CCEK_CaseValue, ///< Expression in a case label.
2233 CCEK_Enumerator, ///< Enumerator value with fixed underlying type.
2234 CCEK_TemplateArg, ///< Value of a non-type template parameter.
2235 CCEK_NewExpr ///< Constant expression in a noptr-new-declarator.
2237 ExprResult CheckConvertedConstantExpression(Expr *From, QualType T,
2238 llvm::APSInt &Value, CCEKind CCE);
2239 ExprResult CheckConvertedConstantExpression(Expr *From, QualType T,
2240 APValue &Value, CCEKind CCE);
2242 /// \brief Abstract base class used to perform a contextual implicit
2243 /// conversion from an expression to any type passing a filter.
2244 class ContextualImplicitConverter {
2247 bool SuppressConversion;
2249 ContextualImplicitConverter(bool Suppress = false,
2250 bool SuppressConversion = false)
2251 : Suppress(Suppress), SuppressConversion(SuppressConversion) {}
2253 /// \brief Determine whether the specified type is a valid destination type
2254 /// for this conversion.
2255 virtual bool match(QualType T) = 0;
2257 /// \brief Emits a diagnostic complaining that the expression does not have
2258 /// integral or enumeration type.
2259 virtual SemaDiagnosticBuilder
2260 diagnoseNoMatch(Sema &S, SourceLocation Loc, QualType T) = 0;
2262 /// \brief Emits a diagnostic when the expression has incomplete class type.
2263 virtual SemaDiagnosticBuilder
2264 diagnoseIncomplete(Sema &S, SourceLocation Loc, QualType T) = 0;
2266 /// \brief Emits a diagnostic when the only matching conversion function
2268 virtual SemaDiagnosticBuilder diagnoseExplicitConv(
2269 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) = 0;
2271 /// \brief Emits a note for the explicit conversion function.
2272 virtual SemaDiagnosticBuilder
2273 noteExplicitConv(Sema &S, CXXConversionDecl *Conv, QualType ConvTy) = 0;
2275 /// \brief Emits a diagnostic when there are multiple possible conversion
2277 virtual SemaDiagnosticBuilder
2278 diagnoseAmbiguous(Sema &S, SourceLocation Loc, QualType T) = 0;
2280 /// \brief Emits a note for one of the candidate conversions.
2281 virtual SemaDiagnosticBuilder
2282 noteAmbiguous(Sema &S, CXXConversionDecl *Conv, QualType ConvTy) = 0;
2284 /// \brief Emits a diagnostic when we picked a conversion function
2285 /// (for cases when we are not allowed to pick a conversion function).
2286 virtual SemaDiagnosticBuilder diagnoseConversion(
2287 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) = 0;
2289 virtual ~ContextualImplicitConverter() {}
2292 class ICEConvertDiagnoser : public ContextualImplicitConverter {
2293 bool AllowScopedEnumerations;
2296 ICEConvertDiagnoser(bool AllowScopedEnumerations,
2297 bool Suppress, bool SuppressConversion)
2298 : ContextualImplicitConverter(Suppress, SuppressConversion),
2299 AllowScopedEnumerations(AllowScopedEnumerations) {}
2301 /// Match an integral or (possibly scoped) enumeration type.
2302 bool match(QualType T) override;
2304 SemaDiagnosticBuilder
2305 diagnoseNoMatch(Sema &S, SourceLocation Loc, QualType T) override {
2306 return diagnoseNotInt(S, Loc, T);
2309 /// \brief Emits a diagnostic complaining that the expression does not have
2310 /// integral or enumeration type.
2311 virtual SemaDiagnosticBuilder
2312 diagnoseNotInt(Sema &S, SourceLocation Loc, QualType T) = 0;
2315 /// Perform a contextual implicit conversion.
2316 ExprResult PerformContextualImplicitConversion(
2317 SourceLocation Loc, Expr *FromE, ContextualImplicitConverter &Converter);
2320 enum ObjCSubscriptKind {
2325 ObjCSubscriptKind CheckSubscriptingKind(Expr *FromE);
2327 // Note that LK_String is intentionally after the other literals, as
2328 // this is used for diagnostics logic.
2329 enum ObjCLiteralKind {
2338 ObjCLiteralKind CheckLiteralKind(Expr *FromE);
2340 ExprResult PerformObjectMemberConversion(Expr *From,
2341 NestedNameSpecifier *Qualifier,
2342 NamedDecl *FoundDecl,
2345 // Members have to be NamespaceDecl* or TranslationUnitDecl*.
2346 // TODO: make this is a typesafe union.
2347 typedef llvm::SmallPtrSet<DeclContext *, 16> AssociatedNamespaceSet;
2348 typedef llvm::SmallPtrSet<CXXRecordDecl *, 16> AssociatedClassSet;
2350 void AddOverloadCandidate(FunctionDecl *Function,
2351 DeclAccessPair FoundDecl,
2352 ArrayRef<Expr *> Args,
2353 OverloadCandidateSet& CandidateSet,
2354 bool SuppressUserConversions = false,
2355 bool PartialOverloading = false,
2356 bool AllowExplicit = false);
2357 void AddFunctionCandidates(const UnresolvedSetImpl &Functions,
2358 ArrayRef<Expr *> Args,
2359 OverloadCandidateSet &CandidateSet,
2360 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr,
2361 bool SuppressUserConversions = false,
2362 bool PartialOverloading = false);
2363 void AddMethodCandidate(DeclAccessPair FoundDecl,
2364 QualType ObjectType,
2365 Expr::Classification ObjectClassification,
2366 ArrayRef<Expr *> Args,
2367 OverloadCandidateSet& CandidateSet,
2368 bool SuppressUserConversion = false);
2369 void AddMethodCandidate(CXXMethodDecl *Method,
2370 DeclAccessPair FoundDecl,
2371 CXXRecordDecl *ActingContext, QualType ObjectType,
2372 Expr::Classification ObjectClassification,
2373 ArrayRef<Expr *> Args,
2374 OverloadCandidateSet& CandidateSet,
2375 bool SuppressUserConversions = false,
2376 bool PartialOverloading = false);
2377 void AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
2378 DeclAccessPair FoundDecl,
2379 CXXRecordDecl *ActingContext,
2380 TemplateArgumentListInfo *ExplicitTemplateArgs,
2381 QualType ObjectType,
2382 Expr::Classification ObjectClassification,
2383 ArrayRef<Expr *> Args,
2384 OverloadCandidateSet& CandidateSet,
2385 bool SuppressUserConversions = false,
2386 bool PartialOverloading = false);
2387 void AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
2388 DeclAccessPair FoundDecl,
2389 TemplateArgumentListInfo *ExplicitTemplateArgs,
2390 ArrayRef<Expr *> Args,
2391 OverloadCandidateSet& CandidateSet,
2392 bool SuppressUserConversions = false,
2393 bool PartialOverloading = false);
2394 void AddConversionCandidate(CXXConversionDecl *Conversion,
2395 DeclAccessPair FoundDecl,
2396 CXXRecordDecl *ActingContext,
2397 Expr *From, QualType ToType,
2398 OverloadCandidateSet& CandidateSet,
2399 bool AllowObjCConversionOnExplicit);
2400 void AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
2401 DeclAccessPair FoundDecl,
2402 CXXRecordDecl *ActingContext,
2403 Expr *From, QualType ToType,
2404 OverloadCandidateSet &CandidateSet,
2405 bool AllowObjCConversionOnExplicit);
2406 void AddSurrogateCandidate(CXXConversionDecl *Conversion,
2407 DeclAccessPair FoundDecl,
2408 CXXRecordDecl *ActingContext,
2409 const FunctionProtoType *Proto,
2410 Expr *Object, ArrayRef<Expr *> Args,
2411 OverloadCandidateSet& CandidateSet);
2412 void AddMemberOperatorCandidates(OverloadedOperatorKind Op,
2413 SourceLocation OpLoc, ArrayRef<Expr *> Args,
2414 OverloadCandidateSet& CandidateSet,
2415 SourceRange OpRange = SourceRange());
2416 void AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
2417 ArrayRef<Expr *> Args,
2418 OverloadCandidateSet& CandidateSet,
2419 bool IsAssignmentOperator = false,
2420 unsigned NumContextualBoolArguments = 0);
2421 void AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
2422 SourceLocation OpLoc, ArrayRef<Expr *> Args,
2423 OverloadCandidateSet& CandidateSet);
2424 void AddArgumentDependentLookupCandidates(DeclarationName Name,
2426 ArrayRef<Expr *> Args,
2427 TemplateArgumentListInfo *ExplicitTemplateArgs,
2428 OverloadCandidateSet& CandidateSet,
2429 bool PartialOverloading = false);
2431 // Emit as a 'note' the specific overload candidate
2432 void NoteOverloadCandidate(FunctionDecl *Fn, QualType DestType = QualType());
2434 // Emit as a series of 'note's all template and non-templates
2435 // identified by the expression Expr
2436 void NoteAllOverloadCandidates(Expr* E, QualType DestType = QualType());
2438 /// Check the enable_if expressions on the given function. Returns the first
2439 /// failing attribute, or NULL if they were all successful.
2440 EnableIfAttr *CheckEnableIf(FunctionDecl *Function, ArrayRef<Expr *> Args,
2441 bool MissingImplicitThis = false);
2443 // [PossiblyAFunctionType] --> [Return]
2444 // NonFunctionType --> NonFunctionType
2446 // R (*)(A) --> R (A)
2447 // R (&)(A) --> R (A)
2448 // R (S::*)(A) --> R (A)
2449 QualType ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType);
2452 ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
2453 QualType TargetType,
2455 DeclAccessPair &Found,
2456 bool *pHadMultipleCandidates = nullptr);
2459 ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
2460 bool Complain = false,
2461 DeclAccessPair *Found = nullptr);
2463 bool ResolveAndFixSingleFunctionTemplateSpecialization(
2464 ExprResult &SrcExpr,
2465 bool DoFunctionPointerConverion = false,
2466 bool Complain = false,
2467 const SourceRange& OpRangeForComplaining = SourceRange(),
2468 QualType DestTypeForComplaining = QualType(),
2469 unsigned DiagIDForComplaining = 0);
2472 Expr *FixOverloadedFunctionReference(Expr *E,
2473 DeclAccessPair FoundDecl,
2475 ExprResult FixOverloadedFunctionReference(ExprResult,
2476 DeclAccessPair FoundDecl,
2479 void AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
2480 ArrayRef<Expr *> Args,
2481 OverloadCandidateSet &CandidateSet,
2482 bool PartialOverloading = false);
2484 // An enum used to represent the different possible results of building a
2485 // range-based for loop.
2486 enum ForRangeStatus {
2488 FRS_NoViableFunction,
2489 FRS_DiagnosticIssued
2492 // An enum to represent whether something is dealing with a call to begin()
2493 // or a call to end() in a range-based for loop.
2494 enum BeginEndFunction {
2499 ForRangeStatus BuildForRangeBeginEndCall(Scope *S, SourceLocation Loc,
2500 SourceLocation RangeLoc,
2502 BeginEndFunction BEF,
2503 const DeclarationNameInfo &NameInfo,
2504 LookupResult &MemberLookup,
2505 OverloadCandidateSet *CandidateSet,
2506 Expr *Range, ExprResult *CallExpr);
2508 ExprResult BuildOverloadedCallExpr(Scope *S, Expr *Fn,
2509 UnresolvedLookupExpr *ULE,
2510 SourceLocation LParenLoc,
2512 SourceLocation RParenLoc,
2514 bool AllowTypoCorrection=true);
2516 bool buildOverloadedCallSet(Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE,
2517 MultiExprArg Args, SourceLocation RParenLoc,
2518 OverloadCandidateSet *CandidateSet,
2519 ExprResult *Result);
2521 ExprResult CreateOverloadedUnaryOp(SourceLocation OpLoc,
2523 const UnresolvedSetImpl &Fns,
2526 ExprResult CreateOverloadedBinOp(SourceLocation OpLoc,
2528 const UnresolvedSetImpl &Fns,
2529 Expr *LHS, Expr *RHS);
2531 ExprResult CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
2532 SourceLocation RLoc,
2533 Expr *Base,Expr *Idx);
2536 BuildCallToMemberFunction(Scope *S, Expr *MemExpr,
2537 SourceLocation LParenLoc,
2539 SourceLocation RParenLoc);
2541 BuildCallToObjectOfClassType(Scope *S, Expr *Object, SourceLocation LParenLoc,
2543 SourceLocation RParenLoc);
2545 ExprResult BuildOverloadedArrowExpr(Scope *S, Expr *Base,
2546 SourceLocation OpLoc,
2547 bool *NoArrowOperatorFound = nullptr);
2549 /// CheckCallReturnType - Checks that a call expression's return type is
2550 /// complete. Returns true on failure. The location passed in is the location
2551 /// that best represents the call.
2552 bool CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
2553 CallExpr *CE, FunctionDecl *FD);
2555 /// Helpers for dealing with blocks and functions.
2556 bool CheckParmsForFunctionDef(ParmVarDecl *const *Param,
2557 ParmVarDecl *const *ParamEnd,
2558 bool CheckParameterNames);
2559 void CheckCXXDefaultArguments(FunctionDecl *FD);
2560 void CheckExtraCXXDefaultArguments(Declarator &D);
2561 Scope *getNonFieldDeclScope(Scope *S);
2563 /// \name Name lookup
2565 /// These routines provide name lookup that is used during semantic
2566 /// analysis to resolve the various kinds of names (identifiers,
2567 /// overloaded operator names, constructor names, etc.) into zero or
2568 /// more declarations within a particular scope. The major entry
2569 /// points are LookupName, which performs unqualified name lookup,
2570 /// and LookupQualifiedName, which performs qualified name lookup.
2572 /// All name lookup is performed based on some specific criteria,
2573 /// which specify what names will be visible to name lookup and how
2574 /// far name lookup should work. These criteria are important both
2575 /// for capturing language semantics (certain lookups will ignore
2576 /// certain names, for example) and for performance, since name
2577 /// lookup is often a bottleneck in the compilation of C++. Name
2578 /// lookup criteria is specified via the LookupCriteria enumeration.
2580 /// The results of name lookup can vary based on the kind of name
2581 /// lookup performed, the current language, and the translation
2582 /// unit. In C, for example, name lookup will either return nothing
2583 /// (no entity found) or a single declaration. In C++, name lookup
2584 /// can additionally refer to a set of overloaded functions or
2585 /// result in an ambiguity. All of the possible results of name
2586 /// lookup are captured by the LookupResult class, which provides
2587 /// the ability to distinguish among them.
2590 /// @brief Describes the kind of name lookup to perform.
2591 enum LookupNameKind {
2592 /// Ordinary name lookup, which finds ordinary names (functions,
2593 /// variables, typedefs, etc.) in C and most kinds of names
2594 /// (functions, variables, members, types, etc.) in C++.
2595 LookupOrdinaryName = 0,
2596 /// Tag name lookup, which finds the names of enums, classes,
2597 /// structs, and unions.
2599 /// Label name lookup.
2601 /// Member name lookup, which finds the names of
2602 /// class/struct/union members.
2604 /// Look up of an operator name (e.g., operator+) for use with
2605 /// operator overloading. This lookup is similar to ordinary name
2606 /// lookup, but will ignore any declarations that are class members.
2608 /// Look up of a name that precedes the '::' scope resolution
2609 /// operator in C++. This lookup completely ignores operator, object,
2610 /// function, and enumerator names (C++ [basic.lookup.qual]p1).
2611 LookupNestedNameSpecifierName,
2612 /// Look up a namespace name within a C++ using directive or
2613 /// namespace alias definition, ignoring non-namespace names (C++
2614 /// [basic.lookup.udir]p1).
2615 LookupNamespaceName,
2616 /// Look up all declarations in a scope with the given name,
2617 /// including resolved using declarations. This is appropriate
2618 /// for checking redeclarations for a using declaration.
2619 LookupUsingDeclName,
2620 /// Look up an ordinary name that is going to be redeclared as a
2621 /// name with linkage. This lookup ignores any declarations that
2622 /// are outside of the current scope unless they have linkage. See
2623 /// C99 6.2.2p4-5 and C++ [basic.link]p6.
2624 LookupRedeclarationWithLinkage,
2625 /// Look up a friend of a local class. This lookup does not look
2626 /// outside the innermost non-class scope. See C++11 [class.friend]p11.
2627 LookupLocalFriendName,
2628 /// Look up the name of an Objective-C protocol.
2629 LookupObjCProtocolName,
2630 /// Look up implicit 'self' parameter of an objective-c method.
2631 LookupObjCImplicitSelfParam,
2632 /// \brief Look up any declaration with any name.
2636 /// \brief Specifies whether (or how) name lookup is being performed for a
2637 /// redeclaration (vs. a reference).
2638 enum RedeclarationKind {
2639 /// \brief The lookup is a reference to this name that is not for the
2640 /// purpose of redeclaring the name.
2641 NotForRedeclaration = 0,
2642 /// \brief The lookup results will be used for redeclaration of a name,
2643 /// if an entity by that name already exists.
2647 /// \brief The possible outcomes of name lookup for a literal operator.
2648 enum LiteralOperatorLookupResult {
2649 /// \brief The lookup resulted in an error.
2651 /// \brief The lookup found a single 'cooked' literal operator, which
2652 /// expects a normal literal to be built and passed to it.
2654 /// \brief The lookup found a single 'raw' literal operator, which expects
2655 /// a string literal containing the spelling of the literal token.
2657 /// \brief The lookup found an overload set of literal operator templates,
2658 /// which expect the characters of the spelling of the literal token to be
2659 /// passed as a non-type template argument pack.
2661 /// \brief The lookup found an overload set of literal operator templates,
2662 /// which expect the character type and characters of the spelling of the
2663 /// string literal token to be passed as template arguments.
2667 SpecialMemberOverloadResult *LookupSpecialMember(CXXRecordDecl *D,
2668 CXXSpecialMember SM,
2675 typedef std::function<void(const TypoCorrection &)> TypoDiagnosticGenerator;
2676 typedef std::function<ExprResult(Sema &, TypoExpr *, TypoCorrection)>
2677 TypoRecoveryCallback;
2680 bool CppLookupName(LookupResult &R, Scope *S);
2682 struct TypoExprState {
2683 std::unique_ptr<TypoCorrectionConsumer> Consumer;
2684 TypoDiagnosticGenerator DiagHandler;
2685 TypoRecoveryCallback RecoveryHandler;
2687 TypoExprState(TypoExprState&& other) LLVM_NOEXCEPT;
2688 TypoExprState& operator=(TypoExprState&& other) LLVM_NOEXCEPT;
2691 /// \brief The set of unhandled TypoExprs and their associated state.
2692 llvm::MapVector<TypoExpr *, TypoExprState> DelayedTypos;
2694 /// \brief Creates a new TypoExpr AST node.
2695 TypoExpr *createDelayedTypo(std::unique_ptr<TypoCorrectionConsumer> TCC,
2696 TypoDiagnosticGenerator TDG,
2697 TypoRecoveryCallback TRC);
2699 // \brief The set of known/encountered (unique, canonicalized) NamespaceDecls.
2701 // The boolean value will be true to indicate that the namespace was loaded
2702 // from an AST/PCH file, or false otherwise.
2703 llvm::MapVector<NamespaceDecl*, bool> KnownNamespaces;
2705 /// \brief Whether we have already loaded known namespaces from an extenal
2707 bool LoadedExternalKnownNamespaces;
2709 /// \brief Helper for CorrectTypo and CorrectTypoDelayed used to create and
2710 /// populate a new TypoCorrectionConsumer. Returns nullptr if typo correction
2711 /// should be skipped entirely.
2712 std::unique_ptr<TypoCorrectionConsumer>
2713 makeTypoCorrectionConsumer(const DeclarationNameInfo &Typo,
2714 Sema::LookupNameKind LookupKind, Scope *S,
2716 std::unique_ptr<CorrectionCandidateCallback> CCC,
2717 DeclContext *MemberContext, bool EnteringContext,
2718 const ObjCObjectPointerType *OPT,
2719 bool ErrorRecovery);
2722 const TypoExprState &getTypoExprState(TypoExpr *TE) const;
2724 /// \brief Clears the state of the given TypoExpr.
2725 void clearDelayedTypo(TypoExpr *TE);
2727 /// \brief Look up a name, looking for a single declaration. Return
2728 /// null if the results were absent, ambiguous, or overloaded.
2730 /// It is preferable to use the elaborated form and explicitly handle
2731 /// ambiguity and overloaded.
2732 NamedDecl *LookupSingleName(Scope *S, DeclarationName Name,
2734 LookupNameKind NameKind,
2735 RedeclarationKind Redecl
2736 = NotForRedeclaration);
2737 bool LookupName(LookupResult &R, Scope *S,
2738 bool AllowBuiltinCreation = false);
2739 bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
2740 bool InUnqualifiedLookup = false);
2741 bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
2743 bool LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS,
2744 bool AllowBuiltinCreation = false,
2745 bool EnteringContext = false);
2746 ObjCProtocolDecl *LookupProtocol(IdentifierInfo *II, SourceLocation IdLoc,
2747 RedeclarationKind Redecl
2748 = NotForRedeclaration);
2749 bool LookupInSuper(LookupResult &R, CXXRecordDecl *Class);
2751 void LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S,
2752 QualType T1, QualType T2,
2753 UnresolvedSetImpl &Functions);
2754 void addOverloadedOperatorToUnresolvedSet(UnresolvedSetImpl &Functions,
2755 DeclAccessPair Operator,
2756 QualType T1, QualType T2);
2758 LabelDecl *LookupOrCreateLabel(IdentifierInfo *II, SourceLocation IdentLoc,
2759 SourceLocation GnuLabelLoc = SourceLocation());
2761 DeclContextLookupResult LookupConstructors(CXXRecordDecl *Class);
2762 CXXConstructorDecl *LookupDefaultConstructor(CXXRecordDecl *Class);
2763 CXXConstructorDecl *LookupCopyingConstructor(CXXRecordDecl *Class,
2765 CXXMethodDecl *LookupCopyingAssignment(CXXRecordDecl *Class, unsigned Quals,
2766 bool RValueThis, unsigned ThisQuals);
2767 CXXConstructorDecl *LookupMovingConstructor(CXXRecordDecl *Class,
2769 CXXMethodDecl *LookupMovingAssignment(CXXRecordDecl *Class, unsigned Quals,
2770 bool RValueThis, unsigned ThisQuals);
2771 CXXDestructorDecl *LookupDestructor(CXXRecordDecl *Class);
2773 bool checkLiteralOperatorId(const CXXScopeSpec &SS, const UnqualifiedId &Id);
2774 LiteralOperatorLookupResult LookupLiteralOperator(Scope *S, LookupResult &R,
2775 ArrayRef<QualType> ArgTys,
2778 bool AllowStringTemplate);
2779 bool isKnownName(StringRef name);
2781 void ArgumentDependentLookup(DeclarationName Name, SourceLocation Loc,
2782 ArrayRef<Expr *> Args, ADLResult &Functions);
2784 void LookupVisibleDecls(Scope *S, LookupNameKind Kind,
2785 VisibleDeclConsumer &Consumer,
2786 bool IncludeGlobalScope = true);
2787 void LookupVisibleDecls(DeclContext *Ctx, LookupNameKind Kind,
2788 VisibleDeclConsumer &Consumer,
2789 bool IncludeGlobalScope = true);
2791 enum CorrectTypoKind {
2792 CTK_NonError, // CorrectTypo used in a non error recovery situation.
2793 CTK_ErrorRecovery // CorrectTypo used in normal error recovery.
2796 TypoCorrection CorrectTypo(const DeclarationNameInfo &Typo,
2797 Sema::LookupNameKind LookupKind,
2798 Scope *S, CXXScopeSpec *SS,
2799 std::unique_ptr<CorrectionCandidateCallback> CCC,
2800 CorrectTypoKind Mode,
2801 DeclContext *MemberContext = nullptr,
2802 bool EnteringContext = false,
2803 const ObjCObjectPointerType *OPT = nullptr,
2804 bool RecordFailure = true);
2806 TypoExpr *CorrectTypoDelayed(const DeclarationNameInfo &Typo,
2807 Sema::LookupNameKind LookupKind, Scope *S,
2809 std::unique_ptr<CorrectionCandidateCallback> CCC,
2810 TypoDiagnosticGenerator TDG,
2811 TypoRecoveryCallback TRC, CorrectTypoKind Mode,
2812 DeclContext *MemberContext = nullptr,
2813 bool EnteringContext = false,
2814 const ObjCObjectPointerType *OPT = nullptr);
2816 /// \brief Process any TypoExprs in the given Expr and its children,
2817 /// generating diagnostics as appropriate and returning a new Expr if there
2818 /// were typos that were all successfully corrected and ExprError if one or
2819 /// more typos could not be corrected.
2821 /// \param E The Expr to check for TypoExprs.
2823 /// \param InitDecl A VarDecl to avoid because the Expr being corrected is its
2826 /// \param Filter A function applied to a newly rebuilt Expr to determine if
2827 /// it is an acceptable/usable result from a single combination of typo
2828 /// corrections. As long as the filter returns ExprError, different
2829 /// combinations of corrections will be tried until all are exhausted.
2831 CorrectDelayedTyposInExpr(Expr *E, VarDecl *InitDecl = nullptr,
2832 llvm::function_ref<ExprResult(Expr *)> Filter =
2833 [](Expr *E) -> ExprResult { return E; });
2836 CorrectDelayedTyposInExpr(Expr *E,
2837 llvm::function_ref<ExprResult(Expr *)> Filter) {
2838 return CorrectDelayedTyposInExpr(E, nullptr, Filter);
2842 CorrectDelayedTyposInExpr(ExprResult ER, VarDecl *InitDecl = nullptr,
2843 llvm::function_ref<ExprResult(Expr *)> Filter =
2844 [](Expr *E) -> ExprResult { return E; }) {
2845 return ER.isInvalid() ? ER : CorrectDelayedTyposInExpr(ER.get(), Filter);
2849 CorrectDelayedTyposInExpr(ExprResult ER,
2850 llvm::function_ref<ExprResult(Expr *)> Filter) {
2851 return CorrectDelayedTyposInExpr(ER, nullptr, Filter);
2854 void diagnoseTypo(const TypoCorrection &Correction,
2855 const PartialDiagnostic &TypoDiag,
2856 bool ErrorRecovery = true);
2858 void diagnoseTypo(const TypoCorrection &Correction,
2859 const PartialDiagnostic &TypoDiag,
2860 const PartialDiagnostic &PrevNote,
2861 bool ErrorRecovery = true);
2863 void FindAssociatedClassesAndNamespaces(SourceLocation InstantiationLoc,
2864 ArrayRef<Expr *> Args,
2865 AssociatedNamespaceSet &AssociatedNamespaces,
2866 AssociatedClassSet &AssociatedClasses);
2868 void FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S,
2869 bool ConsiderLinkage, bool AllowInlineNamespace);
2871 void DiagnoseAmbiguousLookup(LookupResult &Result);
2874 ObjCInterfaceDecl *getObjCInterfaceDecl(IdentifierInfo *&Id,
2875 SourceLocation IdLoc,
2876 bool TypoCorrection = false);
2877 NamedDecl *LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID,
2878 Scope *S, bool ForRedeclaration,
2879 SourceLocation Loc);
2880 NamedDecl *ImplicitlyDefineFunction(SourceLocation Loc, IdentifierInfo &II,
2882 void AddKnownFunctionAttributes(FunctionDecl *FD);
2884 // More parsing and symbol table subroutines.
2886 void ProcessPragmaWeak(Scope *S, Decl *D);
2887 // Decl attributes - this routine is the top level dispatcher.
2888 void ProcessDeclAttributes(Scope *S, Decl *D, const Declarator &PD);
2889 void ProcessDeclAttributeList(Scope *S, Decl *D, const AttributeList *AL,
2890 bool IncludeCXX11Attributes = true);
2891 bool ProcessAccessDeclAttributeList(AccessSpecDecl *ASDecl,
2892 const AttributeList *AttrList);
2894 void checkUnusedDeclAttributes(Declarator &D);
2896 /// Determine if type T is a valid subject for a nonnull and similar
2897 /// attributes. By default, we look through references (the behavior used by
2898 /// nonnull), but if the second parameter is true, then we treat a reference
2900 bool isValidPointerAttrType(QualType T, bool RefOkay = false);
2902 bool CheckRegparmAttr(const AttributeList &attr, unsigned &value);
2903 bool CheckCallingConvAttr(const AttributeList &attr, CallingConv &CC,
2904 const FunctionDecl *FD = nullptr);
2905 bool CheckNoReturnAttr(const AttributeList &attr);
2906 bool checkStringLiteralArgumentAttr(const AttributeList &Attr,
2907 unsigned ArgNum, StringRef &Str,
2908 SourceLocation *ArgLocation = nullptr);
2909 bool checkSectionName(SourceLocation LiteralLoc, StringRef Str);
2910 void checkTargetAttr(SourceLocation LiteralLoc, StringRef Str);
2911 bool checkMSInheritanceAttrOnDefinition(
2912 CXXRecordDecl *RD, SourceRange Range, bool BestCase,
2913 MSInheritanceAttr::Spelling SemanticSpelling);
2915 void CheckAlignasUnderalignment(Decl *D);
2917 /// Adjust the calling convention of a method to be the ABI default if it
2918 /// wasn't specified explicitly. This handles method types formed from
2919 /// function type typedefs and typename template arguments.
2920 void adjustMemberFunctionCC(QualType &T, bool IsStatic);
2922 // Check if there is an explicit attribute, but only look through parens.
2923 // The intent is to look for an attribute on the current declarator, but not
2924 // one that came from a typedef.
2925 bool hasExplicitCallingConv(QualType &T);
2927 /// Get the outermost AttributedType node that sets a calling convention.
2928 /// Valid types should not have multiple attributes with different CCs.
2929 const AttributedType *getCallingConvAttributedType(QualType T) const;
2931 /// Check whether a nullability type specifier can be added to the given
2934 /// \param type The type to which the nullability specifier will be
2935 /// added. On success, this type will be updated appropriately.
2937 /// \param nullability The nullability specifier to add.
2939 /// \param nullabilityLoc The location of the nullability specifier.
2941 /// \param isContextSensitive Whether this nullability specifier was
2942 /// written as a context-sensitive keyword (in an Objective-C
2943 /// method) or an Objective-C property attribute, rather than as an
2944 /// underscored type specifier.
2946 /// \returns true if nullability cannot be applied, false otherwise.
2947 bool checkNullabilityTypeSpecifier(QualType &type, NullabilityKind nullability,
2948 SourceLocation nullabilityLoc,
2949 bool isContextSensitive);
2951 /// \brief Stmt attributes - this routine is the top level dispatcher.
2952 StmtResult ProcessStmtAttributes(Stmt *Stmt, AttributeList *Attrs,
2955 void WarnConflictingTypedMethods(ObjCMethodDecl *Method,
2956 ObjCMethodDecl *MethodDecl,
2957 bool IsProtocolMethodDecl);
2959 void CheckConflictingOverridingMethod(ObjCMethodDecl *Method,
2960 ObjCMethodDecl *Overridden,
2961 bool IsProtocolMethodDecl);
2963 /// WarnExactTypedMethods - This routine issues a warning if method
2964 /// implementation declaration matches exactly that of its declaration.
2965 void WarnExactTypedMethods(ObjCMethodDecl *Method,
2966 ObjCMethodDecl *MethodDecl,
2967 bool IsProtocolMethodDecl);
2969 typedef llvm::SmallPtrSet<Selector, 8> SelectorSet;
2970 typedef llvm::DenseMap<Selector, ObjCMethodDecl*> ProtocolsMethodsMap;
2972 /// CheckImplementationIvars - This routine checks if the instance variables
2973 /// listed in the implelementation match those listed in the interface.
2974 void CheckImplementationIvars(ObjCImplementationDecl *ImpDecl,
2975 ObjCIvarDecl **Fields, unsigned nIvars,
2976 SourceLocation Loc);
2978 /// ImplMethodsVsClassMethods - This is main routine to warn if any method
2979 /// remains unimplemented in the class or category \@implementation.
2980 void ImplMethodsVsClassMethods(Scope *S, ObjCImplDecl* IMPDecl,
2981 ObjCContainerDecl* IDecl,
2982 bool IncompleteImpl = false);
2984 /// DiagnoseUnimplementedProperties - This routine warns on those properties
2985 /// which must be implemented by this implementation.
2986 void DiagnoseUnimplementedProperties(Scope *S, ObjCImplDecl* IMPDecl,
2987 ObjCContainerDecl *CDecl,
2988 bool SynthesizeProperties);
2990 /// Diagnose any null-resettable synthesized setters.
2991 void diagnoseNullResettableSynthesizedSetters(const ObjCImplDecl *impDecl);
2993 /// DefaultSynthesizeProperties - This routine default synthesizes all
2994 /// properties which must be synthesized in the class's \@implementation.
2995 void DefaultSynthesizeProperties (Scope *S, ObjCImplDecl* IMPDecl,
2996 ObjCInterfaceDecl *IDecl);
2997 void DefaultSynthesizeProperties(Scope *S, Decl *D);
2999 /// IvarBacksCurrentMethodAccessor - This routine returns 'true' if 'IV' is
3000 /// an ivar synthesized for 'Method' and 'Method' is a property accessor
3001 /// declared in class 'IFace'.
3002 bool IvarBacksCurrentMethodAccessor(ObjCInterfaceDecl *IFace,
3003 ObjCMethodDecl *Method, ObjCIvarDecl *IV);
3005 /// DiagnoseUnusedBackingIvarInAccessor - Issue an 'unused' warning if ivar which
3006 /// backs the property is not used in the property's accessor.
3007 void DiagnoseUnusedBackingIvarInAccessor(Scope *S,
3008 const ObjCImplementationDecl *ImplD);
3010 /// GetIvarBackingPropertyAccessor - If method is a property setter/getter and
3011 /// it property has a backing ivar, returns this ivar; otherwise, returns NULL.
3012 /// It also returns ivar's property on success.
3013 ObjCIvarDecl *GetIvarBackingPropertyAccessor(const ObjCMethodDecl *Method,
3014 const ObjCPropertyDecl *&PDecl) const;
3016 /// Called by ActOnProperty to handle \@property declarations in
3017 /// class extensions.
3018 ObjCPropertyDecl *HandlePropertyInClassExtension(Scope *S,
3019 SourceLocation AtLoc,
3020 SourceLocation LParenLoc,
3021 FieldDeclarator &FD,
3024 const bool isAssign,
3025 const bool isReadWrite,
3026 const unsigned Attributes,
3027 const unsigned AttributesAsWritten,
3028 bool *isOverridingProperty,
3030 TypeSourceInfo *TSI,
3031 tok::ObjCKeywordKind MethodImplKind);
3033 /// Called by ActOnProperty and HandlePropertyInClassExtension to
3034 /// handle creating the ObjcPropertyDecl for a category or \@interface.
3035 ObjCPropertyDecl *CreatePropertyDecl(Scope *S,
3036 ObjCContainerDecl *CDecl,
3037 SourceLocation AtLoc,
3038 SourceLocation LParenLoc,
3039 FieldDeclarator &FD,
3042 const bool isAssign,
3043 const bool isReadWrite,
3044 const unsigned Attributes,
3045 const unsigned AttributesAsWritten,
3047 TypeSourceInfo *TSI,
3048 tok::ObjCKeywordKind MethodImplKind,
3049 DeclContext *lexicalDC = nullptr);
3051 /// AtomicPropertySetterGetterRules - This routine enforces the rule (via
3052 /// warning) when atomic property has one but not the other user-declared
3053 /// setter or getter.
3054 void AtomicPropertySetterGetterRules(ObjCImplDecl* IMPDecl,
3055 ObjCContainerDecl* IDecl);
3057 void DiagnoseOwningPropertyGetterSynthesis(const ObjCImplementationDecl *D);
3059 void DiagnoseMissingDesignatedInitOverrides(
3060 const ObjCImplementationDecl *ImplD,
3061 const ObjCInterfaceDecl *IFD);
3063 void DiagnoseDuplicateIvars(ObjCInterfaceDecl *ID, ObjCInterfaceDecl *SID);
3065 enum MethodMatchStrategy {
3070 /// MatchTwoMethodDeclarations - Checks if two methods' type match and returns
3071 /// true, or false, accordingly.
3072 bool MatchTwoMethodDeclarations(const ObjCMethodDecl *Method,
3073 const ObjCMethodDecl *PrevMethod,
3074 MethodMatchStrategy strategy = MMS_strict);
3076 /// MatchAllMethodDeclarations - Check methods declaraed in interface or
3077 /// or protocol against those declared in their implementations.
3078 void MatchAllMethodDeclarations(const SelectorSet &InsMap,
3079 const SelectorSet &ClsMap,
3080 SelectorSet &InsMapSeen,
3081 SelectorSet &ClsMapSeen,
3082 ObjCImplDecl* IMPDecl,
3083 ObjCContainerDecl* IDecl,
3084 bool &IncompleteImpl,
3085 bool ImmediateClass,
3086 bool WarnCategoryMethodImpl=false);
3088 /// CheckCategoryVsClassMethodMatches - Checks that methods implemented in
3089 /// category matches with those implemented in its primary class and
3090 /// warns each time an exact match is found.
3091 void CheckCategoryVsClassMethodMatches(ObjCCategoryImplDecl *CatIMP);
3093 /// \brief Add the given method to the list of globally-known methods.
3094 void addMethodToGlobalList(ObjCMethodList *List, ObjCMethodDecl *Method);
3097 /// AddMethodToGlobalPool - Add an instance or factory method to the global
3098 /// pool. See descriptoin of AddInstanceMethodToGlobalPool.
3099 void AddMethodToGlobalPool(ObjCMethodDecl *Method, bool impl, bool instance);
3101 /// LookupMethodInGlobalPool - Returns the instance or factory method and
3102 /// optionally warns if there are multiple signatures.
3103 ObjCMethodDecl *LookupMethodInGlobalPool(Selector Sel, SourceRange R,
3104 bool receiverIdOrClass,
3108 /// \brief - Returns instance or factory methods in global method pool for
3109 /// given selector. If no such method or only one method found, function returns
3110 /// false; otherwise, it returns true
3111 bool CollectMultipleMethodsInGlobalPool(Selector Sel,
3112 SmallVectorImpl<ObjCMethodDecl*>& Methods,
3115 bool AreMultipleMethodsInGlobalPool(Selector Sel, ObjCMethodDecl *BestMethod,
3117 bool receiverIdOrClass);
3119 void DiagnoseMultipleMethodInGlobalPool(SmallVectorImpl<ObjCMethodDecl*> &Methods,
3120 Selector Sel, SourceRange R,
3121 bool receiverIdOrClass);
3124 /// \brief - Returns a selector which best matches given argument list or
3125 /// nullptr if none could be found
3126 ObjCMethodDecl *SelectBestMethod(Selector Sel, MultiExprArg Args,
3130 /// \brief Record the typo correction failure and return an empty correction.
3131 TypoCorrection FailedCorrection(IdentifierInfo *Typo, SourceLocation TypoLoc,
3132 bool RecordFailure = true) {
3134 TypoCorrectionFailures[Typo].insert(TypoLoc);
3135 return TypoCorrection();
3139 /// AddInstanceMethodToGlobalPool - All instance methods in a translation
3140 /// unit are added to a global pool. This allows us to efficiently associate
3141 /// a selector with a method declaraation for purposes of typechecking
3142 /// messages sent to "id" (where the class of the object is unknown).
3143 void AddInstanceMethodToGlobalPool(ObjCMethodDecl *Method, bool impl=false) {
3144 AddMethodToGlobalPool(Method, impl, /*instance*/true);
3147 /// AddFactoryMethodToGlobalPool - Same as above, but for factory methods.
3148 void AddFactoryMethodToGlobalPool(ObjCMethodDecl *Method, bool impl=false) {
3149 AddMethodToGlobalPool(Method, impl, /*instance*/false);
3152 /// AddAnyMethodToGlobalPool - Add any method, instance or factory to global
3154 void AddAnyMethodToGlobalPool(Decl *D);
3156 /// LookupInstanceMethodInGlobalPool - Returns the method and warns if
3157 /// there are multiple signatures.
3158 ObjCMethodDecl *LookupInstanceMethodInGlobalPool(Selector Sel, SourceRange R,
3159 bool receiverIdOrClass=false) {
3160 return LookupMethodInGlobalPool(Sel, R, receiverIdOrClass,
3164 /// LookupFactoryMethodInGlobalPool - Returns the method and warns if
3165 /// there are multiple signatures.
3166 ObjCMethodDecl *LookupFactoryMethodInGlobalPool(Selector Sel, SourceRange R,
3167 bool receiverIdOrClass=false) {
3168 return LookupMethodInGlobalPool(Sel, R, receiverIdOrClass,
3172 const ObjCMethodDecl *SelectorsForTypoCorrection(Selector Sel,
3173 QualType ObjectType=QualType());
3174 /// LookupImplementedMethodInGlobalPool - Returns the method which has an
3176 ObjCMethodDecl *LookupImplementedMethodInGlobalPool(Selector Sel);
3178 /// CollectIvarsToConstructOrDestruct - Collect those ivars which require
3180 void CollectIvarsToConstructOrDestruct(ObjCInterfaceDecl *OI,
3181 SmallVectorImpl<ObjCIvarDecl*> &Ivars);
3183 //===--------------------------------------------------------------------===//
3184 // Statement Parsing Callbacks: SemaStmt.cpp.
3188 FullExprArg(Sema &actions) : E(nullptr) { }
3190 ExprResult release() {
3194 Expr *get() const { return E; }
3196 Expr *operator->() {
3201 // FIXME: No need to make the entire Sema class a friend when it's just
3202 // Sema::MakeFullExpr that needs access to the constructor below.
3205 explicit FullExprArg(Expr *expr) : E(expr) {}
3210 FullExprArg MakeFullExpr(Expr *Arg) {
3211 return MakeFullExpr(Arg, Arg ? Arg->getExprLoc() : SourceLocation());
3213 FullExprArg MakeFullExpr(Expr *Arg, SourceLocation CC) {
3214 return FullExprArg(ActOnFinishFullExpr(Arg, CC).get());
3216 FullExprArg MakeFullDiscardedValueExpr(Expr *Arg) {
3218 ActOnFinishFullExpr(Arg, Arg ? Arg->getExprLoc() : SourceLocation(),
3219 /*DiscardedValue*/ true);
3220 return FullExprArg(FE.get());
3223 StmtResult ActOnExprStmt(ExprResult Arg);
3224 StmtResult ActOnExprStmtError();
3226 StmtResult ActOnNullStmt(SourceLocation SemiLoc,
3227 bool HasLeadingEmptyMacro = false);
3229 void ActOnStartOfCompoundStmt();
3230 void ActOnFinishOfCompoundStmt();
3231 StmtResult ActOnCompoundStmt(SourceLocation L, SourceLocation R,
3232 ArrayRef<Stmt *> Elts, bool isStmtExpr);
3234 /// \brief A RAII object to enter scope of a compound statement.
3235 class CompoundScopeRAII {
3237 CompoundScopeRAII(Sema &S): S(S) {
3238 S.ActOnStartOfCompoundStmt();
3241 ~CompoundScopeRAII() {
3242 S.ActOnFinishOfCompoundStmt();
3249 /// An RAII helper that pops function a function scope on exit.
3250 struct FunctionScopeRAII {
3253 FunctionScopeRAII(Sema &S) : S(S), Active(true) {}
3254 ~FunctionScopeRAII() {
3256 S.PopFunctionScopeInfo();
3258 void disable() { Active = false; }
3261 StmtResult ActOnDeclStmt(DeclGroupPtrTy Decl,
3262 SourceLocation StartLoc,
3263 SourceLocation EndLoc);
3264 void ActOnForEachDeclStmt(DeclGroupPtrTy Decl);
3265 StmtResult ActOnForEachLValueExpr(Expr *E);
3266 StmtResult ActOnCaseStmt(SourceLocation CaseLoc, Expr *LHSVal,
3267 SourceLocation DotDotDotLoc, Expr *RHSVal,
3268 SourceLocation ColonLoc);
3269 void ActOnCaseStmtBody(Stmt *CaseStmt, Stmt *SubStmt);
3271 StmtResult ActOnDefaultStmt(SourceLocation DefaultLoc,
3272 SourceLocation ColonLoc,
3273 Stmt *SubStmt, Scope *CurScope);
3274 StmtResult ActOnLabelStmt(SourceLocation IdentLoc, LabelDecl *TheDecl,
3275 SourceLocation ColonLoc, Stmt *SubStmt);
3277 StmtResult ActOnAttributedStmt(SourceLocation AttrLoc,
3278 ArrayRef<const Attr*> Attrs,
3281 StmtResult ActOnIfStmt(SourceLocation IfLoc,
3282 FullExprArg CondVal, Decl *CondVar,
3284 SourceLocation ElseLoc, Stmt *ElseVal);
3285 StmtResult ActOnStartOfSwitchStmt(SourceLocation SwitchLoc,
3288 StmtResult ActOnFinishSwitchStmt(SourceLocation SwitchLoc,
3289 Stmt *Switch, Stmt *Body);
3290 StmtResult ActOnWhileStmt(SourceLocation WhileLoc,
3292 Decl *CondVar, Stmt *Body);
3293 StmtResult ActOnDoStmt(SourceLocation DoLoc, Stmt *Body,
3294 SourceLocation WhileLoc,
3295 SourceLocation CondLParen, Expr *Cond,
3296 SourceLocation CondRParen);
3298 StmtResult ActOnForStmt(SourceLocation ForLoc,
3299 SourceLocation LParenLoc,
3300 Stmt *First, FullExprArg Second,
3303 SourceLocation RParenLoc,
3305 ExprResult CheckObjCForCollectionOperand(SourceLocation forLoc,
3307 StmtResult ActOnObjCForCollectionStmt(SourceLocation ForColLoc,
3308 Stmt *First, Expr *collection,
3309 SourceLocation RParenLoc);
3310 StmtResult FinishObjCForCollectionStmt(Stmt *ForCollection, Stmt *Body);
3312 enum BuildForRangeKind {
3313 /// Initial building of a for-range statement.
3315 /// Instantiation or recovery rebuild of a for-range statement. Don't
3316 /// attempt any typo-correction.
3318 /// Determining whether a for-range statement could be built. Avoid any
3319 /// unnecessary or irreversible actions.
3323 StmtResult ActOnCXXForRangeStmt(SourceLocation ForLoc, Stmt *LoopVar,
3324 SourceLocation ColonLoc, Expr *Collection,
3325 SourceLocation RParenLoc,
3326 BuildForRangeKind Kind);
3327 StmtResult BuildCXXForRangeStmt(SourceLocation ForLoc,
3328 SourceLocation ColonLoc,
3329 Stmt *RangeDecl, Stmt *BeginEndDecl,
3330 Expr *Cond, Expr *Inc,
3332 SourceLocation RParenLoc,
3333 BuildForRangeKind Kind);
3334 StmtResult FinishCXXForRangeStmt(Stmt *ForRange, Stmt *Body);
3336 StmtResult ActOnGotoStmt(SourceLocation GotoLoc,
3337 SourceLocation LabelLoc,
3338 LabelDecl *TheDecl);
3339 StmtResult ActOnIndirectGotoStmt(SourceLocation GotoLoc,
3340 SourceLocation StarLoc,
3342 StmtResult ActOnContinueStmt(SourceLocation ContinueLoc, Scope *CurScope);
3343 StmtResult ActOnBreakStmt(SourceLocation BreakLoc, Scope *CurScope);
3345 void ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope,
3346 CapturedRegionKind Kind, unsigned NumParams);
3347 typedef std::pair<StringRef, QualType> CapturedParamNameType;
3348 void ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope,
3349 CapturedRegionKind Kind,
3350 ArrayRef<CapturedParamNameType> Params);
3351 StmtResult ActOnCapturedRegionEnd(Stmt *S);
3352 void ActOnCapturedRegionError();
3353 RecordDecl *CreateCapturedStmtRecordDecl(CapturedDecl *&CD,
3355 unsigned NumParams);
3356 VarDecl *getCopyElisionCandidate(QualType ReturnType, Expr *E,
3357 bool AllowFunctionParameters);
3358 bool isCopyElisionCandidate(QualType ReturnType, const VarDecl *VD,
3359 bool AllowFunctionParameters);
3361 StmtResult ActOnReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp,
3363 StmtResult BuildReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp);
3364 StmtResult ActOnCapScopeReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp);
3366 StmtResult ActOnGCCAsmStmt(SourceLocation AsmLoc, bool IsSimple,
3367 bool IsVolatile, unsigned NumOutputs,
3368 unsigned NumInputs, IdentifierInfo **Names,
3369 MultiExprArg Constraints, MultiExprArg Exprs,
3370 Expr *AsmString, MultiExprArg Clobbers,
3371 SourceLocation RParenLoc);
3373 ExprResult LookupInlineAsmIdentifier(CXXScopeSpec &SS,
3374 SourceLocation TemplateKWLoc,
3376 llvm::InlineAsmIdentifierInfo &Info,
3377 bool IsUnevaluatedContext);
3378 bool LookupInlineAsmField(StringRef Base, StringRef Member,
3379 unsigned &Offset, SourceLocation AsmLoc);
3380 StmtResult ActOnMSAsmStmt(SourceLocation AsmLoc, SourceLocation LBraceLoc,
3381 ArrayRef<Token> AsmToks,
3382 StringRef AsmString,
3383 unsigned NumOutputs, unsigned NumInputs,
3384 ArrayRef<StringRef> Constraints,
3385 ArrayRef<StringRef> Clobbers,
3386 ArrayRef<Expr*> Exprs,
3387 SourceLocation EndLoc);
3388 LabelDecl *GetOrCreateMSAsmLabel(StringRef ExternalLabelName,
3389 SourceLocation Location,
3392 VarDecl *BuildObjCExceptionDecl(TypeSourceInfo *TInfo, QualType ExceptionType,
3393 SourceLocation StartLoc,
3394 SourceLocation IdLoc, IdentifierInfo *Id,
3395 bool Invalid = false);
3397 Decl *ActOnObjCExceptionDecl(Scope *S, Declarator &D);
3399 StmtResult ActOnObjCAtCatchStmt(SourceLocation AtLoc, SourceLocation RParen,
3400 Decl *Parm, Stmt *Body);
3402 StmtResult ActOnObjCAtFinallyStmt(SourceLocation AtLoc, Stmt *Body);
3404 StmtResult ActOnObjCAtTryStmt(SourceLocation AtLoc, Stmt *Try,
3405 MultiStmtArg Catch, Stmt *Finally);
3407 StmtResult BuildObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw);
3408 StmtResult ActOnObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw,
3410 ExprResult ActOnObjCAtSynchronizedOperand(SourceLocation atLoc,
3412 StmtResult ActOnObjCAtSynchronizedStmt(SourceLocation AtLoc,
3416 StmtResult ActOnObjCAutoreleasePoolStmt(SourceLocation AtLoc, Stmt *Body);
3418 VarDecl *BuildExceptionDeclaration(Scope *S, TypeSourceInfo *TInfo,
3419 SourceLocation StartLoc,
3420 SourceLocation IdLoc,
3421 IdentifierInfo *Id);
3423 Decl *ActOnExceptionDeclarator(Scope *S, Declarator &D);
3425 StmtResult ActOnCXXCatchBlock(SourceLocation CatchLoc,
3426 Decl *ExDecl, Stmt *HandlerBlock);
3427 StmtResult ActOnCXXTryBlock(SourceLocation TryLoc, Stmt *TryBlock,
3428 ArrayRef<Stmt *> Handlers);
3430 StmtResult ActOnSEHTryBlock(bool IsCXXTry, // try (true) or __try (false) ?
3431 SourceLocation TryLoc, Stmt *TryBlock,
3433 StmtResult ActOnSEHExceptBlock(SourceLocation Loc,
3436 void ActOnStartSEHFinallyBlock();
3437 void ActOnAbortSEHFinallyBlock();
3438 StmtResult ActOnFinishSEHFinallyBlock(SourceLocation Loc, Stmt *Block);
3439 StmtResult ActOnSEHLeaveStmt(SourceLocation Loc, Scope *CurScope);
3441 void DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock);
3443 bool ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const;
3445 /// \brief If it's a file scoped decl that must warn if not used, keep track
3447 void MarkUnusedFileScopedDecl(const DeclaratorDecl *D);
3449 /// DiagnoseUnusedExprResult - If the statement passed in is an expression
3450 /// whose result is unused, warn.
3451 void DiagnoseUnusedExprResult(const Stmt *S);
3452 void DiagnoseUnusedNestedTypedefs(const RecordDecl *D);
3453 void DiagnoseUnusedDecl(const NamedDecl *ND);
3455 /// Emit \p DiagID if statement located on \p StmtLoc has a suspicious null
3456 /// statement as a \p Body, and it is located on the same line.
3458 /// This helps prevent bugs due to typos, such as:
3461 void DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
3465 /// Warn if a for/while loop statement \p S, which is followed by
3466 /// \p PossibleBody, has a suspicious null statement as a body.
3467 void DiagnoseEmptyLoopBody(const Stmt *S,
3468 const Stmt *PossibleBody);
3470 /// Warn if a value is moved to itself.
3471 void DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
3472 SourceLocation OpLoc);
3474 ParsingDeclState PushParsingDeclaration(sema::DelayedDiagnosticPool &pool) {
3475 return DelayedDiagnostics.push(pool);
3477 void PopParsingDeclaration(ParsingDeclState state, Decl *decl);
3479 typedef ProcessingContextState ParsingClassState;
3480 ParsingClassState PushParsingClass() {
3481 return DelayedDiagnostics.pushUndelayed();
3483 void PopParsingClass(ParsingClassState state) {
3484 DelayedDiagnostics.popUndelayed(state);
3487 void redelayDiagnostics(sema::DelayedDiagnosticPool &pool);
3489 enum AvailabilityDiagnostic { AD_Deprecation, AD_Unavailable, AD_Partial };
3491 void EmitAvailabilityWarning(AvailabilityDiagnostic AD,
3492 NamedDecl *D, StringRef Message,
3494 const ObjCInterfaceDecl *UnknownObjCClass,
3495 const ObjCPropertyDecl *ObjCProperty,
3496 bool ObjCPropertyAccess);
3498 bool makeUnavailableInSystemHeader(SourceLocation loc,
3501 //===--------------------------------------------------------------------===//
3502 // Expression Parsing Callbacks: SemaExpr.cpp.
3504 bool CanUseDecl(NamedDecl *D);
3505 bool DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc,
3506 const ObjCInterfaceDecl *UnknownObjCClass=nullptr,
3507 bool ObjCPropertyAccess=false);
3508 void NoteDeletedFunction(FunctionDecl *FD);
3509 std::string getDeletedOrUnavailableSuffix(const FunctionDecl *FD);
3510 bool DiagnosePropertyAccessorMismatch(ObjCPropertyDecl *PD,
3511 ObjCMethodDecl *Getter,
3512 SourceLocation Loc);
3513 void DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
3514 ArrayRef<Expr *> Args);
3516 void PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
3517 Decl *LambdaContextDecl = nullptr,
3518 bool IsDecltype = false);
3519 enum ReuseLambdaContextDecl_t { ReuseLambdaContextDecl };
3520 void PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
3521 ReuseLambdaContextDecl_t,
3522 bool IsDecltype = false);
3523 void PopExpressionEvaluationContext();
3525 void DiscardCleanupsInEvaluationContext();
3527 ExprResult TransformToPotentiallyEvaluated(Expr *E);
3528 ExprResult HandleExprEvaluationContextForTypeof(Expr *E);
3530 ExprResult ActOnConstantExpression(ExprResult Res);
3532 // Functions for marking a declaration referenced. These functions also
3533 // contain the relevant logic for marking if a reference to a function or
3534 // variable is an odr-use (in the C++11 sense). There are separate variants
3535 // for expressions referring to a decl; these exist because odr-use marking
3536 // needs to be delayed for some constant variables when we build one of the
3537 // named expressions.
3538 void MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, bool OdrUse);
3539 void MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func,
3540 bool OdrUse = true);
3541 void MarkVariableReferenced(SourceLocation Loc, VarDecl *Var);
3542 void MarkDeclRefReferenced(DeclRefExpr *E);
3543 void MarkMemberReferenced(MemberExpr *E);
3545 void UpdateMarkingForLValueToRValue(Expr *E);
3546 void CleanupVarDeclMarking();
3548 enum TryCaptureKind {
3549 TryCapture_Implicit, TryCapture_ExplicitByVal, TryCapture_ExplicitByRef
3552 /// \brief Try to capture the given variable.
3554 /// \param Var The variable to capture.
3556 /// \param Loc The location at which the capture occurs.
3558 /// \param Kind The kind of capture, which may be implicit (for either a
3559 /// block or a lambda), or explicit by-value or by-reference (for a lambda).
3561 /// \param EllipsisLoc The location of the ellipsis, if one is provided in
3562 /// an explicit lambda capture.
3564 /// \param BuildAndDiagnose Whether we are actually supposed to add the
3565 /// captures or diagnose errors. If false, this routine merely check whether
3566 /// the capture can occur without performing the capture itself or complaining
3567 /// if the variable cannot be captured.
3569 /// \param CaptureType Will be set to the type of the field used to capture
3570 /// this variable in the innermost block or lambda. Only valid when the
3571 /// variable can be captured.
3573 /// \param DeclRefType Will be set to the type of a reference to the capture
3574 /// from within the current scope. Only valid when the variable can be
3577 /// \param FunctionScopeIndexToStopAt If non-null, it points to the index
3578 /// of the FunctionScopeInfo stack beyond which we do not attempt to capture.
3579 /// This is useful when enclosing lambdas must speculatively capture
3580 /// variables that may or may not be used in certain specializations of
3581 /// a nested generic lambda.
3583 /// \returns true if an error occurred (i.e., the variable cannot be
3584 /// captured) and false if the capture succeeded.
3585 bool tryCaptureVariable(VarDecl *Var, SourceLocation Loc, TryCaptureKind Kind,
3586 SourceLocation EllipsisLoc, bool BuildAndDiagnose,
3587 QualType &CaptureType,
3588 QualType &DeclRefType,
3589 const unsigned *const FunctionScopeIndexToStopAt);
3591 /// \brief Try to capture the given variable.
3592 bool tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
3593 TryCaptureKind Kind = TryCapture_Implicit,
3594 SourceLocation EllipsisLoc = SourceLocation());
3596 /// \brief Checks if the variable must be captured.
3597 bool NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc);
3599 /// \brief Given a variable, determine the type that a reference to that
3600 /// variable will have in the given scope.
3601 QualType getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc);
3603 void MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T);
3604 void MarkDeclarationsReferencedInExpr(Expr *E,
3605 bool SkipLocalVariables = false);
3607 /// \brief Try to recover by turning the given expression into a
3608 /// call. Returns true if recovery was attempted or an error was
3609 /// emitted; this may also leave the ExprResult invalid.
3610 bool tryToRecoverWithCall(ExprResult &E, const PartialDiagnostic &PD,
3611 bool ForceComplain = false,
3612 bool (*IsPlausibleResult)(QualType) = nullptr);
3614 /// \brief Figure out if an expression could be turned into a call.
3615 bool tryExprAsCall(Expr &E, QualType &ZeroArgCallReturnTy,
3616 UnresolvedSetImpl &NonTemplateOverloads);
3618 /// \brief Conditionally issue a diagnostic based on the current
3619 /// evaluation context.
3621 /// \param Statement If Statement is non-null, delay reporting the
3622 /// diagnostic until the function body is parsed, and then do a basic
3623 /// reachability analysis to determine if the statement is reachable.
3624 /// If it is unreachable, the diagnostic will not be emitted.
3625 bool DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
3626 const PartialDiagnostic &PD);
3628 // Primary Expressions.
3629 SourceRange getExprRange(Expr *E) const;
3631 ExprResult ActOnIdExpression(
3632 Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
3633 UnqualifiedId &Id, bool HasTrailingLParen, bool IsAddressOfOperand,
3634 std::unique_ptr<CorrectionCandidateCallback> CCC = nullptr,
3635 bool IsInlineAsmIdentifier = false, Token *KeywordReplacement = nullptr);
3637 void DecomposeUnqualifiedId(const UnqualifiedId &Id,
3638 TemplateArgumentListInfo &Buffer,
3639 DeclarationNameInfo &NameInfo,
3640 const TemplateArgumentListInfo *&TemplateArgs);
3643 DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
3644 std::unique_ptr<CorrectionCandidateCallback> CCC,
3645 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr,
3646 ArrayRef<Expr *> Args = None, TypoExpr **Out = nullptr);
3648 ExprResult LookupInObjCMethod(LookupResult &LookUp, Scope *S,
3650 bool AllowBuiltinCreation=false);
3652 ExprResult ActOnDependentIdExpression(const CXXScopeSpec &SS,
3653 SourceLocation TemplateKWLoc,
3654 const DeclarationNameInfo &NameInfo,
3655 bool isAddressOfOperand,
3656 const TemplateArgumentListInfo *TemplateArgs);
3658 ExprResult BuildDeclRefExpr(ValueDecl *D, QualType Ty,
3661 const CXXScopeSpec *SS = nullptr);
3663 BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
3664 const DeclarationNameInfo &NameInfo,
3665 const CXXScopeSpec *SS = nullptr,
3666 NamedDecl *FoundD = nullptr,
3667 const TemplateArgumentListInfo *TemplateArgs = nullptr);
3669 BuildAnonymousStructUnionMemberReference(
3670 const CXXScopeSpec &SS,
3671 SourceLocation nameLoc,
3672 IndirectFieldDecl *indirectField,
3673 DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_none),
3674 Expr *baseObjectExpr = nullptr,
3675 SourceLocation opLoc = SourceLocation());
3677 ExprResult BuildPossibleImplicitMemberExpr(const CXXScopeSpec &SS,
3678 SourceLocation TemplateKWLoc,
3680 const TemplateArgumentListInfo *TemplateArgs);
3681 ExprResult BuildImplicitMemberExpr(const CXXScopeSpec &SS,
3682 SourceLocation TemplateKWLoc,
3684 const TemplateArgumentListInfo *TemplateArgs,
3685 bool IsDefiniteInstance);
3686 bool UseArgumentDependentLookup(const CXXScopeSpec &SS,
3687 const LookupResult &R,
3688 bool HasTrailingLParen);
3690 ExprResult BuildQualifiedDeclarationNameExpr(
3691 CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo,
3692 bool IsAddressOfOperand, TypeSourceInfo **RecoveryTSI = nullptr);
3694 ExprResult BuildDependentDeclRefExpr(const CXXScopeSpec &SS,
3695 SourceLocation TemplateKWLoc,
3696 const DeclarationNameInfo &NameInfo,
3697 const TemplateArgumentListInfo *TemplateArgs);
3699 ExprResult BuildDeclarationNameExpr(const CXXScopeSpec &SS,
3702 bool AcceptInvalidDecl = false);
3703 ExprResult BuildDeclarationNameExpr(
3704 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
3705 NamedDecl *FoundD = nullptr,
3706 const TemplateArgumentListInfo *TemplateArgs = nullptr,
3707 bool AcceptInvalidDecl = false);
3709 ExprResult BuildLiteralOperatorCall(LookupResult &R,
3710 DeclarationNameInfo &SuffixInfo,
3711 ArrayRef<Expr *> Args,
3712 SourceLocation LitEndLoc,
3713 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr);
3715 ExprResult BuildPredefinedExpr(SourceLocation Loc,
3716 PredefinedExpr::IdentType IT);
3717 ExprResult ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind);
3718 ExprResult ActOnIntegerConstant(SourceLocation Loc, uint64_t Val);
3720 bool CheckLoopHintExpr(Expr *E, SourceLocation Loc);
3722 ExprResult ActOnNumericConstant(const Token &Tok, Scope *UDLScope = nullptr);
3723 ExprResult ActOnCharacterConstant(const Token &Tok,
3724 Scope *UDLScope = nullptr);
3725 ExprResult ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E);
3726 ExprResult ActOnParenListExpr(SourceLocation L,
3730 /// ActOnStringLiteral - The specified tokens were lexed as pasted string
3731 /// fragments (e.g. "foo" "bar" L"baz").
3732 ExprResult ActOnStringLiteral(ArrayRef<Token> StringToks,
3733 Scope *UDLScope = nullptr);
3735 ExprResult ActOnGenericSelectionExpr(SourceLocation KeyLoc,
3736 SourceLocation DefaultLoc,
3737 SourceLocation RParenLoc,
3738 Expr *ControllingExpr,
3739 ArrayRef<ParsedType> ArgTypes,
3740 ArrayRef<Expr *> ArgExprs);
3741 ExprResult CreateGenericSelectionExpr(SourceLocation KeyLoc,
3742 SourceLocation DefaultLoc,
3743 SourceLocation RParenLoc,
3744 Expr *ControllingExpr,
3745 ArrayRef<TypeSourceInfo *> Types,
3746 ArrayRef<Expr *> Exprs);
3748 // Binary/Unary Operators. 'Tok' is the token for the operator.
3749 ExprResult CreateBuiltinUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc,
3751 ExprResult BuildUnaryOp(Scope *S, SourceLocation OpLoc,
3752 UnaryOperatorKind Opc, Expr *Input);
3753 ExprResult ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
3754 tok::TokenKind Op, Expr *Input);
3756 QualType CheckAddressOfOperand(ExprResult &Operand, SourceLocation OpLoc);
3758 ExprResult CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
3759 SourceLocation OpLoc,
3760 UnaryExprOrTypeTrait ExprKind,
3762 ExprResult CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
3763 UnaryExprOrTypeTrait ExprKind);
3765 ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
3766 UnaryExprOrTypeTrait ExprKind,
3767 bool IsType, void *TyOrEx,
3768 const SourceRange &ArgRange);
3770 ExprResult CheckPlaceholderExpr(Expr *E);
3771 bool CheckVecStepExpr(Expr *E);
3773 bool CheckUnaryExprOrTypeTraitOperand(Expr *E, UnaryExprOrTypeTrait ExprKind);
3774 bool CheckUnaryExprOrTypeTraitOperand(QualType ExprType, SourceLocation OpLoc,
3775 SourceRange ExprRange,
3776 UnaryExprOrTypeTrait ExprKind);
3777 ExprResult ActOnSizeofParameterPackExpr(Scope *S,
3778 SourceLocation OpLoc,
3779 IdentifierInfo &Name,
3780 SourceLocation NameLoc,
3781 SourceLocation RParenLoc);
3782 ExprResult ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
3783 tok::TokenKind Kind, Expr *Input);
3785 ExprResult ActOnArraySubscriptExpr(Scope *S, Expr *Base, SourceLocation LLoc,
3786 Expr *Idx, SourceLocation RLoc);
3787 ExprResult CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
3788 Expr *Idx, SourceLocation RLoc);
3790 // This struct is for use by ActOnMemberAccess to allow
3791 // BuildMemberReferenceExpr to be able to reinvoke ActOnMemberAccess after
3792 // changing the access operator from a '.' to a '->' (to see if that is the
3793 // change needed to fix an error about an unknown member, e.g. when the class
3794 // defines a custom operator->).
3795 struct ActOnMemberAccessExtraArgs {
3801 ExprResult BuildMemberReferenceExpr(
3802 Expr *Base, QualType BaseType, SourceLocation OpLoc, bool IsArrow,
3803 CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
3804 NamedDecl *FirstQualifierInScope, const DeclarationNameInfo &NameInfo,
3805 const TemplateArgumentListInfo *TemplateArgs,
3806 ActOnMemberAccessExtraArgs *ExtraArgs = nullptr);
3809 BuildMemberReferenceExpr(Expr *Base, QualType BaseType, SourceLocation OpLoc,
3810 bool IsArrow, const CXXScopeSpec &SS,
3811 SourceLocation TemplateKWLoc,
3812 NamedDecl *FirstQualifierInScope, LookupResult &R,
3813 const TemplateArgumentListInfo *TemplateArgs,
3814 bool SuppressQualifierCheck = false,
3815 ActOnMemberAccessExtraArgs *ExtraArgs = nullptr);
3817 ExprResult PerformMemberExprBaseConversion(Expr *Base, bool IsArrow);
3819 bool CheckQualifiedMemberReference(Expr *BaseExpr, QualType BaseType,
3820 const CXXScopeSpec &SS,
3821 const LookupResult &R);
3823 ExprResult ActOnDependentMemberExpr(Expr *Base, QualType BaseType,
3824 bool IsArrow, SourceLocation OpLoc,
3825 const CXXScopeSpec &SS,
3826 SourceLocation TemplateKWLoc,
3827 NamedDecl *FirstQualifierInScope,
3828 const DeclarationNameInfo &NameInfo,
3829 const TemplateArgumentListInfo *TemplateArgs);
3831 ExprResult ActOnMemberAccessExpr(Scope *S, Expr *Base,
3832 SourceLocation OpLoc,
3833 tok::TokenKind OpKind,
3835 SourceLocation TemplateKWLoc,
3836 UnqualifiedId &Member,
3839 void ActOnDefaultCtorInitializers(Decl *CDtorDecl);
3840 bool ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
3841 FunctionDecl *FDecl,
3842 const FunctionProtoType *Proto,
3843 ArrayRef<Expr *> Args,
3844 SourceLocation RParenLoc,
3845 bool ExecConfig = false);
3846 void CheckStaticArrayArgument(SourceLocation CallLoc,
3848 const Expr *ArgExpr);
3850 /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
3851 /// This provides the location of the left/right parens and a list of comma
3853 ExprResult ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
3854 MultiExprArg ArgExprs, SourceLocation RParenLoc,
3855 Expr *ExecConfig = nullptr,
3856 bool IsExecConfig = false);
3857 ExprResult BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
3858 SourceLocation LParenLoc,
3859 ArrayRef<Expr *> Arg,
3860 SourceLocation RParenLoc,
3861 Expr *Config = nullptr,
3862 bool IsExecConfig = false);
3864 ExprResult ActOnCUDAExecConfigExpr(Scope *S, SourceLocation LLLLoc,
3865 MultiExprArg ExecConfig,
3866 SourceLocation GGGLoc);
3868 ExprResult ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
3869 Declarator &D, ParsedType &Ty,
3870 SourceLocation RParenLoc, Expr *CastExpr);
3871 ExprResult BuildCStyleCastExpr(SourceLocation LParenLoc,
3873 SourceLocation RParenLoc,
3875 CastKind PrepareScalarCast(ExprResult &src, QualType destType);
3877 /// \brief Build an altivec or OpenCL literal.
3878 ExprResult BuildVectorLiteral(SourceLocation LParenLoc,
3879 SourceLocation RParenLoc, Expr *E,
3880 TypeSourceInfo *TInfo);
3882 ExprResult MaybeConvertParenListExprToParenExpr(Scope *S, Expr *ME);
3884 ExprResult ActOnCompoundLiteral(SourceLocation LParenLoc,
3886 SourceLocation RParenLoc,
3889 ExprResult BuildCompoundLiteralExpr(SourceLocation LParenLoc,
3890 TypeSourceInfo *TInfo,
3891 SourceLocation RParenLoc,
3894 ExprResult ActOnInitList(SourceLocation LBraceLoc,
3895 MultiExprArg InitArgList,
3896 SourceLocation RBraceLoc);
3898 ExprResult ActOnDesignatedInitializer(Designation &Desig,
3904 static BinaryOperatorKind ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind);
3907 ExprResult ActOnBinOp(Scope *S, SourceLocation TokLoc,
3908 tok::TokenKind Kind, Expr *LHSExpr, Expr *RHSExpr);
3909 ExprResult BuildBinOp(Scope *S, SourceLocation OpLoc,
3910 BinaryOperatorKind Opc, Expr *LHSExpr, Expr *RHSExpr);
3911 ExprResult CreateBuiltinBinOp(SourceLocation OpLoc, BinaryOperatorKind Opc,
3912 Expr *LHSExpr, Expr *RHSExpr);
3914 /// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
3915 /// in the case of a the GNU conditional expr extension.
3916 ExprResult ActOnConditionalOp(SourceLocation QuestionLoc,
3917 SourceLocation ColonLoc,
3918 Expr *CondExpr, Expr *LHSExpr, Expr *RHSExpr);
3920 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
3921 ExprResult ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
3922 LabelDecl *TheDecl);
3924 void ActOnStartStmtExpr();
3925 ExprResult ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
3926 SourceLocation RPLoc); // "({..})"
3927 void ActOnStmtExprError();
3929 // __builtin_offsetof(type, identifier(.identifier|[expr])*)
3930 struct OffsetOfComponent {
3931 SourceLocation LocStart, LocEnd;
3932 bool isBrackets; // true if [expr], false if .ident
3934 IdentifierInfo *IdentInfo;
3939 /// __builtin_offsetof(type, a.b[123][456].c)
3940 ExprResult BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
3941 TypeSourceInfo *TInfo,
3942 OffsetOfComponent *CompPtr,
3943 unsigned NumComponents,
3944 SourceLocation RParenLoc);
3945 ExprResult ActOnBuiltinOffsetOf(Scope *S,
3946 SourceLocation BuiltinLoc,
3947 SourceLocation TypeLoc,
3948 ParsedType ParsedArgTy,
3949 OffsetOfComponent *CompPtr,
3950 unsigned NumComponents,
3951 SourceLocation RParenLoc);
3953 // __builtin_choose_expr(constExpr, expr1, expr2)
3954 ExprResult ActOnChooseExpr(SourceLocation BuiltinLoc,
3955 Expr *CondExpr, Expr *LHSExpr,
3956 Expr *RHSExpr, SourceLocation RPLoc);
3958 // __builtin_va_arg(expr, type)
3959 ExprResult ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty,
3960 SourceLocation RPLoc);
3961 ExprResult BuildVAArgExpr(SourceLocation BuiltinLoc, Expr *E,
3962 TypeSourceInfo *TInfo, SourceLocation RPLoc);
3965 ExprResult ActOnGNUNullExpr(SourceLocation TokenLoc);
3967 bool CheckCaseExpression(Expr *E);
3969 /// \brief Describes the result of an "if-exists" condition check.
3970 enum IfExistsResult {
3971 /// \brief The symbol exists.
3974 /// \brief The symbol does not exist.
3977 /// \brief The name is a dependent name, so the results will differ
3978 /// from one instantiation to the next.
3981 /// \brief An error occurred.
3986 CheckMicrosoftIfExistsSymbol(Scope *S, CXXScopeSpec &SS,
3987 const DeclarationNameInfo &TargetNameInfo);
3990 CheckMicrosoftIfExistsSymbol(Scope *S, SourceLocation KeywordLoc,
3991 bool IsIfExists, CXXScopeSpec &SS,
3992 UnqualifiedId &Name);
3994 StmtResult BuildMSDependentExistsStmt(SourceLocation KeywordLoc,
3996 NestedNameSpecifierLoc QualifierLoc,
3997 DeclarationNameInfo NameInfo,
3999 StmtResult ActOnMSDependentExistsStmt(SourceLocation KeywordLoc,
4001 CXXScopeSpec &SS, UnqualifiedId &Name,
4004 //===------------------------- "Block" Extension ------------------------===//
4006 /// ActOnBlockStart - This callback is invoked when a block literal is
4008 void ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope);
4010 /// ActOnBlockArguments - This callback allows processing of block arguments.
4011 /// If there are no arguments, this is still invoked.
4012 void ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
4015 /// ActOnBlockError - If there is an error parsing a block, this callback
4016 /// is invoked to pop the information about the block from the action impl.
4017 void ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope);
4019 /// ActOnBlockStmtExpr - This is called when the body of a block statement
4020 /// literal was successfully completed. ^(int x){...}
4021 ExprResult ActOnBlockStmtExpr(SourceLocation CaretLoc, Stmt *Body,
4024 //===---------------------------- Clang Extensions ----------------------===//
4026 /// __builtin_convertvector(...)
4027 ExprResult ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy,
4028 SourceLocation BuiltinLoc,
4029 SourceLocation RParenLoc);
4031 //===---------------------------- OpenCL Features -----------------------===//
4033 /// __builtin_astype(...)
4034 ExprResult ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
4035 SourceLocation BuiltinLoc,
4036 SourceLocation RParenLoc);
4038 //===---------------------------- C++ Features --------------------------===//
4040 // Act on C++ namespaces
4041 Decl *ActOnStartNamespaceDef(Scope *S, SourceLocation InlineLoc,
4042 SourceLocation NamespaceLoc,
4043 SourceLocation IdentLoc,
4044 IdentifierInfo *Ident,
4045 SourceLocation LBrace,
4046 AttributeList *AttrList);
4047 void ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace);
4049 NamespaceDecl *getStdNamespace() const;
4050 NamespaceDecl *getOrCreateStdNamespace();
4052 CXXRecordDecl *getStdBadAlloc() const;
4054 /// \brief Tests whether Ty is an instance of std::initializer_list and, if
4055 /// it is and Element is not NULL, assigns the element type to Element.
4056 bool isStdInitializerList(QualType Ty, QualType *Element);
4058 /// \brief Looks for the std::initializer_list template and instantiates it
4059 /// with Element, or emits an error if it's not found.
4061 /// \returns The instantiated template, or null on error.
4062 QualType BuildStdInitializerList(QualType Element, SourceLocation Loc);
4064 /// \brief Determine whether Ctor is an initializer-list constructor, as
4065 /// defined in [dcl.init.list]p2.
4066 bool isInitListConstructor(const CXXConstructorDecl *Ctor);
4068 Decl *ActOnUsingDirective(Scope *CurScope,
4069 SourceLocation UsingLoc,
4070 SourceLocation NamespcLoc,
4072 SourceLocation IdentLoc,
4073 IdentifierInfo *NamespcName,
4074 AttributeList *AttrList);
4076 void PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir);
4078 Decl *ActOnNamespaceAliasDef(Scope *CurScope,
4079 SourceLocation NamespaceLoc,
4080 SourceLocation AliasLoc,
4081 IdentifierInfo *Alias,
4083 SourceLocation IdentLoc,
4084 IdentifierInfo *Ident);
4086 void HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow);
4087 bool CheckUsingShadowDecl(UsingDecl *UD, NamedDecl *Target,
4088 const LookupResult &PreviousDecls,
4089 UsingShadowDecl *&PrevShadow);
4090 UsingShadowDecl *BuildUsingShadowDecl(Scope *S, UsingDecl *UD,
4092 UsingShadowDecl *PrevDecl);
4094 bool CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
4095 bool HasTypenameKeyword,
4096 const CXXScopeSpec &SS,
4097 SourceLocation NameLoc,
4098 const LookupResult &Previous);
4099 bool CheckUsingDeclQualifier(SourceLocation UsingLoc,
4100 const CXXScopeSpec &SS,
4101 const DeclarationNameInfo &NameInfo,
4102 SourceLocation NameLoc);
4104 NamedDecl *BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
4105 SourceLocation UsingLoc,
4107 DeclarationNameInfo NameInfo,
4108 AttributeList *AttrList,
4109 bool IsInstantiation,
4110 bool HasTypenameKeyword,
4111 SourceLocation TypenameLoc);
4113 bool CheckInheritingConstructorUsingDecl(UsingDecl *UD);
4115 Decl *ActOnUsingDeclaration(Scope *CurScope,
4117 bool HasUsingKeyword,
4118 SourceLocation UsingLoc,
4120 UnqualifiedId &Name,
4121 AttributeList *AttrList,
4122 bool HasTypenameKeyword,
4123 SourceLocation TypenameLoc);
4124 Decl *ActOnAliasDeclaration(Scope *CurScope,
4126 MultiTemplateParamsArg TemplateParams,
4127 SourceLocation UsingLoc,
4128 UnqualifiedId &Name,
4129 AttributeList *AttrList,
4131 Decl *DeclFromDeclSpec);
4133 /// BuildCXXConstructExpr - Creates a complete call to a constructor,
4134 /// including handling of its default argument expressions.
4136 /// \param ConstructKind - a CXXConstructExpr::ConstructionKind
4138 BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
4139 CXXConstructorDecl *Constructor, MultiExprArg Exprs,
4140 bool HadMultipleCandidates, bool IsListInitialization,
4141 bool IsStdInitListInitialization,
4142 bool RequiresZeroInit, unsigned ConstructKind,
4143 SourceRange ParenRange);
4145 // FIXME: Can we remove this and have the above BuildCXXConstructExpr check if
4146 // the constructor can be elidable?
4148 BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
4149 CXXConstructorDecl *Constructor, bool Elidable,
4150 MultiExprArg Exprs, bool HadMultipleCandidates,
4151 bool IsListInitialization,
4152 bool IsStdInitListInitialization, bool RequiresZeroInit,
4153 unsigned ConstructKind, SourceRange ParenRange);
4155 ExprResult BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field);
4157 /// BuildCXXDefaultArgExpr - Creates a CXXDefaultArgExpr, instantiating
4158 /// the default expr if needed.
4159 ExprResult BuildCXXDefaultArgExpr(SourceLocation CallLoc,
4161 ParmVarDecl *Param);
4163 /// FinalizeVarWithDestructor - Prepare for calling destructor on the
4164 /// constructed variable.
4165 void FinalizeVarWithDestructor(VarDecl *VD, const RecordType *DeclInitType);
4167 /// \brief Helper class that collects exception specifications for
4168 /// implicitly-declared special member functions.
4169 class ImplicitExceptionSpecification {
4170 // Pointer to allow copying
4172 // We order exception specifications thus:
4173 // noexcept is the most restrictive, but is only used in C++11.
4174 // throw() comes next.
4175 // Then a throw(collected exceptions)
4176 // Finally no specification, which is expressed as noexcept(false).
4177 // throw(...) is used instead if any called function uses it.
4178 ExceptionSpecificationType ComputedEST;
4179 llvm::SmallPtrSet<CanQualType, 4> ExceptionsSeen;
4180 SmallVector<QualType, 4> Exceptions;
4182 void ClearExceptions() {
4183 ExceptionsSeen.clear();
4188 explicit ImplicitExceptionSpecification(Sema &Self)
4189 : Self(&Self), ComputedEST(EST_BasicNoexcept) {
4190 if (!Self.getLangOpts().CPlusPlus11)
4191 ComputedEST = EST_DynamicNone;
4194 /// \brief Get the computed exception specification type.
4195 ExceptionSpecificationType getExceptionSpecType() const {
4196 assert(ComputedEST != EST_ComputedNoexcept &&
4197 "noexcept(expr) should not be a possible result");
4201 /// \brief The number of exceptions in the exception specification.
4202 unsigned size() const { return Exceptions.size(); }
4204 /// \brief The set of exceptions in the exception specification.
4205 const QualType *data() const { return Exceptions.data(); }
4207 /// \brief Integrate another called method into the collected data.
4208 void CalledDecl(SourceLocation CallLoc, const CXXMethodDecl *Method);
4210 /// \brief Integrate an invoked expression into the collected data.
4211 void CalledExpr(Expr *E);
4213 /// \brief Overwrite an EPI's exception specification with this
4214 /// computed exception specification.
4215 FunctionProtoType::ExceptionSpecInfo getExceptionSpec() const {
4216 FunctionProtoType::ExceptionSpecInfo ESI;
4217 ESI.Type = getExceptionSpecType();
4218 if (ESI.Type == EST_Dynamic) {
4219 ESI.Exceptions = Exceptions;
4220 } else if (ESI.Type == EST_None) {
4221 /// C++11 [except.spec]p14:
4222 /// The exception-specification is noexcept(false) if the set of
4223 /// potential exceptions of the special member function contains "any"
4224 ESI.Type = EST_ComputedNoexcept;
4225 ESI.NoexceptExpr = Self->ActOnCXXBoolLiteral(SourceLocation(),
4226 tok::kw_false).get();
4232 /// \brief Determine what sort of exception specification a defaulted
4233 /// copy constructor of a class will have.
4234 ImplicitExceptionSpecification
4235 ComputeDefaultedDefaultCtorExceptionSpec(SourceLocation Loc,
4238 /// \brief Determine what sort of exception specification a defaulted
4239 /// default constructor of a class will have, and whether the parameter
4241 ImplicitExceptionSpecification
4242 ComputeDefaultedCopyCtorExceptionSpec(CXXMethodDecl *MD);
4244 /// \brief Determine what sort of exception specification a defautled
4245 /// copy assignment operator of a class will have, and whether the
4246 /// parameter will be const.
4247 ImplicitExceptionSpecification
4248 ComputeDefaultedCopyAssignmentExceptionSpec(CXXMethodDecl *MD);
4250 /// \brief Determine what sort of exception specification a defaulted move
4251 /// constructor of a class will have.
4252 ImplicitExceptionSpecification
4253 ComputeDefaultedMoveCtorExceptionSpec(CXXMethodDecl *MD);
4255 /// \brief Determine what sort of exception specification a defaulted move
4256 /// assignment operator of a class will have.
4257 ImplicitExceptionSpecification
4258 ComputeDefaultedMoveAssignmentExceptionSpec(CXXMethodDecl *MD);
4260 /// \brief Determine what sort of exception specification a defaulted
4261 /// destructor of a class will have.
4262 ImplicitExceptionSpecification
4263 ComputeDefaultedDtorExceptionSpec(CXXMethodDecl *MD);
4265 /// \brief Determine what sort of exception specification an inheriting
4266 /// constructor of a class will have.
4267 ImplicitExceptionSpecification
4268 ComputeInheritingCtorExceptionSpec(CXXConstructorDecl *CD);
4270 /// \brief Evaluate the implicit exception specification for a defaulted
4271 /// special member function.
4272 void EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD);
4274 /// \brief Check the given exception-specification and update the
4275 /// exception specification information with the results.
4276 void checkExceptionSpecification(bool IsTopLevel,
4277 ExceptionSpecificationType EST,
4278 ArrayRef<ParsedType> DynamicExceptions,
4279 ArrayRef<SourceRange> DynamicExceptionRanges,
4281 SmallVectorImpl<QualType> &Exceptions,
4282 FunctionProtoType::ExceptionSpecInfo &ESI);
4284 /// \brief Determine if we're in a case where we need to (incorrectly) eagerly
4285 /// parse an exception specification to work around a libstdc++ bug.
4286 bool isLibstdcxxEagerExceptionSpecHack(const Declarator &D);
4288 /// \brief Add an exception-specification to the given member function
4289 /// (or member function template). The exception-specification was parsed
4290 /// after the method itself was declared.
4291 void actOnDelayedExceptionSpecification(Decl *Method,
4292 ExceptionSpecificationType EST,
4293 SourceRange SpecificationRange,
4294 ArrayRef<ParsedType> DynamicExceptions,
4295 ArrayRef<SourceRange> DynamicExceptionRanges,
4296 Expr *NoexceptExpr);
4298 /// \brief Determine if a special member function should have a deleted
4299 /// definition when it is defaulted.
4300 bool ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
4301 bool Diagnose = false);
4303 /// \brief Declare the implicit default constructor for the given class.
4305 /// \param ClassDecl The class declaration into which the implicit
4306 /// default constructor will be added.
4308 /// \returns The implicitly-declared default constructor.
4309 CXXConstructorDecl *DeclareImplicitDefaultConstructor(
4310 CXXRecordDecl *ClassDecl);
4312 /// DefineImplicitDefaultConstructor - Checks for feasibility of
4313 /// defining this constructor as the default constructor.
4314 void DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
4315 CXXConstructorDecl *Constructor);
4317 /// \brief Declare the implicit destructor for the given class.
4319 /// \param ClassDecl The class declaration into which the implicit
4320 /// destructor will be added.
4322 /// \returns The implicitly-declared destructor.
4323 CXXDestructorDecl *DeclareImplicitDestructor(CXXRecordDecl *ClassDecl);
4325 /// DefineImplicitDestructor - Checks for feasibility of
4326 /// defining this destructor as the default destructor.
4327 void DefineImplicitDestructor(SourceLocation CurrentLocation,
4328 CXXDestructorDecl *Destructor);
4330 /// \brief Build an exception spec for destructors that don't have one.
4332 /// C++11 says that user-defined destructors with no exception spec get one
4333 /// that looks as if the destructor was implicitly declared.
4334 void AdjustDestructorExceptionSpec(CXXRecordDecl *ClassDecl,
4335 CXXDestructorDecl *Destructor);
4337 /// \brief Declare all inheriting constructors for the given class.
4339 /// \param ClassDecl The class declaration into which the inheriting
4340 /// constructors will be added.
4341 void DeclareInheritingConstructors(CXXRecordDecl *ClassDecl);
4343 /// \brief Define the specified inheriting constructor.
4344 void DefineInheritingConstructor(SourceLocation UseLoc,
4345 CXXConstructorDecl *Constructor);
4347 /// \brief Declare the implicit copy constructor for the given class.
4349 /// \param ClassDecl The class declaration into which the implicit
4350 /// copy constructor will be added.
4352 /// \returns The implicitly-declared copy constructor.
4353 CXXConstructorDecl *DeclareImplicitCopyConstructor(CXXRecordDecl *ClassDecl);
4355 /// DefineImplicitCopyConstructor - Checks for feasibility of
4356 /// defining this constructor as the copy constructor.
4357 void DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
4358 CXXConstructorDecl *Constructor);
4360 /// \brief Declare the implicit move constructor for the given class.
4362 /// \param ClassDecl The Class declaration into which the implicit
4363 /// move constructor will be added.
4365 /// \returns The implicitly-declared move constructor, or NULL if it wasn't
4367 CXXConstructorDecl *DeclareImplicitMoveConstructor(CXXRecordDecl *ClassDecl);
4369 /// DefineImplicitMoveConstructor - Checks for feasibility of
4370 /// defining this constructor as the move constructor.
4371 void DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
4372 CXXConstructorDecl *Constructor);
4374 /// \brief Declare the implicit copy assignment operator for the given class.
4376 /// \param ClassDecl The class declaration into which the implicit
4377 /// copy assignment operator will be added.
4379 /// \returns The implicitly-declared copy assignment operator.
4380 CXXMethodDecl *DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl);
4382 /// \brief Defines an implicitly-declared copy assignment operator.
4383 void DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
4384 CXXMethodDecl *MethodDecl);
4386 /// \brief Declare the implicit move assignment operator for the given class.
4388 /// \param ClassDecl The Class declaration into which the implicit
4389 /// move assignment operator will be added.
4391 /// \returns The implicitly-declared move assignment operator, or NULL if it
4392 /// wasn't declared.
4393 CXXMethodDecl *DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl);
4395 /// \brief Defines an implicitly-declared move assignment operator.
4396 void DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
4397 CXXMethodDecl *MethodDecl);
4399 /// \brief Force the declaration of any implicitly-declared members of this
4401 void ForceDeclarationOfImplicitMembers(CXXRecordDecl *Class);
4403 /// \brief Determine whether the given function is an implicitly-deleted
4404 /// special member function.
4405 bool isImplicitlyDeleted(FunctionDecl *FD);
4407 /// \brief Check whether 'this' shows up in the type of a static member
4408 /// function after the (naturally empty) cv-qualifier-seq would be.
4410 /// \returns true if an error occurred.
4411 bool checkThisInStaticMemberFunctionType(CXXMethodDecl *Method);
4413 /// \brief Whether this' shows up in the exception specification of a static
4414 /// member function.
4415 bool checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method);
4417 /// \brief Check whether 'this' shows up in the attributes of the given
4418 /// static member function.
4420 /// \returns true if an error occurred.
4421 bool checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method);
4423 /// MaybeBindToTemporary - If the passed in expression has a record type with
4424 /// a non-trivial destructor, this will return CXXBindTemporaryExpr. Otherwise
4425 /// it simply returns the passed in expression.
4426 ExprResult MaybeBindToTemporary(Expr *E);
4428 bool CompleteConstructorCall(CXXConstructorDecl *Constructor,
4429 MultiExprArg ArgsPtr,
4431 SmallVectorImpl<Expr*> &ConvertedArgs,
4432 bool AllowExplicit = false,
4433 bool IsListInitialization = false);
4435 ParsedType getInheritingConstructorName(CXXScopeSpec &SS,
4436 SourceLocation NameLoc,
4437 IdentifierInfo &Name);
4439 ParsedType getDestructorName(SourceLocation TildeLoc,
4440 IdentifierInfo &II, SourceLocation NameLoc,
4441 Scope *S, CXXScopeSpec &SS,
4442 ParsedType ObjectType,
4443 bool EnteringContext);
4445 ParsedType getDestructorType(const DeclSpec& DS, ParsedType ObjectType);
4447 // Checks that reinterpret casts don't have undefined behavior.
4448 void CheckCompatibleReinterpretCast(QualType SrcType, QualType DestType,
4449 bool IsDereference, SourceRange Range);
4451 /// ActOnCXXNamedCast - Parse {dynamic,static,reinterpret,const}_cast's.
4452 ExprResult ActOnCXXNamedCast(SourceLocation OpLoc,
4453 tok::TokenKind Kind,
4454 SourceLocation LAngleBracketLoc,
4456 SourceLocation RAngleBracketLoc,
4457 SourceLocation LParenLoc,
4459 SourceLocation RParenLoc);
4461 ExprResult BuildCXXNamedCast(SourceLocation OpLoc,
4462 tok::TokenKind Kind,
4465 SourceRange AngleBrackets,
4466 SourceRange Parens);
4468 ExprResult BuildCXXTypeId(QualType TypeInfoType,
4469 SourceLocation TypeidLoc,
4470 TypeSourceInfo *Operand,
4471 SourceLocation RParenLoc);
4472 ExprResult BuildCXXTypeId(QualType TypeInfoType,
4473 SourceLocation TypeidLoc,
4475 SourceLocation RParenLoc);
4477 /// ActOnCXXTypeid - Parse typeid( something ).
4478 ExprResult ActOnCXXTypeid(SourceLocation OpLoc,
4479 SourceLocation LParenLoc, bool isType,
4481 SourceLocation RParenLoc);
4483 ExprResult BuildCXXUuidof(QualType TypeInfoType,
4484 SourceLocation TypeidLoc,
4485 TypeSourceInfo *Operand,
4486 SourceLocation RParenLoc);
4487 ExprResult BuildCXXUuidof(QualType TypeInfoType,
4488 SourceLocation TypeidLoc,
4490 SourceLocation RParenLoc);
4492 /// ActOnCXXUuidof - Parse __uuidof( something ).
4493 ExprResult ActOnCXXUuidof(SourceLocation OpLoc,
4494 SourceLocation LParenLoc, bool isType,
4496 SourceLocation RParenLoc);
4498 /// \brief Handle a C++1z fold-expression: ( expr op ... op expr ).
4499 ExprResult ActOnCXXFoldExpr(SourceLocation LParenLoc, Expr *LHS,
4500 tok::TokenKind Operator,
4501 SourceLocation EllipsisLoc, Expr *RHS,
4502 SourceLocation RParenLoc);
4503 ExprResult BuildCXXFoldExpr(SourceLocation LParenLoc, Expr *LHS,
4504 BinaryOperatorKind Operator,
4505 SourceLocation EllipsisLoc, Expr *RHS,
4506 SourceLocation RParenLoc);
4507 ExprResult BuildEmptyCXXFoldExpr(SourceLocation EllipsisLoc,
4508 BinaryOperatorKind Operator);
4510 //// ActOnCXXThis - Parse 'this' pointer.
4511 ExprResult ActOnCXXThis(SourceLocation loc);
4513 /// \brief Try to retrieve the type of the 'this' pointer.
4515 /// \returns The type of 'this', if possible. Otherwise, returns a NULL type.
4516 QualType getCurrentThisType();
4518 /// \brief When non-NULL, the C++ 'this' expression is allowed despite the
4519 /// current context not being a non-static member function. In such cases,
4520 /// this provides the type used for 'this'.
4521 QualType CXXThisTypeOverride;
4523 /// \brief RAII object used to temporarily allow the C++ 'this' expression
4524 /// to be used, with the given qualifiers on the current class type.
4525 class CXXThisScopeRAII {
4527 QualType OldCXXThisTypeOverride;
4531 /// \brief Introduce a new scope where 'this' may be allowed (when enabled),
4532 /// using the given declaration (which is either a class template or a
4533 /// class) along with the given qualifiers.
4534 /// along with the qualifiers placed on '*this'.
4535 CXXThisScopeRAII(Sema &S, Decl *ContextDecl, unsigned CXXThisTypeQuals,
4536 bool Enabled = true);
4538 ~CXXThisScopeRAII();
4541 /// \brief Make sure the value of 'this' is actually available in the current
4542 /// context, if it is a potentially evaluated context.
4544 /// \param Loc The location at which the capture of 'this' occurs.
4546 /// \param Explicit Whether 'this' is explicitly captured in a lambda
4549 /// \param FunctionScopeIndexToStopAt If non-null, it points to the index
4550 /// of the FunctionScopeInfo stack beyond which we do not attempt to capture.
4551 /// This is useful when enclosing lambdas must speculatively capture
4552 /// 'this' that may or may not be used in certain specializations of
4553 /// a nested generic lambda (depending on whether the name resolves to
4554 /// a non-static member function or a static function).
4555 /// \return returns 'true' if failed, 'false' if success.
4556 bool CheckCXXThisCapture(SourceLocation Loc, bool Explicit = false,
4557 bool BuildAndDiagnose = true,
4558 const unsigned *const FunctionScopeIndexToStopAt = nullptr);
4560 /// \brief Determine whether the given type is the type of *this that is used
4561 /// outside of the body of a member function for a type that is currently
4563 bool isThisOutsideMemberFunctionBody(QualType BaseType);
4565 /// ActOnCXXBoolLiteral - Parse {true,false} literals.
4566 ExprResult ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind);
4569 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
4570 ExprResult ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind);
4572 /// ActOnCXXNullPtrLiteral - Parse 'nullptr'.
4573 ExprResult ActOnCXXNullPtrLiteral(SourceLocation Loc);
4575 //// ActOnCXXThrow - Parse throw expressions.
4576 ExprResult ActOnCXXThrow(Scope *S, SourceLocation OpLoc, Expr *expr);
4577 ExprResult BuildCXXThrow(SourceLocation OpLoc, Expr *Ex,
4578 bool IsThrownVarInScope);
4579 bool CheckCXXThrowOperand(SourceLocation ThrowLoc, QualType ThrowTy, Expr *E);
4581 /// ActOnCXXTypeConstructExpr - Parse construction of a specified type.
4582 /// Can be interpreted either as function-style casting ("int(x)")
4583 /// or class type construction ("ClassType(x,y,z)")
4584 /// or creation of a value-initialized type ("int()").
4585 ExprResult ActOnCXXTypeConstructExpr(ParsedType TypeRep,
4586 SourceLocation LParenLoc,
4588 SourceLocation RParenLoc);
4590 ExprResult BuildCXXTypeConstructExpr(TypeSourceInfo *Type,
4591 SourceLocation LParenLoc,
4593 SourceLocation RParenLoc);
4595 /// ActOnCXXNew - Parsed a C++ 'new' expression.
4596 ExprResult ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
4597 SourceLocation PlacementLParen,
4598 MultiExprArg PlacementArgs,
4599 SourceLocation PlacementRParen,
4600 SourceRange TypeIdParens, Declarator &D,
4602 ExprResult BuildCXXNew(SourceRange Range, bool UseGlobal,
4603 SourceLocation PlacementLParen,
4604 MultiExprArg PlacementArgs,
4605 SourceLocation PlacementRParen,
4606 SourceRange TypeIdParens,
4608 TypeSourceInfo *AllocTypeInfo,
4610 SourceRange DirectInitRange,
4612 bool TypeMayContainAuto = true);
4614 bool CheckAllocatedType(QualType AllocType, SourceLocation Loc,
4616 bool FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,
4617 bool UseGlobal, QualType AllocType, bool IsArray,
4618 MultiExprArg PlaceArgs,
4619 FunctionDecl *&OperatorNew,
4620 FunctionDecl *&OperatorDelete);
4621 bool FindAllocationOverload(SourceLocation StartLoc, SourceRange Range,
4622 DeclarationName Name, MultiExprArg Args,
4624 bool AllowMissing, FunctionDecl *&Operator,
4625 bool Diagnose = true);
4626 void DeclareGlobalNewDelete();
4627 void DeclareGlobalAllocationFunction(DeclarationName Name, QualType Return,
4629 QualType Param2 = QualType(),
4630 bool addRestrictAttr = false);
4632 bool FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD,
4633 DeclarationName Name, FunctionDecl* &Operator,
4634 bool Diagnose = true);
4635 FunctionDecl *FindUsualDeallocationFunction(SourceLocation StartLoc,
4636 bool CanProvideSize,
4637 DeclarationName Name);
4639 /// ActOnCXXDelete - Parsed a C++ 'delete' expression
4640 ExprResult ActOnCXXDelete(SourceLocation StartLoc,
4641 bool UseGlobal, bool ArrayForm,
4644 DeclResult ActOnCXXConditionDeclaration(Scope *S, Declarator &D);
4645 ExprResult CheckConditionVariable(VarDecl *ConditionVar,
4646 SourceLocation StmtLoc,
4647 bool ConvertToBoolean);
4649 ExprResult ActOnNoexceptExpr(SourceLocation KeyLoc, SourceLocation LParen,
4650 Expr *Operand, SourceLocation RParen);
4651 ExprResult BuildCXXNoexceptExpr(SourceLocation KeyLoc, Expr *Operand,
4652 SourceLocation RParen);
4654 /// \brief Parsed one of the type trait support pseudo-functions.
4655 ExprResult ActOnTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
4656 ArrayRef<ParsedType> Args,
4657 SourceLocation RParenLoc);
4658 ExprResult BuildTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
4659 ArrayRef<TypeSourceInfo *> Args,
4660 SourceLocation RParenLoc);
4662 /// ActOnArrayTypeTrait - Parsed one of the bianry type trait support
4663 /// pseudo-functions.
4664 ExprResult ActOnArrayTypeTrait(ArrayTypeTrait ATT,
4665 SourceLocation KWLoc,
4668 SourceLocation RParen);
4670 ExprResult BuildArrayTypeTrait(ArrayTypeTrait ATT,
4671 SourceLocation KWLoc,
4672 TypeSourceInfo *TSInfo,
4674 SourceLocation RParen);
4676 /// ActOnExpressionTrait - Parsed one of the unary type trait support
4677 /// pseudo-functions.
4678 ExprResult ActOnExpressionTrait(ExpressionTrait OET,
4679 SourceLocation KWLoc,
4681 SourceLocation RParen);
4683 ExprResult BuildExpressionTrait(ExpressionTrait OET,
4684 SourceLocation KWLoc,
4686 SourceLocation RParen);
4688 ExprResult ActOnStartCXXMemberReference(Scope *S,
4690 SourceLocation OpLoc,
4691 tok::TokenKind OpKind,
4692 ParsedType &ObjectType,
4693 bool &MayBePseudoDestructor);
4695 ExprResult BuildPseudoDestructorExpr(Expr *Base,
4696 SourceLocation OpLoc,
4697 tok::TokenKind OpKind,
4698 const CXXScopeSpec &SS,
4699 TypeSourceInfo *ScopeType,
4700 SourceLocation CCLoc,
4701 SourceLocation TildeLoc,
4702 PseudoDestructorTypeStorage DestroyedType);
4704 ExprResult ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
4705 SourceLocation OpLoc,
4706 tok::TokenKind OpKind,
4708 UnqualifiedId &FirstTypeName,
4709 SourceLocation CCLoc,
4710 SourceLocation TildeLoc,
4711 UnqualifiedId &SecondTypeName);
4713 ExprResult ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
4714 SourceLocation OpLoc,
4715 tok::TokenKind OpKind,
4716 SourceLocation TildeLoc,
4717 const DeclSpec& DS);
4719 /// MaybeCreateExprWithCleanups - If the current full-expression
4720 /// requires any cleanups, surround it with a ExprWithCleanups node.
4721 /// Otherwise, just returns the passed-in expression.
4722 Expr *MaybeCreateExprWithCleanups(Expr *SubExpr);
4723 Stmt *MaybeCreateStmtWithCleanups(Stmt *SubStmt);
4724 ExprResult MaybeCreateExprWithCleanups(ExprResult SubExpr);
4726 ExprResult ActOnFinishFullExpr(Expr *Expr) {
4727 return ActOnFinishFullExpr(Expr, Expr ? Expr->getExprLoc()
4728 : SourceLocation());
4730 ExprResult ActOnFinishFullExpr(Expr *Expr, SourceLocation CC,
4731 bool DiscardedValue = false,
4732 bool IsConstexpr = false,
4733 bool IsLambdaInitCaptureInitializer = false);
4734 StmtResult ActOnFinishFullStmt(Stmt *Stmt);
4736 // Marks SS invalid if it represents an incomplete type.
4737 bool RequireCompleteDeclContext(CXXScopeSpec &SS, DeclContext *DC);
4739 DeclContext *computeDeclContext(QualType T);
4740 DeclContext *computeDeclContext(const CXXScopeSpec &SS,
4741 bool EnteringContext = false);
4742 bool isDependentScopeSpecifier(const CXXScopeSpec &SS);
4743 CXXRecordDecl *getCurrentInstantiationOf(NestedNameSpecifier *NNS);
4745 /// \brief The parser has parsed a global nested-name-specifier '::'.
4747 /// \param CCLoc 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 ActOnCXXGlobalScopeSpecifier(SourceLocation CCLoc, CXXScopeSpec &SS);
4755 /// \brief The parser has parsed a '__super' nested-name-specifier.
4757 /// \param SuperLoc The location of the '__super' keyword.
4759 /// \param ColonColonLoc The location of the '::'.
4761 /// \param SS The nested-name-specifier, which will be updated in-place
4762 /// to reflect the parsed nested-name-specifier.
4764 /// \returns true if an error occurred, false otherwise.
4765 bool ActOnSuperScopeSpecifier(SourceLocation SuperLoc,
4766 SourceLocation ColonColonLoc, CXXScopeSpec &SS);
4768 bool isAcceptableNestedNameSpecifier(const NamedDecl *SD,
4769 bool *CanCorrect = nullptr);
4770 NamedDecl *FindFirstQualifierInScope(Scope *S, NestedNameSpecifier *NNS);
4772 bool isNonTypeNestedNameSpecifier(Scope *S, CXXScopeSpec &SS,
4773 SourceLocation IdLoc,
4775 ParsedType ObjectType);
4777 bool BuildCXXNestedNameSpecifier(Scope *S,
4778 IdentifierInfo &Identifier,
4779 SourceLocation IdentifierLoc,
4780 SourceLocation CCLoc,
4781 QualType ObjectType,
4782 bool EnteringContext,
4784 NamedDecl *ScopeLookupResult,
4785 bool ErrorRecoveryLookup,
4786 bool *IsCorrectedToColon = nullptr);
4788 /// \brief The parser has parsed a nested-name-specifier 'identifier::'.
4790 /// \param S The scope in which this nested-name-specifier occurs.
4792 /// \param Identifier The identifier preceding the '::'.
4794 /// \param IdentifierLoc The location of the identifier.
4796 /// \param CCLoc The location of the '::'.
4798 /// \param ObjectType The type of the object, if we're parsing
4799 /// nested-name-specifier in a member access expression.
4801 /// \param EnteringContext Whether we're entering the context nominated by
4802 /// this nested-name-specifier.
4804 /// \param SS The nested-name-specifier, which is both an input
4805 /// parameter (the nested-name-specifier before this type) and an
4806 /// output parameter (containing the full nested-name-specifier,
4807 /// including this new type).
4809 /// \param ErrorRecoveryLookup If true, then this method is called to improve
4810 /// error recovery. In this case do not emit error message.
4812 /// \param IsCorrectedToColon If not null, suggestions to replace '::' -> ':'
4813 /// are allowed. The bool value pointed by this parameter is set to 'true'
4814 /// if the identifier is treated as if it was followed by ':', not '::'.
4816 /// \returns true if an error occurred, false otherwise.
4817 bool ActOnCXXNestedNameSpecifier(Scope *S,
4818 IdentifierInfo &Identifier,
4819 SourceLocation IdentifierLoc,
4820 SourceLocation CCLoc,
4821 ParsedType ObjectType,
4822 bool EnteringContext,
4824 bool ErrorRecoveryLookup = false,
4825 bool *IsCorrectedToColon = nullptr);
4827 ExprResult ActOnDecltypeExpression(Expr *E);
4829 bool ActOnCXXNestedNameSpecifierDecltype(CXXScopeSpec &SS,
4831 SourceLocation ColonColonLoc);
4833 bool IsInvalidUnlessNestedName(Scope *S, CXXScopeSpec &SS,
4834 IdentifierInfo &Identifier,
4835 SourceLocation IdentifierLoc,
4836 SourceLocation ColonLoc,
4837 ParsedType ObjectType,
4838 bool EnteringContext);
4840 /// \brief The parser has parsed a nested-name-specifier
4841 /// 'template[opt] template-name < template-args >::'.
4843 /// \param S The scope in which this nested-name-specifier occurs.
4845 /// \param SS The nested-name-specifier, which is both an input
4846 /// parameter (the nested-name-specifier before this type) and an
4847 /// output parameter (containing the full nested-name-specifier,
4848 /// including this new type).
4850 /// \param TemplateKWLoc the location of the 'template' keyword, if any.
4851 /// \param TemplateName the template name.
4852 /// \param TemplateNameLoc The location of the template name.
4853 /// \param LAngleLoc The location of the opening angle bracket ('<').
4854 /// \param TemplateArgs The template arguments.
4855 /// \param RAngleLoc The location of the closing angle bracket ('>').
4856 /// \param CCLoc The location of the '::'.
4858 /// \param EnteringContext Whether we're entering the context of the
4859 /// nested-name-specifier.
4862 /// \returns true if an error occurred, false otherwise.
4863 bool ActOnCXXNestedNameSpecifier(Scope *S,
4865 SourceLocation TemplateKWLoc,
4866 TemplateTy TemplateName,
4867 SourceLocation TemplateNameLoc,
4868 SourceLocation LAngleLoc,
4869 ASTTemplateArgsPtr TemplateArgs,
4870 SourceLocation RAngleLoc,
4871 SourceLocation CCLoc,
4872 bool EnteringContext);
4874 /// \brief Given a C++ nested-name-specifier, produce an annotation value
4875 /// that the parser can use later to reconstruct the given
4876 /// nested-name-specifier.
4878 /// \param SS A nested-name-specifier.
4880 /// \returns A pointer containing all of the information in the
4881 /// nested-name-specifier \p SS.
4882 void *SaveNestedNameSpecifierAnnotation(CXXScopeSpec &SS);
4884 /// \brief Given an annotation pointer for a nested-name-specifier, restore
4885 /// the nested-name-specifier structure.
4887 /// \param Annotation The annotation pointer, produced by
4888 /// \c SaveNestedNameSpecifierAnnotation().
4890 /// \param AnnotationRange The source range corresponding to the annotation.
4892 /// \param SS The nested-name-specifier that will be updated with the contents
4893 /// of the annotation pointer.
4894 void RestoreNestedNameSpecifierAnnotation(void *Annotation,
4895 SourceRange AnnotationRange,
4898 bool ShouldEnterDeclaratorScope(Scope *S, const CXXScopeSpec &SS);
4900 /// ActOnCXXEnterDeclaratorScope - Called when a C++ scope specifier (global
4901 /// scope or nested-name-specifier) is parsed, part of a declarator-id.
4902 /// After this method is called, according to [C++ 3.4.3p3], names should be
4903 /// looked up in the declarator-id's scope, until the declarator is parsed and
4904 /// ActOnCXXExitDeclaratorScope is called.
4905 /// The 'SS' should be a non-empty valid CXXScopeSpec.
4906 bool ActOnCXXEnterDeclaratorScope(Scope *S, CXXScopeSpec &SS);
4908 /// ActOnCXXExitDeclaratorScope - Called when a declarator that previously
4909 /// invoked ActOnCXXEnterDeclaratorScope(), is finished. 'SS' is the same
4910 /// CXXScopeSpec that was passed to ActOnCXXEnterDeclaratorScope as well.
4911 /// Used to indicate that names should revert to being looked up in the
4913 void ActOnCXXExitDeclaratorScope(Scope *S, const CXXScopeSpec &SS);
4915 /// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse an
4916 /// initializer for the declaration 'Dcl'.
4917 /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
4918 /// static data member of class X, names should be looked up in the scope of
4920 void ActOnCXXEnterDeclInitializer(Scope *S, Decl *Dcl);
4922 /// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
4923 /// initializer for the declaration 'Dcl'.
4924 void ActOnCXXExitDeclInitializer(Scope *S, Decl *Dcl);
4926 /// \brief Create a new lambda closure type.
4927 CXXRecordDecl *createLambdaClosureType(SourceRange IntroducerRange,
4928 TypeSourceInfo *Info,
4929 bool KnownDependent,
4930 LambdaCaptureDefault CaptureDefault);
4932 /// \brief Start the definition of a lambda expression.
4933 CXXMethodDecl *startLambdaDefinition(CXXRecordDecl *Class,
4934 SourceRange IntroducerRange,
4935 TypeSourceInfo *MethodType,
4936 SourceLocation EndLoc,
4937 ArrayRef<ParmVarDecl *> Params);
4939 /// \brief Endow the lambda scope info with the relevant properties.
4940 void buildLambdaScope(sema::LambdaScopeInfo *LSI,
4941 CXXMethodDecl *CallOperator,
4942 SourceRange IntroducerRange,
4943 LambdaCaptureDefault CaptureDefault,
4944 SourceLocation CaptureDefaultLoc,
4945 bool ExplicitParams,
4946 bool ExplicitResultType,
4949 /// \brief Perform initialization analysis of the init-capture and perform
4950 /// any implicit conversions such as an lvalue-to-rvalue conversion if
4951 /// not being used to initialize a reference.
4952 QualType performLambdaInitCaptureInitialization(SourceLocation Loc,
4953 bool ByRef, IdentifierInfo *Id, Expr *&Init);
4954 /// \brief Create a dummy variable within the declcontext of the lambda's
4955 /// call operator, for name lookup purposes for a lambda init capture.
4957 /// CodeGen handles emission of lambda captures, ignoring these dummy
4958 /// variables appropriately.
4959 VarDecl *createLambdaInitCaptureVarDecl(SourceLocation Loc,
4960 QualType InitCaptureType, IdentifierInfo *Id, Expr *Init);
4962 /// \brief Build the implicit field for an init-capture.
4963 FieldDecl *buildInitCaptureField(sema::LambdaScopeInfo *LSI, VarDecl *Var);
4965 /// \brief Note that we have finished the explicit captures for the
4967 void finishLambdaExplicitCaptures(sema::LambdaScopeInfo *LSI);
4969 /// \brief Introduce the lambda parameters into scope.
4970 void addLambdaParameters(CXXMethodDecl *CallOperator, Scope *CurScope);
4972 /// \brief Deduce a block or lambda's return type based on the return
4973 /// statements present in the body.
4974 void deduceClosureReturnType(sema::CapturingScopeInfo &CSI);
4976 /// ActOnStartOfLambdaDefinition - This is called just before we start
4977 /// parsing the body of a lambda; it analyzes the explicit captures and
4978 /// arguments, and sets up various data-structures for the body of the
4980 void ActOnStartOfLambdaDefinition(LambdaIntroducer &Intro,
4981 Declarator &ParamInfo, Scope *CurScope);
4983 /// ActOnLambdaError - If there is an error parsing a lambda, this callback
4984 /// is invoked to pop the information about the lambda.
4985 void ActOnLambdaError(SourceLocation StartLoc, Scope *CurScope,
4986 bool IsInstantiation = false);
4988 /// ActOnLambdaExpr - This is called when the body of a lambda expression
4989 /// was successfully completed.
4990 ExprResult ActOnLambdaExpr(SourceLocation StartLoc, Stmt *Body,
4993 /// \brief Complete a lambda-expression having processed and attached the
4995 ExprResult BuildLambdaExpr(SourceLocation StartLoc, SourceLocation EndLoc,
4996 sema::LambdaScopeInfo *LSI);
4998 /// \brief Define the "body" of the conversion from a lambda object to a
4999 /// function pointer.
5001 /// This routine doesn't actually define a sensible body; rather, it fills
5002 /// in the initialization expression needed to copy the lambda object into
5003 /// the block, and IR generation actually generates the real body of the
5004 /// block pointer conversion.
5005 void DefineImplicitLambdaToFunctionPointerConversion(
5006 SourceLocation CurrentLoc, CXXConversionDecl *Conv);
5008 /// \brief Define the "body" of the conversion from a lambda object to a
5011 /// This routine doesn't actually define a sensible body; rather, it fills
5012 /// in the initialization expression needed to copy the lambda object into
5013 /// the block, and IR generation actually generates the real body of the
5014 /// block pointer conversion.
5015 void DefineImplicitLambdaToBlockPointerConversion(SourceLocation CurrentLoc,
5016 CXXConversionDecl *Conv);
5018 ExprResult BuildBlockForLambdaConversion(SourceLocation CurrentLocation,
5019 SourceLocation ConvLocation,
5020 CXXConversionDecl *Conv,
5023 // ParseObjCStringLiteral - Parse Objective-C string literals.
5024 ExprResult ParseObjCStringLiteral(SourceLocation *AtLocs,
5026 unsigned NumStrings);
5028 ExprResult BuildObjCStringLiteral(SourceLocation AtLoc, StringLiteral *S);
5030 /// BuildObjCNumericLiteral - builds an ObjCBoxedExpr AST node for the
5031 /// numeric literal expression. Type of the expression will be "NSNumber *"
5032 /// or "id" if NSNumber is unavailable.
5033 ExprResult BuildObjCNumericLiteral(SourceLocation AtLoc, Expr *Number);
5034 ExprResult ActOnObjCBoolLiteral(SourceLocation AtLoc, SourceLocation ValueLoc,
5036 ExprResult BuildObjCArrayLiteral(SourceRange SR, MultiExprArg Elements);
5038 /// BuildObjCBoxedExpr - builds an ObjCBoxedExpr AST node for the
5039 /// '@' prefixed parenthesized expression. The type of the expression will
5040 /// either be "NSNumber *", "NSString *" or "NSValue *" depending on the type
5041 /// of ValueType, which is allowed to be a built-in numeric type, "char *",
5042 /// "const char *" or C structure with attribute 'objc_boxable'.
5043 ExprResult BuildObjCBoxedExpr(SourceRange SR, Expr *ValueExpr);
5045 ExprResult BuildObjCSubscriptExpression(SourceLocation RB, Expr *BaseExpr,
5047 ObjCMethodDecl *getterMethod,
5048 ObjCMethodDecl *setterMethod);
5050 ExprResult BuildObjCDictionaryLiteral(SourceRange SR,
5051 ObjCDictionaryElement *Elements,
5052 unsigned NumElements);
5054 ExprResult BuildObjCEncodeExpression(SourceLocation AtLoc,
5055 TypeSourceInfo *EncodedTypeInfo,
5056 SourceLocation RParenLoc);
5057 ExprResult BuildCXXMemberCallExpr(Expr *Exp, NamedDecl *FoundDecl,
5058 CXXConversionDecl *Method,
5059 bool HadMultipleCandidates);
5061 ExprResult ParseObjCEncodeExpression(SourceLocation AtLoc,
5062 SourceLocation EncodeLoc,
5063 SourceLocation LParenLoc,
5065 SourceLocation RParenLoc);
5067 /// ParseObjCSelectorExpression - Build selector expression for \@selector
5068 ExprResult ParseObjCSelectorExpression(Selector Sel,
5069 SourceLocation AtLoc,
5070 SourceLocation SelLoc,
5071 SourceLocation LParenLoc,
5072 SourceLocation RParenLoc,
5073 bool WarnMultipleSelectors);
5075 /// ParseObjCProtocolExpression - Build protocol expression for \@protocol
5076 ExprResult ParseObjCProtocolExpression(IdentifierInfo * ProtocolName,
5077 SourceLocation AtLoc,
5078 SourceLocation ProtoLoc,
5079 SourceLocation LParenLoc,
5080 SourceLocation ProtoIdLoc,
5081 SourceLocation RParenLoc);
5083 //===--------------------------------------------------------------------===//
5086 Decl *ActOnStartLinkageSpecification(Scope *S,
5087 SourceLocation ExternLoc,
5089 SourceLocation LBraceLoc);
5090 Decl *ActOnFinishLinkageSpecification(Scope *S,
5092 SourceLocation RBraceLoc);
5095 //===--------------------------------------------------------------------===//
5098 bool isCurrentClassName(const IdentifierInfo &II, Scope *S,
5099 const CXXScopeSpec *SS = nullptr);
5100 bool isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS);
5102 bool ActOnAccessSpecifier(AccessSpecifier Access,
5103 SourceLocation ASLoc,
5104 SourceLocation ColonLoc,
5105 AttributeList *Attrs = nullptr);
5107 NamedDecl *ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS,
5109 MultiTemplateParamsArg TemplateParameterLists,
5110 Expr *BitfieldWidth, const VirtSpecifiers &VS,
5111 InClassInitStyle InitStyle);
5113 void ActOnStartCXXInClassMemberInitializer();
5114 void ActOnFinishCXXInClassMemberInitializer(Decl *VarDecl,
5115 SourceLocation EqualLoc,
5118 MemInitResult ActOnMemInitializer(Decl *ConstructorD,
5121 IdentifierInfo *MemberOrBase,
5122 ParsedType TemplateTypeTy,
5124 SourceLocation IdLoc,
5125 SourceLocation LParenLoc,
5126 ArrayRef<Expr *> Args,
5127 SourceLocation RParenLoc,
5128 SourceLocation EllipsisLoc);
5130 MemInitResult ActOnMemInitializer(Decl *ConstructorD,
5133 IdentifierInfo *MemberOrBase,
5134 ParsedType TemplateTypeTy,
5136 SourceLocation IdLoc,
5138 SourceLocation EllipsisLoc);
5140 MemInitResult BuildMemInitializer(Decl *ConstructorD,
5143 IdentifierInfo *MemberOrBase,
5144 ParsedType TemplateTypeTy,
5146 SourceLocation IdLoc,
5148 SourceLocation EllipsisLoc);
5150 MemInitResult BuildMemberInitializer(ValueDecl *Member,
5152 SourceLocation IdLoc);
5154 MemInitResult BuildBaseInitializer(QualType BaseType,
5155 TypeSourceInfo *BaseTInfo,
5157 CXXRecordDecl *ClassDecl,
5158 SourceLocation EllipsisLoc);
5160 MemInitResult BuildDelegatingInitializer(TypeSourceInfo *TInfo,
5162 CXXRecordDecl *ClassDecl);
5164 bool SetDelegatingInitializer(CXXConstructorDecl *Constructor,
5165 CXXCtorInitializer *Initializer);
5167 bool SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
5168 ArrayRef<CXXCtorInitializer *> Initializers = None);
5170 void SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation);
5173 /// MarkBaseAndMemberDestructorsReferenced - Given a record decl,
5174 /// mark all the non-trivial destructors of its members and bases as
5176 void MarkBaseAndMemberDestructorsReferenced(SourceLocation Loc,
5177 CXXRecordDecl *Record);
5179 /// \brief The list of classes whose vtables have been used within
5180 /// this translation unit, and the source locations at which the
5181 /// first use occurred.
5182 typedef std::pair<CXXRecordDecl*, SourceLocation> VTableUse;
5184 /// \brief The list of vtables that are required but have not yet been
5186 SmallVector<VTableUse, 16> VTableUses;
5188 /// \brief The set of classes whose vtables have been used within
5189 /// this translation unit, and a bit that will be true if the vtable is
5190 /// required to be emitted (otherwise, it should be emitted only if needed
5191 /// by code generation).
5192 llvm::DenseMap<CXXRecordDecl *, bool> VTablesUsed;
5194 /// \brief Load any externally-stored vtable uses.
5195 void LoadExternalVTableUses();
5197 /// \brief Note that the vtable for the given class was used at the
5199 void MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
5200 bool DefinitionRequired = false);
5202 /// \brief Mark the exception specifications of all virtual member functions
5203 /// in the given class as needed.
5204 void MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
5205 const CXXRecordDecl *RD);
5207 /// MarkVirtualMembersReferenced - Will mark all members of the given
5208 /// CXXRecordDecl referenced.
5209 void MarkVirtualMembersReferenced(SourceLocation Loc,
5210 const CXXRecordDecl *RD);
5212 /// \brief Define all of the vtables that have been used in this
5213 /// translation unit and reference any virtual members used by those
5216 /// \returns true if any work was done, false otherwise.
5217 bool DefineUsedVTables();
5219 void AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl);
5221 void ActOnMemInitializers(Decl *ConstructorDecl,
5222 SourceLocation ColonLoc,
5223 ArrayRef<CXXCtorInitializer*> MemInits,
5226 void checkClassLevelDLLAttribute(CXXRecordDecl *Class);
5227 void propagateDLLAttrToBaseClassTemplate(
5228 CXXRecordDecl *Class, Attr *ClassAttr,
5229 ClassTemplateSpecializationDecl *BaseTemplateSpec,
5230 SourceLocation BaseLoc);
5231 void CheckCompletedCXXClass(CXXRecordDecl *Record);
5232 void ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
5234 SourceLocation LBrac,
5235 SourceLocation RBrac,
5236 AttributeList *AttrList);
5237 void ActOnFinishCXXMemberDecls();
5238 void ActOnFinishCXXMemberDefaultArgs(Decl *D);
5240 void ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param);
5241 unsigned ActOnReenterTemplateScope(Scope *S, Decl *Template);
5242 void ActOnStartDelayedMemberDeclarations(Scope *S, Decl *Record);
5243 void ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *Method);
5244 void ActOnDelayedCXXMethodParameter(Scope *S, Decl *Param);
5245 void ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *Record);
5246 void ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *Method);
5247 void ActOnFinishDelayedMemberInitializers(Decl *Record);
5248 void MarkAsLateParsedTemplate(FunctionDecl *FD, Decl *FnD,
5249 CachedTokens &Toks);
5250 void UnmarkAsLateParsedTemplate(FunctionDecl *FD);
5251 bool IsInsideALocalClassWithinATemplateFunction();
5253 Decl *ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
5255 Expr *AssertMessageExpr,
5256 SourceLocation RParenLoc);
5257 Decl *BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
5259 StringLiteral *AssertMessageExpr,
5260 SourceLocation RParenLoc,
5263 FriendDecl *CheckFriendTypeDecl(SourceLocation LocStart,
5264 SourceLocation FriendLoc,
5265 TypeSourceInfo *TSInfo);
5266 Decl *ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
5267 MultiTemplateParamsArg TemplateParams);
5268 NamedDecl *ActOnFriendFunctionDecl(Scope *S, Declarator &D,
5269 MultiTemplateParamsArg TemplateParams);
5271 QualType CheckConstructorDeclarator(Declarator &D, QualType R,
5273 void CheckConstructor(CXXConstructorDecl *Constructor);
5274 QualType CheckDestructorDeclarator(Declarator &D, QualType R,
5276 bool CheckDestructor(CXXDestructorDecl *Destructor);
5277 void CheckConversionDeclarator(Declarator &D, QualType &R,
5279 Decl *ActOnConversionDeclarator(CXXConversionDecl *Conversion);
5281 void CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD);
5282 void CheckExplicitlyDefaultedMemberExceptionSpec(CXXMethodDecl *MD,
5283 const FunctionProtoType *T);
5284 void CheckDelayedMemberExceptionSpecs();
5286 //===--------------------------------------------------------------------===//
5287 // C++ Derived Classes
5290 /// ActOnBaseSpecifier - Parsed a base specifier
5291 CXXBaseSpecifier *CheckBaseSpecifier(CXXRecordDecl *Class,
5292 SourceRange SpecifierRange,
5293 bool Virtual, AccessSpecifier Access,
5294 TypeSourceInfo *TInfo,
5295 SourceLocation EllipsisLoc);
5297 BaseResult ActOnBaseSpecifier(Decl *classdecl,
5298 SourceRange SpecifierRange,
5299 ParsedAttributes &Attrs,
5300 bool Virtual, AccessSpecifier Access,
5301 ParsedType basetype,
5302 SourceLocation BaseLoc,
5303 SourceLocation EllipsisLoc);
5305 bool AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
5307 void ActOnBaseSpecifiers(Decl *ClassDecl, CXXBaseSpecifier **Bases,
5310 bool IsDerivedFrom(QualType Derived, QualType Base);
5311 bool IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths);
5313 // FIXME: I don't like this name.
5314 void BuildBasePathArray(const CXXBasePaths &Paths, CXXCastPath &BasePath);
5316 bool CheckDerivedToBaseConversion(QualType Derived, QualType Base,
5317 SourceLocation Loc, SourceRange Range,
5318 CXXCastPath *BasePath = nullptr,
5319 bool IgnoreAccess = false);
5320 bool CheckDerivedToBaseConversion(QualType Derived, QualType Base,
5321 unsigned InaccessibleBaseID,
5322 unsigned AmbigiousBaseConvID,
5323 SourceLocation Loc, SourceRange Range,
5324 DeclarationName Name,
5325 CXXCastPath *BasePath);
5327 std::string getAmbiguousPathsDisplayString(CXXBasePaths &Paths);
5329 bool CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
5330 const CXXMethodDecl *Old);
5332 /// CheckOverridingFunctionReturnType - Checks whether the return types are
5333 /// covariant, according to C++ [class.virtual]p5.
5334 bool CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
5335 const CXXMethodDecl *Old);
5337 /// CheckOverridingFunctionExceptionSpec - Checks whether the exception
5338 /// spec is a subset of base spec.
5339 bool CheckOverridingFunctionExceptionSpec(const CXXMethodDecl *New,
5340 const CXXMethodDecl *Old);
5342 bool CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange);
5344 /// CheckOverrideControl - Check C++11 override control semantics.
5345 void CheckOverrideControl(NamedDecl *D);
5347 /// DiagnoseAbsenceOfOverrideControl - Diagnose if 'override' keyword was
5348 /// not used in the declaration of an overriding method.
5349 void DiagnoseAbsenceOfOverrideControl(NamedDecl *D);
5351 /// CheckForFunctionMarkedFinal - Checks whether a virtual member function
5352 /// overrides a virtual member function marked 'final', according to
5353 /// C++11 [class.virtual]p4.
5354 bool CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
5355 const CXXMethodDecl *Old);
5358 //===--------------------------------------------------------------------===//
5359 // C++ Access Control
5369 bool SetMemberAccessSpecifier(NamedDecl *MemberDecl,
5370 NamedDecl *PrevMemberDecl,
5371 AccessSpecifier LexicalAS);
5373 AccessResult CheckUnresolvedMemberAccess(UnresolvedMemberExpr *E,
5374 DeclAccessPair FoundDecl);
5375 AccessResult CheckUnresolvedLookupAccess(UnresolvedLookupExpr *E,
5376 DeclAccessPair FoundDecl);
5377 AccessResult CheckAllocationAccess(SourceLocation OperatorLoc,
5378 SourceRange PlacementRange,
5379 CXXRecordDecl *NamingClass,
5380 DeclAccessPair FoundDecl,
5381 bool Diagnose = true);
5382 AccessResult CheckConstructorAccess(SourceLocation Loc,
5383 CXXConstructorDecl *D,
5384 const InitializedEntity &Entity,
5385 AccessSpecifier Access,
5386 bool IsCopyBindingRefToTemp = false);
5387 AccessResult CheckConstructorAccess(SourceLocation Loc,
5388 CXXConstructorDecl *D,
5389 const InitializedEntity &Entity,
5390 AccessSpecifier Access,
5391 const PartialDiagnostic &PDiag);
5392 AccessResult CheckDestructorAccess(SourceLocation Loc,
5393 CXXDestructorDecl *Dtor,
5394 const PartialDiagnostic &PDiag,
5395 QualType objectType = QualType());
5396 AccessResult CheckFriendAccess(NamedDecl *D);
5397 AccessResult CheckMemberAccess(SourceLocation UseLoc,
5398 CXXRecordDecl *NamingClass,
5399 DeclAccessPair Found);
5400 AccessResult CheckMemberOperatorAccess(SourceLocation Loc,
5403 DeclAccessPair FoundDecl);
5404 AccessResult CheckAddressOfMemberAccess(Expr *OvlExpr,
5405 DeclAccessPair FoundDecl);
5406 AccessResult CheckBaseClassAccess(SourceLocation AccessLoc,
5407 QualType Base, QualType Derived,
5408 const CXXBasePath &Path,
5410 bool ForceCheck = false,
5411 bool ForceUnprivileged = false);
5412 void CheckLookupAccess(const LookupResult &R);
5413 bool IsSimplyAccessible(NamedDecl *decl, DeclContext *Ctx);
5414 bool isSpecialMemberAccessibleForDeletion(CXXMethodDecl *decl,
5415 AccessSpecifier access,
5416 QualType objectType);
5418 void HandleDependentAccessCheck(const DependentDiagnostic &DD,
5419 const MultiLevelTemplateArgumentList &TemplateArgs);
5420 void PerformDependentDiagnostics(const DeclContext *Pattern,
5421 const MultiLevelTemplateArgumentList &TemplateArgs);
5423 void HandleDelayedAccessCheck(sema::DelayedDiagnostic &DD, Decl *Ctx);
5425 /// \brief When true, access checking violations are treated as SFINAE
5426 /// failures rather than hard errors.
5427 bool AccessCheckingSFINAE;
5429 enum AbstractDiagSelID {
5433 AbstractVariableType,
5436 AbstractSynthesizedIvarType,
5440 bool RequireNonAbstractType(SourceLocation Loc, QualType T,
5441 TypeDiagnoser &Diagnoser);
5442 template <typename... Ts>
5443 bool RequireNonAbstractType(SourceLocation Loc, QualType T, unsigned DiagID,
5444 const Ts &...Args) {
5445 BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
5446 return RequireNonAbstractType(Loc, T, Diagnoser);
5449 void DiagnoseAbstractType(const CXXRecordDecl *RD);
5451 bool RequireNonAbstractType(SourceLocation Loc, QualType T, unsigned DiagID,
5452 AbstractDiagSelID SelID = AbstractNone);
5454 //===--------------------------------------------------------------------===//
5455 // C++ Overloaded Operators [C++ 13.5]
5458 bool CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl);
5460 bool CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl);
5462 //===--------------------------------------------------------------------===//
5463 // C++ Templates [C++ 14]
5465 void FilterAcceptableTemplateNames(LookupResult &R,
5466 bool AllowFunctionTemplates = true);
5467 bool hasAnyAcceptableTemplateNames(LookupResult &R,
5468 bool AllowFunctionTemplates = true);
5470 void LookupTemplateName(LookupResult &R, Scope *S, CXXScopeSpec &SS,
5471 QualType ObjectType, bool EnteringContext,
5472 bool &MemberOfUnknownSpecialization);
5474 TemplateNameKind isTemplateName(Scope *S,
5476 bool hasTemplateKeyword,
5477 UnqualifiedId &Name,
5478 ParsedType ObjectType,
5479 bool EnteringContext,
5480 TemplateTy &Template,
5481 bool &MemberOfUnknownSpecialization);
5483 bool DiagnoseUnknownTemplateName(const IdentifierInfo &II,
5484 SourceLocation IILoc,
5486 const CXXScopeSpec *SS,
5487 TemplateTy &SuggestedTemplate,
5488 TemplateNameKind &SuggestedKind);
5490 void DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl);
5491 TemplateDecl *AdjustDeclIfTemplate(Decl *&Decl);
5493 Decl *ActOnTypeParameter(Scope *S, bool Typename,
5494 SourceLocation EllipsisLoc,
5495 SourceLocation KeyLoc,
5496 IdentifierInfo *ParamName,
5497 SourceLocation ParamNameLoc,
5498 unsigned Depth, unsigned Position,
5499 SourceLocation EqualLoc,
5500 ParsedType DefaultArg);
5502 QualType CheckNonTypeTemplateParameterType(QualType T, SourceLocation Loc);
5503 Decl *ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
5506 SourceLocation EqualLoc,
5508 Decl *ActOnTemplateTemplateParameter(Scope *S,
5509 SourceLocation TmpLoc,
5510 TemplateParameterList *Params,
5511 SourceLocation EllipsisLoc,
5512 IdentifierInfo *ParamName,
5513 SourceLocation ParamNameLoc,
5516 SourceLocation EqualLoc,
5517 ParsedTemplateArgument DefaultArg);
5519 TemplateParameterList *
5520 ActOnTemplateParameterList(unsigned Depth,
5521 SourceLocation ExportLoc,
5522 SourceLocation TemplateLoc,
5523 SourceLocation LAngleLoc,
5524 Decl **Params, unsigned NumParams,
5525 SourceLocation RAngleLoc);
5527 /// \brief The context in which we are checking a template parameter list.
5528 enum TemplateParamListContext {
5531 TPC_FunctionTemplate,
5532 TPC_ClassTemplateMember,
5533 TPC_FriendClassTemplate,
5534 TPC_FriendFunctionTemplate,
5535 TPC_FriendFunctionTemplateDefinition,
5536 TPC_TypeAliasTemplate
5539 bool CheckTemplateParameterList(TemplateParameterList *NewParams,
5540 TemplateParameterList *OldParams,
5541 TemplateParamListContext TPC);
5542 TemplateParameterList *MatchTemplateParametersToScopeSpecifier(
5543 SourceLocation DeclStartLoc, SourceLocation DeclLoc,
5544 const CXXScopeSpec &SS, TemplateIdAnnotation *TemplateId,
5545 ArrayRef<TemplateParameterList *> ParamLists,
5546 bool IsFriend, bool &IsExplicitSpecialization, bool &Invalid);
5548 DeclResult CheckClassTemplate(Scope *S, unsigned TagSpec, TagUseKind TUK,
5549 SourceLocation KWLoc, CXXScopeSpec &SS,
5550 IdentifierInfo *Name, SourceLocation NameLoc,
5551 AttributeList *Attr,
5552 TemplateParameterList *TemplateParams,
5554 SourceLocation ModulePrivateLoc,
5555 SourceLocation FriendLoc,
5556 unsigned NumOuterTemplateParamLists,
5557 TemplateParameterList **OuterTemplateParamLists,
5558 SkipBodyInfo *SkipBody = nullptr);
5560 void translateTemplateArguments(const ASTTemplateArgsPtr &In,
5561 TemplateArgumentListInfo &Out);
5563 void NoteAllFoundTemplates(TemplateName Name);
5565 QualType CheckTemplateIdType(TemplateName Template,
5566 SourceLocation TemplateLoc,
5567 TemplateArgumentListInfo &TemplateArgs);
5570 ActOnTemplateIdType(CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
5571 TemplateTy Template, SourceLocation TemplateLoc,
5572 SourceLocation LAngleLoc,
5573 ASTTemplateArgsPtr TemplateArgs,
5574 SourceLocation RAngleLoc,
5575 bool IsCtorOrDtorName = false);
5577 /// \brief Parsed an elaborated-type-specifier that refers to a template-id,
5578 /// such as \c class T::template apply<U>.
5579 TypeResult ActOnTagTemplateIdType(TagUseKind TUK,
5580 TypeSpecifierType TagSpec,
5581 SourceLocation TagLoc,
5583 SourceLocation TemplateKWLoc,
5584 TemplateTy TemplateD,
5585 SourceLocation TemplateLoc,
5586 SourceLocation LAngleLoc,
5587 ASTTemplateArgsPtr TemplateArgsIn,
5588 SourceLocation RAngleLoc);
5590 DeclResult ActOnVarTemplateSpecialization(
5591 Scope *S, Declarator &D, TypeSourceInfo *DI,
5592 SourceLocation TemplateKWLoc, TemplateParameterList *TemplateParams,
5593 StorageClass SC, bool IsPartialSpecialization);
5595 DeclResult CheckVarTemplateId(VarTemplateDecl *Template,
5596 SourceLocation TemplateLoc,
5597 SourceLocation TemplateNameLoc,
5598 const TemplateArgumentListInfo &TemplateArgs);
5600 ExprResult CheckVarTemplateId(const CXXScopeSpec &SS,
5601 const DeclarationNameInfo &NameInfo,
5602 VarTemplateDecl *Template,
5603 SourceLocation TemplateLoc,
5604 const TemplateArgumentListInfo *TemplateArgs);
5606 ExprResult BuildTemplateIdExpr(const CXXScopeSpec &SS,
5607 SourceLocation TemplateKWLoc,
5610 const TemplateArgumentListInfo *TemplateArgs);
5612 ExprResult BuildQualifiedTemplateIdExpr(CXXScopeSpec &SS,
5613 SourceLocation TemplateKWLoc,
5614 const DeclarationNameInfo &NameInfo,
5615 const TemplateArgumentListInfo *TemplateArgs);
5617 TemplateNameKind ActOnDependentTemplateName(Scope *S,
5619 SourceLocation TemplateKWLoc,
5620 UnqualifiedId &Name,
5621 ParsedType ObjectType,
5622 bool EnteringContext,
5623 TemplateTy &Template);
5626 ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec, TagUseKind TUK,
5627 SourceLocation KWLoc,
5628 SourceLocation ModulePrivateLoc,
5629 TemplateIdAnnotation &TemplateId,
5630 AttributeList *Attr,
5631 MultiTemplateParamsArg TemplateParameterLists,
5632 SkipBodyInfo *SkipBody = nullptr);
5634 Decl *ActOnTemplateDeclarator(Scope *S,
5635 MultiTemplateParamsArg TemplateParameterLists,
5638 Decl *ActOnStartOfFunctionTemplateDef(Scope *FnBodyScope,
5639 MultiTemplateParamsArg TemplateParameterLists,
5643 CheckSpecializationInstantiationRedecl(SourceLocation NewLoc,
5644 TemplateSpecializationKind NewTSK,
5645 NamedDecl *PrevDecl,
5646 TemplateSpecializationKind PrevTSK,
5647 SourceLocation PrevPtOfInstantiation,
5650 bool CheckDependentFunctionTemplateSpecialization(FunctionDecl *FD,
5651 const TemplateArgumentListInfo &ExplicitTemplateArgs,
5652 LookupResult &Previous);
5654 bool CheckFunctionTemplateSpecialization(FunctionDecl *FD,
5655 TemplateArgumentListInfo *ExplicitTemplateArgs,
5656 LookupResult &Previous);
5657 bool CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous);
5660 ActOnExplicitInstantiation(Scope *S,
5661 SourceLocation ExternLoc,
5662 SourceLocation TemplateLoc,
5664 SourceLocation KWLoc,
5665 const CXXScopeSpec &SS,
5666 TemplateTy Template,
5667 SourceLocation TemplateNameLoc,
5668 SourceLocation LAngleLoc,
5669 ASTTemplateArgsPtr TemplateArgs,
5670 SourceLocation RAngleLoc,
5671 AttributeList *Attr);
5674 ActOnExplicitInstantiation(Scope *S,
5675 SourceLocation ExternLoc,
5676 SourceLocation TemplateLoc,
5678 SourceLocation KWLoc,
5680 IdentifierInfo *Name,
5681 SourceLocation NameLoc,
5682 AttributeList *Attr);
5684 DeclResult ActOnExplicitInstantiation(Scope *S,
5685 SourceLocation ExternLoc,
5686 SourceLocation TemplateLoc,
5690 SubstDefaultTemplateArgumentIfAvailable(TemplateDecl *Template,
5691 SourceLocation TemplateLoc,
5692 SourceLocation RAngleLoc,
5694 SmallVectorImpl<TemplateArgument>
5696 bool &HasDefaultArg);
5698 /// \brief Specifies the context in which a particular template
5699 /// argument is being checked.
5700 enum CheckTemplateArgumentKind {
5701 /// \brief The template argument was specified in the code or was
5702 /// instantiated with some deduced template arguments.
5705 /// \brief The template argument was deduced via template argument
5709 /// \brief The template argument was deduced from an array bound
5710 /// via template argument deduction.
5711 CTAK_DeducedFromArrayBound
5714 bool CheckTemplateArgument(NamedDecl *Param,
5715 TemplateArgumentLoc &Arg,
5716 NamedDecl *Template,
5717 SourceLocation TemplateLoc,
5718 SourceLocation RAngleLoc,
5719 unsigned ArgumentPackIndex,
5720 SmallVectorImpl<TemplateArgument> &Converted,
5721 CheckTemplateArgumentKind CTAK = CTAK_Specified);
5723 /// \brief Check that the given template arguments can be be provided to
5724 /// the given template, converting the arguments along the way.
5726 /// \param Template The template to which the template arguments are being
5729 /// \param TemplateLoc The location of the template name in the source.
5731 /// \param TemplateArgs The list of template arguments. If the template is
5732 /// a template template parameter, this function may extend the set of
5733 /// template arguments to also include substituted, defaulted template
5736 /// \param PartialTemplateArgs True if the list of template arguments is
5737 /// intentionally partial, e.g., because we're checking just the initial
5738 /// set of template arguments.
5740 /// \param Converted Will receive the converted, canonicalized template
5743 /// \returns true if an error occurred, false otherwise.
5744 bool CheckTemplateArgumentList(TemplateDecl *Template,
5745 SourceLocation TemplateLoc,
5746 TemplateArgumentListInfo &TemplateArgs,
5747 bool PartialTemplateArgs,
5748 SmallVectorImpl<TemplateArgument> &Converted);
5750 bool CheckTemplateTypeArgument(TemplateTypeParmDecl *Param,
5751 TemplateArgumentLoc &Arg,
5752 SmallVectorImpl<TemplateArgument> &Converted);
5754 bool CheckTemplateArgument(TemplateTypeParmDecl *Param,
5755 TypeSourceInfo *Arg);
5756 ExprResult CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
5757 QualType InstantiatedParamType, Expr *Arg,
5758 TemplateArgument &Converted,
5759 CheckTemplateArgumentKind CTAK = CTAK_Specified);
5760 bool CheckTemplateArgument(TemplateTemplateParmDecl *Param,
5761 TemplateArgumentLoc &Arg,
5762 unsigned ArgumentPackIndex);
5765 BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg,
5767 SourceLocation Loc);
5769 BuildExpressionFromIntegralTemplateArgument(const TemplateArgument &Arg,
5770 SourceLocation Loc);
5772 /// \brief Enumeration describing how template parameter lists are compared
5774 enum TemplateParameterListEqualKind {
5775 /// \brief We are matching the template parameter lists of two templates
5776 /// that might be redeclarations.
5779 /// template<typename T> struct X;
5780 /// template<typename T> struct X;
5784 /// \brief We are matching the template parameter lists of two template
5785 /// template parameters as part of matching the template parameter lists
5786 /// of two templates that might be redeclarations.
5789 /// template<template<int I> class TT> struct X;
5790 /// template<template<int Value> class Other> struct X;
5792 TPL_TemplateTemplateParmMatch,
5794 /// \brief We are matching the template parameter lists of a template
5795 /// template argument against the template parameter lists of a template
5796 /// template parameter.
5799 /// template<template<int Value> class Metafun> struct X;
5800 /// template<int Value> struct integer_c;
5801 /// X<integer_c> xic;
5803 TPL_TemplateTemplateArgumentMatch
5806 bool TemplateParameterListsAreEqual(TemplateParameterList *New,
5807 TemplateParameterList *Old,
5809 TemplateParameterListEqualKind Kind,
5810 SourceLocation TemplateArgLoc
5811 = SourceLocation());
5813 bool CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams);
5815 /// \brief Called when the parser has parsed a C++ typename
5816 /// specifier, e.g., "typename T::type".
5818 /// \param S The scope in which this typename type occurs.
5819 /// \param TypenameLoc the location of the 'typename' keyword
5820 /// \param SS the nested-name-specifier following the typename (e.g., 'T::').
5821 /// \param II the identifier we're retrieving (e.g., 'type' in the example).
5822 /// \param IdLoc the location of the identifier.
5824 ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
5825 const CXXScopeSpec &SS, const IdentifierInfo &II,
5826 SourceLocation IdLoc);
5828 /// \brief Called when the parser has parsed a C++ typename
5829 /// specifier that ends in a template-id, e.g.,
5830 /// "typename MetaFun::template apply<T1, T2>".
5832 /// \param S The scope in which this typename type occurs.
5833 /// \param TypenameLoc the location of the 'typename' keyword
5834 /// \param SS the nested-name-specifier following the typename (e.g., 'T::').
5835 /// \param TemplateLoc the location of the 'template' keyword, if any.
5836 /// \param TemplateName The template name.
5837 /// \param TemplateNameLoc The location of the template name.
5838 /// \param LAngleLoc The location of the opening angle bracket ('<').
5839 /// \param TemplateArgs The template arguments.
5840 /// \param RAngleLoc The location of the closing angle bracket ('>').
5842 ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
5843 const CXXScopeSpec &SS,
5844 SourceLocation TemplateLoc,
5845 TemplateTy TemplateName,
5846 SourceLocation TemplateNameLoc,
5847 SourceLocation LAngleLoc,
5848 ASTTemplateArgsPtr TemplateArgs,
5849 SourceLocation RAngleLoc);
5851 QualType CheckTypenameType(ElaboratedTypeKeyword Keyword,
5852 SourceLocation KeywordLoc,
5853 NestedNameSpecifierLoc QualifierLoc,
5854 const IdentifierInfo &II,
5855 SourceLocation IILoc);
5857 TypeSourceInfo *RebuildTypeInCurrentInstantiation(TypeSourceInfo *T,
5859 DeclarationName Name);
5860 bool RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS);
5862 ExprResult RebuildExprInCurrentInstantiation(Expr *E);
5863 bool RebuildTemplateParamsInCurrentInstantiation(
5864 TemplateParameterList *Params);
5867 getTemplateArgumentBindingsText(const TemplateParameterList *Params,
5868 const TemplateArgumentList &Args);
5871 getTemplateArgumentBindingsText(const TemplateParameterList *Params,
5872 const TemplateArgument *Args,
5875 //===--------------------------------------------------------------------===//
5876 // C++ Variadic Templates (C++0x [temp.variadic])
5877 //===--------------------------------------------------------------------===//
5879 /// Determine whether an unexpanded parameter pack might be permitted in this
5880 /// location. Useful for error recovery.
5881 bool isUnexpandedParameterPackPermitted();
5883 /// \brief The context in which an unexpanded parameter pack is
5884 /// being diagnosed.
5886 /// Note that the values of this enumeration line up with the first
5887 /// argument to the \c err_unexpanded_parameter_pack diagnostic.
5888 enum UnexpandedParameterPackContext {
5889 /// \brief An arbitrary expression.
5890 UPPC_Expression = 0,
5892 /// \brief The base type of a class type.
5895 /// \brief The type of an arbitrary declaration.
5896 UPPC_DeclarationType,
5898 /// \brief The type of a data member.
5899 UPPC_DataMemberType,
5901 /// \brief The size of a bit-field.
5904 /// \brief The expression in a static assertion.
5905 UPPC_StaticAssertExpression,
5907 /// \brief The fixed underlying type of an enumeration.
5908 UPPC_FixedUnderlyingType,
5910 /// \brief The enumerator value.
5911 UPPC_EnumeratorValue,
5913 /// \brief A using declaration.
5914 UPPC_UsingDeclaration,
5916 /// \brief A friend declaration.
5917 UPPC_FriendDeclaration,
5919 /// \brief A declaration qualifier.
5920 UPPC_DeclarationQualifier,
5922 /// \brief An initializer.
5925 /// \brief A default argument.
5926 UPPC_DefaultArgument,
5928 /// \brief The type of a non-type template parameter.
5929 UPPC_NonTypeTemplateParameterType,
5931 /// \brief The type of an exception.
5934 /// \brief Partial specialization.
5935 UPPC_PartialSpecialization,
5937 /// \brief Microsoft __if_exists.
5940 /// \brief Microsoft __if_not_exists.
5943 /// \brief Lambda expression.
5946 /// \brief Block expression,
5950 /// \brief Diagnose unexpanded parameter packs.
5952 /// \param Loc The location at which we should emit the diagnostic.
5954 /// \param UPPC The context in which we are diagnosing unexpanded
5955 /// parameter packs.
5957 /// \param Unexpanded the set of unexpanded parameter packs.
5959 /// \returns true if an error occurred, false otherwise.
5960 bool DiagnoseUnexpandedParameterPacks(SourceLocation Loc,
5961 UnexpandedParameterPackContext UPPC,
5962 ArrayRef<UnexpandedParameterPack> Unexpanded);
5964 /// \brief If the given type contains an unexpanded parameter pack,
5965 /// diagnose the error.
5967 /// \param Loc The source location where a diagnostc should be emitted.
5969 /// \param T The type that is being checked for unexpanded parameter
5972 /// \returns true if an error occurred, false otherwise.
5973 bool DiagnoseUnexpandedParameterPack(SourceLocation Loc, TypeSourceInfo *T,
5974 UnexpandedParameterPackContext UPPC);
5976 /// \brief If the given expression contains an unexpanded parameter
5977 /// pack, diagnose the error.
5979 /// \param E The expression that is being checked for unexpanded
5980 /// parameter packs.
5982 /// \returns true if an error occurred, false otherwise.
5983 bool DiagnoseUnexpandedParameterPack(Expr *E,
5984 UnexpandedParameterPackContext UPPC = UPPC_Expression);
5986 /// \brief If the given nested-name-specifier contains an unexpanded
5987 /// parameter pack, diagnose the error.
5989 /// \param SS The nested-name-specifier that is being checked for
5990 /// unexpanded parameter packs.
5992 /// \returns true if an error occurred, false otherwise.
5993 bool DiagnoseUnexpandedParameterPack(const CXXScopeSpec &SS,
5994 UnexpandedParameterPackContext UPPC);
5996 /// \brief If the given name contains an unexpanded parameter pack,
5997 /// diagnose the error.
5999 /// \param NameInfo The name (with source location information) that
6000 /// is being checked for unexpanded parameter packs.
6002 /// \returns true if an error occurred, false otherwise.
6003 bool DiagnoseUnexpandedParameterPack(const DeclarationNameInfo &NameInfo,
6004 UnexpandedParameterPackContext UPPC);
6006 /// \brief If the given template name contains an unexpanded parameter pack,
6007 /// diagnose the error.
6009 /// \param Loc The location of the template name.
6011 /// \param Template The template name that is being checked for unexpanded
6012 /// parameter packs.
6014 /// \returns true if an error occurred, false otherwise.
6015 bool DiagnoseUnexpandedParameterPack(SourceLocation Loc,
6016 TemplateName Template,
6017 UnexpandedParameterPackContext UPPC);
6019 /// \brief If the given template argument contains an unexpanded parameter
6020 /// pack, diagnose the error.
6022 /// \param Arg The template argument that is being checked for unexpanded
6023 /// parameter packs.
6025 /// \returns true if an error occurred, false otherwise.
6026 bool DiagnoseUnexpandedParameterPack(TemplateArgumentLoc Arg,
6027 UnexpandedParameterPackContext UPPC);
6029 /// \brief Collect the set of unexpanded parameter packs within the given
6030 /// template argument.
6032 /// \param Arg The template argument that will be traversed to find
6033 /// unexpanded parameter packs.
6034 void collectUnexpandedParameterPacks(TemplateArgument Arg,
6035 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
6037 /// \brief Collect the set of unexpanded parameter packs within the given
6038 /// template argument.
6040 /// \param Arg The template argument that will be traversed to find
6041 /// unexpanded parameter packs.
6042 void collectUnexpandedParameterPacks(TemplateArgumentLoc Arg,
6043 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
6045 /// \brief Collect the set of unexpanded parameter packs within the given
6048 /// \param T The type that will be traversed to find
6049 /// unexpanded parameter packs.
6050 void collectUnexpandedParameterPacks(QualType T,
6051 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
6053 /// \brief Collect the set of unexpanded parameter packs within the given
6056 /// \param TL The type that will be traversed to find
6057 /// unexpanded parameter packs.
6058 void collectUnexpandedParameterPacks(TypeLoc TL,
6059 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
6061 /// \brief Collect the set of unexpanded parameter packs within the given
6062 /// nested-name-specifier.
6064 /// \param SS The nested-name-specifier that will be traversed to find
6065 /// unexpanded parameter packs.
6066 void collectUnexpandedParameterPacks(CXXScopeSpec &SS,
6067 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
6069 /// \brief Collect the set of unexpanded parameter packs within the given
6072 /// \param NameInfo The name that will be traversed to find
6073 /// unexpanded parameter packs.
6074 void collectUnexpandedParameterPacks(const DeclarationNameInfo &NameInfo,
6075 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
6077 /// \brief Invoked when parsing a template argument followed by an
6078 /// ellipsis, which creates a pack expansion.
6080 /// \param Arg The template argument preceding the ellipsis, which
6081 /// may already be invalid.
6083 /// \param EllipsisLoc The location of the ellipsis.
6084 ParsedTemplateArgument ActOnPackExpansion(const ParsedTemplateArgument &Arg,
6085 SourceLocation EllipsisLoc);
6087 /// \brief Invoked when parsing a type followed by an ellipsis, which
6088 /// creates a pack expansion.
6090 /// \param Type The type preceding the ellipsis, which will become
6091 /// the pattern of the pack expansion.
6093 /// \param EllipsisLoc The location of the ellipsis.
6094 TypeResult ActOnPackExpansion(ParsedType Type, SourceLocation EllipsisLoc);
6096 /// \brief Construct a pack expansion type from the pattern of the pack
6098 TypeSourceInfo *CheckPackExpansion(TypeSourceInfo *Pattern,
6099 SourceLocation EllipsisLoc,
6100 Optional<unsigned> NumExpansions);
6102 /// \brief Construct a pack expansion type from the pattern of the pack
6104 QualType CheckPackExpansion(QualType Pattern,
6105 SourceRange PatternRange,
6106 SourceLocation EllipsisLoc,
6107 Optional<unsigned> NumExpansions);
6109 /// \brief Invoked when parsing an expression followed by an ellipsis, which
6110 /// creates a pack expansion.
6112 /// \param Pattern The expression preceding the ellipsis, which will become
6113 /// the pattern of the pack expansion.
6115 /// \param EllipsisLoc The location of the ellipsis.
6116 ExprResult ActOnPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc);
6118 /// \brief Invoked when parsing an expression followed by an ellipsis, which
6119 /// creates a pack expansion.
6121 /// \param Pattern The expression preceding the ellipsis, which will become
6122 /// the pattern of the pack expansion.
6124 /// \param EllipsisLoc The location of the ellipsis.
6125 ExprResult CheckPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc,
6126 Optional<unsigned> NumExpansions);
6128 /// \brief Determine whether we could expand a pack expansion with the
6129 /// given set of parameter packs into separate arguments by repeatedly
6130 /// transforming the pattern.
6132 /// \param EllipsisLoc The location of the ellipsis that identifies the
6135 /// \param PatternRange The source range that covers the entire pattern of
6136 /// the pack expansion.
6138 /// \param Unexpanded The set of unexpanded parameter packs within the
6141 /// \param ShouldExpand Will be set to \c true if the transformer should
6142 /// expand the corresponding pack expansions into separate arguments. When
6143 /// set, \c NumExpansions must also be set.
6145 /// \param RetainExpansion Whether the caller should add an unexpanded
6146 /// pack expansion after all of the expanded arguments. This is used
6147 /// when extending explicitly-specified template argument packs per
6148 /// C++0x [temp.arg.explicit]p9.
6150 /// \param NumExpansions The number of separate arguments that will be in
6151 /// the expanded form of the corresponding pack expansion. This is both an
6152 /// input and an output parameter, which can be set by the caller if the
6153 /// number of expansions is known a priori (e.g., due to a prior substitution)
6154 /// and will be set by the callee when the number of expansions is known.
6155 /// The callee must set this value when \c ShouldExpand is \c true; it may
6156 /// set this value in other cases.
6158 /// \returns true if an error occurred (e.g., because the parameter packs
6159 /// are to be instantiated with arguments of different lengths), false
6160 /// otherwise. If false, \c ShouldExpand (and possibly \c NumExpansions)
6162 bool CheckParameterPacksForExpansion(SourceLocation EllipsisLoc,
6163 SourceRange PatternRange,
6164 ArrayRef<UnexpandedParameterPack> Unexpanded,
6165 const MultiLevelTemplateArgumentList &TemplateArgs,
6167 bool &RetainExpansion,
6168 Optional<unsigned> &NumExpansions);
6170 /// \brief Determine the number of arguments in the given pack expansion
6173 /// This routine assumes that the number of arguments in the expansion is
6174 /// consistent across all of the unexpanded parameter packs in its pattern.
6176 /// Returns an empty Optional if the type can't be expanded.
6177 Optional<unsigned> getNumArgumentsInExpansion(QualType T,
6178 const MultiLevelTemplateArgumentList &TemplateArgs);
6180 /// \brief Determine whether the given declarator contains any unexpanded
6181 /// parameter packs.
6183 /// This routine is used by the parser to disambiguate function declarators
6184 /// with an ellipsis prior to the ')', e.g.,
6190 /// To determine whether we have an (unnamed) function parameter pack or
6191 /// a variadic function.
6193 /// \returns true if the declarator contains any unexpanded parameter packs,
6194 /// false otherwise.
6195 bool containsUnexpandedParameterPacks(Declarator &D);
6197 /// \brief Returns the pattern of the pack expansion for a template argument.
6199 /// \param OrigLoc The template argument to expand.
6201 /// \param Ellipsis Will be set to the location of the ellipsis.
6203 /// \param NumExpansions Will be set to the number of expansions that will
6204 /// be generated from this pack expansion, if known a priori.
6205 TemplateArgumentLoc getTemplateArgumentPackExpansionPattern(
6206 TemplateArgumentLoc OrigLoc,
6207 SourceLocation &Ellipsis,
6208 Optional<unsigned> &NumExpansions) const;
6210 //===--------------------------------------------------------------------===//
6211 // C++ Template Argument Deduction (C++ [temp.deduct])
6212 //===--------------------------------------------------------------------===//
6214 QualType adjustCCAndNoReturn(QualType ArgFunctionType, QualType FunctionType);
6216 /// \brief Describes the result of template argument deduction.
6218 /// The TemplateDeductionResult enumeration describes the result of
6219 /// template argument deduction, as returned from
6220 /// DeduceTemplateArguments(). The separate TemplateDeductionInfo
6221 /// structure provides additional information about the results of
6222 /// template argument deduction, e.g., the deduced template argument
6223 /// list (if successful) or the specific template parameters or
6224 /// deduced arguments that were involved in the failure.
6225 enum TemplateDeductionResult {
6226 /// \brief Template argument deduction was successful.
6228 /// \brief The declaration was invalid; do nothing.
6230 /// \brief Template argument deduction exceeded the maximum template
6231 /// instantiation depth (which has already been diagnosed).
6232 TDK_InstantiationDepth,
6233 /// \brief Template argument deduction did not deduce a value
6234 /// for every template parameter.
6236 /// \brief Template argument deduction produced inconsistent
6237 /// deduced values for the given template parameter.
6239 /// \brief Template argument deduction failed due to inconsistent
6240 /// cv-qualifiers on a template parameter type that would
6241 /// otherwise be deduced, e.g., we tried to deduce T in "const T"
6242 /// but were given a non-const "X".
6244 /// \brief Substitution of the deduced template argument values
6245 /// resulted in an error.
6246 TDK_SubstitutionFailure,
6247 /// \brief A non-depnedent component of the parameter did not match the
6248 /// corresponding component of the argument.
6249 TDK_NonDeducedMismatch,
6250 /// \brief When performing template argument deduction for a function
6251 /// template, there were too many call arguments.
6252 TDK_TooManyArguments,
6253 /// \brief When performing template argument deduction for a function
6254 /// template, there were too few call arguments.
6255 TDK_TooFewArguments,
6256 /// \brief The explicitly-specified template arguments were not valid
6257 /// template arguments for the given template.
6258 TDK_InvalidExplicitArguments,
6259 /// \brief The arguments included an overloaded function name that could
6260 /// not be resolved to a suitable function.
6261 TDK_FailedOverloadResolution,
6262 /// \brief Deduction failed; that's all we know.
6263 TDK_MiscellaneousDeductionFailure
6266 TemplateDeductionResult
6267 DeduceTemplateArguments(ClassTemplatePartialSpecializationDecl *Partial,
6268 const TemplateArgumentList &TemplateArgs,
6269 sema::TemplateDeductionInfo &Info);
6271 TemplateDeductionResult
6272 DeduceTemplateArguments(VarTemplatePartialSpecializationDecl *Partial,
6273 const TemplateArgumentList &TemplateArgs,
6274 sema::TemplateDeductionInfo &Info);
6276 TemplateDeductionResult SubstituteExplicitTemplateArguments(
6277 FunctionTemplateDecl *FunctionTemplate,
6278 TemplateArgumentListInfo &ExplicitTemplateArgs,
6279 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
6280 SmallVectorImpl<QualType> &ParamTypes, QualType *FunctionType,
6281 sema::TemplateDeductionInfo &Info);
6283 /// brief A function argument from which we performed template argument
6284 // deduction for a call.
6285 struct OriginalCallArg {
6286 OriginalCallArg(QualType OriginalParamType,
6288 QualType OriginalArgType)
6289 : OriginalParamType(OriginalParamType), ArgIdx(ArgIdx),
6290 OriginalArgType(OriginalArgType) { }
6292 QualType OriginalParamType;
6294 QualType OriginalArgType;
6297 TemplateDeductionResult
6298 FinishTemplateArgumentDeduction(FunctionTemplateDecl *FunctionTemplate,
6299 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
6300 unsigned NumExplicitlySpecified,
6301 FunctionDecl *&Specialization,
6302 sema::TemplateDeductionInfo &Info,
6303 SmallVectorImpl<OriginalCallArg> const *OriginalCallArgs = nullptr,
6304 bool PartialOverloading = false);
6306 TemplateDeductionResult
6307 DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
6308 TemplateArgumentListInfo *ExplicitTemplateArgs,
6309 ArrayRef<Expr *> Args,
6310 FunctionDecl *&Specialization,
6311 sema::TemplateDeductionInfo &Info,
6312 bool PartialOverloading = false);
6314 TemplateDeductionResult
6315 DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
6316 TemplateArgumentListInfo *ExplicitTemplateArgs,
6317 QualType ArgFunctionType,
6318 FunctionDecl *&Specialization,
6319 sema::TemplateDeductionInfo &Info,
6320 bool InOverloadResolution = false);
6322 TemplateDeductionResult
6323 DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
6325 CXXConversionDecl *&Specialization,
6326 sema::TemplateDeductionInfo &Info);
6328 TemplateDeductionResult
6329 DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
6330 TemplateArgumentListInfo *ExplicitTemplateArgs,
6331 FunctionDecl *&Specialization,
6332 sema::TemplateDeductionInfo &Info,
6333 bool InOverloadResolution = false);
6335 /// \brief Substitute Replacement for \p auto in \p TypeWithAuto
6336 QualType SubstAutoType(QualType TypeWithAuto, QualType Replacement);
6337 /// \brief Substitute Replacement for auto in TypeWithAuto
6338 TypeSourceInfo* SubstAutoTypeSourceInfo(TypeSourceInfo *TypeWithAuto,
6339 QualType Replacement);
6341 /// \brief Result type of DeduceAutoType.
6342 enum DeduceAutoResult {
6345 DAR_FailedAlreadyDiagnosed
6348 DeduceAutoResult DeduceAutoType(TypeSourceInfo *AutoType, Expr *&Initializer,
6350 DeduceAutoResult DeduceAutoType(TypeLoc AutoTypeLoc, Expr *&Initializer,
6352 void DiagnoseAutoDeductionFailure(VarDecl *VDecl, Expr *Init);
6353 bool DeduceReturnType(FunctionDecl *FD, SourceLocation Loc,
6354 bool Diagnose = true);
6356 TypeLoc getReturnTypeLoc(FunctionDecl *FD) const;
6358 bool DeduceFunctionTypeFromReturnExpr(FunctionDecl *FD,
6359 SourceLocation ReturnLoc,
6360 Expr *&RetExpr, AutoType *AT);
6362 FunctionTemplateDecl *getMoreSpecializedTemplate(FunctionTemplateDecl *FT1,
6363 FunctionTemplateDecl *FT2,
6365 TemplatePartialOrderingContext TPOC,
6366 unsigned NumCallArguments1,
6367 unsigned NumCallArguments2);
6368 UnresolvedSetIterator
6369 getMostSpecialized(UnresolvedSetIterator SBegin, UnresolvedSetIterator SEnd,
6370 TemplateSpecCandidateSet &FailedCandidates,
6372 const PartialDiagnostic &NoneDiag,
6373 const PartialDiagnostic &AmbigDiag,
6374 const PartialDiagnostic &CandidateDiag,
6375 bool Complain = true, QualType TargetType = QualType());
6377 ClassTemplatePartialSpecializationDecl *
6378 getMoreSpecializedPartialSpecialization(
6379 ClassTemplatePartialSpecializationDecl *PS1,
6380 ClassTemplatePartialSpecializationDecl *PS2,
6381 SourceLocation Loc);
6383 VarTemplatePartialSpecializationDecl *getMoreSpecializedPartialSpecialization(
6384 VarTemplatePartialSpecializationDecl *PS1,
6385 VarTemplatePartialSpecializationDecl *PS2, SourceLocation Loc);
6387 void MarkUsedTemplateParameters(const TemplateArgumentList &TemplateArgs,
6390 llvm::SmallBitVector &Used);
6391 void MarkDeducedTemplateParameters(
6392 const FunctionTemplateDecl *FunctionTemplate,
6393 llvm::SmallBitVector &Deduced) {
6394 return MarkDeducedTemplateParameters(Context, FunctionTemplate, Deduced);
6396 static void MarkDeducedTemplateParameters(ASTContext &Ctx,
6397 const FunctionTemplateDecl *FunctionTemplate,
6398 llvm::SmallBitVector &Deduced);
6400 //===--------------------------------------------------------------------===//
6401 // C++ Template Instantiation
6404 MultiLevelTemplateArgumentList
6405 getTemplateInstantiationArgs(NamedDecl *D,
6406 const TemplateArgumentList *Innermost = nullptr,
6407 bool RelativeToPrimary = false,
6408 const FunctionDecl *Pattern = nullptr);
6410 /// \brief A template instantiation that is currently in progress.
6411 struct ActiveTemplateInstantiation {
6412 /// \brief The kind of template instantiation we are performing
6413 enum InstantiationKind {
6414 /// We are instantiating a template declaration. The entity is
6415 /// the declaration we're instantiating (e.g., a CXXRecordDecl).
6416 TemplateInstantiation,
6418 /// We are instantiating a default argument for a template
6419 /// parameter. The Entity is the template, and
6420 /// TemplateArgs/NumTemplateArguments provides the template
6421 /// arguments as specified.
6422 /// FIXME: Use a TemplateArgumentList
6423 DefaultTemplateArgumentInstantiation,
6425 /// We are instantiating a default argument for a function.
6426 /// The Entity is the ParmVarDecl, and TemplateArgs/NumTemplateArgs
6427 /// provides the template arguments as specified.
6428 DefaultFunctionArgumentInstantiation,
6430 /// We are substituting explicit template arguments provided for
6431 /// a function template. The entity is a FunctionTemplateDecl.
6432 ExplicitTemplateArgumentSubstitution,
6434 /// We are substituting template argument determined as part of
6435 /// template argument deduction for either a class template
6436 /// partial specialization or a function template. The
6437 /// Entity is either a ClassTemplatePartialSpecializationDecl or
6438 /// a FunctionTemplateDecl.
6439 DeducedTemplateArgumentSubstitution,
6441 /// We are substituting prior template arguments into a new
6442 /// template parameter. The template parameter itself is either a
6443 /// NonTypeTemplateParmDecl or a TemplateTemplateParmDecl.
6444 PriorTemplateArgumentSubstitution,
6446 /// We are checking the validity of a default template argument that
6447 /// has been used when naming a template-id.
6448 DefaultTemplateArgumentChecking,
6450 /// We are instantiating the exception specification for a function
6451 /// template which was deferred until it was needed.
6452 ExceptionSpecInstantiation
6455 /// \brief The point of instantiation within the source code.
6456 SourceLocation PointOfInstantiation;
6458 /// \brief The template (or partial specialization) in which we are
6459 /// performing the instantiation, for substitutions of prior template
6461 NamedDecl *Template;
6463 /// \brief The entity that is being instantiated.
6466 /// \brief The list of template arguments we are substituting, if they
6467 /// are not part of the entity.
6468 const TemplateArgument *TemplateArgs;
6470 /// \brief The number of template arguments in TemplateArgs.
6471 unsigned NumTemplateArgs;
6473 /// \brief The template deduction info object associated with the
6474 /// substitution or checking of explicit or deduced template arguments.
6475 sema::TemplateDeductionInfo *DeductionInfo;
6477 /// \brief The source range that covers the construct that cause
6478 /// the instantiation, e.g., the template-id that causes a class
6479 /// template instantiation.
6480 SourceRange InstantiationRange;
6482 ActiveTemplateInstantiation()
6483 : Kind(TemplateInstantiation), Template(nullptr), Entity(nullptr),
6484 TemplateArgs(nullptr), NumTemplateArgs(0), DeductionInfo(nullptr) {}
6486 /// \brief Determines whether this template is an actual instantiation
6487 /// that should be counted toward the maximum instantiation depth.
6488 bool isInstantiationRecord() const;
6490 friend bool operator==(const ActiveTemplateInstantiation &X,
6491 const ActiveTemplateInstantiation &Y) {
6492 if (X.Kind != Y.Kind)
6495 if (X.Entity != Y.Entity)
6499 case TemplateInstantiation:
6500 case ExceptionSpecInstantiation:
6503 case PriorTemplateArgumentSubstitution:
6504 case DefaultTemplateArgumentChecking:
6505 return X.Template == Y.Template && X.TemplateArgs == Y.TemplateArgs;
6507 case DefaultTemplateArgumentInstantiation:
6508 case ExplicitTemplateArgumentSubstitution:
6509 case DeducedTemplateArgumentSubstitution:
6510 case DefaultFunctionArgumentInstantiation:
6511 return X.TemplateArgs == Y.TemplateArgs;
6515 llvm_unreachable("Invalid InstantiationKind!");
6518 friend bool operator!=(const ActiveTemplateInstantiation &X,
6519 const ActiveTemplateInstantiation &Y) {
6524 /// \brief List of active template instantiations.
6526 /// This vector is treated as a stack. As one template instantiation
6527 /// requires another template instantiation, additional
6528 /// instantiations are pushed onto the stack up to a
6529 /// user-configurable limit LangOptions::InstantiationDepth.
6530 SmallVector<ActiveTemplateInstantiation, 16>
6531 ActiveTemplateInstantiations;
6533 /// \brief Extra modules inspected when performing a lookup during a template
6534 /// instantiation. Computed lazily.
6535 SmallVector<Module*, 16> ActiveTemplateInstantiationLookupModules;
6537 /// \brief Cache of additional modules that should be used for name lookup
6538 /// within the current template instantiation. Computed lazily; use
6539 /// getLookupModules() to get a complete set.
6540 llvm::DenseSet<Module*> LookupModulesCache;
6542 /// \brief Get the set of additional modules that should be checked during
6543 /// name lookup. A module and its imports become visible when instanting a
6544 /// template defined within it.
6545 llvm::DenseSet<Module*> &getLookupModules();
6547 /// \brief Whether we are in a SFINAE context that is not associated with
6548 /// template instantiation.
6550 /// This is used when setting up a SFINAE trap (\c see SFINAETrap) outside
6551 /// of a template instantiation or template argument deduction.
6552 bool InNonInstantiationSFINAEContext;
6554 /// \brief The number of ActiveTemplateInstantiation entries in
6555 /// \c ActiveTemplateInstantiations that are not actual instantiations and,
6556 /// therefore, should not be counted as part of the instantiation depth.
6557 unsigned NonInstantiationEntries;
6559 /// \brief The last template from which a template instantiation
6560 /// error or warning was produced.
6562 /// This value is used to suppress printing of redundant template
6563 /// instantiation backtraces when there are multiple errors in the
6564 /// same instantiation. FIXME: Does this belong in Sema? It's tough
6565 /// to implement it anywhere else.
6566 ActiveTemplateInstantiation LastTemplateInstantiationErrorContext;
6568 /// \brief The current index into pack expansion arguments that will be
6569 /// used for substitution of parameter packs.
6571 /// The pack expansion index will be -1 to indicate that parameter packs
6572 /// should be instantiated as themselves. Otherwise, the index specifies
6573 /// which argument within the parameter pack will be used for substitution.
6574 int ArgumentPackSubstitutionIndex;
6576 /// \brief RAII object used to change the argument pack substitution index
6577 /// within a \c Sema object.
6579 /// See \c ArgumentPackSubstitutionIndex for more information.
6580 class ArgumentPackSubstitutionIndexRAII {
6582 int OldSubstitutionIndex;
6585 ArgumentPackSubstitutionIndexRAII(Sema &Self, int NewSubstitutionIndex)
6586 : Self(Self), OldSubstitutionIndex(Self.ArgumentPackSubstitutionIndex) {
6587 Self.ArgumentPackSubstitutionIndex = NewSubstitutionIndex;
6590 ~ArgumentPackSubstitutionIndexRAII() {
6591 Self.ArgumentPackSubstitutionIndex = OldSubstitutionIndex;
6595 friend class ArgumentPackSubstitutionRAII;
6597 /// \brief The stack of calls expression undergoing template instantiation.
6599 /// The top of this stack is used by a fixit instantiating unresolved
6600 /// function calls to fix the AST to match the textual change it prints.
6601 SmallVector<CallExpr *, 8> CallsUndergoingInstantiation;
6603 /// \brief For each declaration that involved template argument deduction, the
6604 /// set of diagnostics that were suppressed during that template argument
6607 /// FIXME: Serialize this structure to the AST file.
6608 typedef llvm::DenseMap<Decl *, SmallVector<PartialDiagnosticAt, 1> >
6609 SuppressedDiagnosticsMap;
6610 SuppressedDiagnosticsMap SuppressedDiagnostics;
6612 /// \brief A stack object to be created when performing template
6615 /// Construction of an object of type \c InstantiatingTemplate
6616 /// pushes the current instantiation onto the stack of active
6617 /// instantiations. If the size of this stack exceeds the maximum
6618 /// number of recursive template instantiations, construction
6619 /// produces an error and evaluates true.
6621 /// Destruction of this object will pop the named instantiation off
6623 struct InstantiatingTemplate {
6624 /// \brief Note that we are instantiating a class template,
6625 /// function template, or a member thereof.
6626 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
6628 SourceRange InstantiationRange = SourceRange());
6630 struct ExceptionSpecification {};
6631 /// \brief Note that we are instantiating an exception specification
6632 /// of a function template.
6633 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
6634 FunctionDecl *Entity, ExceptionSpecification,
6635 SourceRange InstantiationRange = SourceRange());
6637 /// \brief Note that we are instantiating a default argument in a
6639 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
6640 TemplateDecl *Template,
6641 ArrayRef<TemplateArgument> TemplateArgs,
6642 SourceRange InstantiationRange = SourceRange());
6644 /// \brief Note that we are instantiating a default argument in a
6646 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
6647 FunctionTemplateDecl *FunctionTemplate,
6648 ArrayRef<TemplateArgument> TemplateArgs,
6649 ActiveTemplateInstantiation::InstantiationKind Kind,
6650 sema::TemplateDeductionInfo &DeductionInfo,
6651 SourceRange InstantiationRange = SourceRange());
6653 /// \brief Note that we are instantiating as part of template
6654 /// argument deduction for a class template partial
6656 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
6657 ClassTemplatePartialSpecializationDecl *PartialSpec,
6658 ArrayRef<TemplateArgument> TemplateArgs,
6659 sema::TemplateDeductionInfo &DeductionInfo,
6660 SourceRange InstantiationRange = SourceRange());
6662 /// \brief Note that we are instantiating as part of template
6663 /// argument deduction for a variable template partial
6665 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
6666 VarTemplatePartialSpecializationDecl *PartialSpec,
6667 ArrayRef<TemplateArgument> TemplateArgs,
6668 sema::TemplateDeductionInfo &DeductionInfo,
6669 SourceRange InstantiationRange = SourceRange());
6671 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
6673 ArrayRef<TemplateArgument> TemplateArgs,
6674 SourceRange InstantiationRange = SourceRange());
6676 /// \brief Note that we are substituting prior template arguments into a
6677 /// non-type parameter.
6678 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
6679 NamedDecl *Template,
6680 NonTypeTemplateParmDecl *Param,
6681 ArrayRef<TemplateArgument> TemplateArgs,
6682 SourceRange InstantiationRange);
6684 /// \brief Note that we are substituting prior template arguments into a
6685 /// template template parameter.
6686 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
6687 NamedDecl *Template,
6688 TemplateTemplateParmDecl *Param,
6689 ArrayRef<TemplateArgument> TemplateArgs,
6690 SourceRange InstantiationRange);
6692 /// \brief Note that we are checking the default template argument
6693 /// against the template parameter for a given template-id.
6694 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
6695 TemplateDecl *Template,
6697 ArrayRef<TemplateArgument> TemplateArgs,
6698 SourceRange InstantiationRange);
6701 /// \brief Note that we have finished instantiating this template.
6704 ~InstantiatingTemplate() { Clear(); }
6706 /// \brief Determines whether we have exceeded the maximum
6707 /// recursive template instantiations.
6708 bool isInvalid() const { return Invalid; }
6713 bool SavedInNonInstantiationSFINAEContext;
6714 bool CheckInstantiationDepth(SourceLocation PointOfInstantiation,
6715 SourceRange InstantiationRange);
6717 InstantiatingTemplate(
6718 Sema &SemaRef, ActiveTemplateInstantiation::InstantiationKind Kind,
6719 SourceLocation PointOfInstantiation, SourceRange InstantiationRange,
6720 Decl *Entity, NamedDecl *Template = nullptr,
6721 ArrayRef<TemplateArgument> TemplateArgs = ArrayRef<TemplateArgument>(),
6722 sema::TemplateDeductionInfo *DeductionInfo = nullptr);
6724 InstantiatingTemplate(const InstantiatingTemplate&) = delete;
6726 InstantiatingTemplate&
6727 operator=(const InstantiatingTemplate&) = delete;
6730 void PrintInstantiationStack();
6732 /// \brief Determines whether we are currently in a context where
6733 /// template argument substitution failures are not considered
6736 /// \returns An empty \c Optional if we're not in a SFINAE context.
6737 /// Otherwise, contains a pointer that, if non-NULL, contains the nearest
6738 /// template-deduction context object, which can be used to capture
6739 /// diagnostics that will be suppressed.
6740 Optional<sema::TemplateDeductionInfo *> isSFINAEContext() const;
6742 /// \brief Determines whether we are currently in a context that
6743 /// is not evaluated as per C++ [expr] p5.
6744 bool isUnevaluatedContext() const {
6745 assert(!ExprEvalContexts.empty() &&
6746 "Must be in an expression evaluation context");
6747 return ExprEvalContexts.back().isUnevaluated();
6750 /// \brief RAII class used to determine whether SFINAE has
6751 /// trapped any errors that occur during template argument
6755 unsigned PrevSFINAEErrors;
6756 bool PrevInNonInstantiationSFINAEContext;
6757 bool PrevAccessCheckingSFINAE;
6760 explicit SFINAETrap(Sema &SemaRef, bool AccessCheckingSFINAE = false)
6761 : SemaRef(SemaRef), PrevSFINAEErrors(SemaRef.NumSFINAEErrors),
6762 PrevInNonInstantiationSFINAEContext(
6763 SemaRef.InNonInstantiationSFINAEContext),
6764 PrevAccessCheckingSFINAE(SemaRef.AccessCheckingSFINAE)
6766 if (!SemaRef.isSFINAEContext())
6767 SemaRef.InNonInstantiationSFINAEContext = true;
6768 SemaRef.AccessCheckingSFINAE = AccessCheckingSFINAE;
6772 SemaRef.NumSFINAEErrors = PrevSFINAEErrors;
6773 SemaRef.InNonInstantiationSFINAEContext
6774 = PrevInNonInstantiationSFINAEContext;
6775 SemaRef.AccessCheckingSFINAE = PrevAccessCheckingSFINAE;
6778 /// \brief Determine whether any SFINAE errors have been trapped.
6779 bool hasErrorOccurred() const {
6780 return SemaRef.NumSFINAEErrors > PrevSFINAEErrors;
6784 /// \brief RAII class used to indicate that we are performing provisional
6785 /// semantic analysis to determine the validity of a construct, so
6786 /// typo-correction and diagnostics in the immediate context (not within
6787 /// implicitly-instantiated templates) should be suppressed.
6788 class TentativeAnalysisScope {
6790 // FIXME: Using a SFINAETrap for this is a hack.
6792 bool PrevDisableTypoCorrection;
6794 explicit TentativeAnalysisScope(Sema &SemaRef)
6795 : SemaRef(SemaRef), Trap(SemaRef, true),
6796 PrevDisableTypoCorrection(SemaRef.DisableTypoCorrection) {
6797 SemaRef.DisableTypoCorrection = true;
6799 ~TentativeAnalysisScope() {
6800 SemaRef.DisableTypoCorrection = PrevDisableTypoCorrection;
6804 /// \brief The current instantiation scope used to store local
6806 LocalInstantiationScope *CurrentInstantiationScope;
6808 /// \brief Tracks whether we are in a context where typo correction is
6810 bool DisableTypoCorrection;
6812 /// \brief The number of typos corrected by CorrectTypo.
6813 unsigned TyposCorrected;
6815 typedef llvm::SmallSet<SourceLocation, 2> SrcLocSet;
6816 typedef llvm::DenseMap<IdentifierInfo *, SrcLocSet> IdentifierSourceLocations;
6818 /// \brief A cache containing identifiers for which typo correction failed and
6819 /// their locations, so that repeated attempts to correct an identifier in a
6820 /// given location are ignored if typo correction already failed for it.
6821 IdentifierSourceLocations TypoCorrectionFailures;
6823 /// \brief Worker object for performing CFG-based warnings.
6824 sema::AnalysisBasedWarnings AnalysisWarnings;
6825 threadSafety::BeforeSet *ThreadSafetyDeclCache;
6827 /// \brief An entity for which implicit template instantiation is required.
6829 /// The source location associated with the declaration is the first place in
6830 /// the source code where the declaration was "used". It is not necessarily
6831 /// the point of instantiation (which will be either before or after the
6832 /// namespace-scope declaration that triggered this implicit instantiation),
6833 /// However, it is the location that diagnostics should generally refer to,
6834 /// because users will need to know what code triggered the instantiation.
6835 typedef std::pair<ValueDecl *, SourceLocation> PendingImplicitInstantiation;
6837 /// \brief The queue of implicit template instantiations that are required
6838 /// but have not yet been performed.
6839 std::deque<PendingImplicitInstantiation> PendingInstantiations;
6841 class SavePendingInstantiationsAndVTableUsesRAII {
6843 SavePendingInstantiationsAndVTableUsesRAII(Sema &S, bool Enabled)
6844 : S(S), Enabled(Enabled) {
6845 if (!Enabled) return;
6847 SavedPendingInstantiations.swap(S.PendingInstantiations);
6848 SavedVTableUses.swap(S.VTableUses);
6851 ~SavePendingInstantiationsAndVTableUsesRAII() {
6852 if (!Enabled) return;
6854 // Restore the set of pending vtables.
6855 assert(S.VTableUses.empty() &&
6856 "VTableUses should be empty before it is discarded.");
6857 S.VTableUses.swap(SavedVTableUses);
6859 // Restore the set of pending implicit instantiations.
6860 assert(S.PendingInstantiations.empty() &&
6861 "PendingInstantiations should be empty before it is discarded.");
6862 S.PendingInstantiations.swap(SavedPendingInstantiations);
6867 SmallVector<VTableUse, 16> SavedVTableUses;
6868 std::deque<PendingImplicitInstantiation> SavedPendingInstantiations;
6872 /// \brief The queue of implicit template instantiations that are required
6873 /// and must be performed within the current local scope.
6875 /// This queue is only used for member functions of local classes in
6876 /// templates, which must be instantiated in the same scope as their
6877 /// enclosing function, so that they can reference function-local
6878 /// types, static variables, enumerators, etc.
6879 std::deque<PendingImplicitInstantiation> PendingLocalImplicitInstantiations;
6881 class SavePendingLocalImplicitInstantiationsRAII {
6883 SavePendingLocalImplicitInstantiationsRAII(Sema &S): S(S) {
6884 SavedPendingLocalImplicitInstantiations.swap(
6885 S.PendingLocalImplicitInstantiations);
6888 ~SavePendingLocalImplicitInstantiationsRAII() {
6889 assert(S.PendingLocalImplicitInstantiations.empty() &&
6890 "there shouldn't be any pending local implicit instantiations");
6891 SavedPendingLocalImplicitInstantiations.swap(
6892 S.PendingLocalImplicitInstantiations);
6897 std::deque<PendingImplicitInstantiation>
6898 SavedPendingLocalImplicitInstantiations;
6901 void PerformPendingInstantiations(bool LocalOnly = false);
6903 TypeSourceInfo *SubstType(TypeSourceInfo *T,
6904 const MultiLevelTemplateArgumentList &TemplateArgs,
6905 SourceLocation Loc, DeclarationName Entity);
6907 QualType SubstType(QualType T,
6908 const MultiLevelTemplateArgumentList &TemplateArgs,
6909 SourceLocation Loc, DeclarationName Entity);
6911 TypeSourceInfo *SubstType(TypeLoc TL,
6912 const MultiLevelTemplateArgumentList &TemplateArgs,
6913 SourceLocation Loc, DeclarationName Entity);
6915 TypeSourceInfo *SubstFunctionDeclType(TypeSourceInfo *T,
6916 const MultiLevelTemplateArgumentList &TemplateArgs,
6918 DeclarationName Entity,
6919 CXXRecordDecl *ThisContext,
6920 unsigned ThisTypeQuals);
6921 void SubstExceptionSpec(FunctionDecl *New, const FunctionProtoType *Proto,
6922 const MultiLevelTemplateArgumentList &Args);
6923 ParmVarDecl *SubstParmVarDecl(ParmVarDecl *D,
6924 const MultiLevelTemplateArgumentList &TemplateArgs,
6925 int indexAdjustment,
6926 Optional<unsigned> NumExpansions,
6927 bool ExpectParameterPack);
6928 bool SubstParmTypes(SourceLocation Loc,
6929 ParmVarDecl **Params, unsigned NumParams,
6930 const MultiLevelTemplateArgumentList &TemplateArgs,
6931 SmallVectorImpl<QualType> &ParamTypes,
6932 SmallVectorImpl<ParmVarDecl *> *OutParams = nullptr);
6933 ExprResult SubstExpr(Expr *E,
6934 const MultiLevelTemplateArgumentList &TemplateArgs);
6936 /// \brief Substitute the given template arguments into a list of
6937 /// expressions, expanding pack expansions if required.
6939 /// \param Exprs The list of expressions to substitute into.
6941 /// \param NumExprs The number of expressions in \p Exprs.
6943 /// \param IsCall Whether this is some form of call, in which case
6944 /// default arguments will be dropped.
6946 /// \param TemplateArgs The set of template arguments to substitute.
6948 /// \param Outputs Will receive all of the substituted arguments.
6950 /// \returns true if an error occurred, false otherwise.
6951 bool SubstExprs(Expr **Exprs, unsigned NumExprs, bool IsCall,
6952 const MultiLevelTemplateArgumentList &TemplateArgs,
6953 SmallVectorImpl<Expr *> &Outputs);
6955 StmtResult SubstStmt(Stmt *S,
6956 const MultiLevelTemplateArgumentList &TemplateArgs);
6958 Decl *SubstDecl(Decl *D, DeclContext *Owner,
6959 const MultiLevelTemplateArgumentList &TemplateArgs);
6961 ExprResult SubstInitializer(Expr *E,
6962 const MultiLevelTemplateArgumentList &TemplateArgs,
6963 bool CXXDirectInit);
6966 SubstBaseSpecifiers(CXXRecordDecl *Instantiation,
6967 CXXRecordDecl *Pattern,
6968 const MultiLevelTemplateArgumentList &TemplateArgs);
6971 InstantiateClass(SourceLocation PointOfInstantiation,
6972 CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern,
6973 const MultiLevelTemplateArgumentList &TemplateArgs,
6974 TemplateSpecializationKind TSK,
6975 bool Complain = true);
6977 bool InstantiateEnum(SourceLocation PointOfInstantiation,
6978 EnumDecl *Instantiation, EnumDecl *Pattern,
6979 const MultiLevelTemplateArgumentList &TemplateArgs,
6980 TemplateSpecializationKind TSK);
6982 bool InstantiateInClassInitializer(
6983 SourceLocation PointOfInstantiation, FieldDecl *Instantiation,
6984 FieldDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs);
6986 struct LateInstantiatedAttribute {
6987 const Attr *TmplAttr;
6988 LocalInstantiationScope *Scope;
6991 LateInstantiatedAttribute(const Attr *A, LocalInstantiationScope *S,
6993 : TmplAttr(A), Scope(S), NewDecl(D)
6996 typedef SmallVector<LateInstantiatedAttribute, 16> LateInstantiatedAttrVec;
6998 void InstantiateAttrs(const MultiLevelTemplateArgumentList &TemplateArgs,
6999 const Decl *Pattern, Decl *Inst,
7000 LateInstantiatedAttrVec *LateAttrs = nullptr,
7001 LocalInstantiationScope *OuterMostScope = nullptr);
7004 InstantiateClassTemplateSpecialization(SourceLocation PointOfInstantiation,
7005 ClassTemplateSpecializationDecl *ClassTemplateSpec,
7006 TemplateSpecializationKind TSK,
7007 bool Complain = true);
7009 void InstantiateClassMembers(SourceLocation PointOfInstantiation,
7010 CXXRecordDecl *Instantiation,
7011 const MultiLevelTemplateArgumentList &TemplateArgs,
7012 TemplateSpecializationKind TSK);
7014 void InstantiateClassTemplateSpecializationMembers(
7015 SourceLocation PointOfInstantiation,
7016 ClassTemplateSpecializationDecl *ClassTemplateSpec,
7017 TemplateSpecializationKind TSK);
7019 NestedNameSpecifierLoc
7020 SubstNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS,
7021 const MultiLevelTemplateArgumentList &TemplateArgs);
7024 SubstDeclarationNameInfo(const DeclarationNameInfo &NameInfo,
7025 const MultiLevelTemplateArgumentList &TemplateArgs);
7027 SubstTemplateName(NestedNameSpecifierLoc QualifierLoc, TemplateName Name,
7029 const MultiLevelTemplateArgumentList &TemplateArgs);
7030 bool Subst(const TemplateArgumentLoc *Args, unsigned NumArgs,
7031 TemplateArgumentListInfo &Result,
7032 const MultiLevelTemplateArgumentList &TemplateArgs);
7034 void InstantiateExceptionSpec(SourceLocation PointOfInstantiation,
7035 FunctionDecl *Function);
7036 void InstantiateFunctionDefinition(SourceLocation PointOfInstantiation,
7037 FunctionDecl *Function,
7038 bool Recursive = false,
7039 bool DefinitionRequired = false);
7040 VarTemplateSpecializationDecl *BuildVarTemplateInstantiation(
7041 VarTemplateDecl *VarTemplate, VarDecl *FromVar,
7042 const TemplateArgumentList &TemplateArgList,
7043 const TemplateArgumentListInfo &TemplateArgsInfo,
7044 SmallVectorImpl<TemplateArgument> &Converted,
7045 SourceLocation PointOfInstantiation, void *InsertPos,
7046 LateInstantiatedAttrVec *LateAttrs = nullptr,
7047 LocalInstantiationScope *StartingScope = nullptr);
7048 VarTemplateSpecializationDecl *CompleteVarTemplateSpecializationDecl(
7049 VarTemplateSpecializationDecl *VarSpec, VarDecl *PatternDecl,
7050 const MultiLevelTemplateArgumentList &TemplateArgs);
7052 BuildVariableInstantiation(VarDecl *NewVar, VarDecl *OldVar,
7053 const MultiLevelTemplateArgumentList &TemplateArgs,
7054 LateInstantiatedAttrVec *LateAttrs,
7056 LocalInstantiationScope *StartingScope,
7057 bool InstantiatingVarTemplate = false);
7058 void InstantiateVariableInitializer(
7059 VarDecl *Var, VarDecl *OldVar,
7060 const MultiLevelTemplateArgumentList &TemplateArgs);
7061 void InstantiateVariableDefinition(SourceLocation PointOfInstantiation,
7062 VarDecl *Var, bool Recursive = false,
7063 bool DefinitionRequired = false);
7064 void InstantiateStaticDataMemberDefinition(
7065 SourceLocation PointOfInstantiation,
7067 bool Recursive = false,
7068 bool DefinitionRequired = false);
7070 void InstantiateMemInitializers(CXXConstructorDecl *New,
7071 const CXXConstructorDecl *Tmpl,
7072 const MultiLevelTemplateArgumentList &TemplateArgs);
7074 NamedDecl *FindInstantiatedDecl(SourceLocation Loc, NamedDecl *D,
7075 const MultiLevelTemplateArgumentList &TemplateArgs);
7076 DeclContext *FindInstantiatedContext(SourceLocation Loc, DeclContext *DC,
7077 const MultiLevelTemplateArgumentList &TemplateArgs);
7079 // Objective-C declarations.
7080 enum ObjCContainerKind {
7087 OCK_CategoryImplementation
7089 ObjCContainerKind getObjCContainerKind() const;
7091 Decl *ActOnStartClassInterface(SourceLocation AtInterfaceLoc,
7092 IdentifierInfo *ClassName,
7093 SourceLocation ClassLoc,
7094 IdentifierInfo *SuperName,
7095 SourceLocation SuperLoc,
7096 Decl * const *ProtoRefs,
7097 unsigned NumProtoRefs,
7098 const SourceLocation *ProtoLocs,
7099 SourceLocation EndProtoLoc,
7100 AttributeList *AttrList);
7102 void ActOnTypedefedProtocols(SmallVectorImpl<Decl *> &ProtocolRefs,
7103 IdentifierInfo *SuperName,
7104 SourceLocation SuperLoc);
7106 Decl *ActOnCompatibilityAlias(
7107 SourceLocation AtCompatibilityAliasLoc,
7108 IdentifierInfo *AliasName, SourceLocation AliasLocation,
7109 IdentifierInfo *ClassName, SourceLocation ClassLocation);
7111 bool CheckForwardProtocolDeclarationForCircularDependency(
7112 IdentifierInfo *PName,
7113 SourceLocation &PLoc, SourceLocation PrevLoc,
7114 const ObjCList<ObjCProtocolDecl> &PList);
7116 Decl *ActOnStartProtocolInterface(
7117 SourceLocation AtProtoInterfaceLoc,
7118 IdentifierInfo *ProtocolName, SourceLocation ProtocolLoc,
7119 Decl * const *ProtoRefNames, unsigned NumProtoRefs,
7120 const SourceLocation *ProtoLocs,
7121 SourceLocation EndProtoLoc,
7122 AttributeList *AttrList);
7124 Decl *ActOnStartCategoryInterface(SourceLocation AtInterfaceLoc,
7125 IdentifierInfo *ClassName,
7126 SourceLocation ClassLoc,
7127 IdentifierInfo *CategoryName,
7128 SourceLocation CategoryLoc,
7129 Decl * const *ProtoRefs,
7130 unsigned NumProtoRefs,
7131 const SourceLocation *ProtoLocs,
7132 SourceLocation EndProtoLoc);
7134 Decl *ActOnStartClassImplementation(
7135 SourceLocation AtClassImplLoc,
7136 IdentifierInfo *ClassName, SourceLocation ClassLoc,
7137 IdentifierInfo *SuperClassname,
7138 SourceLocation SuperClassLoc);
7140 Decl *ActOnStartCategoryImplementation(SourceLocation AtCatImplLoc,
7141 IdentifierInfo *ClassName,
7142 SourceLocation ClassLoc,
7143 IdentifierInfo *CatName,
7144 SourceLocation CatLoc);
7146 DeclGroupPtrTy ActOnFinishObjCImplementation(Decl *ObjCImpDecl,
7147 ArrayRef<Decl *> Decls);
7149 DeclGroupPtrTy ActOnForwardClassDeclaration(SourceLocation Loc,
7150 IdentifierInfo **IdentList,
7151 SourceLocation *IdentLocs,
7154 DeclGroupPtrTy ActOnForwardProtocolDeclaration(SourceLocation AtProtoclLoc,
7155 const IdentifierLocPair *IdentList,
7157 AttributeList *attrList);
7159 void FindProtocolDeclaration(bool WarnOnDeclarations, bool ForObjCContainer,
7160 const IdentifierLocPair *ProtocolId,
7161 unsigned NumProtocols,
7162 SmallVectorImpl<Decl *> &Protocols);
7164 /// Ensure attributes are consistent with type.
7165 /// \param [in, out] Attributes The attributes to check; they will
7166 /// be modified to be consistent with \p PropertyTy.
7167 void CheckObjCPropertyAttributes(Decl *PropertyPtrTy,
7169 unsigned &Attributes,
7170 bool propertyInPrimaryClass);
7172 /// Process the specified property declaration and create decls for the
7173 /// setters and getters as needed.
7174 /// \param property The property declaration being processed
7175 /// \param CD The semantic container for the property
7176 /// \param redeclaredProperty Declaration for property if redeclared
7177 /// in class extension.
7178 /// \param lexicalDC Container for redeclaredProperty.
7179 void ProcessPropertyDecl(ObjCPropertyDecl *property,
7180 ObjCContainerDecl *CD,
7181 ObjCPropertyDecl *redeclaredProperty = nullptr,
7182 ObjCContainerDecl *lexicalDC = nullptr);
7185 void DiagnosePropertyMismatch(ObjCPropertyDecl *Property,
7186 ObjCPropertyDecl *SuperProperty,
7187 const IdentifierInfo *Name,
7188 bool OverridingProtocolProperty);
7190 void DiagnoseClassExtensionDupMethods(ObjCCategoryDecl *CAT,
7191 ObjCInterfaceDecl *ID);
7193 Decl *ActOnAtEnd(Scope *S, SourceRange AtEnd,
7194 ArrayRef<Decl *> allMethods = None,
7195 ArrayRef<DeclGroupPtrTy> allTUVars = None);
7197 Decl *ActOnProperty(Scope *S, SourceLocation AtLoc,
7198 SourceLocation LParenLoc,
7199 FieldDeclarator &FD, ObjCDeclSpec &ODS,
7200 Selector GetterSel, Selector SetterSel,
7201 bool *OverridingProperty,
7202 tok::ObjCKeywordKind MethodImplKind,
7203 DeclContext *lexicalDC = nullptr);
7205 Decl *ActOnPropertyImplDecl(Scope *S,
7206 SourceLocation AtLoc,
7207 SourceLocation PropertyLoc,
7209 IdentifierInfo *PropertyId,
7210 IdentifierInfo *PropertyIvar,
7211 SourceLocation PropertyIvarLoc);
7213 enum ObjCSpecialMethodKind {
7219 OSMK_NonRetainingInit
7222 struct ObjCArgInfo {
7223 IdentifierInfo *Name;
7224 SourceLocation NameLoc;
7225 // The Type is null if no type was specified, and the DeclSpec is invalid
7228 ObjCDeclSpec DeclSpec;
7230 /// ArgAttrs - Attribute list for this argument.
7231 AttributeList *ArgAttrs;
7234 Decl *ActOnMethodDeclaration(
7236 SourceLocation BeginLoc, // location of the + or -.
7237 SourceLocation EndLoc, // location of the ; or {.
7238 tok::TokenKind MethodType,
7239 ObjCDeclSpec &ReturnQT, ParsedType ReturnType,
7240 ArrayRef<SourceLocation> SelectorLocs, Selector Sel,
7241 // optional arguments. The number of types/arguments is obtained
7242 // from the Sel.getNumArgs().
7243 ObjCArgInfo *ArgInfo,
7244 DeclaratorChunk::ParamInfo *CParamInfo, unsigned CNumArgs, // c-style args
7245 AttributeList *AttrList, tok::ObjCKeywordKind MethodImplKind,
7246 bool isVariadic, bool MethodDefinition);
7248 ObjCMethodDecl *LookupMethodInQualifiedType(Selector Sel,
7249 const ObjCObjectPointerType *OPT,
7251 ObjCMethodDecl *LookupMethodInObjectType(Selector Sel, QualType Ty,
7254 bool CheckARCMethodDecl(ObjCMethodDecl *method);
7255 bool inferObjCARCLifetime(ValueDecl *decl);
7258 HandleExprPropertyRefExpr(const ObjCObjectPointerType *OPT,
7260 SourceLocation OpLoc,
7261 DeclarationName MemberName,
7262 SourceLocation MemberLoc,
7263 SourceLocation SuperLoc, QualType SuperType,
7267 ActOnClassPropertyRefExpr(IdentifierInfo &receiverName,
7268 IdentifierInfo &propertyName,
7269 SourceLocation receiverNameLoc,
7270 SourceLocation propertyNameLoc);
7272 ObjCMethodDecl *tryCaptureObjCSelf(SourceLocation Loc);
7274 /// \brief Describes the kind of message expression indicated by a message
7275 /// send that starts with an identifier.
7276 enum ObjCMessageKind {
7277 /// \brief The message is sent to 'super'.
7279 /// \brief The message is an instance message.
7280 ObjCInstanceMessage,
7281 /// \brief The message is a class message, and the identifier is a type
7286 ObjCMessageKind getObjCMessageKind(Scope *S,
7287 IdentifierInfo *Name,
7288 SourceLocation NameLoc,
7290 bool HasTrailingDot,
7291 ParsedType &ReceiverType);
7293 ExprResult ActOnSuperMessage(Scope *S, SourceLocation SuperLoc,
7295 SourceLocation LBracLoc,
7296 ArrayRef<SourceLocation> SelectorLocs,
7297 SourceLocation RBracLoc,
7300 ExprResult BuildClassMessage(TypeSourceInfo *ReceiverTypeInfo,
7301 QualType ReceiverType,
7302 SourceLocation SuperLoc,
7304 ObjCMethodDecl *Method,
7305 SourceLocation LBracLoc,
7306 ArrayRef<SourceLocation> SelectorLocs,
7307 SourceLocation RBracLoc,
7309 bool isImplicit = false);
7311 ExprResult BuildClassMessageImplicit(QualType ReceiverType,
7312 bool isSuperReceiver,
7315 ObjCMethodDecl *Method,
7318 ExprResult ActOnClassMessage(Scope *S,
7319 ParsedType Receiver,
7321 SourceLocation LBracLoc,
7322 ArrayRef<SourceLocation> SelectorLocs,
7323 SourceLocation RBracLoc,
7326 ExprResult BuildInstanceMessage(Expr *Receiver,
7327 QualType ReceiverType,
7328 SourceLocation SuperLoc,
7330 ObjCMethodDecl *Method,
7331 SourceLocation LBracLoc,
7332 ArrayRef<SourceLocation> SelectorLocs,
7333 SourceLocation RBracLoc,
7335 bool isImplicit = false);
7337 ExprResult BuildInstanceMessageImplicit(Expr *Receiver,
7338 QualType ReceiverType,
7341 ObjCMethodDecl *Method,
7344 ExprResult ActOnInstanceMessage(Scope *S,
7347 SourceLocation LBracLoc,
7348 ArrayRef<SourceLocation> SelectorLocs,
7349 SourceLocation RBracLoc,
7352 ExprResult BuildObjCBridgedCast(SourceLocation LParenLoc,
7353 ObjCBridgeCastKind Kind,
7354 SourceLocation BridgeKeywordLoc,
7355 TypeSourceInfo *TSInfo,
7358 ExprResult ActOnObjCBridgedCast(Scope *S,
7359 SourceLocation LParenLoc,
7360 ObjCBridgeCastKind Kind,
7361 SourceLocation BridgeKeywordLoc,
7363 SourceLocation RParenLoc,
7366 void CheckTollFreeBridgeCast(QualType castType, Expr *castExpr);
7368 void CheckObjCBridgeRelatedCast(QualType castType, Expr *castExpr);
7370 bool CheckTollFreeBridgeStaticCast(QualType castType, Expr *castExpr,
7373 bool checkObjCBridgeRelatedComponents(SourceLocation Loc,
7374 QualType DestType, QualType SrcType,
7375 ObjCInterfaceDecl *&RelatedClass,
7376 ObjCMethodDecl *&ClassMethod,
7377 ObjCMethodDecl *&InstanceMethod,
7378 TypedefNameDecl *&TDNDecl,
7381 bool CheckObjCBridgeRelatedConversions(SourceLocation Loc,
7382 QualType DestType, QualType SrcType,
7385 bool ConversionToObjCStringLiteralCheck(QualType DstType, Expr *&SrcExpr);
7387 bool checkInitMethod(ObjCMethodDecl *method, QualType receiverTypeIfCall);
7389 /// \brief Check whether the given new method is a valid override of the
7390 /// given overridden method, and set any properties that should be inherited.
7391 void CheckObjCMethodOverride(ObjCMethodDecl *NewMethod,
7392 const ObjCMethodDecl *Overridden);
7394 /// \brief Describes the compatibility of a result type with its method.
7395 enum ResultTypeCompatibilityKind {
7401 void CheckObjCMethodOverrides(ObjCMethodDecl *ObjCMethod,
7402 ObjCInterfaceDecl *CurrentClass,
7403 ResultTypeCompatibilityKind RTC);
7405 enum PragmaOptionsAlignKind {
7406 POAK_Native, // #pragma options align=native
7407 POAK_Natural, // #pragma options align=natural
7408 POAK_Packed, // #pragma options align=packed
7409 POAK_Power, // #pragma options align=power
7410 POAK_Mac68k, // #pragma options align=mac68k
7411 POAK_Reset // #pragma options align=reset
7414 /// ActOnPragmaOptionsAlign - Called on well formed \#pragma options align.
7415 void ActOnPragmaOptionsAlign(PragmaOptionsAlignKind Kind,
7416 SourceLocation PragmaLoc);
7418 enum PragmaPackKind {
7419 PPK_Default, // #pragma pack([n])
7420 PPK_Show, // #pragma pack(show), only supported by MSVC.
7421 PPK_Push, // #pragma pack(push, [identifier], [n])
7422 PPK_Pop // #pragma pack(pop, [identifier], [n])
7425 enum PragmaMSStructKind {
7426 PMSST_OFF, // #pragms ms_struct off
7427 PMSST_ON // #pragms ms_struct on
7430 enum PragmaMSCommentKind {
7432 PCK_Linker, // #pragma comment(linker, ...)
7433 PCK_Lib, // #pragma comment(lib, ...)
7434 PCK_Compiler, // #pragma comment(compiler, ...)
7435 PCK_ExeStr, // #pragma comment(exestr, ...)
7436 PCK_User // #pragma comment(user, ...)
7439 /// ActOnPragmaPack - Called on well formed \#pragma pack(...).
7440 void ActOnPragmaPack(PragmaPackKind Kind,
7441 IdentifierInfo *Name,
7443 SourceLocation PragmaLoc,
7444 SourceLocation LParenLoc,
7445 SourceLocation RParenLoc);
7447 /// ActOnPragmaMSStruct - Called on well formed \#pragma ms_struct [on|off].
7448 void ActOnPragmaMSStruct(PragmaMSStructKind Kind);
7450 /// ActOnPragmaMSComment - Called on well formed
7451 /// \#pragma comment(kind, "arg").
7452 void ActOnPragmaMSComment(PragmaMSCommentKind Kind, StringRef Arg);
7454 /// ActOnPragmaMSPointersToMembers - called on well formed \#pragma
7455 /// pointers_to_members(representation method[, general purpose
7456 /// representation]).
7457 void ActOnPragmaMSPointersToMembers(
7458 LangOptions::PragmaMSPointersToMembersKind Kind,
7459 SourceLocation PragmaLoc);
7461 /// \brief Called on well formed \#pragma vtordisp().
7462 void ActOnPragmaMSVtorDisp(PragmaVtorDispKind Kind, SourceLocation PragmaLoc,
7463 MSVtorDispAttr::Mode Value);
7465 enum PragmaSectionKind {
7472 bool UnifySection(StringRef SectionName,
7474 DeclaratorDecl *TheDecl);
7475 bool UnifySection(StringRef SectionName,
7477 SourceLocation PragmaSectionLocation);
7479 /// \brief Called on well formed \#pragma bss_seg/data_seg/const_seg/code_seg.
7480 void ActOnPragmaMSSeg(SourceLocation PragmaLocation,
7481 PragmaMsStackAction Action,
7482 llvm::StringRef StackSlotLabel,
7483 StringLiteral *SegmentName,
7484 llvm::StringRef PragmaName);
7486 /// \brief Called on well formed \#pragma section().
7487 void ActOnPragmaMSSection(SourceLocation PragmaLocation,
7488 int SectionFlags, StringLiteral *SegmentName);
7490 /// \brief Called on well-formed \#pragma init_seg().
7491 void ActOnPragmaMSInitSeg(SourceLocation PragmaLocation,
7492 StringLiteral *SegmentName);
7494 /// ActOnPragmaDetectMismatch - Call on well-formed \#pragma detect_mismatch
7495 void ActOnPragmaDetectMismatch(StringRef Name, StringRef Value);
7497 /// ActOnPragmaUnused - Called on well-formed '\#pragma unused'.
7498 void ActOnPragmaUnused(const Token &Identifier,
7500 SourceLocation PragmaLoc);
7502 /// ActOnPragmaVisibility - Called on well formed \#pragma GCC visibility... .
7503 void ActOnPragmaVisibility(const IdentifierInfo* VisType,
7504 SourceLocation PragmaLoc);
7506 NamedDecl *DeclClonePragmaWeak(NamedDecl *ND, IdentifierInfo *II,
7507 SourceLocation Loc);
7508 void DeclApplyPragmaWeak(Scope *S, NamedDecl *ND, WeakInfo &W);
7510 /// ActOnPragmaWeakID - Called on well formed \#pragma weak ident.
7511 void ActOnPragmaWeakID(IdentifierInfo* WeakName,
7512 SourceLocation PragmaLoc,
7513 SourceLocation WeakNameLoc);
7515 /// ActOnPragmaRedefineExtname - Called on well formed
7516 /// \#pragma redefine_extname oldname newname.
7517 void ActOnPragmaRedefineExtname(IdentifierInfo* WeakName,
7518 IdentifierInfo* AliasName,
7519 SourceLocation PragmaLoc,
7520 SourceLocation WeakNameLoc,
7521 SourceLocation AliasNameLoc);
7523 /// ActOnPragmaWeakAlias - Called on well formed \#pragma weak ident = ident.
7524 void ActOnPragmaWeakAlias(IdentifierInfo* WeakName,
7525 IdentifierInfo* AliasName,
7526 SourceLocation PragmaLoc,
7527 SourceLocation WeakNameLoc,
7528 SourceLocation AliasNameLoc);
7530 /// ActOnPragmaFPContract - Called on well formed
7531 /// \#pragma {STDC,OPENCL} FP_CONTRACT
7532 void ActOnPragmaFPContract(tok::OnOffSwitch OOS);
7534 /// AddAlignmentAttributesForRecord - Adds any needed alignment attributes to
7535 /// a the record decl, to handle '\#pragma pack' and '\#pragma options align'.
7536 void AddAlignmentAttributesForRecord(RecordDecl *RD);
7538 /// AddMsStructLayoutForRecord - Adds ms_struct layout attribute to record.
7539 void AddMsStructLayoutForRecord(RecordDecl *RD);
7541 /// FreePackedContext - Deallocate and null out PackContext.
7542 void FreePackedContext();
7544 /// PushNamespaceVisibilityAttr - Note that we've entered a
7545 /// namespace with a visibility attribute.
7546 void PushNamespaceVisibilityAttr(const VisibilityAttr *Attr,
7547 SourceLocation Loc);
7549 /// AddPushedVisibilityAttribute - If '\#pragma GCC visibility' was used,
7550 /// add an appropriate visibility attribute.
7551 void AddPushedVisibilityAttribute(Decl *RD);
7553 /// PopPragmaVisibility - Pop the top element of the visibility stack; used
7554 /// for '\#pragma GCC visibility' and visibility attributes on namespaces.
7555 void PopPragmaVisibility(bool IsNamespaceEnd, SourceLocation EndLoc);
7557 /// FreeVisContext - Deallocate and null out VisContext.
7558 void FreeVisContext();
7560 /// AddCFAuditedAttribute - Check whether we're currently within
7561 /// '\#pragma clang arc_cf_code_audited' and, if so, consider adding
7562 /// the appropriate attribute.
7563 void AddCFAuditedAttribute(Decl *D);
7565 /// \brief Called on well formed \#pragma clang optimize.
7566 void ActOnPragmaOptimize(bool On, SourceLocation PragmaLoc);
7568 /// \brief Get the location for the currently active "\#pragma clang optimize
7569 /// off". If this location is invalid, then the state of the pragma is "on".
7570 SourceLocation getOptimizeOffPragmaLocation() const {
7571 return OptimizeOffPragmaLocation;
7574 /// \brief Only called on function definitions; if there is a pragma in scope
7575 /// with the effect of a range-based optnone, consider marking the function
7576 /// with attribute optnone.
7577 void AddRangeBasedOptnone(FunctionDecl *FD);
7579 /// \brief Adds the 'optnone' attribute to the function declaration if there
7580 /// are no conflicts; Loc represents the location causing the 'optnone'
7581 /// attribute to be added (usually because of a pragma).
7582 void AddOptnoneAttributeIfNoConflicts(FunctionDecl *FD, SourceLocation Loc);
7584 /// AddAlignedAttr - Adds an aligned attribute to a particular declaration.
7585 void AddAlignedAttr(SourceRange AttrRange, Decl *D, Expr *E,
7586 unsigned SpellingListIndex, bool IsPackExpansion);
7587 void AddAlignedAttr(SourceRange AttrRange, Decl *D, TypeSourceInfo *T,
7588 unsigned SpellingListIndex, bool IsPackExpansion);
7590 /// AddAssumeAlignedAttr - Adds an assume_aligned attribute to a particular
7592 void AddAssumeAlignedAttr(SourceRange AttrRange, Decl *D, Expr *E, Expr *OE,
7593 unsigned SpellingListIndex);
7595 /// AddAlignValueAttr - Adds an align_value attribute to a particular
7597 void AddAlignValueAttr(SourceRange AttrRange, Decl *D, Expr *E,
7598 unsigned SpellingListIndex);
7600 /// AddLaunchBoundsAttr - Adds a launch_bounds attribute to a particular
7602 void AddLaunchBoundsAttr(SourceRange AttrRange, Decl *D, Expr *MaxThreads,
7603 Expr *MinBlocks, unsigned SpellingListIndex);
7605 // OpenMP directives and clauses.
7607 void *VarDataSharingAttributesStack;
7608 /// \brief Initialization of data-sharing attributes stack.
7609 void InitDataSharingAttributesStack();
7610 void DestroyDataSharingAttributesStack();
7611 ExprResult VerifyPositiveIntegerConstantInClause(Expr *Op,
7612 OpenMPClauseKind CKind);
7613 /// \brief Checks if the specified variable is used in one of the private
7614 /// clauses in OpenMP constructs.
7615 bool IsOpenMPCapturedVar(VarDecl *VD);
7618 /// \brief Check if the specified variable is used in one of the private
7619 /// clauses in OpenMP constructs.
7620 /// \param Level Relative level of nested OpenMP construct for that the check
7622 bool isOpenMPPrivateVar(VarDecl *VD, unsigned Level);
7624 ExprResult PerformOpenMPImplicitIntegerConversion(SourceLocation OpLoc,
7626 /// \brief Called on start of new data sharing attribute block.
7627 void StartOpenMPDSABlock(OpenMPDirectiveKind K,
7628 const DeclarationNameInfo &DirName, Scope *CurScope,
7629 SourceLocation Loc);
7630 /// \brief Start analysis of clauses.
7631 void StartOpenMPClause(OpenMPClauseKind K);
7632 /// \brief End analysis of clauses.
7633 void EndOpenMPClause();
7634 /// \brief Called on end of data sharing attribute block.
7635 void EndOpenMPDSABlock(Stmt *CurDirective);
7637 /// \brief Check if the current region is an OpenMP loop region and if it is,
7638 /// mark loop control variable, used in \p Init for loop initialization, as
7639 /// private by default.
7640 /// \param Init First part of the for loop.
7641 void ActOnOpenMPLoopInitialization(SourceLocation ForLoc, Stmt *Init);
7643 // OpenMP directives and clauses.
7644 /// \brief Called on correct id-expression from the '#pragma omp
7646 ExprResult ActOnOpenMPIdExpression(Scope *CurScope,
7647 CXXScopeSpec &ScopeSpec,
7648 const DeclarationNameInfo &Id);
7649 /// \brief Called on well-formed '#pragma omp threadprivate'.
7650 DeclGroupPtrTy ActOnOpenMPThreadprivateDirective(
7652 ArrayRef<Expr *> VarList);
7653 /// \brief Builds a new OpenMPThreadPrivateDecl and checks its correctness.
7654 OMPThreadPrivateDecl *CheckOMPThreadPrivateDecl(
7656 ArrayRef<Expr *> VarList);
7658 /// \brief Initialization of captured region for OpenMP region.
7659 void ActOnOpenMPRegionStart(OpenMPDirectiveKind DKind, Scope *CurScope);
7660 /// \brief End of OpenMP region.
7662 /// \param S Statement associated with the current OpenMP region.
7663 /// \param Clauses List of clauses for the current OpenMP region.
7665 /// \returns Statement for finished OpenMP region.
7666 StmtResult ActOnOpenMPRegionEnd(StmtResult S, ArrayRef<OMPClause *> Clauses);
7667 StmtResult ActOnOpenMPExecutableDirective(
7668 OpenMPDirectiveKind Kind, const DeclarationNameInfo &DirName,
7669 OpenMPDirectiveKind CancelRegion, ArrayRef<OMPClause *> Clauses,
7670 Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc);
7671 /// \brief Called on well-formed '\#pragma omp parallel' after parsing
7672 /// of the associated statement.
7673 StmtResult ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses,
7675 SourceLocation StartLoc,
7676 SourceLocation EndLoc);
7677 /// \brief Called on well-formed '\#pragma omp simd' after parsing
7678 /// of the associated statement.
7679 StmtResult ActOnOpenMPSimdDirective(
7680 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7681 SourceLocation EndLoc,
7682 llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA);
7683 /// \brief Called on well-formed '\#pragma omp for' after parsing
7684 /// of the associated statement.
7685 StmtResult ActOnOpenMPForDirective(
7686 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7687 SourceLocation EndLoc,
7688 llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA);
7689 /// \brief Called on well-formed '\#pragma omp for simd' after parsing
7690 /// of the associated statement.
7691 StmtResult ActOnOpenMPForSimdDirective(
7692 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7693 SourceLocation EndLoc,
7694 llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA);
7695 /// \brief Called on well-formed '\#pragma omp sections' after parsing
7696 /// of the associated statement.
7697 StmtResult ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses,
7698 Stmt *AStmt, SourceLocation StartLoc,
7699 SourceLocation EndLoc);
7700 /// \brief Called on well-formed '\#pragma omp section' after parsing of the
7701 /// associated statement.
7702 StmtResult ActOnOpenMPSectionDirective(Stmt *AStmt, SourceLocation StartLoc,
7703 SourceLocation EndLoc);
7704 /// \brief Called on well-formed '\#pragma omp single' after parsing of the
7705 /// associated statement.
7706 StmtResult ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses,
7707 Stmt *AStmt, SourceLocation StartLoc,
7708 SourceLocation EndLoc);
7709 /// \brief Called on well-formed '\#pragma omp master' after parsing of the
7710 /// associated statement.
7711 StmtResult ActOnOpenMPMasterDirective(Stmt *AStmt, SourceLocation StartLoc,
7712 SourceLocation EndLoc);
7713 /// \brief Called on well-formed '\#pragma omp critical' after parsing of the
7714 /// associated statement.
7715 StmtResult ActOnOpenMPCriticalDirective(const DeclarationNameInfo &DirName,
7716 Stmt *AStmt, SourceLocation StartLoc,
7717 SourceLocation EndLoc);
7718 /// \brief Called on well-formed '\#pragma omp parallel for' after parsing
7719 /// of the associated statement.
7720 StmtResult ActOnOpenMPParallelForDirective(
7721 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7722 SourceLocation EndLoc,
7723 llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA);
7724 /// \brief Called on well-formed '\#pragma omp parallel for simd' after
7725 /// parsing of the associated statement.
7726 StmtResult ActOnOpenMPParallelForSimdDirective(
7727 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7728 SourceLocation EndLoc,
7729 llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA);
7730 /// \brief Called on well-formed '\#pragma omp parallel sections' after
7731 /// parsing of the associated statement.
7732 StmtResult ActOnOpenMPParallelSectionsDirective(ArrayRef<OMPClause *> Clauses,
7734 SourceLocation StartLoc,
7735 SourceLocation EndLoc);
7736 /// \brief Called on well-formed '\#pragma omp task' after parsing of the
7737 /// associated statement.
7738 StmtResult ActOnOpenMPTaskDirective(ArrayRef<OMPClause *> Clauses,
7739 Stmt *AStmt, SourceLocation StartLoc,
7740 SourceLocation EndLoc);
7741 /// \brief Called on well-formed '\#pragma omp taskyield'.
7742 StmtResult ActOnOpenMPTaskyieldDirective(SourceLocation StartLoc,
7743 SourceLocation EndLoc);
7744 /// \brief Called on well-formed '\#pragma omp barrier'.
7745 StmtResult ActOnOpenMPBarrierDirective(SourceLocation StartLoc,
7746 SourceLocation EndLoc);
7747 /// \brief Called on well-formed '\#pragma omp taskwait'.
7748 StmtResult ActOnOpenMPTaskwaitDirective(SourceLocation StartLoc,
7749 SourceLocation EndLoc);
7750 /// \brief Called on well-formed '\#pragma omp taskgroup'.
7751 StmtResult ActOnOpenMPTaskgroupDirective(Stmt *AStmt, SourceLocation StartLoc,
7752 SourceLocation EndLoc);
7753 /// \brief Called on well-formed '\#pragma omp flush'.
7754 StmtResult ActOnOpenMPFlushDirective(ArrayRef<OMPClause *> Clauses,
7755 SourceLocation StartLoc,
7756 SourceLocation EndLoc);
7757 /// \brief Called on well-formed '\#pragma omp ordered' after parsing of the
7758 /// associated statement.
7759 StmtResult ActOnOpenMPOrderedDirective(Stmt *AStmt, SourceLocation StartLoc,
7760 SourceLocation EndLoc);
7761 /// \brief Called on well-formed '\#pragma omp atomic' after parsing of the
7762 /// associated statement.
7763 StmtResult ActOnOpenMPAtomicDirective(ArrayRef<OMPClause *> Clauses,
7764 Stmt *AStmt, SourceLocation StartLoc,
7765 SourceLocation EndLoc);
7766 /// \brief Called on well-formed '\#pragma omp target' after parsing of the
7767 /// associated statement.
7768 StmtResult ActOnOpenMPTargetDirective(ArrayRef<OMPClause *> Clauses,
7769 Stmt *AStmt, SourceLocation StartLoc,
7770 SourceLocation EndLoc);
7771 /// \brief Called on well-formed '\#pragma omp teams' after parsing of the
7772 /// associated statement.
7773 StmtResult ActOnOpenMPTeamsDirective(ArrayRef<OMPClause *> Clauses,
7774 Stmt *AStmt, SourceLocation StartLoc,
7775 SourceLocation EndLoc);
7776 /// \brief Called on well-formed '\#pragma omp cancellation point'.
7778 ActOnOpenMPCancellationPointDirective(SourceLocation StartLoc,
7779 SourceLocation EndLoc,
7780 OpenMPDirectiveKind CancelRegion);
7781 /// \brief Called on well-formed '\#pragma omp cancel'.
7782 StmtResult ActOnOpenMPCancelDirective(SourceLocation StartLoc,
7783 SourceLocation EndLoc,
7784 OpenMPDirectiveKind CancelRegion);
7786 OMPClause *ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind,
7788 SourceLocation StartLoc,
7789 SourceLocation LParenLoc,
7790 SourceLocation EndLoc);
7791 /// \brief Called on well-formed 'if' clause.
7792 OMPClause *ActOnOpenMPIfClause(Expr *Condition, SourceLocation StartLoc,
7793 SourceLocation LParenLoc,
7794 SourceLocation EndLoc);
7795 /// \brief Called on well-formed 'final' clause.
7796 OMPClause *ActOnOpenMPFinalClause(Expr *Condition, SourceLocation StartLoc,
7797 SourceLocation LParenLoc,
7798 SourceLocation EndLoc);
7799 /// \brief Called on well-formed 'num_threads' clause.
7800 OMPClause *ActOnOpenMPNumThreadsClause(Expr *NumThreads,
7801 SourceLocation StartLoc,
7802 SourceLocation LParenLoc,
7803 SourceLocation EndLoc);
7804 /// \brief Called on well-formed 'safelen' clause.
7805 OMPClause *ActOnOpenMPSafelenClause(Expr *Length,
7806 SourceLocation StartLoc,
7807 SourceLocation LParenLoc,
7808 SourceLocation EndLoc);
7809 /// \brief Called on well-formed 'collapse' clause.
7810 OMPClause *ActOnOpenMPCollapseClause(Expr *NumForLoops,
7811 SourceLocation StartLoc,
7812 SourceLocation LParenLoc,
7813 SourceLocation EndLoc);
7815 OMPClause *ActOnOpenMPSimpleClause(OpenMPClauseKind Kind,
7817 SourceLocation ArgumentLoc,
7818 SourceLocation StartLoc,
7819 SourceLocation LParenLoc,
7820 SourceLocation EndLoc);
7821 /// \brief Called on well-formed 'default' clause.
7822 OMPClause *ActOnOpenMPDefaultClause(OpenMPDefaultClauseKind Kind,
7823 SourceLocation KindLoc,
7824 SourceLocation StartLoc,
7825 SourceLocation LParenLoc,
7826 SourceLocation EndLoc);
7827 /// \brief Called on well-formed 'proc_bind' clause.
7828 OMPClause *ActOnOpenMPProcBindClause(OpenMPProcBindClauseKind Kind,
7829 SourceLocation KindLoc,
7830 SourceLocation StartLoc,
7831 SourceLocation LParenLoc,
7832 SourceLocation EndLoc);
7834 OMPClause *ActOnOpenMPSingleExprWithArgClause(OpenMPClauseKind Kind,
7835 unsigned Argument, Expr *Expr,
7836 SourceLocation StartLoc,
7837 SourceLocation LParenLoc,
7838 SourceLocation ArgumentLoc,
7839 SourceLocation CommaLoc,
7840 SourceLocation EndLoc);
7841 /// \brief Called on well-formed 'schedule' clause.
7842 OMPClause *ActOnOpenMPScheduleClause(OpenMPScheduleClauseKind Kind,
7843 Expr *ChunkSize, SourceLocation StartLoc,
7844 SourceLocation LParenLoc,
7845 SourceLocation KindLoc,
7846 SourceLocation CommaLoc,
7847 SourceLocation EndLoc);
7849 OMPClause *ActOnOpenMPClause(OpenMPClauseKind Kind, SourceLocation StartLoc,
7850 SourceLocation EndLoc);
7851 /// \brief Called on well-formed 'ordered' clause.
7852 OMPClause *ActOnOpenMPOrderedClause(SourceLocation StartLoc,
7853 SourceLocation EndLoc);
7854 /// \brief Called on well-formed 'nowait' clause.
7855 OMPClause *ActOnOpenMPNowaitClause(SourceLocation StartLoc,
7856 SourceLocation EndLoc);
7857 /// \brief Called on well-formed 'untied' clause.
7858 OMPClause *ActOnOpenMPUntiedClause(SourceLocation StartLoc,
7859 SourceLocation EndLoc);
7860 /// \brief Called on well-formed 'mergeable' clause.
7861 OMPClause *ActOnOpenMPMergeableClause(SourceLocation StartLoc,
7862 SourceLocation EndLoc);
7863 /// \brief Called on well-formed 'read' clause.
7864 OMPClause *ActOnOpenMPReadClause(SourceLocation StartLoc,
7865 SourceLocation EndLoc);
7866 /// \brief Called on well-formed 'write' clause.
7867 OMPClause *ActOnOpenMPWriteClause(SourceLocation StartLoc,
7868 SourceLocation EndLoc);
7869 /// \brief Called on well-formed 'update' clause.
7870 OMPClause *ActOnOpenMPUpdateClause(SourceLocation StartLoc,
7871 SourceLocation EndLoc);
7872 /// \brief Called on well-formed 'capture' clause.
7873 OMPClause *ActOnOpenMPCaptureClause(SourceLocation StartLoc,
7874 SourceLocation EndLoc);
7875 /// \brief Called on well-formed 'seq_cst' clause.
7876 OMPClause *ActOnOpenMPSeqCstClause(SourceLocation StartLoc,
7877 SourceLocation EndLoc);
7879 OMPClause *ActOnOpenMPVarListClause(
7880 OpenMPClauseKind Kind, ArrayRef<Expr *> Vars, Expr *TailExpr,
7881 SourceLocation StartLoc, SourceLocation LParenLoc,
7882 SourceLocation ColonLoc, SourceLocation EndLoc,
7883 CXXScopeSpec &ReductionIdScopeSpec,
7884 const DeclarationNameInfo &ReductionId, OpenMPDependClauseKind DepKind,
7885 SourceLocation DepLoc);
7886 /// \brief Called on well-formed 'private' clause.
7887 OMPClause *ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList,
7888 SourceLocation StartLoc,
7889 SourceLocation LParenLoc,
7890 SourceLocation EndLoc);
7891 /// \brief Called on well-formed 'firstprivate' clause.
7892 OMPClause *ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList,
7893 SourceLocation StartLoc,
7894 SourceLocation LParenLoc,
7895 SourceLocation EndLoc);
7896 /// \brief Called on well-formed 'lastprivate' clause.
7897 OMPClause *ActOnOpenMPLastprivateClause(ArrayRef<Expr *> VarList,
7898 SourceLocation StartLoc,
7899 SourceLocation LParenLoc,
7900 SourceLocation EndLoc);
7901 /// \brief Called on well-formed 'shared' clause.
7902 OMPClause *ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList,
7903 SourceLocation StartLoc,
7904 SourceLocation LParenLoc,
7905 SourceLocation EndLoc);
7906 /// \brief Called on well-formed 'reduction' clause.
7908 ActOnOpenMPReductionClause(ArrayRef<Expr *> VarList, SourceLocation StartLoc,
7909 SourceLocation LParenLoc, SourceLocation ColonLoc,
7910 SourceLocation EndLoc,
7911 CXXScopeSpec &ReductionIdScopeSpec,
7912 const DeclarationNameInfo &ReductionId);
7913 /// \brief Called on well-formed 'linear' clause.
7914 OMPClause *ActOnOpenMPLinearClause(ArrayRef<Expr *> VarList,
7916 SourceLocation StartLoc,
7917 SourceLocation LParenLoc,
7918 SourceLocation ColonLoc,
7919 SourceLocation EndLoc);
7920 /// \brief Called on well-formed 'aligned' clause.
7921 OMPClause *ActOnOpenMPAlignedClause(ArrayRef<Expr *> VarList,
7923 SourceLocation StartLoc,
7924 SourceLocation LParenLoc,
7925 SourceLocation ColonLoc,
7926 SourceLocation EndLoc);
7927 /// \brief Called on well-formed 'copyin' clause.
7928 OMPClause *ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList,
7929 SourceLocation StartLoc,
7930 SourceLocation LParenLoc,
7931 SourceLocation EndLoc);
7932 /// \brief Called on well-formed 'copyprivate' clause.
7933 OMPClause *ActOnOpenMPCopyprivateClause(ArrayRef<Expr *> VarList,
7934 SourceLocation StartLoc,
7935 SourceLocation LParenLoc,
7936 SourceLocation EndLoc);
7937 /// \brief Called on well-formed 'flush' pseudo clause.
7938 OMPClause *ActOnOpenMPFlushClause(ArrayRef<Expr *> VarList,
7939 SourceLocation StartLoc,
7940 SourceLocation LParenLoc,
7941 SourceLocation EndLoc);
7942 /// \brief Called on well-formed 'depend' clause.
7944 ActOnOpenMPDependClause(OpenMPDependClauseKind DepKind, SourceLocation DepLoc,
7945 SourceLocation ColonLoc, ArrayRef<Expr *> VarList,
7946 SourceLocation StartLoc, SourceLocation LParenLoc,
7947 SourceLocation EndLoc);
7949 /// \brief The kind of conversion being performed.
7950 enum CheckedConversionKind {
7951 /// \brief An implicit conversion.
7952 CCK_ImplicitConversion,
7953 /// \brief A C-style cast.
7955 /// \brief A functional-style cast.
7957 /// \brief A cast other than a C-style cast.
7961 /// ImpCastExprToType - If Expr is not of type 'Type', insert an implicit
7962 /// cast. If there is already an implicit cast, merge into the existing one.
7963 /// If isLvalue, the result of the cast is an lvalue.
7964 ExprResult ImpCastExprToType(Expr *E, QualType Type, CastKind CK,
7965 ExprValueKind VK = VK_RValue,
7966 const CXXCastPath *BasePath = nullptr,
7967 CheckedConversionKind CCK
7968 = CCK_ImplicitConversion);
7970 /// ScalarTypeToBooleanCastKind - Returns the cast kind corresponding
7971 /// to the conversion from scalar type ScalarTy to the Boolean type.
7972 static CastKind ScalarTypeToBooleanCastKind(QualType ScalarTy);
7974 /// IgnoredValueConversions - Given that an expression's result is
7975 /// syntactically ignored, perform any conversions that are
7977 ExprResult IgnoredValueConversions(Expr *E);
7979 // UsualUnaryConversions - promotes integers (C99 6.3.1.1p2) and converts
7980 // functions and arrays to their respective pointers (C99 6.3.2.1).
7981 ExprResult UsualUnaryConversions(Expr *E);
7983 /// CallExprUnaryConversions - a special case of an unary conversion
7984 /// performed on a function designator of a call expression.
7985 ExprResult CallExprUnaryConversions(Expr *E);
7987 // DefaultFunctionArrayConversion - converts functions and arrays
7988 // to their respective pointers (C99 6.3.2.1).
7989 ExprResult DefaultFunctionArrayConversion(Expr *E);
7991 // DefaultFunctionArrayLvalueConversion - converts functions and
7992 // arrays to their respective pointers and performs the
7993 // lvalue-to-rvalue conversion.
7994 ExprResult DefaultFunctionArrayLvalueConversion(Expr *E);
7996 // DefaultLvalueConversion - performs lvalue-to-rvalue conversion on
7997 // the operand. This is DefaultFunctionArrayLvalueConversion,
7998 // except that it assumes the operand isn't of function or array
8000 ExprResult DefaultLvalueConversion(Expr *E);
8002 // DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
8003 // do not have a prototype. Integer promotions are performed on each
8004 // argument, and arguments that have type float are promoted to double.
8005 ExprResult DefaultArgumentPromotion(Expr *E);
8007 // Used for emitting the right warning by DefaultVariadicArgumentPromotion
8008 enum VariadicCallType {
8012 VariadicConstructor,
8013 VariadicDoesNotApply
8016 VariadicCallType getVariadicCallType(FunctionDecl *FDecl,
8017 const FunctionProtoType *Proto,
8020 // Used for determining in which context a type is allowed to be passed to a
8030 // Determines which VarArgKind fits an expression.
8031 VarArgKind isValidVarArgType(const QualType &Ty);
8033 /// Check to see if the given expression is a valid argument to a variadic
8034 /// function, issuing a diagnostic if not.
8035 void checkVariadicArgument(const Expr *E, VariadicCallType CT);
8037 /// Check to see if a given expression could have '.c_str()' called on it.
8038 bool hasCStrMethod(const Expr *E);
8040 /// GatherArgumentsForCall - Collector argument expressions for various
8041 /// form of call prototypes.
8042 bool GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl,
8043 const FunctionProtoType *Proto,
8044 unsigned FirstParam, ArrayRef<Expr *> Args,
8045 SmallVectorImpl<Expr *> &AllArgs,
8046 VariadicCallType CallType = VariadicDoesNotApply,
8047 bool AllowExplicit = false,
8048 bool IsListInitialization = false);
8050 // DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
8051 // will create a runtime trap if the resulting type is not a POD type.
8052 ExprResult DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
8053 FunctionDecl *FDecl);
8055 // UsualArithmeticConversions - performs the UsualUnaryConversions on it's
8056 // operands and then handles various conversions that are common to binary
8057 // operators (C99 6.3.1.8). If both operands aren't arithmetic, this
8058 // routine returns the first non-arithmetic type found. The client is
8059 // responsible for emitting appropriate error diagnostics.
8060 QualType UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
8061 bool IsCompAssign = false);
8063 /// AssignConvertType - All of the 'assignment' semantic checks return this
8064 /// enum to indicate whether the assignment was allowed. These checks are
8065 /// done for simple assignments, as well as initialization, return from
8066 /// function, argument passing, etc. The query is phrased in terms of a
8067 /// source and destination type.
8068 enum AssignConvertType {
8069 /// Compatible - the types are compatible according to the standard.
8072 /// PointerToInt - The assignment converts a pointer to an int, which we
8073 /// accept as an extension.
8076 /// IntToPointer - The assignment converts an int to a pointer, which we
8077 /// accept as an extension.
8080 /// FunctionVoidPointer - The assignment is between a function pointer and
8081 /// void*, which the standard doesn't allow, but we accept as an extension.
8082 FunctionVoidPointer,
8084 /// IncompatiblePointer - The assignment is between two pointers types that
8085 /// are not compatible, but we accept them as an extension.
8086 IncompatiblePointer,
8088 /// IncompatiblePointer - The assignment is between two pointers types which
8089 /// point to integers which have a different sign, but are otherwise
8090 /// identical. This is a subset of the above, but broken out because it's by
8091 /// far the most common case of incompatible pointers.
8092 IncompatiblePointerSign,
8094 /// CompatiblePointerDiscardsQualifiers - The assignment discards
8095 /// c/v/r qualifiers, which we accept as an extension.
8096 CompatiblePointerDiscardsQualifiers,
8098 /// IncompatiblePointerDiscardsQualifiers - The assignment
8099 /// discards qualifiers that we don't permit to be discarded,
8100 /// like address spaces.
8101 IncompatiblePointerDiscardsQualifiers,
8103 /// IncompatibleNestedPointerQualifiers - The assignment is between two
8104 /// nested pointer types, and the qualifiers other than the first two
8105 /// levels differ e.g. char ** -> const char **, but we accept them as an
8107 IncompatibleNestedPointerQualifiers,
8109 /// IncompatibleVectors - The assignment is between two vector types that
8110 /// have the same size, which we accept as an extension.
8111 IncompatibleVectors,
8113 /// IntToBlockPointer - The assignment converts an int to a block
8114 /// pointer. We disallow this.
8117 /// IncompatibleBlockPointer - The assignment is between two block
8118 /// pointers types that are not compatible.
8119 IncompatibleBlockPointer,
8121 /// IncompatibleObjCQualifiedId - The assignment is between a qualified
8122 /// id type and something else (that is incompatible with it). For example,
8123 /// "id <XXX>" = "Foo *", where "Foo *" doesn't implement the XXX protocol.
8124 IncompatibleObjCQualifiedId,
8126 /// IncompatibleObjCWeakRef - Assigning a weak-unavailable object to an
8127 /// object with __weak qualifier.
8128 IncompatibleObjCWeakRef,
8130 /// Incompatible - We reject this conversion outright, it is invalid to
8131 /// represent it in the AST.
8135 /// DiagnoseAssignmentResult - Emit a diagnostic, if required, for the
8136 /// assignment conversion type specified by ConvTy. This returns true if the
8137 /// conversion was invalid or false if the conversion was accepted.
8138 bool DiagnoseAssignmentResult(AssignConvertType ConvTy,
8140 QualType DstType, QualType SrcType,
8141 Expr *SrcExpr, AssignmentAction Action,
8142 bool *Complained = nullptr);
8144 /// IsValueInFlagEnum - Determine if a value is allowed as part of a flag
8145 /// enum. If AllowMask is true, then we also allow the complement of a valid
8146 /// value, to be used as a mask.
8147 bool IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
8148 bool AllowMask) const;
8150 /// DiagnoseAssignmentEnum - Warn if assignment to enum is a constant
8151 /// integer not in the range of enum values.
8152 void DiagnoseAssignmentEnum(QualType DstType, QualType SrcType,
8155 /// CheckAssignmentConstraints - Perform type checking for assignment,
8156 /// argument passing, variable initialization, and function return values.
8158 AssignConvertType CheckAssignmentConstraints(SourceLocation Loc,
8162 /// Check assignment constraints and prepare for a conversion of the
8163 /// RHS to the LHS type.
8164 AssignConvertType CheckAssignmentConstraints(QualType LHSType,
8168 // CheckSingleAssignmentConstraints - Currently used by
8169 // CheckAssignmentOperands, and ActOnReturnStmt. Prior to type checking,
8170 // this routine performs the default function/array converions.
8171 AssignConvertType CheckSingleAssignmentConstraints(QualType LHSType,
8173 bool Diagnose = true,
8174 bool DiagnoseCFAudited = false);
8176 // \brief If the lhs type is a transparent union, check whether we
8177 // can initialize the transparent union with the given expression.
8178 AssignConvertType CheckTransparentUnionArgumentConstraints(QualType ArgType,
8181 bool IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType);
8183 bool CheckExceptionSpecCompatibility(Expr *From, QualType ToType);
8185 ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
8186 AssignmentAction Action,
8187 bool AllowExplicit = false);
8188 ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
8189 AssignmentAction Action,
8191 ImplicitConversionSequence& ICS);
8192 ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
8193 const ImplicitConversionSequence& ICS,
8194 AssignmentAction Action,
8195 CheckedConversionKind CCK
8196 = CCK_ImplicitConversion);
8197 ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
8198 const StandardConversionSequence& SCS,
8199 AssignmentAction Action,
8200 CheckedConversionKind CCK);
8202 /// the following "Check" methods will return a valid/converted QualType
8203 /// or a null QualType (indicating an error diagnostic was issued).
8205 /// type checking binary operators (subroutines of CreateBuiltinBinOp).
8206 QualType InvalidOperands(SourceLocation Loc, ExprResult &LHS,
8208 QualType CheckPointerToMemberOperands( // C++ 5.5
8209 ExprResult &LHS, ExprResult &RHS, ExprValueKind &VK,
8210 SourceLocation OpLoc, bool isIndirect);
8211 QualType CheckMultiplyDivideOperands( // C99 6.5.5
8212 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign,
8214 QualType CheckRemainderOperands( // C99 6.5.5
8215 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
8216 bool IsCompAssign = false);
8217 QualType CheckAdditionOperands( // C99 6.5.6
8218 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc,
8219 QualType* CompLHSTy = nullptr);
8220 QualType CheckSubtractionOperands( // C99 6.5.6
8221 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
8222 QualType* CompLHSTy = nullptr);
8223 QualType CheckShiftOperands( // C99 6.5.7
8224 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc,
8225 bool IsCompAssign = false);
8226 QualType CheckCompareOperands( // C99 6.5.8/9
8227 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned OpaqueOpc,
8229 QualType CheckBitwiseOperands( // C99 6.5.[10...12]
8230 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
8231 bool IsCompAssign = false);
8232 QualType CheckLogicalOperands( // C99 6.5.[13,14]
8233 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc);
8234 // CheckAssignmentOperands is used for both simple and compound assignment.
8235 // For simple assignment, pass both expressions and a null converted type.
8236 // For compound assignment, pass both expressions and the converted type.
8237 QualType CheckAssignmentOperands( // C99 6.5.16.[1,2]
8238 Expr *LHSExpr, ExprResult &RHS, SourceLocation Loc, QualType CompoundType);
8240 ExprResult checkPseudoObjectIncDec(Scope *S, SourceLocation OpLoc,
8241 UnaryOperatorKind Opcode, Expr *Op);
8242 ExprResult checkPseudoObjectAssignment(Scope *S, SourceLocation OpLoc,
8243 BinaryOperatorKind Opcode,
8244 Expr *LHS, Expr *RHS);
8245 ExprResult checkPseudoObjectRValue(Expr *E);
8246 Expr *recreateSyntacticForm(PseudoObjectExpr *E);
8248 QualType CheckConditionalOperands( // C99 6.5.15
8249 ExprResult &Cond, ExprResult &LHS, ExprResult &RHS,
8250 ExprValueKind &VK, ExprObjectKind &OK, SourceLocation QuestionLoc);
8251 QualType CXXCheckConditionalOperands( // C++ 5.16
8252 ExprResult &cond, ExprResult &lhs, ExprResult &rhs,
8253 ExprValueKind &VK, ExprObjectKind &OK, SourceLocation questionLoc);
8254 QualType FindCompositePointerType(SourceLocation Loc, Expr *&E1, Expr *&E2,
8255 bool *NonStandardCompositeType = nullptr);
8256 QualType FindCompositePointerType(SourceLocation Loc,
8257 ExprResult &E1, ExprResult &E2,
8258 bool *NonStandardCompositeType = nullptr) {
8259 Expr *E1Tmp = E1.get(), *E2Tmp = E2.get();
8260 QualType Composite = FindCompositePointerType(Loc, E1Tmp, E2Tmp,
8261 NonStandardCompositeType);
8267 QualType FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
8268 SourceLocation QuestionLoc);
8270 bool DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
8271 SourceLocation QuestionLoc);
8273 void DiagnoseAlwaysNonNullPointer(Expr *E,
8274 Expr::NullPointerConstantKind NullType,
8275 bool IsEqual, SourceRange Range);
8277 /// type checking for vector binary operators.
8278 QualType CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
8279 SourceLocation Loc, bool IsCompAssign);
8280 QualType GetSignedVectorType(QualType V);
8281 QualType CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
8282 SourceLocation Loc, bool isRelational);
8283 QualType CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
8284 SourceLocation Loc);
8286 bool isLaxVectorConversion(QualType srcType, QualType destType);
8288 /// type checking declaration initializers (C99 6.7.8)
8289 bool CheckForConstantInitializer(Expr *e, QualType t);
8291 // type checking C++ declaration initializers (C++ [dcl.init]).
8293 /// ReferenceCompareResult - Expresses the result of comparing two
8294 /// types (cv1 T1 and cv2 T2) to determine their compatibility for the
8295 /// purposes of initialization by reference (C++ [dcl.init.ref]p4).
8296 enum ReferenceCompareResult {
8297 /// Ref_Incompatible - The two types are incompatible, so direct
8298 /// reference binding is not possible.
8299 Ref_Incompatible = 0,
8300 /// Ref_Related - The two types are reference-related, which means
8301 /// that their unqualified forms (T1 and T2) are either the same
8302 /// or T1 is a base class of T2.
8304 /// Ref_Compatible_With_Added_Qualification - The two types are
8305 /// reference-compatible with added qualification, meaning that
8306 /// they are reference-compatible and the qualifiers on T1 (cv1)
8307 /// are greater than the qualifiers on T2 (cv2).
8308 Ref_Compatible_With_Added_Qualification,
8309 /// Ref_Compatible - The two types are reference-compatible and
8310 /// have equivalent qualifiers (cv1 == cv2).
8314 ReferenceCompareResult CompareReferenceRelationship(SourceLocation Loc,
8315 QualType T1, QualType T2,
8316 bool &DerivedToBase,
8317 bool &ObjCConversion,
8318 bool &ObjCLifetimeConversion);
8320 ExprResult checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
8321 Expr *CastExpr, CastKind &CastKind,
8322 ExprValueKind &VK, CXXCastPath &Path);
8324 /// \brief Force an expression with unknown-type to an expression of the
8326 ExprResult forceUnknownAnyToType(Expr *E, QualType ToType);
8328 /// \brief Type-check an expression that's being passed to an
8329 /// __unknown_anytype parameter.
8330 ExprResult checkUnknownAnyArg(SourceLocation callLoc,
8331 Expr *result, QualType ¶mType);
8333 // CheckVectorCast - check type constraints for vectors.
8334 // Since vectors are an extension, there are no C standard reference for this.
8335 // We allow casting between vectors and integer datatypes of the same size.
8336 // returns true if the cast is invalid
8337 bool CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
8340 // CheckExtVectorCast - check type constraints for extended vectors.
8341 // Since vectors are an extension, there are no C standard reference for this.
8342 // We allow casting between vectors and integer datatypes of the same size,
8343 // or vectors and the element type of that vector.
8344 // returns the cast expr
8345 ExprResult CheckExtVectorCast(SourceRange R, QualType DestTy, Expr *CastExpr,
8348 ExprResult BuildCXXFunctionalCastExpr(TypeSourceInfo *TInfo,
8349 SourceLocation LParenLoc,
8351 SourceLocation RParenLoc);
8353 enum ARCConversionResult { ACR_okay, ACR_unbridged };
8355 /// \brief Checks for invalid conversions and casts between
8356 /// retainable pointers and other pointer kinds.
8357 ARCConversionResult CheckObjCARCConversion(SourceRange castRange,
8358 QualType castType, Expr *&op,
8359 CheckedConversionKind CCK,
8360 bool DiagnoseCFAudited = false,
8361 BinaryOperatorKind Opc = BO_PtrMemD
8364 Expr *stripARCUnbridgedCast(Expr *e);
8365 void diagnoseARCUnbridgedCast(Expr *e);
8367 bool CheckObjCARCUnavailableWeakConversion(QualType castType,
8370 /// checkRetainCycles - Check whether an Objective-C message send
8371 /// might create an obvious retain cycle.
8372 void checkRetainCycles(ObjCMessageExpr *msg);
8373 void checkRetainCycles(Expr *receiver, Expr *argument);
8374 void checkRetainCycles(VarDecl *Var, Expr *Init);
8376 /// checkUnsafeAssigns - Check whether +1 expr is being assigned
8377 /// to weak/__unsafe_unretained type.
8378 bool checkUnsafeAssigns(SourceLocation Loc, QualType LHS, Expr *RHS);
8380 /// checkUnsafeExprAssigns - Check whether +1 expr is being assigned
8381 /// to weak/__unsafe_unretained expression.
8382 void checkUnsafeExprAssigns(SourceLocation Loc, Expr *LHS, Expr *RHS);
8384 /// CheckMessageArgumentTypes - Check types in an Obj-C message send.
8385 /// \param Method - May be null.
8386 /// \param [out] ReturnType - The return type of the send.
8387 /// \return true iff there were any incompatible types.
8388 bool CheckMessageArgumentTypes(QualType ReceiverType,
8389 MultiExprArg Args, Selector Sel,
8390 ArrayRef<SourceLocation> SelectorLocs,
8391 ObjCMethodDecl *Method, bool isClassMessage,
8392 bool isSuperMessage,
8393 SourceLocation lbrac, SourceLocation rbrac,
8394 SourceRange RecRange,
8395 QualType &ReturnType, ExprValueKind &VK);
8397 /// \brief Determine the result of a message send expression based on
8398 /// the type of the receiver, the method expected to receive the message,
8399 /// and the form of the message send.
8400 QualType getMessageSendResultType(QualType ReceiverType,
8401 ObjCMethodDecl *Method,
8402 bool isClassMessage, bool isSuperMessage);
8404 /// \brief If the given expression involves a message send to a method
8405 /// with a related result type, emit a note describing what happened.
8406 void EmitRelatedResultTypeNote(const Expr *E);
8408 /// \brief Given that we had incompatible pointer types in a return
8409 /// statement, check whether we're in a method with a related result
8410 /// type, and if so, emit a note describing what happened.
8411 void EmitRelatedResultTypeNoteForReturn(QualType destType);
8413 /// CheckBooleanCondition - Diagnose problems involving the use of
8414 /// the given expression as a boolean condition (e.g. in an if
8415 /// statement). Also performs the standard function and array
8416 /// decays, possibly changing the input variable.
8418 /// \param Loc - A location associated with the condition, e.g. the
8420 /// \return true iff there were any errors
8421 ExprResult CheckBooleanCondition(Expr *E, SourceLocation Loc);
8423 ExprResult ActOnBooleanCondition(Scope *S, SourceLocation Loc,
8426 /// DiagnoseAssignmentAsCondition - Given that an expression is
8427 /// being used as a boolean condition, warn if it's an assignment.
8428 void DiagnoseAssignmentAsCondition(Expr *E);
8430 /// \brief Redundant parentheses over an equality comparison can indicate
8431 /// that the user intended an assignment used as condition.
8432 void DiagnoseEqualityWithExtraParens(ParenExpr *ParenE);
8434 /// CheckCXXBooleanCondition - Returns true if conversion to bool is invalid.
8435 ExprResult CheckCXXBooleanCondition(Expr *CondExpr);
8437 /// ConvertIntegerToTypeWarnOnOverflow - Convert the specified APInt to have
8438 /// the specified width and sign. If an overflow occurs, detect it and emit
8439 /// the specified diagnostic.
8440 void ConvertIntegerToTypeWarnOnOverflow(llvm::APSInt &OldVal,
8441 unsigned NewWidth, bool NewSign,
8442 SourceLocation Loc, unsigned DiagID);
8444 /// Checks that the Objective-C declaration is declared in the global scope.
8445 /// Emits an error and marks the declaration as invalid if it's not declared
8446 /// in the global scope.
8447 bool CheckObjCDeclScope(Decl *D);
8449 /// \brief Abstract base class used for diagnosing integer constant
8450 /// expression violations.
8451 class VerifyICEDiagnoser {
8455 VerifyICEDiagnoser(bool Suppress = false) : Suppress(Suppress) { }
8457 virtual void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) =0;
8458 virtual void diagnoseFold(Sema &S, SourceLocation Loc, SourceRange SR);
8459 virtual ~VerifyICEDiagnoser() { }
8462 /// VerifyIntegerConstantExpression - Verifies that an expression is an ICE,
8463 /// and reports the appropriate diagnostics. Returns false on success.
8464 /// Can optionally return the value of the expression.
8465 ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
8466 VerifyICEDiagnoser &Diagnoser,
8467 bool AllowFold = true);
8468 ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
8470 bool AllowFold = true);
8471 ExprResult VerifyIntegerConstantExpression(Expr *E,
8472 llvm::APSInt *Result = nullptr);
8474 /// VerifyBitField - verifies that a bit field expression is an ICE and has
8475 /// the correct width, and that the field type is valid.
8476 /// Returns false on success.
8477 /// Can optionally return whether the bit-field is of width 0
8478 ExprResult VerifyBitField(SourceLocation FieldLoc, IdentifierInfo *FieldName,
8479 QualType FieldTy, bool IsMsStruct,
8480 Expr *BitWidth, bool *ZeroWidth = nullptr);
8482 enum CUDAFunctionTarget {
8490 CUDAFunctionTarget IdentifyCUDATarget(const FunctionDecl *D);
8492 bool CheckCUDATarget(const FunctionDecl *Caller, const FunctionDecl *Callee);
8494 /// Given a implicit special member, infer its CUDA target from the
8495 /// calls it needs to make to underlying base/field special members.
8496 /// \param ClassDecl the class for which the member is being created.
8497 /// \param CSM the kind of special member.
8498 /// \param MemberDecl the special member itself.
8499 /// \param ConstRHS true if this is a copy operation with a const object on
8501 /// \param Diagnose true if this call should emit diagnostics.
8502 /// \return true if there was an error inferring.
8503 /// The result of this call is implicit CUDA target attribute(s) attached to
8504 /// the member declaration.
8505 bool inferCUDATargetForImplicitSpecialMember(CXXRecordDecl *ClassDecl,
8506 CXXSpecialMember CSM,
8507 CXXMethodDecl *MemberDecl,
8511 /// \name Code completion
8513 /// \brief Describes the context in which code completion occurs.
8514 enum ParserCompletionContext {
8515 /// \brief Code completion occurs at top-level or namespace context.
8517 /// \brief Code completion occurs within a class, struct, or union.
8519 /// \brief Code completion occurs within an Objective-C interface, protocol,
8522 /// \brief Code completion occurs within an Objective-C implementation or
8523 /// category implementation
8524 PCC_ObjCImplementation,
8525 /// \brief Code completion occurs within the list of instance variables
8526 /// in an Objective-C interface, protocol, category, or implementation.
8527 PCC_ObjCInstanceVariableList,
8528 /// \brief Code completion occurs following one or more template
8531 /// \brief Code completion occurs following one or more template
8532 /// headers within a class.
8534 /// \brief Code completion occurs within an expression.
8536 /// \brief Code completion occurs within a statement, which may
8537 /// also be an expression or a declaration.
8539 /// \brief Code completion occurs at the beginning of the
8540 /// initialization statement (or expression) in a for loop.
8542 /// \brief Code completion occurs within the condition of an if,
8543 /// while, switch, or for statement.
8545 /// \brief Code completion occurs within the body of a function on a
8546 /// recovery path, where we do not have a specific handle on our position
8548 PCC_RecoveryInFunction,
8549 /// \brief Code completion occurs where only a type is permitted.
8551 /// \brief Code completion occurs in a parenthesized expression, which
8552 /// might also be a type cast.
8553 PCC_ParenthesizedExpression,
8554 /// \brief Code completion occurs within a sequence of declaration
8555 /// specifiers within a function, method, or block.
8556 PCC_LocalDeclarationSpecifiers
8559 void CodeCompleteModuleImport(SourceLocation ImportLoc, ModuleIdPath Path);
8560 void CodeCompleteOrdinaryName(Scope *S,
8561 ParserCompletionContext CompletionContext);
8562 void CodeCompleteDeclSpec(Scope *S, DeclSpec &DS,
8563 bool AllowNonIdentifiers,
8564 bool AllowNestedNameSpecifiers);
8566 struct CodeCompleteExpressionData;
8567 void CodeCompleteExpression(Scope *S,
8568 const CodeCompleteExpressionData &Data);
8569 void CodeCompleteMemberReferenceExpr(Scope *S, Expr *Base,
8570 SourceLocation OpLoc,
8572 void CodeCompletePostfixExpression(Scope *S, ExprResult LHS);
8573 void CodeCompleteTag(Scope *S, unsigned TagSpec);
8574 void CodeCompleteTypeQualifiers(DeclSpec &DS);
8575 void CodeCompleteCase(Scope *S);
8576 void CodeCompleteCall(Scope *S, Expr *Fn, ArrayRef<Expr *> Args);
8577 void CodeCompleteConstructor(Scope *S, QualType Type, SourceLocation Loc,
8578 ArrayRef<Expr *> Args);
8579 void CodeCompleteInitializer(Scope *S, Decl *D);
8580 void CodeCompleteReturn(Scope *S);
8581 void CodeCompleteAfterIf(Scope *S);
8582 void CodeCompleteAssignmentRHS(Scope *S, Expr *LHS);
8584 void CodeCompleteQualifiedId(Scope *S, CXXScopeSpec &SS,
8585 bool EnteringContext);
8586 void CodeCompleteUsing(Scope *S);
8587 void CodeCompleteUsingDirective(Scope *S);
8588 void CodeCompleteNamespaceDecl(Scope *S);
8589 void CodeCompleteNamespaceAliasDecl(Scope *S);
8590 void CodeCompleteOperatorName(Scope *S);
8591 void CodeCompleteConstructorInitializer(
8593 ArrayRef<CXXCtorInitializer *> Initializers);
8595 void CodeCompleteLambdaIntroducer(Scope *S, LambdaIntroducer &Intro,
8596 bool AfterAmpersand);
8598 void CodeCompleteObjCAtDirective(Scope *S);
8599 void CodeCompleteObjCAtVisibility(Scope *S);
8600 void CodeCompleteObjCAtStatement(Scope *S);
8601 void CodeCompleteObjCAtExpression(Scope *S);
8602 void CodeCompleteObjCPropertyFlags(Scope *S, ObjCDeclSpec &ODS);
8603 void CodeCompleteObjCPropertyGetter(Scope *S);
8604 void CodeCompleteObjCPropertySetter(Scope *S);
8605 void CodeCompleteObjCPassingType(Scope *S, ObjCDeclSpec &DS,
8607 void CodeCompleteObjCMessageReceiver(Scope *S);
8608 void CodeCompleteObjCSuperMessage(Scope *S, SourceLocation SuperLoc,
8609 ArrayRef<IdentifierInfo *> SelIdents,
8610 bool AtArgumentExpression);
8611 void CodeCompleteObjCClassMessage(Scope *S, ParsedType Receiver,
8612 ArrayRef<IdentifierInfo *> SelIdents,
8613 bool AtArgumentExpression,
8614 bool IsSuper = false);
8615 void CodeCompleteObjCInstanceMessage(Scope *S, Expr *Receiver,
8616 ArrayRef<IdentifierInfo *> SelIdents,
8617 bool AtArgumentExpression,
8618 ObjCInterfaceDecl *Super = nullptr);
8619 void CodeCompleteObjCForCollection(Scope *S,
8620 DeclGroupPtrTy IterationVar);
8621 void CodeCompleteObjCSelector(Scope *S,
8622 ArrayRef<IdentifierInfo *> SelIdents);
8623 void CodeCompleteObjCProtocolReferences(IdentifierLocPair *Protocols,
8624 unsigned NumProtocols);
8625 void CodeCompleteObjCProtocolDecl(Scope *S);
8626 void CodeCompleteObjCInterfaceDecl(Scope *S);
8627 void CodeCompleteObjCSuperclass(Scope *S,
8628 IdentifierInfo *ClassName,
8629 SourceLocation ClassNameLoc);
8630 void CodeCompleteObjCImplementationDecl(Scope *S);
8631 void CodeCompleteObjCInterfaceCategory(Scope *S,
8632 IdentifierInfo *ClassName,
8633 SourceLocation ClassNameLoc);
8634 void CodeCompleteObjCImplementationCategory(Scope *S,
8635 IdentifierInfo *ClassName,
8636 SourceLocation ClassNameLoc);
8637 void CodeCompleteObjCPropertyDefinition(Scope *S);
8638 void CodeCompleteObjCPropertySynthesizeIvar(Scope *S,
8639 IdentifierInfo *PropertyName);
8640 void CodeCompleteObjCMethodDecl(Scope *S,
8641 bool IsInstanceMethod,
8642 ParsedType ReturnType);
8643 void CodeCompleteObjCMethodDeclSelector(Scope *S,
8644 bool IsInstanceMethod,
8645 bool AtParameterName,
8646 ParsedType ReturnType,
8647 ArrayRef<IdentifierInfo *> SelIdents);
8648 void CodeCompletePreprocessorDirective(bool InConditional);
8649 void CodeCompleteInPreprocessorConditionalExclusion(Scope *S);
8650 void CodeCompletePreprocessorMacroName(bool IsDefinition);
8651 void CodeCompletePreprocessorExpression();
8652 void CodeCompletePreprocessorMacroArgument(Scope *S,
8653 IdentifierInfo *Macro,
8654 MacroInfo *MacroInfo,
8656 void CodeCompleteNaturalLanguage();
8657 void GatherGlobalCodeCompletions(CodeCompletionAllocator &Allocator,
8658 CodeCompletionTUInfo &CCTUInfo,
8659 SmallVectorImpl<CodeCompletionResult> &Results);
8662 //===--------------------------------------------------------------------===//
8663 // Extra semantic analysis beyond the C type system
8666 SourceLocation getLocationOfStringLiteralByte(const StringLiteral *SL,
8667 unsigned ByteNo) const;
8670 void CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
8671 const ArraySubscriptExpr *ASE=nullptr,
8672 bool AllowOnePastEnd=true, bool IndexNegated=false);
8673 void CheckArrayAccess(const Expr *E);
8674 // Used to grab the relevant information from a FormatAttr and a
8675 // FunctionDeclaration.
8676 struct FormatStringInfo {
8678 unsigned FirstDataArg;
8682 bool getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
8683 FormatStringInfo *FSI);
8684 bool CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
8685 const FunctionProtoType *Proto);
8686 bool CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation loc,
8687 ArrayRef<const Expr *> Args);
8688 bool CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
8689 const FunctionProtoType *Proto);
8690 bool CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto);
8691 void CheckConstructorCall(FunctionDecl *FDecl,
8692 ArrayRef<const Expr *> Args,
8693 const FunctionProtoType *Proto,
8694 SourceLocation Loc);
8696 void checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
8697 ArrayRef<const Expr *> Args, bool IsMemberFunction,
8698 SourceLocation Loc, SourceRange Range,
8699 VariadicCallType CallType);
8701 bool CheckObjCString(Expr *Arg);
8703 ExprResult CheckBuiltinFunctionCall(FunctionDecl *FDecl,
8704 unsigned BuiltinID, CallExpr *TheCall);
8706 bool CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
8708 bool CheckNeonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
8709 bool CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
8711 bool CheckAArch64BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
8712 bool CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
8713 bool CheckSystemZBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
8714 bool CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
8715 bool CheckPPCBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
8717 bool SemaBuiltinVAStart(CallExpr *TheCall);
8718 bool SemaBuiltinVAStartARM(CallExpr *Call);
8719 bool SemaBuiltinUnorderedCompare(CallExpr *TheCall);
8720 bool SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs);
8723 // Used by C++ template instantiation.
8724 ExprResult SemaBuiltinShuffleVector(CallExpr *TheCall);
8725 ExprResult SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
8726 SourceLocation BuiltinLoc,
8727 SourceLocation RParenLoc);
8730 bool SemaBuiltinPrefetch(CallExpr *TheCall);
8731 bool SemaBuiltinAssume(CallExpr *TheCall);
8732 bool SemaBuiltinAssumeAligned(CallExpr *TheCall);
8733 bool SemaBuiltinLongjmp(CallExpr *TheCall);
8734 bool SemaBuiltinSetjmp(CallExpr *TheCall);
8735 ExprResult SemaBuiltinAtomicOverloaded(ExprResult TheCallResult);
8736 ExprResult SemaAtomicOpsOverloaded(ExprResult TheCallResult,
8737 AtomicExpr::AtomicOp Op);
8738 bool SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
8739 llvm::APSInt &Result);
8740 bool SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
8742 bool SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall,
8743 int ArgNum, unsigned ExpectedFieldNum,
8745 bool SemaBuiltinCpuSupports(CallExpr *TheCall);
8747 enum FormatStringType {
8758 static FormatStringType GetFormatStringType(const FormatAttr *Format);
8760 void CheckFormatString(const StringLiteral *FExpr, const Expr *OrigFormatExpr,
8761 ArrayRef<const Expr *> Args, bool HasVAListArg,
8762 unsigned format_idx, unsigned firstDataArg,
8763 FormatStringType Type, bool inFunctionCall,
8764 VariadicCallType CallType,
8765 llvm::SmallBitVector &CheckedVarArgs);
8767 bool FormatStringHasSArg(const StringLiteral *FExpr);
8769 bool GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx);
8772 bool CheckFormatArguments(const FormatAttr *Format,
8773 ArrayRef<const Expr *> Args,
8775 VariadicCallType CallType,
8776 SourceLocation Loc, SourceRange Range,
8777 llvm::SmallBitVector &CheckedVarArgs);
8778 bool CheckFormatArguments(ArrayRef<const Expr *> Args,
8779 bool HasVAListArg, unsigned format_idx,
8780 unsigned firstDataArg, FormatStringType Type,
8781 VariadicCallType CallType,
8782 SourceLocation Loc, SourceRange range,
8783 llvm::SmallBitVector &CheckedVarArgs);
8785 void CheckAbsoluteValueFunction(const CallExpr *Call,
8786 const FunctionDecl *FDecl,
8787 IdentifierInfo *FnInfo);
8789 void CheckMemaccessArguments(const CallExpr *Call,
8791 IdentifierInfo *FnName);
8793 void CheckStrlcpycatArguments(const CallExpr *Call,
8794 IdentifierInfo *FnName);
8796 void CheckStrncatArguments(const CallExpr *Call,
8797 IdentifierInfo *FnName);
8799 void CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
8800 SourceLocation ReturnLoc,
8801 bool isObjCMethod = false,
8802 const AttrVec *Attrs = nullptr,
8803 const FunctionDecl *FD = nullptr);
8805 void CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr* RHS);
8806 void CheckImplicitConversions(Expr *E, SourceLocation CC = SourceLocation());
8807 void CheckBoolLikeConversion(Expr *E, SourceLocation CC);
8808 void CheckForIntOverflow(Expr *E);
8809 void CheckUnsequencedOperations(Expr *E);
8811 /// \brief Perform semantic checks on a completed expression. This will either
8812 /// be a full-expression or a default argument expression.
8813 void CheckCompletedExpr(Expr *E, SourceLocation CheckLoc = SourceLocation(),
8814 bool IsConstexpr = false);
8816 void CheckBitFieldInitialization(SourceLocation InitLoc, FieldDecl *Field,
8819 /// \brief Check if the given expression contains 'break' or 'continue'
8820 /// statement that produces control flow different from GCC.
8821 void CheckBreakContinueBinding(Expr *E);
8823 /// \brief Check whether receiver is mutable ObjC container which
8824 /// attempts to add itself into the container
8825 void CheckObjCCircularContainer(ObjCMessageExpr *Message);
8827 void AnalyzeDeleteExprMismatch(const CXXDeleteExpr *DE);
8828 void AnalyzeDeleteExprMismatch(FieldDecl *Field, SourceLocation DeleteLoc,
8829 bool DeleteWasArrayForm);
8831 /// \brief Register a magic integral constant to be used as a type tag.
8832 void RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
8833 uint64_t MagicValue, QualType Type,
8834 bool LayoutCompatible, bool MustBeNull);
8836 struct TypeTagData {
8839 TypeTagData(QualType Type, bool LayoutCompatible, bool MustBeNull) :
8840 Type(Type), LayoutCompatible(LayoutCompatible),
8841 MustBeNull(MustBeNull)
8846 /// If true, \c Type should be compared with other expression's types for
8847 /// layout-compatibility.
8848 unsigned LayoutCompatible : 1;
8849 unsigned MustBeNull : 1;
8852 /// A pair of ArgumentKind identifier and magic value. This uniquely
8853 /// identifies the magic value.
8854 typedef std::pair<const IdentifierInfo *, uint64_t> TypeTagMagicValue;
8857 /// \brief A map from magic value to type information.
8858 std::unique_ptr<llvm::DenseMap<TypeTagMagicValue, TypeTagData>>
8859 TypeTagForDatatypeMagicValues;
8861 /// \brief Peform checks on a call of a function with argument_with_type_tag
8862 /// or pointer_with_type_tag attributes.
8863 void CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
8864 const Expr * const *ExprArgs);
8866 /// \brief The parser's current scope.
8868 /// The parser maintains this state here.
8871 mutable IdentifierInfo *Ident_super;
8872 mutable IdentifierInfo *Ident___float128;
8874 /// Nullability type specifiers.
8875 IdentifierInfo *Ident__Nonnull = nullptr;
8876 IdentifierInfo *Ident__Nullable = nullptr;
8877 IdentifierInfo *Ident__Null_unspecified = nullptr;
8879 IdentifierInfo *Ident_NSError = nullptr;
8882 friend class Parser;
8883 friend class InitializationSequence;
8884 friend class ASTReader;
8885 friend class ASTDeclReader;
8886 friend class ASTWriter;
8889 /// Retrieve the keyword associated
8890 IdentifierInfo *getNullabilityKeyword(NullabilityKind nullability);
8892 /// The struct behind the CFErrorRef pointer.
8893 RecordDecl *CFError = nullptr;
8895 /// Retrieve the identifier "NSError".
8896 IdentifierInfo *getNSErrorIdent();
8898 /// \brief Retrieve the parser's current scope.
8900 /// This routine must only be used when it is certain that semantic analysis
8901 /// and the parser are in precisely the same context, which is not the case
8902 /// when, e.g., we are performing any kind of template instantiation.
8903 /// Therefore, the only safe places to use this scope are in the parser
8904 /// itself and in routines directly invoked from the parser and *never* from
8905 /// template substitution or instantiation.
8906 Scope *getCurScope() const { return CurScope; }
8908 void incrementMSManglingNumber() const {
8909 return CurScope->incrementMSManglingNumber();
8912 IdentifierInfo *getSuperIdentifier() const;
8913 IdentifierInfo *getFloat128Identifier() const;
8915 Decl *getObjCDeclContext() const;
8917 DeclContext *getCurLexicalContext() const {
8918 return OriginalLexicalContext ? OriginalLexicalContext : CurContext;
8921 AvailabilityResult getCurContextAvailability() const;
8923 const DeclContext *getCurObjCLexicalContext() const {
8924 const DeclContext *DC = getCurLexicalContext();
8925 // A category implicitly has the attribute of the interface.
8926 if (const ObjCCategoryDecl *CatD = dyn_cast<ObjCCategoryDecl>(DC))
8927 DC = CatD->getClassInterface();
8931 /// \brief To be used for checking whether the arguments being passed to
8932 /// function exceeds the number of parameters expected for it.
8933 static bool TooManyArguments(size_t NumParams, size_t NumArgs,
8934 bool PartialOverloading = false) {
8935 // We check whether we're just after a comma in code-completion.
8936 if (NumArgs > 0 && PartialOverloading)
8937 return NumArgs + 1 > NumParams; // If so, we view as an extra argument.
8938 return NumArgs > NumParams;
8942 /// \brief RAII object that enters a new expression evaluation context.
8943 class EnterExpressionEvaluationContext {
8947 EnterExpressionEvaluationContext(Sema &Actions,
8948 Sema::ExpressionEvaluationContext NewContext,
8949 Decl *LambdaContextDecl = nullptr,
8950 bool IsDecltype = false)
8951 : Actions(Actions) {
8952 Actions.PushExpressionEvaluationContext(NewContext, LambdaContextDecl,
8955 EnterExpressionEvaluationContext(Sema &Actions,
8956 Sema::ExpressionEvaluationContext NewContext,
8957 Sema::ReuseLambdaContextDecl_t,
8958 bool IsDecltype = false)
8959 : Actions(Actions) {
8960 Actions.PushExpressionEvaluationContext(NewContext,
8961 Sema::ReuseLambdaContextDecl,
8965 ~EnterExpressionEvaluationContext() {
8966 Actions.PopExpressionEvaluationContext();
8970 DeductionFailureInfo
8971 MakeDeductionFailureInfo(ASTContext &Context, Sema::TemplateDeductionResult TDK,
8972 sema::TemplateDeductionInfo &Info);
8974 /// \brief Contains a late templated function.
8975 /// Will be parsed at the end of the translation unit, used by Sema & Parser.
8976 struct LateParsedTemplate {
8978 /// \brief The template function declaration to be late parsed.
8982 } // end namespace clang