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 struct OverloadCandidate;
149 class OverloadCandidateSet;
154 class PseudoDestructorTypeStorage;
155 class PseudoObjectExpr;
157 class StandardConversionSequence;
161 class TemplateArgument;
162 class TemplateArgumentList;
163 class TemplateArgumentLoc;
165 class TemplateParameterList;
166 class TemplatePartialOrderingContext;
167 class TemplateTemplateParmDecl;
171 class TypedefNameDecl;
173 class TypoCorrectionConsumer;
175 class UnresolvedLookupExpr;
176 class UnresolvedMemberExpr;
177 class UnresolvedSetImpl;
178 class UnresolvedSetIterator;
180 class UsingShadowDecl;
183 class VarTemplateSpecializationDecl;
184 class VisibilityAttr;
185 class VisibleDeclConsumer;
186 class IndirectFieldDecl;
187 struct DeductionFailureInfo;
188 class TemplateSpecCandidateSet;
191 class AccessedEntity;
192 class BlockScopeInfo;
193 class CapturedRegionScopeInfo;
194 class CapturingScopeInfo;
195 class CompoundScopeInfo;
196 class DelayedDiagnostic;
197 class DelayedDiagnosticPool;
198 class FunctionScopeInfo;
199 class LambdaScopeInfo;
200 class PossiblyUnreachableDiag;
201 class TemplateDeductionInfo;
204 namespace threadSafety {
206 void threadSafetyCleanup(BeforeSet* Cache);
209 // FIXME: No way to easily map from TemplateTypeParmTypes to
210 // TemplateTypeParmDecls, so we have this horrible PointerUnion.
211 typedef std::pair<llvm::PointerUnion<const TemplateTypeParmType*, NamedDecl*>,
212 SourceLocation> UnexpandedParameterPack;
214 /// Describes whether we've seen any nullability information for the given
216 struct FileNullability {
217 /// The first pointer declarator (of any pointer kind) in the file that does
218 /// not have a corresponding nullability annotation.
219 SourceLocation PointerLoc;
221 /// Which kind of pointer declarator we saw.
224 /// Whether we saw any type nullability annotations in the given file.
225 bool SawTypeNullability = false;
228 /// A mapping from file IDs to a record of whether we've seen nullability
229 /// information in that file.
230 class FileNullabilityMap {
231 /// A mapping from file IDs to the nullability information for each file ID.
232 llvm::DenseMap<FileID, FileNullability> Map;
234 /// A single-element cache based on the file ID.
237 FileNullability Nullability;
241 FileNullability &operator[](FileID file) {
242 // Check the single-element cache.
243 if (file == Cache.File)
244 return Cache.Nullability;
246 // It's not in the single-element cache; flush the cache if we have one.
247 if (!Cache.File.isInvalid()) {
248 Map[Cache.File] = Cache.Nullability;
251 // Pull this entry into the cache.
253 Cache.Nullability = Map[file];
254 return Cache.Nullability;
258 /// Sema - This implements semantic analysis and AST building for C.
260 Sema(const Sema &) = delete;
261 void operator=(const Sema &) = delete;
263 ///\brief Source of additional semantic information.
264 ExternalSemaSource *ExternalSource;
266 ///\brief Whether Sema has generated a multiplexer and has to delete it.
267 bool isMultiplexExternalSource;
269 static bool mightHaveNonExternalLinkage(const DeclaratorDecl *FD);
271 bool isVisibleSlow(const NamedDecl *D);
273 bool shouldLinkPossiblyHiddenDecl(const NamedDecl *Old,
274 const NamedDecl *New) {
275 // We are about to link these. It is now safe to compute the linkage of
276 // the new decl. If the new decl has external linkage, we will
277 // link it with the hidden decl (which also has external linkage) and
278 // it will keep having external linkage. If it has internal linkage, we
279 // will not link it. Since it has no previous decls, it will remain
280 // with internal linkage.
281 return isVisible(Old) || New->isExternallyVisible();
283 bool shouldLinkPossiblyHiddenDecl(LookupResult &Old, const NamedDecl *New);
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 The declaration of the arrayWithObjects:count: method.
733 ObjCMethodDecl *ArrayWithObjectsMethod;
735 /// \brief The declaration of the Objective-C NSDictionary class.
736 ObjCInterfaceDecl *NSDictionaryDecl;
738 /// \brief The declaration of the dictionaryWithObjects:forKeys:count: method.
739 ObjCMethodDecl *DictionaryWithObjectsMethod;
741 /// \brief id<NSCopying> type.
742 QualType QIDNSCopying;
744 /// \brief will hold 'respondsToSelector:'
745 Selector RespondsToSelectorSel;
747 /// \brief counter for internal MS Asm label names.
748 unsigned MSAsmLabelNameCounter;
750 /// A flag to remember whether the implicit forms of operator new and delete
751 /// have been declared.
752 bool GlobalNewDeleteDeclared;
754 /// A flag to indicate that we're in a context that permits abstract
755 /// references to fields. This is really a
756 bool AllowAbstractFieldReference;
758 /// \brief Describes how the expressions currently being parsed are
759 /// evaluated at run-time, if at all.
760 enum ExpressionEvaluationContext {
761 /// \brief The current expression and its subexpressions occur within an
762 /// unevaluated operand (C++11 [expr]p7), such as the subexpression of
763 /// \c sizeof, where the type of the expression may be significant but
764 /// no code will be generated to evaluate the value of the expression at
768 /// \brief The current expression occurs within an unevaluated
769 /// operand that unconditionally permits abstract references to
770 /// fields, such as a SIZE operator in MS-style inline assembly.
773 /// \brief The current context is "potentially evaluated" in C++11 terms,
774 /// but the expression is evaluated at compile-time (like the values of
775 /// cases in a switch statement).
778 /// \brief The current expression is potentially evaluated at run time,
779 /// which means that code may be generated to evaluate the value of the
780 /// expression at run time.
781 PotentiallyEvaluated,
783 /// \brief The current expression is potentially evaluated, but any
784 /// declarations referenced inside that expression are only used if
785 /// in fact the current expression is used.
787 /// This value is used when parsing default function arguments, for which
788 /// we would like to provide diagnostics (e.g., passing non-POD arguments
789 /// through varargs) but do not want to mark declarations as "referenced"
790 /// until the default argument is used.
791 PotentiallyEvaluatedIfUsed
794 /// \brief Data structure used to record current or nested
795 /// expression evaluation contexts.
796 struct ExpressionEvaluationContextRecord {
797 /// \brief The expression evaluation context.
798 ExpressionEvaluationContext Context;
800 /// \brief Whether the enclosing context needed a cleanup.
801 bool ParentNeedsCleanups;
803 /// \brief Whether we are in a decltype expression.
806 /// \brief The number of active cleanup objects when we entered
807 /// this expression evaluation context.
808 unsigned NumCleanupObjects;
810 /// \brief The number of typos encountered during this expression evaluation
811 /// context (i.e. the number of TypoExprs created).
814 llvm::SmallPtrSet<Expr*, 2> SavedMaybeODRUseExprs;
816 /// \brief The lambdas that are present within this context, if it
817 /// is indeed an unevaluated context.
818 SmallVector<LambdaExpr *, 2> Lambdas;
820 /// \brief The declaration that provides context for lambda expressions
821 /// and block literals if the normal declaration context does not
822 /// suffice, e.g., in a default function argument.
823 Decl *ManglingContextDecl;
825 /// \brief The context information used to mangle lambda expressions
826 /// and block literals within this context.
828 /// This mangling information is allocated lazily, since most contexts
829 /// do not have lambda expressions or block literals.
830 IntrusiveRefCntPtr<MangleNumberingContext> MangleNumbering;
832 /// \brief If we are processing a decltype type, a set of call expressions
833 /// for which we have deferred checking the completeness of the return type.
834 SmallVector<CallExpr *, 8> DelayedDecltypeCalls;
836 /// \brief If we are processing a decltype type, a set of temporary binding
837 /// expressions for which we have deferred checking the destructor.
838 SmallVector<CXXBindTemporaryExpr *, 8> DelayedDecltypeBinds;
840 ExpressionEvaluationContextRecord(ExpressionEvaluationContext Context,
841 unsigned NumCleanupObjects,
842 bool ParentNeedsCleanups,
843 Decl *ManglingContextDecl,
845 : Context(Context), ParentNeedsCleanups(ParentNeedsCleanups),
846 IsDecltype(IsDecltype), NumCleanupObjects(NumCleanupObjects),
848 ManglingContextDecl(ManglingContextDecl), MangleNumbering() { }
850 /// \brief Retrieve the mangling numbering context, used to consistently
851 /// number constructs like lambdas for mangling.
852 MangleNumberingContext &getMangleNumberingContext(ASTContext &Ctx);
854 bool isUnevaluated() const {
855 return Context == Unevaluated || Context == UnevaluatedAbstract;
859 /// A stack of expression evaluation contexts.
860 SmallVector<ExpressionEvaluationContextRecord, 8> ExprEvalContexts;
862 /// \brief Compute the mangling number context for a lambda expression or
865 /// \param DC - The DeclContext containing the lambda expression or
867 /// \param[out] ManglingContextDecl - Returns the ManglingContextDecl
868 /// associated with the context, if relevant.
869 MangleNumberingContext *getCurrentMangleNumberContext(
870 const DeclContext *DC,
871 Decl *&ManglingContextDecl);
874 /// SpecialMemberOverloadResult - The overloading result for a special member
877 /// This is basically a wrapper around PointerIntPair. The lowest bits of the
878 /// integer are used to determine whether overload resolution succeeded.
879 class SpecialMemberOverloadResult : public llvm::FastFoldingSetNode {
888 llvm::PointerIntPair<CXXMethodDecl*, 2> Pair;
891 SpecialMemberOverloadResult(const llvm::FoldingSetNodeID &ID)
892 : FastFoldingSetNode(ID)
895 CXXMethodDecl *getMethod() const { return Pair.getPointer(); }
896 void setMethod(CXXMethodDecl *MD) { Pair.setPointer(MD); }
898 Kind getKind() const { return static_cast<Kind>(Pair.getInt()); }
899 void setKind(Kind K) { Pair.setInt(K); }
902 /// \brief A cache of special member function overload resolution results
904 llvm::FoldingSet<SpecialMemberOverloadResult> SpecialMemberCache;
906 /// \brief A cache of the flags available in enumerations with the flag_bits
908 mutable llvm::DenseMap<const EnumDecl*, llvm::APInt> FlagBitsCache;
910 /// \brief The kind of translation unit we are processing.
912 /// When we're processing a complete translation unit, Sema will perform
913 /// end-of-translation-unit semantic tasks (such as creating
914 /// initializers for tentative definitions in C) once parsing has
915 /// completed. Modules and precompiled headers perform different kinds of
917 TranslationUnitKind TUKind;
919 llvm::BumpPtrAllocator BumpAlloc;
921 /// \brief The number of SFINAE diagnostics that have been trapped.
922 unsigned NumSFINAEErrors;
924 typedef llvm::DenseMap<ParmVarDecl *, llvm::TinyPtrVector<ParmVarDecl *>>
925 UnparsedDefaultArgInstantiationsMap;
927 /// \brief A mapping from parameters with unparsed default arguments to the
928 /// set of instantiations of each parameter.
930 /// This mapping is a temporary data structure used when parsing
931 /// nested class templates or nested classes of class templates,
932 /// where we might end up instantiating an inner class before the
933 /// default arguments of its methods have been parsed.
934 UnparsedDefaultArgInstantiationsMap UnparsedDefaultArgInstantiations;
936 // Contains the locations of the beginning of unparsed default
937 // argument locations.
938 llvm::DenseMap<ParmVarDecl *, SourceLocation> UnparsedDefaultArgLocs;
940 /// UndefinedInternals - all the used, undefined objects which require a
941 /// definition in this translation unit.
942 llvm::DenseMap<NamedDecl *, SourceLocation> UndefinedButUsed;
944 /// Obtain a sorted list of functions that are undefined but ODR-used.
945 void getUndefinedButUsed(
946 SmallVectorImpl<std::pair<NamedDecl *, SourceLocation> > &Undefined);
948 /// Retrieves list of suspicious delete-expressions that will be checked at
949 /// the end of translation unit.
950 const llvm::MapVector<FieldDecl *, DeleteLocs> &
951 getMismatchingDeleteExpressions() const;
953 typedef std::pair<ObjCMethodList, ObjCMethodList> GlobalMethods;
954 typedef llvm::DenseMap<Selector, GlobalMethods> GlobalMethodPool;
956 /// Method Pool - allows efficient lookup when typechecking messages to "id".
957 /// We need to maintain a list, since selectors can have differing signatures
958 /// across classes. In Cocoa, this happens to be extremely uncommon (only 1%
959 /// of selectors are "overloaded").
960 /// At the head of the list it is recorded whether there were 0, 1, or >= 2
961 /// methods inside categories with a particular selector.
962 GlobalMethodPool MethodPool;
964 /// Method selectors used in a \@selector expression. Used for implementation
966 llvm::MapVector<Selector, SourceLocation> ReferencedSelectors;
968 /// Kinds of C++ special members.
969 enum CXXSpecialMember {
970 CXXDefaultConstructor,
979 typedef std::pair<CXXRecordDecl*, CXXSpecialMember> SpecialMemberDecl;
981 /// The C++ special members which we are currently in the process of
982 /// declaring. If this process recursively triggers the declaration of the
983 /// same special member, we should act as if it is not yet declared.
984 llvm::SmallSet<SpecialMemberDecl, 4> SpecialMembersBeingDeclared;
986 void ReadMethodPool(Selector Sel);
988 /// Private Helper predicate to check for 'self'.
989 bool isSelfExpr(Expr *RExpr);
990 bool isSelfExpr(Expr *RExpr, const ObjCMethodDecl *Method);
992 /// \brief Cause the active diagnostic on the DiagosticsEngine to be
993 /// emitted. This is closely coupled to the SemaDiagnosticBuilder class and
994 /// should not be used elsewhere.
995 void EmitCurrentDiagnostic(unsigned DiagID);
997 /// Records and restores the FP_CONTRACT state on entry/exit of compound
999 class FPContractStateRAII {
1001 FPContractStateRAII(Sema& S)
1002 : S(S), OldFPContractState(S.FPFeatures.fp_contract) {}
1003 ~FPContractStateRAII() {
1004 S.FPFeatures.fp_contract = OldFPContractState;
1008 bool OldFPContractState : 1;
1011 /// Records and restores the vtordisp state on entry/exit of C++ method body.
1012 class VtorDispStackRAII {
1014 VtorDispStackRAII(Sema &S, bool ShouldSaveAndRestore)
1015 : S(S), ShouldSaveAndRestore(ShouldSaveAndRestore), OldVtorDispStack() {
1016 if (ShouldSaveAndRestore)
1017 OldVtorDispStack = S.VtorDispModeStack;
1019 ~VtorDispStackRAII() {
1020 if (ShouldSaveAndRestore)
1021 S.VtorDispModeStack = OldVtorDispStack;
1025 bool ShouldSaveAndRestore;
1026 SmallVector<MSVtorDispAttr::Mode, 2> OldVtorDispStack;
1029 void addImplicitTypedef(StringRef Name, QualType T);
1032 Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer,
1033 TranslationUnitKind TUKind = TU_Complete,
1034 CodeCompleteConsumer *CompletionConsumer = nullptr);
1037 /// \brief Perform initialization that occurs after the parser has been
1038 /// initialized but before it parses anything.
1041 const LangOptions &getLangOpts() const { return LangOpts; }
1042 OpenCLOptions &getOpenCLOptions() { return OpenCLFeatures; }
1043 FPOptions &getFPOptions() { return FPFeatures; }
1045 DiagnosticsEngine &getDiagnostics() const { return Diags; }
1046 SourceManager &getSourceManager() const { return SourceMgr; }
1047 Preprocessor &getPreprocessor() const { return PP; }
1048 ASTContext &getASTContext() const { return Context; }
1049 ASTConsumer &getASTConsumer() const { return Consumer; }
1050 ASTMutationListener *getASTMutationListener() const;
1051 ExternalSemaSource* getExternalSource() const { return ExternalSource; }
1053 ///\brief Registers an external source. If an external source already exists,
1054 /// creates a multiplex external source and appends to it.
1056 ///\param[in] E - A non-null external sema source.
1058 void addExternalSource(ExternalSemaSource *E);
1060 void PrintStats() const;
1062 /// \brief Helper class that creates diagnostics with optional
1063 /// template instantiation stacks.
1065 /// This class provides a wrapper around the basic DiagnosticBuilder
1066 /// class that emits diagnostics. SemaDiagnosticBuilder is
1067 /// responsible for emitting the diagnostic (as DiagnosticBuilder
1068 /// does) and, if the diagnostic comes from inside a template
1069 /// instantiation, printing the template instantiation stack as
1071 class SemaDiagnosticBuilder : public DiagnosticBuilder {
1076 SemaDiagnosticBuilder(DiagnosticBuilder &DB, Sema &SemaRef, unsigned DiagID)
1077 : DiagnosticBuilder(DB), SemaRef(SemaRef), DiagID(DiagID) { }
1079 // This is a cunning lie. DiagnosticBuilder actually performs move
1080 // construction in its copy constructor (but due to varied uses, it's not
1081 // possible to conveniently express this as actual move construction). So
1082 // the default copy ctor here is fine, because the base class disables the
1083 // source anyway, so the user-defined ~SemaDiagnosticBuilder is a safe no-op
1084 // in that case anwyay.
1085 SemaDiagnosticBuilder(const SemaDiagnosticBuilder&) = default;
1087 ~SemaDiagnosticBuilder() {
1088 // If we aren't active, there is nothing to do.
1089 if (!isActive()) return;
1091 // Otherwise, we need to emit the diagnostic. First flush the underlying
1092 // DiagnosticBuilder data, and clear the diagnostic builder itself so it
1093 // won't emit the diagnostic in its own destructor.
1095 // This seems wasteful, in that as written the DiagnosticBuilder dtor will
1096 // do its own needless checks to see if the diagnostic needs to be
1097 // emitted. However, because we take care to ensure that the builder
1098 // objects never escape, a sufficiently smart compiler will be able to
1099 // eliminate that code.
1103 // Dispatch to Sema to emit the diagnostic.
1104 SemaRef.EmitCurrentDiagnostic(DiagID);
1107 /// Teach operator<< to produce an object of the correct type.
1108 template<typename T>
1109 friend const SemaDiagnosticBuilder &operator<<(
1110 const SemaDiagnosticBuilder &Diag, const T &Value) {
1111 const DiagnosticBuilder &BaseDiag = Diag;
1117 /// \brief Emit a diagnostic.
1118 SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID) {
1119 DiagnosticBuilder DB = Diags.Report(Loc, DiagID);
1120 return SemaDiagnosticBuilder(DB, *this, DiagID);
1123 /// \brief Emit a partial diagnostic.
1124 SemaDiagnosticBuilder Diag(SourceLocation Loc, const PartialDiagnostic& PD);
1126 /// \brief Build a partial diagnostic.
1127 PartialDiagnostic PDiag(unsigned DiagID = 0); // in SemaInternal.h
1129 bool findMacroSpelling(SourceLocation &loc, StringRef name);
1131 /// \brief Get a string to suggest for zero-initialization of a type.
1133 getFixItZeroInitializerForType(QualType T, SourceLocation Loc) const;
1134 std::string getFixItZeroLiteralForType(QualType T, SourceLocation Loc) const;
1136 /// \brief Calls \c Lexer::getLocForEndOfToken()
1137 SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset = 0);
1139 /// \brief Retrieve the module loader associated with the preprocessor.
1140 ModuleLoader &getModuleLoader() const;
1142 void emitAndClearUnusedLocalTypedefWarnings();
1144 void ActOnEndOfTranslationUnit();
1146 void CheckDelegatingCtorCycles();
1148 Scope *getScopeForContext(DeclContext *Ctx);
1150 void PushFunctionScope();
1151 void PushBlockScope(Scope *BlockScope, BlockDecl *Block);
1152 sema::LambdaScopeInfo *PushLambdaScope();
1154 /// \brief This is used to inform Sema what the current TemplateParameterDepth
1155 /// is during Parsing. Currently it is used to pass on the depth
1156 /// when parsing generic lambda 'auto' parameters.
1157 void RecordParsingTemplateParameterDepth(unsigned Depth);
1159 void PushCapturedRegionScope(Scope *RegionScope, CapturedDecl *CD,
1161 CapturedRegionKind K);
1163 PopFunctionScopeInfo(const sema::AnalysisBasedWarnings::Policy *WP = nullptr,
1164 const Decl *D = nullptr,
1165 const BlockExpr *blkExpr = nullptr);
1167 sema::FunctionScopeInfo *getCurFunction() const {
1168 return FunctionScopes.back();
1171 sema::FunctionScopeInfo *getEnclosingFunction() const {
1172 if (FunctionScopes.empty())
1175 for (int e = FunctionScopes.size()-1; e >= 0; --e) {
1176 if (isa<sema::BlockScopeInfo>(FunctionScopes[e]))
1178 return FunctionScopes[e];
1183 template <typename ExprT>
1184 void recordUseOfEvaluatedWeak(const ExprT *E, bool IsRead=true) {
1185 if (!isUnevaluatedContext())
1186 getCurFunction()->recordUseOfWeak(E, IsRead);
1189 void PushCompoundScope();
1190 void PopCompoundScope();
1192 sema::CompoundScopeInfo &getCurCompoundScope() const;
1194 bool hasAnyUnrecoverableErrorsInThisFunction() const;
1196 /// \brief Retrieve the current block, if any.
1197 sema::BlockScopeInfo *getCurBlock();
1199 /// \brief Retrieve the current lambda scope info, if any.
1200 sema::LambdaScopeInfo *getCurLambda();
1202 /// \brief Retrieve the current generic lambda info, if any.
1203 sema::LambdaScopeInfo *getCurGenericLambda();
1205 /// \brief Retrieve the current captured region, if any.
1206 sema::CapturedRegionScopeInfo *getCurCapturedRegion();
1208 /// WeakTopLevelDeclDecls - access to \#pragma weak-generated Decls
1209 SmallVectorImpl<Decl *> &WeakTopLevelDecls() { return WeakTopLevelDecl; }
1211 void ActOnComment(SourceRange Comment);
1213 //===--------------------------------------------------------------------===//
1214 // Type Analysis / Processing: SemaType.cpp.
1217 QualType BuildQualifiedType(QualType T, SourceLocation Loc, Qualifiers Qs,
1218 const DeclSpec *DS = nullptr);
1219 QualType BuildQualifiedType(QualType T, SourceLocation Loc, unsigned CVRA,
1220 const DeclSpec *DS = nullptr);
1221 QualType BuildPointerType(QualType T,
1222 SourceLocation Loc, DeclarationName Entity);
1223 QualType BuildReferenceType(QualType T, bool LValueRef,
1224 SourceLocation Loc, DeclarationName Entity);
1225 QualType BuildArrayType(QualType T, ArrayType::ArraySizeModifier ASM,
1226 Expr *ArraySize, unsigned Quals,
1227 SourceRange Brackets, DeclarationName Entity);
1228 QualType BuildExtVectorType(QualType T, Expr *ArraySize,
1229 SourceLocation AttrLoc);
1231 bool CheckFunctionReturnType(QualType T, SourceLocation Loc);
1233 /// \brief Build a function type.
1235 /// This routine checks the function type according to C++ rules and
1236 /// under the assumption that the result type and parameter types have
1237 /// just been instantiated from a template. It therefore duplicates
1238 /// some of the behavior of GetTypeForDeclarator, but in a much
1239 /// simpler form that is only suitable for this narrow use case.
1241 /// \param T The return type of the function.
1243 /// \param ParamTypes The parameter types of the function. This array
1244 /// will be modified to account for adjustments to the types of the
1245 /// function parameters.
1247 /// \param Loc The location of the entity whose type involves this
1248 /// function type or, if there is no such entity, the location of the
1249 /// type that will have function type.
1251 /// \param Entity The name of the entity that involves the function
1254 /// \param EPI Extra information about the function type. Usually this will
1255 /// be taken from an existing function with the same prototype.
1257 /// \returns A suitable function type, if there are no errors. The
1258 /// unqualified type will always be a FunctionProtoType.
1259 /// Otherwise, returns a NULL type.
1260 QualType BuildFunctionType(QualType T,
1261 MutableArrayRef<QualType> ParamTypes,
1262 SourceLocation Loc, DeclarationName Entity,
1263 const FunctionProtoType::ExtProtoInfo &EPI);
1265 QualType BuildMemberPointerType(QualType T, QualType Class,
1267 DeclarationName Entity);
1268 QualType BuildBlockPointerType(QualType T,
1269 SourceLocation Loc, DeclarationName Entity);
1270 QualType BuildParenType(QualType T);
1271 QualType BuildAtomicType(QualType T, SourceLocation Loc);
1272 QualType BuildPipeType(QualType T,
1273 SourceLocation Loc);
1275 TypeSourceInfo *GetTypeForDeclarator(Declarator &D, Scope *S);
1276 TypeSourceInfo *GetTypeForDeclaratorCast(Declarator &D, QualType FromTy);
1277 TypeSourceInfo *GetTypeSourceInfoForDeclarator(Declarator &D, QualType T,
1278 TypeSourceInfo *ReturnTypeInfo);
1280 /// \brief Package the given type and TSI into a ParsedType.
1281 ParsedType CreateParsedType(QualType T, TypeSourceInfo *TInfo);
1282 DeclarationNameInfo GetNameForDeclarator(Declarator &D);
1283 DeclarationNameInfo GetNameFromUnqualifiedId(const UnqualifiedId &Name);
1284 static QualType GetTypeFromParser(ParsedType Ty,
1285 TypeSourceInfo **TInfo = nullptr);
1286 CanThrowResult canThrow(const Expr *E);
1287 const FunctionProtoType *ResolveExceptionSpec(SourceLocation Loc,
1288 const FunctionProtoType *FPT);
1289 void UpdateExceptionSpec(FunctionDecl *FD,
1290 const FunctionProtoType::ExceptionSpecInfo &ESI);
1291 bool CheckSpecifiedExceptionType(QualType &T, SourceRange Range);
1292 bool CheckDistantExceptionSpec(QualType T);
1293 bool CheckEquivalentExceptionSpec(FunctionDecl *Old, FunctionDecl *New);
1294 bool CheckEquivalentExceptionSpec(
1295 const FunctionProtoType *Old, SourceLocation OldLoc,
1296 const FunctionProtoType *New, SourceLocation NewLoc);
1297 bool CheckEquivalentExceptionSpec(
1298 const PartialDiagnostic &DiagID, const PartialDiagnostic & NoteID,
1299 const FunctionProtoType *Old, SourceLocation OldLoc,
1300 const FunctionProtoType *New, SourceLocation NewLoc,
1301 bool *MissingExceptionSpecification = nullptr,
1302 bool *MissingEmptyExceptionSpecification = nullptr,
1303 bool AllowNoexceptAllMatchWithNoSpec = false,
1304 bool IsOperatorNew = false);
1305 bool CheckExceptionSpecSubset(
1306 const PartialDiagnostic &DiagID, const PartialDiagnostic & NoteID,
1307 const FunctionProtoType *Superset, SourceLocation SuperLoc,
1308 const FunctionProtoType *Subset, SourceLocation SubLoc);
1309 bool CheckParamExceptionSpec(const PartialDiagnostic & NoteID,
1310 const FunctionProtoType *Target, SourceLocation TargetLoc,
1311 const FunctionProtoType *Source, SourceLocation SourceLoc);
1313 TypeResult ActOnTypeName(Scope *S, Declarator &D);
1315 /// \brief The parser has parsed the context-sensitive type 'instancetype'
1316 /// in an Objective-C message declaration. Return the appropriate type.
1317 ParsedType ActOnObjCInstanceType(SourceLocation Loc);
1319 /// \brief Abstract class used to diagnose incomplete types.
1320 struct TypeDiagnoser {
1323 virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) = 0;
1324 virtual ~TypeDiagnoser() {}
1327 static int getPrintable(int I) { return I; }
1328 static unsigned getPrintable(unsigned I) { return I; }
1329 static bool getPrintable(bool B) { return B; }
1330 static const char * getPrintable(const char *S) { return S; }
1331 static StringRef getPrintable(StringRef S) { return S; }
1332 static const std::string &getPrintable(const std::string &S) { return S; }
1333 static const IdentifierInfo *getPrintable(const IdentifierInfo *II) {
1336 static DeclarationName getPrintable(DeclarationName N) { return N; }
1337 static QualType getPrintable(QualType T) { return T; }
1338 static SourceRange getPrintable(SourceRange R) { return R; }
1339 static SourceRange getPrintable(SourceLocation L) { return L; }
1340 static SourceRange getPrintable(const Expr *E) { return E->getSourceRange(); }
1341 static SourceRange getPrintable(TypeLoc TL) { return TL.getSourceRange();}
1343 template <typename... Ts> class BoundTypeDiagnoser : public TypeDiagnoser {
1345 std::tuple<const Ts &...> Args;
1347 template <std::size_t... Is>
1348 void emit(const SemaDiagnosticBuilder &DB,
1349 llvm::index_sequence<Is...>) const {
1350 // Apply all tuple elements to the builder in order.
1351 bool Dummy[] = {false, (DB << getPrintable(std::get<Is>(Args)))...};
1356 BoundTypeDiagnoser(unsigned DiagID, const Ts &...Args)
1357 : TypeDiagnoser(), DiagID(DiagID), Args(Args...) {
1358 assert(DiagID != 0 && "no diagnostic for type diagnoser");
1361 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
1362 const SemaDiagnosticBuilder &DB = S.Diag(Loc, DiagID);
1363 emit(DB, llvm::index_sequence_for<Ts...>());
1369 bool RequireCompleteTypeImpl(SourceLocation Loc, QualType T,
1370 TypeDiagnoser *Diagnoser);
1372 VisibleModuleSet VisibleModules;
1373 llvm::SmallVector<VisibleModuleSet, 16> VisibleModulesStack;
1375 Module *CachedFakeTopLevelModule;
1378 /// \brief Get the module owning an entity.
1379 Module *getOwningModule(Decl *Entity);
1381 /// \brief Make a merged definition of an existing hidden definition \p ND
1382 /// visible at the specified location.
1383 void makeMergedDefinitionVisible(NamedDecl *ND, SourceLocation Loc);
1385 bool isModuleVisible(Module *M) { return VisibleModules.isVisible(M); }
1387 /// Determine whether a declaration is visible to name lookup.
1388 bool isVisible(const NamedDecl *D) {
1389 return !D->isHidden() || isVisibleSlow(D);
1391 bool hasVisibleMergedDefinition(NamedDecl *Def);
1393 /// Determine if \p D has a visible definition. If not, suggest a declaration
1394 /// that should be made visible to expose the definition.
1395 bool hasVisibleDefinition(NamedDecl *D, NamedDecl **Suggested,
1396 bool OnlyNeedComplete = false);
1397 bool hasVisibleDefinition(const NamedDecl *D) {
1399 return hasVisibleDefinition(const_cast<NamedDecl*>(D), &Hidden);
1402 /// Determine if the template parameter \p D has a visible default argument.
1404 hasVisibleDefaultArgument(const NamedDecl *D,
1405 llvm::SmallVectorImpl<Module *> *Modules = nullptr);
1407 /// Determine if \p A and \p B are equivalent internal linkage declarations
1408 /// from different modules, and thus an ambiguity error can be downgraded to
1409 /// an extension warning.
1410 bool isEquivalentInternalLinkageDeclaration(const NamedDecl *A,
1411 const NamedDecl *B);
1412 void diagnoseEquivalentInternalLinkageDeclarations(
1413 SourceLocation Loc, const NamedDecl *D,
1414 ArrayRef<const NamedDecl *> Equiv);
1416 bool isCompleteType(SourceLocation Loc, QualType T) {
1417 return !RequireCompleteTypeImpl(Loc, T, nullptr);
1419 bool RequireCompleteType(SourceLocation Loc, QualType T,
1420 TypeDiagnoser &Diagnoser);
1421 bool RequireCompleteType(SourceLocation Loc, QualType T,
1424 template <typename... Ts>
1425 bool RequireCompleteType(SourceLocation Loc, QualType T, unsigned DiagID,
1426 const Ts &...Args) {
1427 BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
1428 return RequireCompleteType(Loc, T, Diagnoser);
1431 void completeExprArrayBound(Expr *E);
1432 bool RequireCompleteExprType(Expr *E, TypeDiagnoser &Diagnoser);
1433 bool RequireCompleteExprType(Expr *E, unsigned DiagID);
1435 template <typename... Ts>
1436 bool RequireCompleteExprType(Expr *E, unsigned DiagID, const Ts &...Args) {
1437 BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
1438 return RequireCompleteExprType(E, Diagnoser);
1441 bool RequireLiteralType(SourceLocation Loc, QualType T,
1442 TypeDiagnoser &Diagnoser);
1443 bool RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID);
1445 template <typename... Ts>
1446 bool RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID,
1447 const Ts &...Args) {
1448 BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
1449 return RequireLiteralType(Loc, T, Diagnoser);
1452 QualType getElaboratedType(ElaboratedTypeKeyword Keyword,
1453 const CXXScopeSpec &SS, QualType T);
1455 QualType BuildTypeofExprType(Expr *E, SourceLocation Loc);
1456 /// If AsUnevaluated is false, E is treated as though it were an evaluated
1457 /// context, such as when building a type for decltype(auto).
1458 QualType BuildDecltypeType(Expr *E, SourceLocation Loc,
1459 bool AsUnevaluated = true);
1460 QualType BuildUnaryTransformType(QualType BaseType,
1461 UnaryTransformType::UTTKind UKind,
1462 SourceLocation Loc);
1464 //===--------------------------------------------------------------------===//
1465 // Symbol table / Decl tracking callbacks: SemaDecl.cpp.
1468 struct SkipBodyInfo {
1469 SkipBodyInfo() : ShouldSkip(false), Previous(nullptr) {}
1471 NamedDecl *Previous;
1474 /// List of decls defined in a function prototype. This contains EnumConstants
1475 /// that incorrectly end up in translation unit scope because there is no
1476 /// function to pin them on. ActOnFunctionDeclarator reads this list and patches
1477 /// them into the FunctionDecl.
1478 std::vector<NamedDecl*> DeclsInPrototypeScope;
1480 DeclGroupPtrTy ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType = nullptr);
1482 void DiagnoseUseOfUnimplementedSelectors();
1484 bool isSimpleTypeSpecifier(tok::TokenKind Kind) const;
1486 ParsedType getTypeName(const IdentifierInfo &II, SourceLocation NameLoc,
1487 Scope *S, CXXScopeSpec *SS = nullptr,
1488 bool isClassName = false,
1489 bool HasTrailingDot = false,
1490 ParsedType ObjectType = ParsedType(),
1491 bool IsCtorOrDtorName = false,
1492 bool WantNontrivialTypeSourceInfo = false,
1493 IdentifierInfo **CorrectedII = nullptr);
1494 TypeSpecifierType isTagName(IdentifierInfo &II, Scope *S);
1495 bool isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S);
1496 void DiagnoseUnknownTypeName(IdentifierInfo *&II,
1497 SourceLocation IILoc,
1500 ParsedType &SuggestedType,
1501 bool AllowClassTemplates = false);
1503 /// \brief For compatibility with MSVC, we delay parsing of some default
1504 /// template type arguments until instantiation time. Emits a warning and
1505 /// returns a synthesized DependentNameType that isn't really dependent on any
1506 /// other template arguments.
1507 ParsedType ActOnDelayedDefaultTemplateArg(const IdentifierInfo &II,
1508 SourceLocation NameLoc);
1510 /// \brief Describes the result of the name lookup and resolution performed
1511 /// by \c ClassifyName().
1512 enum NameClassificationKind {
1518 NC_NestedNameSpecifier,
1524 class NameClassification {
1525 NameClassificationKind Kind;
1527 TemplateName Template;
1529 const IdentifierInfo *Keyword;
1531 explicit NameClassification(NameClassificationKind Kind) : Kind(Kind) {}
1534 NameClassification(ExprResult Expr) : Kind(NC_Expression), Expr(Expr) {}
1536 NameClassification(ParsedType Type) : Kind(NC_Type), Type(Type) {}
1538 NameClassification(const IdentifierInfo *Keyword)
1539 : Kind(NC_Keyword), Keyword(Keyword) { }
1541 static NameClassification Error() {
1542 return NameClassification(NC_Error);
1545 static NameClassification Unknown() {
1546 return NameClassification(NC_Unknown);
1549 static NameClassification NestedNameSpecifier() {
1550 return NameClassification(NC_NestedNameSpecifier);
1553 static NameClassification TypeTemplate(TemplateName Name) {
1554 NameClassification Result(NC_TypeTemplate);
1555 Result.Template = Name;
1559 static NameClassification VarTemplate(TemplateName Name) {
1560 NameClassification Result(NC_VarTemplate);
1561 Result.Template = Name;
1565 static NameClassification FunctionTemplate(TemplateName Name) {
1566 NameClassification Result(NC_FunctionTemplate);
1567 Result.Template = Name;
1571 NameClassificationKind getKind() const { return Kind; }
1573 ParsedType getType() const {
1574 assert(Kind == NC_Type);
1578 ExprResult getExpression() const {
1579 assert(Kind == NC_Expression);
1583 TemplateName getTemplateName() const {
1584 assert(Kind == NC_TypeTemplate || Kind == NC_FunctionTemplate ||
1585 Kind == NC_VarTemplate);
1589 TemplateNameKind getTemplateNameKind() const {
1591 case NC_TypeTemplate:
1592 return TNK_Type_template;
1593 case NC_FunctionTemplate:
1594 return TNK_Function_template;
1595 case NC_VarTemplate:
1596 return TNK_Var_template;
1598 llvm_unreachable("unsupported name classification.");
1603 /// \brief Perform name lookup on the given name, classifying it based on
1604 /// the results of name lookup and the following token.
1606 /// This routine is used by the parser to resolve identifiers and help direct
1607 /// parsing. When the identifier cannot be found, this routine will attempt
1608 /// to correct the typo and classify based on the resulting name.
1610 /// \param S The scope in which we're performing name lookup.
1612 /// \param SS The nested-name-specifier that precedes the name.
1614 /// \param Name The identifier. If typo correction finds an alternative name,
1615 /// this pointer parameter will be updated accordingly.
1617 /// \param NameLoc The location of the identifier.
1619 /// \param NextToken The token following the identifier. Used to help
1620 /// disambiguate the name.
1622 /// \param IsAddressOfOperand True if this name is the operand of a unary
1623 /// address of ('&') expression, assuming it is classified as an
1626 /// \param CCC The correction callback, if typo correction is desired.
1628 ClassifyName(Scope *S, CXXScopeSpec &SS, IdentifierInfo *&Name,
1629 SourceLocation NameLoc, const Token &NextToken,
1630 bool IsAddressOfOperand,
1631 std::unique_ptr<CorrectionCandidateCallback> CCC = nullptr);
1633 Decl *ActOnDeclarator(Scope *S, Declarator &D);
1635 NamedDecl *HandleDeclarator(Scope *S, Declarator &D,
1636 MultiTemplateParamsArg TemplateParameterLists);
1637 void RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S);
1638 bool DiagnoseClassNameShadow(DeclContext *DC, DeclarationNameInfo Info);
1639 bool diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
1640 DeclarationName Name,
1641 SourceLocation Loc);
1643 diagnoseIgnoredQualifiers(unsigned DiagID, unsigned Quals,
1644 SourceLocation FallbackLoc,
1645 SourceLocation ConstQualLoc = SourceLocation(),
1646 SourceLocation VolatileQualLoc = SourceLocation(),
1647 SourceLocation RestrictQualLoc = SourceLocation(),
1648 SourceLocation AtomicQualLoc = SourceLocation());
1650 static bool adjustContextForLocalExternDecl(DeclContext *&DC);
1651 void DiagnoseFunctionSpecifiers(const DeclSpec &DS);
1652 void CheckShadow(Scope *S, VarDecl *D, const LookupResult& R);
1653 void CheckShadow(Scope *S, VarDecl *D);
1654 void CheckCastAlign(Expr *Op, QualType T, SourceRange TRange);
1655 void handleTagNumbering(const TagDecl *Tag, Scope *TagScope);
1656 void setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
1657 TypedefNameDecl *NewTD);
1658 void CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *D);
1659 NamedDecl* ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
1660 TypeSourceInfo *TInfo,
1661 LookupResult &Previous);
1662 NamedDecl* ActOnTypedefNameDecl(Scope* S, DeclContext* DC, TypedefNameDecl *D,
1663 LookupResult &Previous, bool &Redeclaration);
1664 NamedDecl *ActOnVariableDeclarator(Scope *S, Declarator &D, DeclContext *DC,
1665 TypeSourceInfo *TInfo,
1666 LookupResult &Previous,
1667 MultiTemplateParamsArg TemplateParamLists,
1669 // Returns true if the variable declaration is a redeclaration
1670 bool CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous);
1671 void CheckVariableDeclarationType(VarDecl *NewVD);
1672 void CheckCompleteVariableDeclaration(VarDecl *var);
1673 void MaybeSuggestAddingStaticToDecl(const FunctionDecl *D);
1675 NamedDecl* ActOnFunctionDeclarator(Scope* S, Declarator& D, DeclContext* DC,
1676 TypeSourceInfo *TInfo,
1677 LookupResult &Previous,
1678 MultiTemplateParamsArg TemplateParamLists,
1680 bool AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD);
1682 bool CheckConstexprFunctionDecl(const FunctionDecl *FD);
1683 bool CheckConstexprFunctionBody(const FunctionDecl *FD, Stmt *Body);
1685 void DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD);
1686 void FindHiddenVirtualMethods(CXXMethodDecl *MD,
1687 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods);
1688 void NoteHiddenVirtualMethods(CXXMethodDecl *MD,
1689 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods);
1690 // Returns true if the function declaration is a redeclaration
1691 bool CheckFunctionDeclaration(Scope *S,
1692 FunctionDecl *NewFD, LookupResult &Previous,
1693 bool IsExplicitSpecialization);
1694 void CheckMain(FunctionDecl *FD, const DeclSpec &D);
1695 void CheckMSVCRTEntryPoint(FunctionDecl *FD);
1696 Decl *ActOnParamDeclarator(Scope *S, Declarator &D);
1697 ParmVarDecl *BuildParmVarDeclForTypedef(DeclContext *DC,
1700 ParmVarDecl *CheckParameter(DeclContext *DC, SourceLocation StartLoc,
1701 SourceLocation NameLoc, IdentifierInfo *Name,
1702 QualType T, TypeSourceInfo *TSInfo,
1704 void ActOnParamDefaultArgument(Decl *param,
1705 SourceLocation EqualLoc,
1707 void ActOnParamUnparsedDefaultArgument(Decl *param,
1708 SourceLocation EqualLoc,
1709 SourceLocation ArgLoc);
1710 void ActOnParamDefaultArgumentError(Decl *param, SourceLocation EqualLoc);
1711 bool SetParamDefaultArgument(ParmVarDecl *Param, Expr *DefaultArg,
1712 SourceLocation EqualLoc);
1714 void AddInitializerToDecl(Decl *dcl, Expr *init, bool DirectInit,
1715 bool TypeMayContainAuto);
1716 void ActOnUninitializedDecl(Decl *dcl, bool TypeMayContainAuto);
1717 void ActOnInitializerError(Decl *Dcl);
1718 void ActOnPureSpecifier(Decl *D, SourceLocation PureSpecLoc);
1719 void ActOnCXXForRangeDecl(Decl *D);
1720 StmtResult ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc,
1721 IdentifierInfo *Ident,
1722 ParsedAttributes &Attrs,
1723 SourceLocation AttrEnd);
1724 void SetDeclDeleted(Decl *dcl, SourceLocation DelLoc);
1725 void SetDeclDefaulted(Decl *dcl, SourceLocation DefaultLoc);
1726 void FinalizeDeclaration(Decl *D);
1727 DeclGroupPtrTy FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
1728 ArrayRef<Decl *> Group);
1729 DeclGroupPtrTy BuildDeclaratorGroup(MutableArrayRef<Decl *> Group,
1730 bool TypeMayContainAuto = true);
1732 /// Should be called on all declarations that might have attached
1733 /// documentation comments.
1734 void ActOnDocumentableDecl(Decl *D);
1735 void ActOnDocumentableDecls(ArrayRef<Decl *> Group);
1737 void ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
1738 SourceLocation LocAfterDecls);
1739 void CheckForFunctionRedefinition(
1740 FunctionDecl *FD, const FunctionDecl *EffectiveDefinition = nullptr,
1741 SkipBodyInfo *SkipBody = nullptr);
1742 Decl *ActOnStartOfFunctionDef(Scope *S, Declarator &D,
1743 MultiTemplateParamsArg TemplateParamLists,
1744 SkipBodyInfo *SkipBody = nullptr);
1745 Decl *ActOnStartOfFunctionDef(Scope *S, Decl *D,
1746 SkipBodyInfo *SkipBody = nullptr);
1747 void ActOnStartOfObjCMethodDef(Scope *S, Decl *D);
1748 bool isObjCMethodDecl(Decl *D) {
1749 return D && isa<ObjCMethodDecl>(D);
1752 /// \brief Determine whether we can delay parsing the body of a function or
1753 /// function template until it is used, assuming we don't care about emitting
1754 /// code for that function.
1756 /// This will be \c false if we may need the body of the function in the
1757 /// middle of parsing an expression (where it's impractical to switch to
1758 /// parsing a different function), for instance, if it's constexpr in C++11
1759 /// or has an 'auto' return type in C++14. These cases are essentially bugs.
1760 bool canDelayFunctionBody(const Declarator &D);
1762 /// \brief Determine whether we can skip parsing the body of a function
1763 /// definition, assuming we don't care about analyzing its body or emitting
1764 /// code for that function.
1766 /// This will be \c false only if we may need the body of the function in
1767 /// order to parse the rest of the program (for instance, if it is
1768 /// \c constexpr in C++11 or has an 'auto' return type in C++14).
1769 bool canSkipFunctionBody(Decl *D);
1771 void computeNRVO(Stmt *Body, sema::FunctionScopeInfo *Scope);
1772 Decl *ActOnFinishFunctionBody(Decl *Decl, Stmt *Body);
1773 Decl *ActOnFinishFunctionBody(Decl *Decl, Stmt *Body, bool IsInstantiation);
1774 Decl *ActOnSkippedFunctionBody(Decl *Decl);
1775 void ActOnFinishInlineMethodDef(CXXMethodDecl *D);
1777 /// ActOnFinishDelayedAttribute - Invoked when we have finished parsing an
1778 /// attribute for which parsing is delayed.
1779 void ActOnFinishDelayedAttribute(Scope *S, Decl *D, ParsedAttributes &Attrs);
1781 /// \brief Diagnose any unused parameters in the given sequence of
1782 /// ParmVarDecl pointers.
1783 void DiagnoseUnusedParameters(ParmVarDecl * const *Begin,
1784 ParmVarDecl * const *End);
1786 /// \brief Diagnose whether the size of parameters or return value of a
1787 /// function or obj-c method definition is pass-by-value and larger than a
1788 /// specified threshold.
1789 void DiagnoseSizeOfParametersAndReturnValue(ParmVarDecl * const *Begin,
1790 ParmVarDecl * const *End,
1794 void DiagnoseInvalidJumps(Stmt *Body);
1795 Decl *ActOnFileScopeAsmDecl(Expr *expr,
1796 SourceLocation AsmLoc,
1797 SourceLocation RParenLoc);
1799 /// \brief Handle a C++11 empty-declaration and attribute-declaration.
1800 Decl *ActOnEmptyDeclaration(Scope *S,
1801 AttributeList *AttrList,
1802 SourceLocation SemiLoc);
1804 /// \brief The parser has processed a module import declaration.
1806 /// \param AtLoc The location of the '@' symbol, if any.
1808 /// \param ImportLoc The location of the 'import' keyword.
1810 /// \param Path The module access path.
1811 DeclResult ActOnModuleImport(SourceLocation AtLoc, SourceLocation ImportLoc,
1814 /// \brief The parser has processed a module import translated from a
1815 /// #include or similar preprocessing directive.
1816 void ActOnModuleInclude(SourceLocation DirectiveLoc, Module *Mod);
1818 /// \brief The parsed has entered a submodule.
1819 void ActOnModuleBegin(SourceLocation DirectiveLoc, Module *Mod);
1820 /// \brief The parser has left a submodule.
1821 void ActOnModuleEnd(SourceLocation DirectiveLoc, Module *Mod);
1823 /// \brief Check if module import may be found in the current context,
1824 /// emit error if not.
1825 void diagnoseMisplacedModuleImport(Module *M, SourceLocation ImportLoc);
1827 /// \brief Create an implicit import of the given module at the given
1828 /// source location, for error recovery, if possible.
1830 /// This routine is typically used when an entity found by name lookup
1831 /// is actually hidden within a module that we know about but the user
1832 /// has forgotten to import.
1833 void createImplicitModuleImportForErrorRecovery(SourceLocation Loc,
1836 /// Kinds of missing import. Note, the values of these enumerators correspond
1837 /// to %select values in diagnostics.
1838 enum class MissingImportKind {
1844 /// \brief Diagnose that the specified declaration needs to be visible but
1845 /// isn't, and suggest a module import that would resolve the problem.
1846 void diagnoseMissingImport(SourceLocation Loc, NamedDecl *Decl,
1847 bool NeedDefinition, bool Recover = true);
1848 void diagnoseMissingImport(SourceLocation Loc, NamedDecl *Decl,
1849 SourceLocation DeclLoc, ArrayRef<Module *> Modules,
1850 MissingImportKind MIK, bool Recover);
1852 /// \brief Retrieve a suitable printing policy.
1853 PrintingPolicy getPrintingPolicy() const {
1854 return getPrintingPolicy(Context, PP);
1857 /// \brief Retrieve a suitable printing policy.
1858 static PrintingPolicy getPrintingPolicy(const ASTContext &Ctx,
1859 const Preprocessor &PP);
1862 void ActOnPopScope(SourceLocation Loc, Scope *S);
1863 void ActOnTranslationUnitScope(Scope *S);
1865 Decl *ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS,
1867 Decl *ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS,
1869 MultiTemplateParamsArg TemplateParams,
1870 bool IsExplicitInstantiation = false);
1872 Decl *BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
1875 const PrintingPolicy &Policy);
1877 Decl *BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
1878 RecordDecl *Record);
1880 bool isAcceptableTagRedeclaration(const TagDecl *Previous,
1881 TagTypeKind NewTag, bool isDefinition,
1882 SourceLocation NewTagLoc,
1883 const IdentifierInfo *Name);
1886 TUK_Reference, // Reference to a tag: 'struct foo *X;'
1887 TUK_Declaration, // Fwd decl of a tag: 'struct foo;'
1888 TUK_Definition, // Definition of a tag: 'struct foo { int X; } Y;'
1889 TUK_Friend // Friend declaration: 'friend struct foo;'
1892 Decl *ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
1893 SourceLocation KWLoc, CXXScopeSpec &SS,
1894 IdentifierInfo *Name, SourceLocation NameLoc,
1895 AttributeList *Attr, AccessSpecifier AS,
1896 SourceLocation ModulePrivateLoc,
1897 MultiTemplateParamsArg TemplateParameterLists,
1898 bool &OwnedDecl, bool &IsDependent,
1899 SourceLocation ScopedEnumKWLoc,
1900 bool ScopedEnumUsesClassTag, TypeResult UnderlyingType,
1901 bool IsTypeSpecifier, SkipBodyInfo *SkipBody = nullptr);
1903 Decl *ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
1904 unsigned TagSpec, SourceLocation TagLoc,
1906 IdentifierInfo *Name, SourceLocation NameLoc,
1907 AttributeList *Attr,
1908 MultiTemplateParamsArg TempParamLists);
1910 TypeResult ActOnDependentTag(Scope *S,
1913 const CXXScopeSpec &SS,
1914 IdentifierInfo *Name,
1915 SourceLocation TagLoc,
1916 SourceLocation NameLoc);
1918 void ActOnDefs(Scope *S, Decl *TagD, SourceLocation DeclStart,
1919 IdentifierInfo *ClassName,
1920 SmallVectorImpl<Decl *> &Decls);
1921 Decl *ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
1922 Declarator &D, Expr *BitfieldWidth);
1924 FieldDecl *HandleField(Scope *S, RecordDecl *TagD, SourceLocation DeclStart,
1925 Declarator &D, Expr *BitfieldWidth,
1926 InClassInitStyle InitStyle,
1927 AccessSpecifier AS);
1928 MSPropertyDecl *HandleMSProperty(Scope *S, RecordDecl *TagD,
1929 SourceLocation DeclStart,
1930 Declarator &D, Expr *BitfieldWidth,
1931 InClassInitStyle InitStyle,
1933 AttributeList *MSPropertyAttr);
1935 FieldDecl *CheckFieldDecl(DeclarationName Name, QualType T,
1936 TypeSourceInfo *TInfo,
1937 RecordDecl *Record, SourceLocation Loc,
1938 bool Mutable, Expr *BitfieldWidth,
1939 InClassInitStyle InitStyle,
1940 SourceLocation TSSL,
1941 AccessSpecifier AS, NamedDecl *PrevDecl,
1942 Declarator *D = nullptr);
1944 bool CheckNontrivialField(FieldDecl *FD);
1945 void DiagnoseNontrivial(const CXXRecordDecl *Record, CXXSpecialMember CSM);
1946 bool SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
1947 bool Diagnose = false);
1948 CXXSpecialMember getSpecialMember(const CXXMethodDecl *MD);
1949 void ActOnLastBitfield(SourceLocation DeclStart,
1950 SmallVectorImpl<Decl *> &AllIvarDecls);
1951 Decl *ActOnIvar(Scope *S, SourceLocation DeclStart,
1952 Declarator &D, Expr *BitfieldWidth,
1953 tok::ObjCKeywordKind visibility);
1955 // This is used for both record definitions and ObjC interface declarations.
1956 void ActOnFields(Scope* S, SourceLocation RecLoc, Decl *TagDecl,
1957 ArrayRef<Decl *> Fields,
1958 SourceLocation LBrac, SourceLocation RBrac,
1959 AttributeList *AttrList);
1961 /// ActOnTagStartDefinition - Invoked when we have entered the
1962 /// scope of a tag's definition (e.g., for an enumeration, class,
1963 /// struct, or union).
1964 void ActOnTagStartDefinition(Scope *S, Decl *TagDecl);
1966 typedef void *SkippedDefinitionContext;
1968 /// \brief Invoked when we enter a tag definition that we're skipping.
1969 SkippedDefinitionContext ActOnTagStartSkippedDefinition(Scope *S, Decl *TD);
1971 Decl *ActOnObjCContainerStartDefinition(Decl *IDecl);
1973 /// ActOnStartCXXMemberDeclarations - Invoked when we have parsed a
1974 /// C++ record definition's base-specifiers clause and are starting its
1975 /// member declarations.
1976 void ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagDecl,
1977 SourceLocation FinalLoc,
1978 bool IsFinalSpelledSealed,
1979 SourceLocation LBraceLoc);
1981 /// ActOnTagFinishDefinition - Invoked once we have finished parsing
1982 /// the definition of a tag (enumeration, class, struct, or union).
1983 void ActOnTagFinishDefinition(Scope *S, Decl *TagDecl,
1984 SourceLocation RBraceLoc);
1986 void ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context);
1988 void ActOnObjCContainerFinishDefinition();
1990 /// \brief Invoked when we must temporarily exit the objective-c container
1991 /// scope for parsing/looking-up C constructs.
1993 /// Must be followed by a call to \see ActOnObjCReenterContainerContext
1994 void ActOnObjCTemporaryExitContainerContext(DeclContext *DC);
1995 void ActOnObjCReenterContainerContext(DeclContext *DC);
1997 /// ActOnTagDefinitionError - Invoked when there was an unrecoverable
1998 /// error parsing the definition of a tag.
1999 void ActOnTagDefinitionError(Scope *S, Decl *TagDecl);
2001 EnumConstantDecl *CheckEnumConstant(EnumDecl *Enum,
2002 EnumConstantDecl *LastEnumConst,
2003 SourceLocation IdLoc,
2006 bool CheckEnumUnderlyingType(TypeSourceInfo *TI);
2007 bool CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
2008 QualType EnumUnderlyingTy,
2009 bool EnumUnderlyingIsImplicit,
2010 const EnumDecl *Prev);
2012 /// Determine whether the body of an anonymous enumeration should be skipped.
2013 /// \param II The name of the first enumerator.
2014 SkipBodyInfo shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II,
2015 SourceLocation IILoc);
2017 Decl *ActOnEnumConstant(Scope *S, Decl *EnumDecl, Decl *LastEnumConstant,
2018 SourceLocation IdLoc, IdentifierInfo *Id,
2019 AttributeList *Attrs,
2020 SourceLocation EqualLoc, Expr *Val);
2021 void ActOnEnumBody(SourceLocation EnumLoc, SourceLocation LBraceLoc,
2022 SourceLocation RBraceLoc, Decl *EnumDecl,
2023 ArrayRef<Decl *> Elements,
2024 Scope *S, AttributeList *Attr);
2026 DeclContext *getContainingDC(DeclContext *DC);
2028 /// Set the current declaration context until it gets popped.
2029 void PushDeclContext(Scope *S, DeclContext *DC);
2030 void PopDeclContext();
2032 /// EnterDeclaratorContext - Used when we must lookup names in the context
2033 /// of a declarator's nested name specifier.
2034 void EnterDeclaratorContext(Scope *S, DeclContext *DC);
2035 void ExitDeclaratorContext(Scope *S);
2037 /// Push the parameters of D, which must be a function, into scope.
2038 void ActOnReenterFunctionContext(Scope* S, Decl* D);
2039 void ActOnExitFunctionContext();
2041 DeclContext *getFunctionLevelDeclContext();
2043 /// getCurFunctionDecl - If inside of a function body, this returns a pointer
2044 /// to the function decl for the function being parsed. If we're currently
2045 /// in a 'block', this returns the containing context.
2046 FunctionDecl *getCurFunctionDecl();
2048 /// getCurMethodDecl - If inside of a method body, this returns a pointer to
2049 /// the method decl for the method being parsed. If we're currently
2050 /// in a 'block', this returns the containing context.
2051 ObjCMethodDecl *getCurMethodDecl();
2053 /// getCurFunctionOrMethodDecl - Return the Decl for the current ObjC method
2054 /// or C function we're in, otherwise return null. If we're currently
2055 /// in a 'block', this returns the containing context.
2056 NamedDecl *getCurFunctionOrMethodDecl();
2058 /// Add this decl to the scope shadowed decl chains.
2059 void PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext = true);
2061 /// \brief Make the given externally-produced declaration visible at the
2062 /// top level scope.
2064 /// \param D The externally-produced declaration to push.
2066 /// \param Name The name of the externally-produced declaration.
2067 void pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name);
2069 /// isDeclInScope - If 'Ctx' is a function/method, isDeclInScope returns true
2070 /// if 'D' is in Scope 'S', otherwise 'S' is ignored and isDeclInScope returns
2071 /// true if 'D' belongs to the given declaration context.
2073 /// \param AllowInlineNamespace If \c true, allow the declaration to be in the
2074 /// enclosing namespace set of the context, rather than contained
2075 /// directly within it.
2076 bool isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S = nullptr,
2077 bool AllowInlineNamespace = false);
2079 /// Finds the scope corresponding to the given decl context, if it
2080 /// happens to be an enclosing scope. Otherwise return NULL.
2081 static Scope *getScopeForDeclContext(Scope *S, DeclContext *DC);
2083 /// Subroutines of ActOnDeclarator().
2084 TypedefDecl *ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
2085 TypeSourceInfo *TInfo);
2086 bool isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New);
2088 /// \brief Describes the kind of merge to perform for availability
2089 /// attributes (including "deprecated", "unavailable", and "availability").
2090 enum AvailabilityMergeKind {
2091 /// \brief Don't merge availability attributes at all.
2093 /// \brief Merge availability attributes for a redeclaration, which requires
2096 /// \brief Merge availability attributes for an override, which requires
2097 /// an exact match or a weakening of constraints.
2099 /// \brief Merge availability attributes for an implementation of
2100 /// a protocol requirement.
2101 AMK_ProtocolImplementation,
2104 /// Attribute merging methods. Return true if a new attribute was added.
2105 AvailabilityAttr *mergeAvailabilityAttr(NamedDecl *D, SourceRange Range,
2106 IdentifierInfo *Platform,
2107 VersionTuple Introduced,
2108 VersionTuple Deprecated,
2109 VersionTuple Obsoleted,
2112 AvailabilityMergeKind AMK,
2113 unsigned AttrSpellingListIndex);
2114 TypeVisibilityAttr *mergeTypeVisibilityAttr(Decl *D, SourceRange Range,
2115 TypeVisibilityAttr::VisibilityType Vis,
2116 unsigned AttrSpellingListIndex);
2117 VisibilityAttr *mergeVisibilityAttr(Decl *D, SourceRange Range,
2118 VisibilityAttr::VisibilityType Vis,
2119 unsigned AttrSpellingListIndex);
2120 DLLImportAttr *mergeDLLImportAttr(Decl *D, SourceRange Range,
2121 unsigned AttrSpellingListIndex);
2122 DLLExportAttr *mergeDLLExportAttr(Decl *D, SourceRange Range,
2123 unsigned AttrSpellingListIndex);
2125 mergeMSInheritanceAttr(Decl *D, SourceRange Range, bool BestCase,
2126 unsigned AttrSpellingListIndex,
2127 MSInheritanceAttr::Spelling SemanticSpelling);
2128 FormatAttr *mergeFormatAttr(Decl *D, SourceRange Range,
2129 IdentifierInfo *Format, int FormatIdx,
2130 int FirstArg, unsigned AttrSpellingListIndex);
2131 SectionAttr *mergeSectionAttr(Decl *D, SourceRange Range, StringRef Name,
2132 unsigned AttrSpellingListIndex);
2133 AlwaysInlineAttr *mergeAlwaysInlineAttr(Decl *D, SourceRange Range,
2134 IdentifierInfo *Ident,
2135 unsigned AttrSpellingListIndex);
2136 MinSizeAttr *mergeMinSizeAttr(Decl *D, SourceRange Range,
2137 unsigned AttrSpellingListIndex);
2138 OptimizeNoneAttr *mergeOptimizeNoneAttr(Decl *D, SourceRange Range,
2139 unsigned AttrSpellingListIndex);
2140 InternalLinkageAttr *mergeInternalLinkageAttr(Decl *D, SourceRange Range,
2141 IdentifierInfo *Ident,
2142 unsigned AttrSpellingListIndex);
2143 CommonAttr *mergeCommonAttr(Decl *D, SourceRange Range, IdentifierInfo *Ident,
2144 unsigned AttrSpellingListIndex);
2146 void mergeDeclAttributes(NamedDecl *New, Decl *Old,
2147 AvailabilityMergeKind AMK = AMK_Redeclaration);
2148 void MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New,
2149 LookupResult &OldDecls);
2150 bool MergeFunctionDecl(FunctionDecl *New, NamedDecl *&Old, Scope *S,
2151 bool MergeTypeWithOld);
2152 bool MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
2153 Scope *S, bool MergeTypeWithOld);
2154 void mergeObjCMethodDecls(ObjCMethodDecl *New, ObjCMethodDecl *Old);
2155 void MergeVarDecl(VarDecl *New, LookupResult &Previous);
2156 void MergeVarDeclTypes(VarDecl *New, VarDecl *Old, bool MergeTypeWithOld);
2157 void MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old);
2158 bool MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old, Scope *S);
2160 // AssignmentAction - This is used by all the assignment diagnostic functions
2161 // to represent what is actually causing the operation
2162 enum AssignmentAction {
2170 AA_Passing_CFAudited
2173 /// C++ Overloading.
2175 /// This is a legitimate overload: the existing declarations are
2176 /// functions or function templates with different signatures.
2179 /// This is not an overload because the signature exactly matches
2180 /// an existing declaration.
2183 /// This is not an overload because the lookup results contain a
2187 OverloadKind CheckOverload(Scope *S,
2189 const LookupResult &OldDecls,
2190 NamedDecl *&OldDecl,
2191 bool IsForUsingDecl);
2192 bool IsOverload(FunctionDecl *New, FunctionDecl *Old, bool IsForUsingDecl);
2194 /// \brief Checks availability of the function depending on the current
2195 /// function context.Inside an unavailable function,unavailability is ignored.
2197 /// \returns true if \p FD is unavailable and current context is inside
2198 /// an available function, false otherwise.
2199 bool isFunctionConsideredUnavailable(FunctionDecl *FD);
2201 ImplicitConversionSequence
2202 TryImplicitConversion(Expr *From, QualType ToType,
2203 bool SuppressUserConversions,
2205 bool InOverloadResolution,
2207 bool AllowObjCWritebackConversion);
2209 bool IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType);
2210 bool IsFloatingPointPromotion(QualType FromType, QualType ToType);
2211 bool IsComplexPromotion(QualType FromType, QualType ToType);
2212 bool IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
2213 bool InOverloadResolution,
2214 QualType& ConvertedType, bool &IncompatibleObjC);
2215 bool isObjCPointerConversion(QualType FromType, QualType ToType,
2216 QualType& ConvertedType, bool &IncompatibleObjC);
2217 bool isObjCWritebackConversion(QualType FromType, QualType ToType,
2218 QualType &ConvertedType);
2219 bool IsBlockPointerConversion(QualType FromType, QualType ToType,
2220 QualType& ConvertedType);
2221 bool FunctionParamTypesAreEqual(const FunctionProtoType *OldType,
2222 const FunctionProtoType *NewType,
2223 unsigned *ArgPos = nullptr);
2224 void HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
2225 QualType FromType, QualType ToType);
2227 void maybeExtendBlockObject(ExprResult &E);
2228 CastKind PrepareCastToObjCObjectPointer(ExprResult &E);
2229 bool CheckPointerConversion(Expr *From, QualType ToType,
2231 CXXCastPath& BasePath,
2232 bool IgnoreBaseAccess,
2233 bool Diagnose = true);
2234 bool IsMemberPointerConversion(Expr *From, QualType FromType, QualType ToType,
2235 bool InOverloadResolution,
2236 QualType &ConvertedType);
2237 bool CheckMemberPointerConversion(Expr *From, QualType ToType,
2239 CXXCastPath &BasePath,
2240 bool IgnoreBaseAccess);
2241 bool IsQualificationConversion(QualType FromType, QualType ToType,
2242 bool CStyle, bool &ObjCLifetimeConversion);
2243 bool IsNoReturnConversion(QualType FromType, QualType ToType,
2244 QualType &ResultTy);
2245 bool DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType);
2246 bool isSameOrCompatibleFunctionType(CanQualType Param, CanQualType Arg);
2248 ExprResult PerformMoveOrCopyInitialization(const InitializedEntity &Entity,
2249 const VarDecl *NRVOCandidate,
2250 QualType ResultType,
2252 bool AllowNRVO = true);
2254 bool CanPerformCopyInitialization(const InitializedEntity &Entity,
2256 ExprResult PerformCopyInitialization(const InitializedEntity &Entity,
2257 SourceLocation EqualLoc,
2259 bool TopLevelOfInitList = false,
2260 bool AllowExplicit = false);
2261 ExprResult PerformObjectArgumentInitialization(Expr *From,
2262 NestedNameSpecifier *Qualifier,
2263 NamedDecl *FoundDecl,
2264 CXXMethodDecl *Method);
2266 ExprResult PerformContextuallyConvertToBool(Expr *From);
2267 ExprResult PerformContextuallyConvertToObjCPointer(Expr *From);
2269 /// Contexts in which a converted constant expression is required.
2271 CCEK_CaseValue, ///< Expression in a case label.
2272 CCEK_Enumerator, ///< Enumerator value with fixed underlying type.
2273 CCEK_TemplateArg, ///< Value of a non-type template parameter.
2274 CCEK_NewExpr ///< Constant expression in a noptr-new-declarator.
2276 ExprResult CheckConvertedConstantExpression(Expr *From, QualType T,
2277 llvm::APSInt &Value, CCEKind CCE);
2278 ExprResult CheckConvertedConstantExpression(Expr *From, QualType T,
2279 APValue &Value, CCEKind CCE);
2281 /// \brief Abstract base class used to perform a contextual implicit
2282 /// conversion from an expression to any type passing a filter.
2283 class ContextualImplicitConverter {
2286 bool SuppressConversion;
2288 ContextualImplicitConverter(bool Suppress = false,
2289 bool SuppressConversion = false)
2290 : Suppress(Suppress), SuppressConversion(SuppressConversion) {}
2292 /// \brief Determine whether the specified type is a valid destination type
2293 /// for this conversion.
2294 virtual bool match(QualType T) = 0;
2296 /// \brief Emits a diagnostic complaining that the expression does not have
2297 /// integral or enumeration type.
2298 virtual SemaDiagnosticBuilder
2299 diagnoseNoMatch(Sema &S, SourceLocation Loc, QualType T) = 0;
2301 /// \brief Emits a diagnostic when the expression has incomplete class type.
2302 virtual SemaDiagnosticBuilder
2303 diagnoseIncomplete(Sema &S, SourceLocation Loc, QualType T) = 0;
2305 /// \brief Emits a diagnostic when the only matching conversion function
2307 virtual SemaDiagnosticBuilder diagnoseExplicitConv(
2308 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) = 0;
2310 /// \brief Emits a note for the explicit conversion function.
2311 virtual SemaDiagnosticBuilder
2312 noteExplicitConv(Sema &S, CXXConversionDecl *Conv, QualType ConvTy) = 0;
2314 /// \brief Emits a diagnostic when there are multiple possible conversion
2316 virtual SemaDiagnosticBuilder
2317 diagnoseAmbiguous(Sema &S, SourceLocation Loc, QualType T) = 0;
2319 /// \brief Emits a note for one of the candidate conversions.
2320 virtual SemaDiagnosticBuilder
2321 noteAmbiguous(Sema &S, CXXConversionDecl *Conv, QualType ConvTy) = 0;
2323 /// \brief Emits a diagnostic when we picked a conversion function
2324 /// (for cases when we are not allowed to pick a conversion function).
2325 virtual SemaDiagnosticBuilder diagnoseConversion(
2326 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) = 0;
2328 virtual ~ContextualImplicitConverter() {}
2331 class ICEConvertDiagnoser : public ContextualImplicitConverter {
2332 bool AllowScopedEnumerations;
2335 ICEConvertDiagnoser(bool AllowScopedEnumerations,
2336 bool Suppress, bool SuppressConversion)
2337 : ContextualImplicitConverter(Suppress, SuppressConversion),
2338 AllowScopedEnumerations(AllowScopedEnumerations) {}
2340 /// Match an integral or (possibly scoped) enumeration type.
2341 bool match(QualType T) override;
2343 SemaDiagnosticBuilder
2344 diagnoseNoMatch(Sema &S, SourceLocation Loc, QualType T) override {
2345 return diagnoseNotInt(S, Loc, T);
2348 /// \brief Emits a diagnostic complaining that the expression does not have
2349 /// integral or enumeration type.
2350 virtual SemaDiagnosticBuilder
2351 diagnoseNotInt(Sema &S, SourceLocation Loc, QualType T) = 0;
2354 /// Perform a contextual implicit conversion.
2355 ExprResult PerformContextualImplicitConversion(
2356 SourceLocation Loc, Expr *FromE, ContextualImplicitConverter &Converter);
2359 enum ObjCSubscriptKind {
2364 ObjCSubscriptKind CheckSubscriptingKind(Expr *FromE);
2366 // Note that LK_String is intentionally after the other literals, as
2367 // this is used for diagnostics logic.
2368 enum ObjCLiteralKind {
2377 ObjCLiteralKind CheckLiteralKind(Expr *FromE);
2379 ExprResult PerformObjectMemberConversion(Expr *From,
2380 NestedNameSpecifier *Qualifier,
2381 NamedDecl *FoundDecl,
2384 // Members have to be NamespaceDecl* or TranslationUnitDecl*.
2385 // TODO: make this is a typesafe union.
2386 typedef llvm::SmallPtrSet<DeclContext *, 16> AssociatedNamespaceSet;
2387 typedef llvm::SmallPtrSet<CXXRecordDecl *, 16> AssociatedClassSet;
2389 void AddOverloadCandidate(FunctionDecl *Function,
2390 DeclAccessPair FoundDecl,
2391 ArrayRef<Expr *> Args,
2392 OverloadCandidateSet& CandidateSet,
2393 bool SuppressUserConversions = false,
2394 bool PartialOverloading = false,
2395 bool AllowExplicit = false);
2396 void AddFunctionCandidates(const UnresolvedSetImpl &Functions,
2397 ArrayRef<Expr *> Args,
2398 OverloadCandidateSet &CandidateSet,
2399 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr,
2400 bool SuppressUserConversions = false,
2401 bool PartialOverloading = false);
2402 void AddMethodCandidate(DeclAccessPair FoundDecl,
2403 QualType ObjectType,
2404 Expr::Classification ObjectClassification,
2405 ArrayRef<Expr *> Args,
2406 OverloadCandidateSet& CandidateSet,
2407 bool SuppressUserConversion = false);
2408 void AddMethodCandidate(CXXMethodDecl *Method,
2409 DeclAccessPair FoundDecl,
2410 CXXRecordDecl *ActingContext, QualType ObjectType,
2411 Expr::Classification ObjectClassification,
2412 ArrayRef<Expr *> Args,
2413 OverloadCandidateSet& CandidateSet,
2414 bool SuppressUserConversions = false,
2415 bool PartialOverloading = false);
2416 void AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
2417 DeclAccessPair FoundDecl,
2418 CXXRecordDecl *ActingContext,
2419 TemplateArgumentListInfo *ExplicitTemplateArgs,
2420 QualType ObjectType,
2421 Expr::Classification ObjectClassification,
2422 ArrayRef<Expr *> Args,
2423 OverloadCandidateSet& CandidateSet,
2424 bool SuppressUserConversions = false,
2425 bool PartialOverloading = false);
2426 void AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
2427 DeclAccessPair FoundDecl,
2428 TemplateArgumentListInfo *ExplicitTemplateArgs,
2429 ArrayRef<Expr *> Args,
2430 OverloadCandidateSet& CandidateSet,
2431 bool SuppressUserConversions = false,
2432 bool PartialOverloading = false);
2433 void AddConversionCandidate(CXXConversionDecl *Conversion,
2434 DeclAccessPair FoundDecl,
2435 CXXRecordDecl *ActingContext,
2436 Expr *From, QualType ToType,
2437 OverloadCandidateSet& CandidateSet,
2438 bool AllowObjCConversionOnExplicit);
2439 void AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
2440 DeclAccessPair FoundDecl,
2441 CXXRecordDecl *ActingContext,
2442 Expr *From, QualType ToType,
2443 OverloadCandidateSet &CandidateSet,
2444 bool AllowObjCConversionOnExplicit);
2445 void AddSurrogateCandidate(CXXConversionDecl *Conversion,
2446 DeclAccessPair FoundDecl,
2447 CXXRecordDecl *ActingContext,
2448 const FunctionProtoType *Proto,
2449 Expr *Object, ArrayRef<Expr *> Args,
2450 OverloadCandidateSet& CandidateSet);
2451 void AddMemberOperatorCandidates(OverloadedOperatorKind Op,
2452 SourceLocation OpLoc, ArrayRef<Expr *> Args,
2453 OverloadCandidateSet& CandidateSet,
2454 SourceRange OpRange = SourceRange());
2455 void AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
2456 ArrayRef<Expr *> Args,
2457 OverloadCandidateSet& CandidateSet,
2458 bool IsAssignmentOperator = false,
2459 unsigned NumContextualBoolArguments = 0);
2460 void AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
2461 SourceLocation OpLoc, ArrayRef<Expr *> Args,
2462 OverloadCandidateSet& CandidateSet);
2463 void AddArgumentDependentLookupCandidates(DeclarationName Name,
2465 ArrayRef<Expr *> Args,
2466 TemplateArgumentListInfo *ExplicitTemplateArgs,
2467 OverloadCandidateSet& CandidateSet,
2468 bool PartialOverloading = false);
2470 // Emit as a 'note' the specific overload candidate
2471 void NoteOverloadCandidate(FunctionDecl *Fn, QualType DestType = QualType(),
2472 bool TakingAddress = false);
2474 // Emit as a series of 'note's all template and non-templates identified by
2475 // the expression Expr
2476 void NoteAllOverloadCandidates(Expr *E, QualType DestType = QualType(),
2477 bool TakingAddress = false);
2479 /// Check the enable_if expressions on the given function. Returns the first
2480 /// failing attribute, or NULL if they were all successful.
2481 EnableIfAttr *CheckEnableIf(FunctionDecl *Function, ArrayRef<Expr *> Args,
2482 bool MissingImplicitThis = false);
2484 /// Returns whether the given function's address can be taken or not,
2485 /// optionally emitting a diagnostic if the address can't be taken.
2487 /// Returns false if taking the address of the function is illegal.
2488 bool checkAddressOfFunctionIsAvailable(const FunctionDecl *Function,
2489 bool Complain = false,
2490 SourceLocation Loc = SourceLocation());
2492 // [PossiblyAFunctionType] --> [Return]
2493 // NonFunctionType --> NonFunctionType
2495 // R (*)(A) --> R (A)
2496 // R (&)(A) --> R (A)
2497 // R (S::*)(A) --> R (A)
2498 QualType ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType);
2501 ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
2502 QualType TargetType,
2504 DeclAccessPair &Found,
2505 bool *pHadMultipleCandidates = nullptr);
2508 ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
2509 bool Complain = false,
2510 DeclAccessPair *Found = nullptr);
2512 bool ResolveAndFixSingleFunctionTemplateSpecialization(
2513 ExprResult &SrcExpr,
2514 bool DoFunctionPointerConverion = false,
2515 bool Complain = false,
2516 SourceRange OpRangeForComplaining = SourceRange(),
2517 QualType DestTypeForComplaining = QualType(),
2518 unsigned DiagIDForComplaining = 0);
2521 Expr *FixOverloadedFunctionReference(Expr *E,
2522 DeclAccessPair FoundDecl,
2524 ExprResult FixOverloadedFunctionReference(ExprResult,
2525 DeclAccessPair FoundDecl,
2528 void AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
2529 ArrayRef<Expr *> Args,
2530 OverloadCandidateSet &CandidateSet,
2531 bool PartialOverloading = false);
2533 // An enum used to represent the different possible results of building a
2534 // range-based for loop.
2535 enum ForRangeStatus {
2537 FRS_NoViableFunction,
2538 FRS_DiagnosticIssued
2541 ForRangeStatus BuildForRangeBeginEndCall(SourceLocation Loc,
2542 SourceLocation RangeLoc,
2543 const DeclarationNameInfo &NameInfo,
2544 LookupResult &MemberLookup,
2545 OverloadCandidateSet *CandidateSet,
2546 Expr *Range, ExprResult *CallExpr);
2548 ExprResult BuildOverloadedCallExpr(Scope *S, Expr *Fn,
2549 UnresolvedLookupExpr *ULE,
2550 SourceLocation LParenLoc,
2552 SourceLocation RParenLoc,
2554 bool AllowTypoCorrection=true,
2555 bool CalleesAddressIsTaken=false);
2557 bool buildOverloadedCallSet(Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE,
2558 MultiExprArg Args, SourceLocation RParenLoc,
2559 OverloadCandidateSet *CandidateSet,
2560 ExprResult *Result);
2562 ExprResult CreateOverloadedUnaryOp(SourceLocation OpLoc,
2563 UnaryOperatorKind Opc,
2564 const UnresolvedSetImpl &Fns,
2567 ExprResult CreateOverloadedBinOp(SourceLocation OpLoc,
2568 BinaryOperatorKind Opc,
2569 const UnresolvedSetImpl &Fns,
2570 Expr *LHS, Expr *RHS);
2572 ExprResult CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
2573 SourceLocation RLoc,
2574 Expr *Base,Expr *Idx);
2577 BuildCallToMemberFunction(Scope *S, Expr *MemExpr,
2578 SourceLocation LParenLoc,
2580 SourceLocation RParenLoc);
2582 BuildCallToObjectOfClassType(Scope *S, Expr *Object, SourceLocation LParenLoc,
2584 SourceLocation RParenLoc);
2586 ExprResult BuildOverloadedArrowExpr(Scope *S, Expr *Base,
2587 SourceLocation OpLoc,
2588 bool *NoArrowOperatorFound = nullptr);
2590 /// CheckCallReturnType - Checks that a call expression's return type is
2591 /// complete. Returns true on failure. The location passed in is the location
2592 /// that best represents the call.
2593 bool CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
2594 CallExpr *CE, FunctionDecl *FD);
2596 /// Helpers for dealing with blocks and functions.
2597 bool CheckParmsForFunctionDef(ParmVarDecl *const *Param,
2598 ParmVarDecl *const *ParamEnd,
2599 bool CheckParameterNames);
2600 void CheckCXXDefaultArguments(FunctionDecl *FD);
2601 void CheckExtraCXXDefaultArguments(Declarator &D);
2602 Scope *getNonFieldDeclScope(Scope *S);
2604 /// \name Name lookup
2606 /// These routines provide name lookup that is used during semantic
2607 /// analysis to resolve the various kinds of names (identifiers,
2608 /// overloaded operator names, constructor names, etc.) into zero or
2609 /// more declarations within a particular scope. The major entry
2610 /// points are LookupName, which performs unqualified name lookup,
2611 /// and LookupQualifiedName, which performs qualified name lookup.
2613 /// All name lookup is performed based on some specific criteria,
2614 /// which specify what names will be visible to name lookup and how
2615 /// far name lookup should work. These criteria are important both
2616 /// for capturing language semantics (certain lookups will ignore
2617 /// certain names, for example) and for performance, since name
2618 /// lookup is often a bottleneck in the compilation of C++. Name
2619 /// lookup criteria is specified via the LookupCriteria enumeration.
2621 /// The results of name lookup can vary based on the kind of name
2622 /// lookup performed, the current language, and the translation
2623 /// unit. In C, for example, name lookup will either return nothing
2624 /// (no entity found) or a single declaration. In C++, name lookup
2625 /// can additionally refer to a set of overloaded functions or
2626 /// result in an ambiguity. All of the possible results of name
2627 /// lookup are captured by the LookupResult class, which provides
2628 /// the ability to distinguish among them.
2631 /// @brief Describes the kind of name lookup to perform.
2632 enum LookupNameKind {
2633 /// Ordinary name lookup, which finds ordinary names (functions,
2634 /// variables, typedefs, etc.) in C and most kinds of names
2635 /// (functions, variables, members, types, etc.) in C++.
2636 LookupOrdinaryName = 0,
2637 /// Tag name lookup, which finds the names of enums, classes,
2638 /// structs, and unions.
2640 /// Label name lookup.
2642 /// Member name lookup, which finds the names of
2643 /// class/struct/union members.
2645 /// Look up of an operator name (e.g., operator+) for use with
2646 /// operator overloading. This lookup is similar to ordinary name
2647 /// lookup, but will ignore any declarations that are class members.
2649 /// Look up of a name that precedes the '::' scope resolution
2650 /// operator in C++. This lookup completely ignores operator, object,
2651 /// function, and enumerator names (C++ [basic.lookup.qual]p1).
2652 LookupNestedNameSpecifierName,
2653 /// Look up a namespace name within a C++ using directive or
2654 /// namespace alias definition, ignoring non-namespace names (C++
2655 /// [basic.lookup.udir]p1).
2656 LookupNamespaceName,
2657 /// Look up all declarations in a scope with the given name,
2658 /// including resolved using declarations. This is appropriate
2659 /// for checking redeclarations for a using declaration.
2660 LookupUsingDeclName,
2661 /// Look up an ordinary name that is going to be redeclared as a
2662 /// name with linkage. This lookup ignores any declarations that
2663 /// are outside of the current scope unless they have linkage. See
2664 /// C99 6.2.2p4-5 and C++ [basic.link]p6.
2665 LookupRedeclarationWithLinkage,
2666 /// Look up a friend of a local class. This lookup does not look
2667 /// outside the innermost non-class scope. See C++11 [class.friend]p11.
2668 LookupLocalFriendName,
2669 /// Look up the name of an Objective-C protocol.
2670 LookupObjCProtocolName,
2671 /// Look up implicit 'self' parameter of an objective-c method.
2672 LookupObjCImplicitSelfParam,
2673 /// \brief Look up any declaration with any name.
2677 /// \brief Specifies whether (or how) name lookup is being performed for a
2678 /// redeclaration (vs. a reference).
2679 enum RedeclarationKind {
2680 /// \brief The lookup is a reference to this name that is not for the
2681 /// purpose of redeclaring the name.
2682 NotForRedeclaration = 0,
2683 /// \brief The lookup results will be used for redeclaration of a name,
2684 /// if an entity by that name already exists.
2688 /// \brief The possible outcomes of name lookup for a literal operator.
2689 enum LiteralOperatorLookupResult {
2690 /// \brief The lookup resulted in an error.
2692 /// \brief The lookup found a single 'cooked' literal operator, which
2693 /// expects a normal literal to be built and passed to it.
2695 /// \brief The lookup found a single 'raw' literal operator, which expects
2696 /// a string literal containing the spelling of the literal token.
2698 /// \brief The lookup found an overload set of literal operator templates,
2699 /// which expect the characters of the spelling of the literal token to be
2700 /// passed as a non-type template argument pack.
2702 /// \brief The lookup found an overload set of literal operator templates,
2703 /// which expect the character type and characters of the spelling of the
2704 /// string literal token to be passed as template arguments.
2708 SpecialMemberOverloadResult *LookupSpecialMember(CXXRecordDecl *D,
2709 CXXSpecialMember SM,
2716 typedef std::function<void(const TypoCorrection &)> TypoDiagnosticGenerator;
2717 typedef std::function<ExprResult(Sema &, TypoExpr *, TypoCorrection)>
2718 TypoRecoveryCallback;
2721 bool CppLookupName(LookupResult &R, Scope *S);
2723 struct TypoExprState {
2724 std::unique_ptr<TypoCorrectionConsumer> Consumer;
2725 TypoDiagnosticGenerator DiagHandler;
2726 TypoRecoveryCallback RecoveryHandler;
2728 TypoExprState(TypoExprState&& other) LLVM_NOEXCEPT;
2729 TypoExprState& operator=(TypoExprState&& other) LLVM_NOEXCEPT;
2732 /// \brief The set of unhandled TypoExprs and their associated state.
2733 llvm::MapVector<TypoExpr *, TypoExprState> DelayedTypos;
2735 /// \brief Creates a new TypoExpr AST node.
2736 TypoExpr *createDelayedTypo(std::unique_ptr<TypoCorrectionConsumer> TCC,
2737 TypoDiagnosticGenerator TDG,
2738 TypoRecoveryCallback TRC);
2740 // \brief The set of known/encountered (unique, canonicalized) NamespaceDecls.
2742 // The boolean value will be true to indicate that the namespace was loaded
2743 // from an AST/PCH file, or false otherwise.
2744 llvm::MapVector<NamespaceDecl*, bool> KnownNamespaces;
2746 /// \brief Whether we have already loaded known namespaces from an extenal
2748 bool LoadedExternalKnownNamespaces;
2750 /// \brief Helper for CorrectTypo and CorrectTypoDelayed used to create and
2751 /// populate a new TypoCorrectionConsumer. Returns nullptr if typo correction
2752 /// should be skipped entirely.
2753 std::unique_ptr<TypoCorrectionConsumer>
2754 makeTypoCorrectionConsumer(const DeclarationNameInfo &Typo,
2755 Sema::LookupNameKind LookupKind, Scope *S,
2757 std::unique_ptr<CorrectionCandidateCallback> CCC,
2758 DeclContext *MemberContext, bool EnteringContext,
2759 const ObjCObjectPointerType *OPT,
2760 bool ErrorRecovery);
2763 const TypoExprState &getTypoExprState(TypoExpr *TE) const;
2765 /// \brief Clears the state of the given TypoExpr.
2766 void clearDelayedTypo(TypoExpr *TE);
2768 /// \brief Look up a name, looking for a single declaration. Return
2769 /// null if the results were absent, ambiguous, or overloaded.
2771 /// It is preferable to use the elaborated form and explicitly handle
2772 /// ambiguity and overloaded.
2773 NamedDecl *LookupSingleName(Scope *S, DeclarationName Name,
2775 LookupNameKind NameKind,
2776 RedeclarationKind Redecl
2777 = NotForRedeclaration);
2778 bool LookupName(LookupResult &R, Scope *S,
2779 bool AllowBuiltinCreation = false);
2780 bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
2781 bool InUnqualifiedLookup = false);
2782 bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
2784 bool LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS,
2785 bool AllowBuiltinCreation = false,
2786 bool EnteringContext = false);
2787 ObjCProtocolDecl *LookupProtocol(IdentifierInfo *II, SourceLocation IdLoc,
2788 RedeclarationKind Redecl
2789 = NotForRedeclaration);
2790 bool LookupInSuper(LookupResult &R, CXXRecordDecl *Class);
2792 void LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S,
2793 QualType T1, QualType T2,
2794 UnresolvedSetImpl &Functions);
2795 void addOverloadedOperatorToUnresolvedSet(UnresolvedSetImpl &Functions,
2796 DeclAccessPair Operator,
2797 QualType T1, QualType T2);
2799 LabelDecl *LookupOrCreateLabel(IdentifierInfo *II, SourceLocation IdentLoc,
2800 SourceLocation GnuLabelLoc = SourceLocation());
2802 DeclContextLookupResult LookupConstructors(CXXRecordDecl *Class);
2803 CXXConstructorDecl *LookupDefaultConstructor(CXXRecordDecl *Class);
2804 CXXConstructorDecl *LookupCopyingConstructor(CXXRecordDecl *Class,
2806 CXXMethodDecl *LookupCopyingAssignment(CXXRecordDecl *Class, unsigned Quals,
2807 bool RValueThis, unsigned ThisQuals);
2808 CXXConstructorDecl *LookupMovingConstructor(CXXRecordDecl *Class,
2810 CXXMethodDecl *LookupMovingAssignment(CXXRecordDecl *Class, unsigned Quals,
2811 bool RValueThis, unsigned ThisQuals);
2812 CXXDestructorDecl *LookupDestructor(CXXRecordDecl *Class);
2814 bool checkLiteralOperatorId(const CXXScopeSpec &SS, const UnqualifiedId &Id);
2815 LiteralOperatorLookupResult LookupLiteralOperator(Scope *S, LookupResult &R,
2816 ArrayRef<QualType> ArgTys,
2819 bool AllowStringTemplate);
2820 bool isKnownName(StringRef name);
2822 void ArgumentDependentLookup(DeclarationName Name, SourceLocation Loc,
2823 ArrayRef<Expr *> Args, ADLResult &Functions);
2825 void LookupVisibleDecls(Scope *S, LookupNameKind Kind,
2826 VisibleDeclConsumer &Consumer,
2827 bool IncludeGlobalScope = true);
2828 void LookupVisibleDecls(DeclContext *Ctx, LookupNameKind Kind,
2829 VisibleDeclConsumer &Consumer,
2830 bool IncludeGlobalScope = true);
2832 enum CorrectTypoKind {
2833 CTK_NonError, // CorrectTypo used in a non error recovery situation.
2834 CTK_ErrorRecovery // CorrectTypo used in normal error recovery.
2837 TypoCorrection CorrectTypo(const DeclarationNameInfo &Typo,
2838 Sema::LookupNameKind LookupKind,
2839 Scope *S, CXXScopeSpec *SS,
2840 std::unique_ptr<CorrectionCandidateCallback> CCC,
2841 CorrectTypoKind Mode,
2842 DeclContext *MemberContext = nullptr,
2843 bool EnteringContext = false,
2844 const ObjCObjectPointerType *OPT = nullptr,
2845 bool RecordFailure = true);
2847 TypoExpr *CorrectTypoDelayed(const DeclarationNameInfo &Typo,
2848 Sema::LookupNameKind LookupKind, Scope *S,
2850 std::unique_ptr<CorrectionCandidateCallback> CCC,
2851 TypoDiagnosticGenerator TDG,
2852 TypoRecoveryCallback TRC, CorrectTypoKind Mode,
2853 DeclContext *MemberContext = nullptr,
2854 bool EnteringContext = false,
2855 const ObjCObjectPointerType *OPT = nullptr);
2857 /// \brief Process any TypoExprs in the given Expr and its children,
2858 /// generating diagnostics as appropriate and returning a new Expr if there
2859 /// were typos that were all successfully corrected and ExprError if one or
2860 /// more typos could not be corrected.
2862 /// \param E The Expr to check for TypoExprs.
2864 /// \param InitDecl A VarDecl to avoid because the Expr being corrected is its
2867 /// \param Filter A function applied to a newly rebuilt Expr to determine if
2868 /// it is an acceptable/usable result from a single combination of typo
2869 /// corrections. As long as the filter returns ExprError, different
2870 /// combinations of corrections will be tried until all are exhausted.
2872 CorrectDelayedTyposInExpr(Expr *E, VarDecl *InitDecl = nullptr,
2873 llvm::function_ref<ExprResult(Expr *)> Filter =
2874 [](Expr *E) -> ExprResult { return E; });
2877 CorrectDelayedTyposInExpr(Expr *E,
2878 llvm::function_ref<ExprResult(Expr *)> Filter) {
2879 return CorrectDelayedTyposInExpr(E, nullptr, Filter);
2883 CorrectDelayedTyposInExpr(ExprResult ER, VarDecl *InitDecl = nullptr,
2884 llvm::function_ref<ExprResult(Expr *)> Filter =
2885 [](Expr *E) -> ExprResult { return E; }) {
2886 return ER.isInvalid() ? ER : CorrectDelayedTyposInExpr(ER.get(), Filter);
2890 CorrectDelayedTyposInExpr(ExprResult ER,
2891 llvm::function_ref<ExprResult(Expr *)> Filter) {
2892 return CorrectDelayedTyposInExpr(ER, nullptr, Filter);
2895 void diagnoseTypo(const TypoCorrection &Correction,
2896 const PartialDiagnostic &TypoDiag,
2897 bool ErrorRecovery = true);
2899 void diagnoseTypo(const TypoCorrection &Correction,
2900 const PartialDiagnostic &TypoDiag,
2901 const PartialDiagnostic &PrevNote,
2902 bool ErrorRecovery = true);
2904 void FindAssociatedClassesAndNamespaces(SourceLocation InstantiationLoc,
2905 ArrayRef<Expr *> Args,
2906 AssociatedNamespaceSet &AssociatedNamespaces,
2907 AssociatedClassSet &AssociatedClasses);
2909 void FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S,
2910 bool ConsiderLinkage, bool AllowInlineNamespace);
2912 void DiagnoseAmbiguousLookup(LookupResult &Result);
2915 ObjCInterfaceDecl *getObjCInterfaceDecl(IdentifierInfo *&Id,
2916 SourceLocation IdLoc,
2917 bool TypoCorrection = false);
2918 NamedDecl *LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID,
2919 Scope *S, bool ForRedeclaration,
2920 SourceLocation Loc);
2921 NamedDecl *ImplicitlyDefineFunction(SourceLocation Loc, IdentifierInfo &II,
2923 void AddKnownFunctionAttributes(FunctionDecl *FD);
2925 // More parsing and symbol table subroutines.
2927 void ProcessPragmaWeak(Scope *S, Decl *D);
2928 // Decl attributes - this routine is the top level dispatcher.
2929 void ProcessDeclAttributes(Scope *S, Decl *D, const Declarator &PD);
2930 void ProcessDeclAttributeList(Scope *S, Decl *D, const AttributeList *AL,
2931 bool IncludeCXX11Attributes = true);
2932 bool ProcessAccessDeclAttributeList(AccessSpecDecl *ASDecl,
2933 const AttributeList *AttrList);
2935 void checkUnusedDeclAttributes(Declarator &D);
2937 /// Determine if type T is a valid subject for a nonnull and similar
2938 /// attributes. By default, we look through references (the behavior used by
2939 /// nonnull), but if the second parameter is true, then we treat a reference
2941 bool isValidPointerAttrType(QualType T, bool RefOkay = false);
2943 bool CheckRegparmAttr(const AttributeList &attr, unsigned &value);
2944 bool CheckCallingConvAttr(const AttributeList &attr, CallingConv &CC,
2945 const FunctionDecl *FD = nullptr);
2946 bool CheckNoReturnAttr(const AttributeList &attr);
2947 bool checkStringLiteralArgumentAttr(const AttributeList &Attr,
2948 unsigned ArgNum, StringRef &Str,
2949 SourceLocation *ArgLocation = nullptr);
2950 bool checkSectionName(SourceLocation LiteralLoc, StringRef Str);
2951 void checkTargetAttr(SourceLocation LiteralLoc, StringRef Str);
2952 bool checkMSInheritanceAttrOnDefinition(
2953 CXXRecordDecl *RD, SourceRange Range, bool BestCase,
2954 MSInheritanceAttr::Spelling SemanticSpelling);
2956 void CheckAlignasUnderalignment(Decl *D);
2958 /// Adjust the calling convention of a method to be the ABI default if it
2959 /// wasn't specified explicitly. This handles method types formed from
2960 /// function type typedefs and typename template arguments.
2961 void adjustMemberFunctionCC(QualType &T, bool IsStatic, bool IsCtorOrDtor,
2962 SourceLocation Loc);
2964 // Check if there is an explicit attribute, but only look through parens.
2965 // The intent is to look for an attribute on the current declarator, but not
2966 // one that came from a typedef.
2967 bool hasExplicitCallingConv(QualType &T);
2969 /// Get the outermost AttributedType node that sets a calling convention.
2970 /// Valid types should not have multiple attributes with different CCs.
2971 const AttributedType *getCallingConvAttributedType(QualType T) const;
2973 /// Check whether a nullability type specifier can be added to the given
2976 /// \param type The type to which the nullability specifier will be
2977 /// added. On success, this type will be updated appropriately.
2979 /// \param nullability The nullability specifier to add.
2981 /// \param nullabilityLoc The location of the nullability specifier.
2983 /// \param isContextSensitive Whether this nullability specifier was
2984 /// written as a context-sensitive keyword (in an Objective-C
2985 /// method) or an Objective-C property attribute, rather than as an
2986 /// underscored type specifier.
2988 /// \returns true if nullability cannot be applied, false otherwise.
2989 bool checkNullabilityTypeSpecifier(QualType &type, NullabilityKind nullability,
2990 SourceLocation nullabilityLoc,
2991 bool isContextSensitive);
2993 /// \brief Stmt attributes - this routine is the top level dispatcher.
2994 StmtResult ProcessStmtAttributes(Stmt *Stmt, AttributeList *Attrs,
2997 void WarnConflictingTypedMethods(ObjCMethodDecl *Method,
2998 ObjCMethodDecl *MethodDecl,
2999 bool IsProtocolMethodDecl);
3001 void CheckConflictingOverridingMethod(ObjCMethodDecl *Method,
3002 ObjCMethodDecl *Overridden,
3003 bool IsProtocolMethodDecl);
3005 /// WarnExactTypedMethods - This routine issues a warning if method
3006 /// implementation declaration matches exactly that of its declaration.
3007 void WarnExactTypedMethods(ObjCMethodDecl *Method,
3008 ObjCMethodDecl *MethodDecl,
3009 bool IsProtocolMethodDecl);
3011 typedef llvm::SmallPtrSet<Selector, 8> SelectorSet;
3012 typedef llvm::DenseMap<Selector, ObjCMethodDecl*> ProtocolsMethodsMap;
3014 /// CheckImplementationIvars - This routine checks if the instance variables
3015 /// listed in the implelementation match those listed in the interface.
3016 void CheckImplementationIvars(ObjCImplementationDecl *ImpDecl,
3017 ObjCIvarDecl **Fields, unsigned nIvars,
3018 SourceLocation Loc);
3020 /// ImplMethodsVsClassMethods - This is main routine to warn if any method
3021 /// remains unimplemented in the class or category \@implementation.
3022 void ImplMethodsVsClassMethods(Scope *S, ObjCImplDecl* IMPDecl,
3023 ObjCContainerDecl* IDecl,
3024 bool IncompleteImpl = false);
3026 /// DiagnoseUnimplementedProperties - This routine warns on those properties
3027 /// which must be implemented by this implementation.
3028 void DiagnoseUnimplementedProperties(Scope *S, ObjCImplDecl* IMPDecl,
3029 ObjCContainerDecl *CDecl,
3030 bool SynthesizeProperties);
3032 /// Diagnose any null-resettable synthesized setters.
3033 void diagnoseNullResettableSynthesizedSetters(const ObjCImplDecl *impDecl);
3035 /// DefaultSynthesizeProperties - This routine default synthesizes all
3036 /// properties which must be synthesized in the class's \@implementation.
3037 void DefaultSynthesizeProperties (Scope *S, ObjCImplDecl* IMPDecl,
3038 ObjCInterfaceDecl *IDecl);
3039 void DefaultSynthesizeProperties(Scope *S, Decl *D);
3041 /// IvarBacksCurrentMethodAccessor - This routine returns 'true' if 'IV' is
3042 /// an ivar synthesized for 'Method' and 'Method' is a property accessor
3043 /// declared in class 'IFace'.
3044 bool IvarBacksCurrentMethodAccessor(ObjCInterfaceDecl *IFace,
3045 ObjCMethodDecl *Method, ObjCIvarDecl *IV);
3047 /// DiagnoseUnusedBackingIvarInAccessor - Issue an 'unused' warning if ivar which
3048 /// backs the property is not used in the property's accessor.
3049 void DiagnoseUnusedBackingIvarInAccessor(Scope *S,
3050 const ObjCImplementationDecl *ImplD);
3052 /// GetIvarBackingPropertyAccessor - If method is a property setter/getter and
3053 /// it property has a backing ivar, returns this ivar; otherwise, returns NULL.
3054 /// It also returns ivar's property on success.
3055 ObjCIvarDecl *GetIvarBackingPropertyAccessor(const ObjCMethodDecl *Method,
3056 const ObjCPropertyDecl *&PDecl) const;
3058 /// Called by ActOnProperty to handle \@property declarations in
3059 /// class extensions.
3060 ObjCPropertyDecl *HandlePropertyInClassExtension(Scope *S,
3061 SourceLocation AtLoc,
3062 SourceLocation LParenLoc,
3063 FieldDeclarator &FD,
3066 const bool isReadWrite,
3067 unsigned &Attributes,
3068 const unsigned AttributesAsWritten,
3070 TypeSourceInfo *TSI,
3071 tok::ObjCKeywordKind MethodImplKind);
3073 /// Called by ActOnProperty and HandlePropertyInClassExtension to
3074 /// handle creating the ObjcPropertyDecl for a category or \@interface.
3075 ObjCPropertyDecl *CreatePropertyDecl(Scope *S,
3076 ObjCContainerDecl *CDecl,
3077 SourceLocation AtLoc,
3078 SourceLocation LParenLoc,
3079 FieldDeclarator &FD,
3082 const bool isReadWrite,
3083 const unsigned Attributes,
3084 const unsigned AttributesAsWritten,
3086 TypeSourceInfo *TSI,
3087 tok::ObjCKeywordKind MethodImplKind,
3088 DeclContext *lexicalDC = nullptr);
3090 /// AtomicPropertySetterGetterRules - This routine enforces the rule (via
3091 /// warning) when atomic property has one but not the other user-declared
3092 /// setter or getter.
3093 void AtomicPropertySetterGetterRules(ObjCImplDecl* IMPDecl,
3094 ObjCInterfaceDecl* IDecl);
3096 void DiagnoseOwningPropertyGetterSynthesis(const ObjCImplementationDecl *D);
3098 void DiagnoseMissingDesignatedInitOverrides(
3099 const ObjCImplementationDecl *ImplD,
3100 const ObjCInterfaceDecl *IFD);
3102 void DiagnoseDuplicateIvars(ObjCInterfaceDecl *ID, ObjCInterfaceDecl *SID);
3104 enum MethodMatchStrategy {
3109 /// MatchTwoMethodDeclarations - Checks if two methods' type match and returns
3110 /// true, or false, accordingly.
3111 bool MatchTwoMethodDeclarations(const ObjCMethodDecl *Method,
3112 const ObjCMethodDecl *PrevMethod,
3113 MethodMatchStrategy strategy = MMS_strict);
3115 /// MatchAllMethodDeclarations - Check methods declaraed in interface or
3116 /// or protocol against those declared in their implementations.
3117 void MatchAllMethodDeclarations(const SelectorSet &InsMap,
3118 const SelectorSet &ClsMap,
3119 SelectorSet &InsMapSeen,
3120 SelectorSet &ClsMapSeen,
3121 ObjCImplDecl* IMPDecl,
3122 ObjCContainerDecl* IDecl,
3123 bool &IncompleteImpl,
3124 bool ImmediateClass,
3125 bool WarnCategoryMethodImpl=false);
3127 /// CheckCategoryVsClassMethodMatches - Checks that methods implemented in
3128 /// category matches with those implemented in its primary class and
3129 /// warns each time an exact match is found.
3130 void CheckCategoryVsClassMethodMatches(ObjCCategoryImplDecl *CatIMP);
3132 /// \brief Add the given method to the list of globally-known methods.
3133 void addMethodToGlobalList(ObjCMethodList *List, ObjCMethodDecl *Method);
3136 /// AddMethodToGlobalPool - Add an instance or factory method to the global
3137 /// pool. See descriptoin of AddInstanceMethodToGlobalPool.
3138 void AddMethodToGlobalPool(ObjCMethodDecl *Method, bool impl, bool instance);
3140 /// LookupMethodInGlobalPool - Returns the instance or factory method and
3141 /// optionally warns if there are multiple signatures.
3142 ObjCMethodDecl *LookupMethodInGlobalPool(Selector Sel, SourceRange R,
3143 bool receiverIdOrClass,
3147 /// \brief - Returns instance or factory methods in global method pool for
3148 /// given selector. If no such method or only one method found, function returns
3149 /// false; otherwise, it returns true
3150 bool CollectMultipleMethodsInGlobalPool(Selector Sel,
3151 SmallVectorImpl<ObjCMethodDecl*>& Methods,
3154 bool AreMultipleMethodsInGlobalPool(Selector Sel, ObjCMethodDecl *BestMethod,
3156 bool receiverIdOrClass);
3158 void DiagnoseMultipleMethodInGlobalPool(SmallVectorImpl<ObjCMethodDecl*> &Methods,
3159 Selector Sel, SourceRange R,
3160 bool receiverIdOrClass);
3163 /// \brief - Returns a selector which best matches given argument list or
3164 /// nullptr if none could be found
3165 ObjCMethodDecl *SelectBestMethod(Selector Sel, MultiExprArg Args,
3169 /// \brief Record the typo correction failure and return an empty correction.
3170 TypoCorrection FailedCorrection(IdentifierInfo *Typo, SourceLocation TypoLoc,
3171 bool RecordFailure = true) {
3173 TypoCorrectionFailures[Typo].insert(TypoLoc);
3174 return TypoCorrection();
3178 /// AddInstanceMethodToGlobalPool - All instance methods in a translation
3179 /// unit are added to a global pool. This allows us to efficiently associate
3180 /// a selector with a method declaraation for purposes of typechecking
3181 /// messages sent to "id" (where the class of the object is unknown).
3182 void AddInstanceMethodToGlobalPool(ObjCMethodDecl *Method, bool impl=false) {
3183 AddMethodToGlobalPool(Method, impl, /*instance*/true);
3186 /// AddFactoryMethodToGlobalPool - Same as above, but for factory methods.
3187 void AddFactoryMethodToGlobalPool(ObjCMethodDecl *Method, bool impl=false) {
3188 AddMethodToGlobalPool(Method, impl, /*instance*/false);
3191 /// AddAnyMethodToGlobalPool - Add any method, instance or factory to global
3193 void AddAnyMethodToGlobalPool(Decl *D);
3195 /// LookupInstanceMethodInGlobalPool - Returns the method and warns if
3196 /// there are multiple signatures.
3197 ObjCMethodDecl *LookupInstanceMethodInGlobalPool(Selector Sel, SourceRange R,
3198 bool receiverIdOrClass=false) {
3199 return LookupMethodInGlobalPool(Sel, R, receiverIdOrClass,
3203 /// LookupFactoryMethodInGlobalPool - Returns the method and warns if
3204 /// there are multiple signatures.
3205 ObjCMethodDecl *LookupFactoryMethodInGlobalPool(Selector Sel, SourceRange R,
3206 bool receiverIdOrClass=false) {
3207 return LookupMethodInGlobalPool(Sel, R, receiverIdOrClass,
3211 const ObjCMethodDecl *SelectorsForTypoCorrection(Selector Sel,
3212 QualType ObjectType=QualType());
3213 /// LookupImplementedMethodInGlobalPool - Returns the method which has an
3215 ObjCMethodDecl *LookupImplementedMethodInGlobalPool(Selector Sel);
3217 /// CollectIvarsToConstructOrDestruct - Collect those ivars which require
3219 void CollectIvarsToConstructOrDestruct(ObjCInterfaceDecl *OI,
3220 SmallVectorImpl<ObjCIvarDecl*> &Ivars);
3222 //===--------------------------------------------------------------------===//
3223 // Statement Parsing Callbacks: SemaStmt.cpp.
3227 FullExprArg(Sema &actions) : E(nullptr) { }
3229 ExprResult release() {
3233 Expr *get() const { return E; }
3235 Expr *operator->() {
3240 // FIXME: No need to make the entire Sema class a friend when it's just
3241 // Sema::MakeFullExpr that needs access to the constructor below.
3244 explicit FullExprArg(Expr *expr) : E(expr) {}
3249 FullExprArg MakeFullExpr(Expr *Arg) {
3250 return MakeFullExpr(Arg, Arg ? Arg->getExprLoc() : SourceLocation());
3252 FullExprArg MakeFullExpr(Expr *Arg, SourceLocation CC) {
3253 return FullExprArg(ActOnFinishFullExpr(Arg, CC).get());
3255 FullExprArg MakeFullDiscardedValueExpr(Expr *Arg) {
3257 ActOnFinishFullExpr(Arg, Arg ? Arg->getExprLoc() : SourceLocation(),
3258 /*DiscardedValue*/ true);
3259 return FullExprArg(FE.get());
3262 StmtResult ActOnExprStmt(ExprResult Arg);
3263 StmtResult ActOnExprStmtError();
3265 StmtResult ActOnNullStmt(SourceLocation SemiLoc,
3266 bool HasLeadingEmptyMacro = false);
3268 void ActOnStartOfCompoundStmt();
3269 void ActOnFinishOfCompoundStmt();
3270 StmtResult ActOnCompoundStmt(SourceLocation L, SourceLocation R,
3271 ArrayRef<Stmt *> Elts, bool isStmtExpr);
3273 /// \brief A RAII object to enter scope of a compound statement.
3274 class CompoundScopeRAII {
3276 CompoundScopeRAII(Sema &S): S(S) {
3277 S.ActOnStartOfCompoundStmt();
3280 ~CompoundScopeRAII() {
3281 S.ActOnFinishOfCompoundStmt();
3288 /// An RAII helper that pops function a function scope on exit.
3289 struct FunctionScopeRAII {
3292 FunctionScopeRAII(Sema &S) : S(S), Active(true) {}
3293 ~FunctionScopeRAII() {
3295 S.PopFunctionScopeInfo();
3297 void disable() { Active = false; }
3300 StmtResult ActOnDeclStmt(DeclGroupPtrTy Decl,
3301 SourceLocation StartLoc,
3302 SourceLocation EndLoc);
3303 void ActOnForEachDeclStmt(DeclGroupPtrTy Decl);
3304 StmtResult ActOnForEachLValueExpr(Expr *E);
3305 StmtResult ActOnCaseStmt(SourceLocation CaseLoc, Expr *LHSVal,
3306 SourceLocation DotDotDotLoc, Expr *RHSVal,
3307 SourceLocation ColonLoc);
3308 void ActOnCaseStmtBody(Stmt *CaseStmt, Stmt *SubStmt);
3310 StmtResult ActOnDefaultStmt(SourceLocation DefaultLoc,
3311 SourceLocation ColonLoc,
3312 Stmt *SubStmt, Scope *CurScope);
3313 StmtResult ActOnLabelStmt(SourceLocation IdentLoc, LabelDecl *TheDecl,
3314 SourceLocation ColonLoc, Stmt *SubStmt);
3316 StmtResult ActOnAttributedStmt(SourceLocation AttrLoc,
3317 ArrayRef<const Attr*> Attrs,
3320 StmtResult ActOnIfStmt(SourceLocation IfLoc,
3321 FullExprArg CondVal, Decl *CondVar,
3323 SourceLocation ElseLoc, Stmt *ElseVal);
3324 StmtResult ActOnStartOfSwitchStmt(SourceLocation SwitchLoc,
3327 StmtResult ActOnFinishSwitchStmt(SourceLocation SwitchLoc,
3328 Stmt *Switch, Stmt *Body);
3329 StmtResult ActOnWhileStmt(SourceLocation WhileLoc,
3331 Decl *CondVar, Stmt *Body);
3332 StmtResult ActOnDoStmt(SourceLocation DoLoc, Stmt *Body,
3333 SourceLocation WhileLoc,
3334 SourceLocation CondLParen, Expr *Cond,
3335 SourceLocation CondRParen);
3337 StmtResult ActOnForStmt(SourceLocation ForLoc,
3338 SourceLocation LParenLoc,
3339 Stmt *First, FullExprArg Second,
3342 SourceLocation RParenLoc,
3344 ExprResult CheckObjCForCollectionOperand(SourceLocation forLoc,
3346 StmtResult ActOnObjCForCollectionStmt(SourceLocation ForColLoc,
3347 Stmt *First, Expr *collection,
3348 SourceLocation RParenLoc);
3349 StmtResult FinishObjCForCollectionStmt(Stmt *ForCollection, Stmt *Body);
3351 enum BuildForRangeKind {
3352 /// Initial building of a for-range statement.
3354 /// Instantiation or recovery rebuild of a for-range statement. Don't
3355 /// attempt any typo-correction.
3357 /// Determining whether a for-range statement could be built. Avoid any
3358 /// unnecessary or irreversible actions.
3362 StmtResult ActOnCXXForRangeStmt(Scope *S, SourceLocation ForLoc,
3363 SourceLocation CoawaitLoc,
3365 SourceLocation ColonLoc, Expr *Collection,
3366 SourceLocation RParenLoc,
3367 BuildForRangeKind Kind);
3368 StmtResult BuildCXXForRangeStmt(SourceLocation ForLoc,
3369 SourceLocation CoawaitLoc,
3370 SourceLocation ColonLoc,
3371 Stmt *RangeDecl, Stmt *BeginEndDecl,
3372 Expr *Cond, Expr *Inc,
3374 SourceLocation RParenLoc,
3375 BuildForRangeKind Kind);
3376 StmtResult FinishCXXForRangeStmt(Stmt *ForRange, Stmt *Body);
3378 StmtResult ActOnGotoStmt(SourceLocation GotoLoc,
3379 SourceLocation LabelLoc,
3380 LabelDecl *TheDecl);
3381 StmtResult ActOnIndirectGotoStmt(SourceLocation GotoLoc,
3382 SourceLocation StarLoc,
3384 StmtResult ActOnContinueStmt(SourceLocation ContinueLoc, Scope *CurScope);
3385 StmtResult ActOnBreakStmt(SourceLocation BreakLoc, Scope *CurScope);
3387 void ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope,
3388 CapturedRegionKind Kind, unsigned NumParams);
3389 typedef std::pair<StringRef, QualType> CapturedParamNameType;
3390 void ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope,
3391 CapturedRegionKind Kind,
3392 ArrayRef<CapturedParamNameType> Params);
3393 StmtResult ActOnCapturedRegionEnd(Stmt *S);
3394 void ActOnCapturedRegionError();
3395 RecordDecl *CreateCapturedStmtRecordDecl(CapturedDecl *&CD,
3397 unsigned NumParams);
3398 VarDecl *getCopyElisionCandidate(QualType ReturnType, Expr *E,
3399 bool AllowFunctionParameters);
3400 bool isCopyElisionCandidate(QualType ReturnType, const VarDecl *VD,
3401 bool AllowFunctionParameters);
3403 StmtResult ActOnReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp,
3405 StmtResult BuildReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp);
3406 StmtResult ActOnCapScopeReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp);
3408 StmtResult ActOnGCCAsmStmt(SourceLocation AsmLoc, bool IsSimple,
3409 bool IsVolatile, unsigned NumOutputs,
3410 unsigned NumInputs, IdentifierInfo **Names,
3411 MultiExprArg Constraints, MultiExprArg Exprs,
3412 Expr *AsmString, MultiExprArg Clobbers,
3413 SourceLocation RParenLoc);
3415 ExprResult LookupInlineAsmIdentifier(CXXScopeSpec &SS,
3416 SourceLocation TemplateKWLoc,
3418 llvm::InlineAsmIdentifierInfo &Info,
3419 bool IsUnevaluatedContext);
3420 bool LookupInlineAsmField(StringRef Base, StringRef Member,
3421 unsigned &Offset, SourceLocation AsmLoc);
3422 ExprResult LookupInlineAsmVarDeclField(Expr *RefExpr, StringRef Member,
3423 llvm::InlineAsmIdentifierInfo &Info,
3424 SourceLocation AsmLoc);
3425 StmtResult ActOnMSAsmStmt(SourceLocation AsmLoc, SourceLocation LBraceLoc,
3426 ArrayRef<Token> AsmToks,
3427 StringRef AsmString,
3428 unsigned NumOutputs, unsigned NumInputs,
3429 ArrayRef<StringRef> Constraints,
3430 ArrayRef<StringRef> Clobbers,
3431 ArrayRef<Expr*> Exprs,
3432 SourceLocation EndLoc);
3433 LabelDecl *GetOrCreateMSAsmLabel(StringRef ExternalLabelName,
3434 SourceLocation Location,
3437 VarDecl *BuildObjCExceptionDecl(TypeSourceInfo *TInfo, QualType ExceptionType,
3438 SourceLocation StartLoc,
3439 SourceLocation IdLoc, IdentifierInfo *Id,
3440 bool Invalid = false);
3442 Decl *ActOnObjCExceptionDecl(Scope *S, Declarator &D);
3444 StmtResult ActOnObjCAtCatchStmt(SourceLocation AtLoc, SourceLocation RParen,
3445 Decl *Parm, Stmt *Body);
3447 StmtResult ActOnObjCAtFinallyStmt(SourceLocation AtLoc, Stmt *Body);
3449 StmtResult ActOnObjCAtTryStmt(SourceLocation AtLoc, Stmt *Try,
3450 MultiStmtArg Catch, Stmt *Finally);
3452 StmtResult BuildObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw);
3453 StmtResult ActOnObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw,
3455 ExprResult ActOnObjCAtSynchronizedOperand(SourceLocation atLoc,
3457 StmtResult ActOnObjCAtSynchronizedStmt(SourceLocation AtLoc,
3461 StmtResult ActOnObjCAutoreleasePoolStmt(SourceLocation AtLoc, Stmt *Body);
3463 VarDecl *BuildExceptionDeclaration(Scope *S, TypeSourceInfo *TInfo,
3464 SourceLocation StartLoc,
3465 SourceLocation IdLoc,
3466 IdentifierInfo *Id);
3468 Decl *ActOnExceptionDeclarator(Scope *S, Declarator &D);
3470 StmtResult ActOnCXXCatchBlock(SourceLocation CatchLoc,
3471 Decl *ExDecl, Stmt *HandlerBlock);
3472 StmtResult ActOnCXXTryBlock(SourceLocation TryLoc, Stmt *TryBlock,
3473 ArrayRef<Stmt *> Handlers);
3475 StmtResult ActOnSEHTryBlock(bool IsCXXTry, // try (true) or __try (false) ?
3476 SourceLocation TryLoc, Stmt *TryBlock,
3478 StmtResult ActOnSEHExceptBlock(SourceLocation Loc,
3481 void ActOnStartSEHFinallyBlock();
3482 void ActOnAbortSEHFinallyBlock();
3483 StmtResult ActOnFinishSEHFinallyBlock(SourceLocation Loc, Stmt *Block);
3484 StmtResult ActOnSEHLeaveStmt(SourceLocation Loc, Scope *CurScope);
3486 void DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock);
3488 bool ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const;
3490 /// \brief If it's a file scoped decl that must warn if not used, keep track
3492 void MarkUnusedFileScopedDecl(const DeclaratorDecl *D);
3494 /// DiagnoseUnusedExprResult - If the statement passed in is an expression
3495 /// whose result is unused, warn.
3496 void DiagnoseUnusedExprResult(const Stmt *S);
3497 void DiagnoseUnusedNestedTypedefs(const RecordDecl *D);
3498 void DiagnoseUnusedDecl(const NamedDecl *ND);
3500 /// Emit \p DiagID if statement located on \p StmtLoc has a suspicious null
3501 /// statement as a \p Body, and it is located on the same line.
3503 /// This helps prevent bugs due to typos, such as:
3506 void DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
3510 /// Warn if a for/while loop statement \p S, which is followed by
3511 /// \p PossibleBody, has a suspicious null statement as a body.
3512 void DiagnoseEmptyLoopBody(const Stmt *S,
3513 const Stmt *PossibleBody);
3515 /// Warn if a value is moved to itself.
3516 void DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
3517 SourceLocation OpLoc);
3519 /// \brief Warn if we're implicitly casting from a _Nullable pointer type to a
3521 void diagnoseNullableToNonnullConversion(QualType DstType, QualType SrcType,
3522 SourceLocation Loc);
3524 ParsingDeclState PushParsingDeclaration(sema::DelayedDiagnosticPool &pool) {
3525 return DelayedDiagnostics.push(pool);
3527 void PopParsingDeclaration(ParsingDeclState state, Decl *decl);
3529 typedef ProcessingContextState ParsingClassState;
3530 ParsingClassState PushParsingClass() {
3531 return DelayedDiagnostics.pushUndelayed();
3533 void PopParsingClass(ParsingClassState state) {
3534 DelayedDiagnostics.popUndelayed(state);
3537 void redelayDiagnostics(sema::DelayedDiagnosticPool &pool);
3539 enum AvailabilityDiagnostic { AD_Deprecation, AD_Unavailable, AD_Partial };
3541 void EmitAvailabilityWarning(AvailabilityDiagnostic AD,
3542 NamedDecl *D, StringRef Message,
3544 const ObjCInterfaceDecl *UnknownObjCClass,
3545 const ObjCPropertyDecl *ObjCProperty,
3546 bool ObjCPropertyAccess);
3548 bool makeUnavailableInSystemHeader(SourceLocation loc,
3549 UnavailableAttr::ImplicitReason reason);
3551 //===--------------------------------------------------------------------===//
3552 // Expression Parsing Callbacks: SemaExpr.cpp.
3554 bool CanUseDecl(NamedDecl *D);
3555 bool DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc,
3556 const ObjCInterfaceDecl *UnknownObjCClass=nullptr,
3557 bool ObjCPropertyAccess=false);
3558 void NoteDeletedFunction(FunctionDecl *FD);
3559 std::string getDeletedOrUnavailableSuffix(const FunctionDecl *FD);
3560 bool DiagnosePropertyAccessorMismatch(ObjCPropertyDecl *PD,
3561 ObjCMethodDecl *Getter,
3562 SourceLocation Loc);
3563 void DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
3564 ArrayRef<Expr *> Args);
3566 void PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
3567 Decl *LambdaContextDecl = nullptr,
3568 bool IsDecltype = false);
3569 enum ReuseLambdaContextDecl_t { ReuseLambdaContextDecl };
3570 void PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
3571 ReuseLambdaContextDecl_t,
3572 bool IsDecltype = false);
3573 void PopExpressionEvaluationContext();
3575 void DiscardCleanupsInEvaluationContext();
3577 ExprResult TransformToPotentiallyEvaluated(Expr *E);
3578 ExprResult HandleExprEvaluationContextForTypeof(Expr *E);
3580 ExprResult ActOnConstantExpression(ExprResult Res);
3582 // Functions for marking a declaration referenced. These functions also
3583 // contain the relevant logic for marking if a reference to a function or
3584 // variable is an odr-use (in the C++11 sense). There are separate variants
3585 // for expressions referring to a decl; these exist because odr-use marking
3586 // needs to be delayed for some constant variables when we build one of the
3587 // named expressions.
3588 void MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, bool OdrUse);
3589 void MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func,
3590 bool OdrUse = true);
3591 void MarkVariableReferenced(SourceLocation Loc, VarDecl *Var);
3592 void MarkDeclRefReferenced(DeclRefExpr *E);
3593 void MarkMemberReferenced(MemberExpr *E);
3595 void UpdateMarkingForLValueToRValue(Expr *E);
3596 void CleanupVarDeclMarking();
3598 enum TryCaptureKind {
3599 TryCapture_Implicit, TryCapture_ExplicitByVal, TryCapture_ExplicitByRef
3602 /// \brief Try to capture the given variable.
3604 /// \param Var The variable to capture.
3606 /// \param Loc The location at which the capture occurs.
3608 /// \param Kind The kind of capture, which may be implicit (for either a
3609 /// block or a lambda), or explicit by-value or by-reference (for a lambda).
3611 /// \param EllipsisLoc The location of the ellipsis, if one is provided in
3612 /// an explicit lambda capture.
3614 /// \param BuildAndDiagnose Whether we are actually supposed to add the
3615 /// captures or diagnose errors. If false, this routine merely check whether
3616 /// the capture can occur without performing the capture itself or complaining
3617 /// if the variable cannot be captured.
3619 /// \param CaptureType Will be set to the type of the field used to capture
3620 /// this variable in the innermost block or lambda. Only valid when the
3621 /// variable can be captured.
3623 /// \param DeclRefType Will be set to the type of a reference to the capture
3624 /// from within the current scope. Only valid when the variable can be
3627 /// \param FunctionScopeIndexToStopAt If non-null, it points to the index
3628 /// of the FunctionScopeInfo stack beyond which we do not attempt to capture.
3629 /// This is useful when enclosing lambdas must speculatively capture
3630 /// variables that may or may not be used in certain specializations of
3631 /// a nested generic lambda.
3633 /// \returns true if an error occurred (i.e., the variable cannot be
3634 /// captured) and false if the capture succeeded.
3635 bool tryCaptureVariable(VarDecl *Var, SourceLocation Loc, TryCaptureKind Kind,
3636 SourceLocation EllipsisLoc, bool BuildAndDiagnose,
3637 QualType &CaptureType,
3638 QualType &DeclRefType,
3639 const unsigned *const FunctionScopeIndexToStopAt);
3641 /// \brief Try to capture the given variable.
3642 bool tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
3643 TryCaptureKind Kind = TryCapture_Implicit,
3644 SourceLocation EllipsisLoc = SourceLocation());
3646 /// \brief Checks if the variable must be captured.
3647 bool NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc);
3649 /// \brief Given a variable, determine the type that a reference to that
3650 /// variable will have in the given scope.
3651 QualType getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc);
3653 void MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T);
3654 void MarkDeclarationsReferencedInExpr(Expr *E,
3655 bool SkipLocalVariables = false);
3657 /// \brief Try to recover by turning the given expression into a
3658 /// call. Returns true if recovery was attempted or an error was
3659 /// emitted; this may also leave the ExprResult invalid.
3660 bool tryToRecoverWithCall(ExprResult &E, const PartialDiagnostic &PD,
3661 bool ForceComplain = false,
3662 bool (*IsPlausibleResult)(QualType) = nullptr);
3664 /// \brief Figure out if an expression could be turned into a call.
3665 bool tryExprAsCall(Expr &E, QualType &ZeroArgCallReturnTy,
3666 UnresolvedSetImpl &NonTemplateOverloads);
3668 /// \brief Conditionally issue a diagnostic based on the current
3669 /// evaluation context.
3671 /// \param Statement If Statement is non-null, delay reporting the
3672 /// diagnostic until the function body is parsed, and then do a basic
3673 /// reachability analysis to determine if the statement is reachable.
3674 /// If it is unreachable, the diagnostic will not be emitted.
3675 bool DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
3676 const PartialDiagnostic &PD);
3678 // Primary Expressions.
3679 SourceRange getExprRange(Expr *E) const;
3681 ExprResult ActOnIdExpression(
3682 Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
3683 UnqualifiedId &Id, bool HasTrailingLParen, bool IsAddressOfOperand,
3684 std::unique_ptr<CorrectionCandidateCallback> CCC = nullptr,
3685 bool IsInlineAsmIdentifier = false, Token *KeywordReplacement = nullptr);
3687 void DecomposeUnqualifiedId(const UnqualifiedId &Id,
3688 TemplateArgumentListInfo &Buffer,
3689 DeclarationNameInfo &NameInfo,
3690 const TemplateArgumentListInfo *&TemplateArgs);
3693 DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
3694 std::unique_ptr<CorrectionCandidateCallback> CCC,
3695 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr,
3696 ArrayRef<Expr *> Args = None, TypoExpr **Out = nullptr);
3698 ExprResult LookupInObjCMethod(LookupResult &LookUp, Scope *S,
3700 bool AllowBuiltinCreation=false);
3702 ExprResult ActOnDependentIdExpression(const CXXScopeSpec &SS,
3703 SourceLocation TemplateKWLoc,
3704 const DeclarationNameInfo &NameInfo,
3705 bool isAddressOfOperand,
3706 const TemplateArgumentListInfo *TemplateArgs);
3708 ExprResult BuildDeclRefExpr(ValueDecl *D, QualType Ty,
3711 const CXXScopeSpec *SS = nullptr);
3713 BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
3714 const DeclarationNameInfo &NameInfo,
3715 const CXXScopeSpec *SS = nullptr,
3716 NamedDecl *FoundD = nullptr,
3717 const TemplateArgumentListInfo *TemplateArgs = nullptr);
3719 BuildAnonymousStructUnionMemberReference(
3720 const CXXScopeSpec &SS,
3721 SourceLocation nameLoc,
3722 IndirectFieldDecl *indirectField,
3723 DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_none),
3724 Expr *baseObjectExpr = nullptr,
3725 SourceLocation opLoc = SourceLocation());
3727 ExprResult BuildPossibleImplicitMemberExpr(const CXXScopeSpec &SS,
3728 SourceLocation TemplateKWLoc,
3730 const TemplateArgumentListInfo *TemplateArgs,
3732 ExprResult BuildImplicitMemberExpr(const CXXScopeSpec &SS,
3733 SourceLocation TemplateKWLoc,
3735 const TemplateArgumentListInfo *TemplateArgs,
3736 bool IsDefiniteInstance,
3738 bool UseArgumentDependentLookup(const CXXScopeSpec &SS,
3739 const LookupResult &R,
3740 bool HasTrailingLParen);
3743 BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS,
3744 const DeclarationNameInfo &NameInfo,
3745 bool IsAddressOfOperand, const Scope *S,
3746 TypeSourceInfo **RecoveryTSI = nullptr);
3748 ExprResult BuildDependentDeclRefExpr(const CXXScopeSpec &SS,
3749 SourceLocation TemplateKWLoc,
3750 const DeclarationNameInfo &NameInfo,
3751 const TemplateArgumentListInfo *TemplateArgs);
3753 ExprResult BuildDeclarationNameExpr(const CXXScopeSpec &SS,
3756 bool AcceptInvalidDecl = false);
3757 ExprResult BuildDeclarationNameExpr(
3758 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
3759 NamedDecl *FoundD = nullptr,
3760 const TemplateArgumentListInfo *TemplateArgs = nullptr,
3761 bool AcceptInvalidDecl = false);
3763 ExprResult BuildLiteralOperatorCall(LookupResult &R,
3764 DeclarationNameInfo &SuffixInfo,
3765 ArrayRef<Expr *> Args,
3766 SourceLocation LitEndLoc,
3767 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr);
3769 ExprResult BuildPredefinedExpr(SourceLocation Loc,
3770 PredefinedExpr::IdentType IT);
3771 ExprResult ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind);
3772 ExprResult ActOnIntegerConstant(SourceLocation Loc, uint64_t Val);
3774 bool CheckLoopHintExpr(Expr *E, SourceLocation Loc);
3776 ExprResult ActOnNumericConstant(const Token &Tok, Scope *UDLScope = nullptr);
3777 ExprResult ActOnCharacterConstant(const Token &Tok,
3778 Scope *UDLScope = nullptr);
3779 ExprResult ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E);
3780 ExprResult ActOnParenListExpr(SourceLocation L,
3784 /// ActOnStringLiteral - The specified tokens were lexed as pasted string
3785 /// fragments (e.g. "foo" "bar" L"baz").
3786 ExprResult ActOnStringLiteral(ArrayRef<Token> StringToks,
3787 Scope *UDLScope = nullptr);
3789 ExprResult ActOnGenericSelectionExpr(SourceLocation KeyLoc,
3790 SourceLocation DefaultLoc,
3791 SourceLocation RParenLoc,
3792 Expr *ControllingExpr,
3793 ArrayRef<ParsedType> ArgTypes,
3794 ArrayRef<Expr *> ArgExprs);
3795 ExprResult CreateGenericSelectionExpr(SourceLocation KeyLoc,
3796 SourceLocation DefaultLoc,
3797 SourceLocation RParenLoc,
3798 Expr *ControllingExpr,
3799 ArrayRef<TypeSourceInfo *> Types,
3800 ArrayRef<Expr *> Exprs);
3802 // Binary/Unary Operators. 'Tok' is the token for the operator.
3803 ExprResult CreateBuiltinUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc,
3805 ExprResult BuildUnaryOp(Scope *S, SourceLocation OpLoc,
3806 UnaryOperatorKind Opc, Expr *Input);
3807 ExprResult ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
3808 tok::TokenKind Op, Expr *Input);
3810 QualType CheckAddressOfOperand(ExprResult &Operand, SourceLocation OpLoc);
3812 ExprResult CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
3813 SourceLocation OpLoc,
3814 UnaryExprOrTypeTrait ExprKind,
3816 ExprResult CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
3817 UnaryExprOrTypeTrait ExprKind);
3819 ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
3820 UnaryExprOrTypeTrait ExprKind,
3821 bool IsType, void *TyOrEx,
3822 SourceRange ArgRange);
3824 ExprResult CheckPlaceholderExpr(Expr *E);
3825 bool CheckVecStepExpr(Expr *E);
3827 bool CheckUnaryExprOrTypeTraitOperand(Expr *E, UnaryExprOrTypeTrait ExprKind);
3828 bool CheckUnaryExprOrTypeTraitOperand(QualType ExprType, SourceLocation OpLoc,
3829 SourceRange ExprRange,
3830 UnaryExprOrTypeTrait ExprKind);
3831 ExprResult ActOnSizeofParameterPackExpr(Scope *S,
3832 SourceLocation OpLoc,
3833 IdentifierInfo &Name,
3834 SourceLocation NameLoc,
3835 SourceLocation RParenLoc);
3836 ExprResult ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
3837 tok::TokenKind Kind, Expr *Input);
3839 ExprResult ActOnArraySubscriptExpr(Scope *S, Expr *Base, SourceLocation LLoc,
3840 Expr *Idx, SourceLocation RLoc);
3841 ExprResult CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
3842 Expr *Idx, SourceLocation RLoc);
3843 ExprResult ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc,
3844 Expr *LowerBound, SourceLocation ColonLoc,
3845 Expr *Length, SourceLocation RBLoc);
3847 // This struct is for use by ActOnMemberAccess to allow
3848 // BuildMemberReferenceExpr to be able to reinvoke ActOnMemberAccess after
3849 // changing the access operator from a '.' to a '->' (to see if that is the
3850 // change needed to fix an error about an unknown member, e.g. when the class
3851 // defines a custom operator->).
3852 struct ActOnMemberAccessExtraArgs {
3858 ExprResult BuildMemberReferenceExpr(
3859 Expr *Base, QualType BaseType, SourceLocation OpLoc, bool IsArrow,
3860 CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
3861 NamedDecl *FirstQualifierInScope, const DeclarationNameInfo &NameInfo,
3862 const TemplateArgumentListInfo *TemplateArgs,
3864 ActOnMemberAccessExtraArgs *ExtraArgs = nullptr);
3867 BuildMemberReferenceExpr(Expr *Base, QualType BaseType, SourceLocation OpLoc,
3868 bool IsArrow, const CXXScopeSpec &SS,
3869 SourceLocation TemplateKWLoc,
3870 NamedDecl *FirstQualifierInScope, LookupResult &R,
3871 const TemplateArgumentListInfo *TemplateArgs,
3873 bool SuppressQualifierCheck = false,
3874 ActOnMemberAccessExtraArgs *ExtraArgs = nullptr);
3876 ExprResult PerformMemberExprBaseConversion(Expr *Base, bool IsArrow);
3878 bool CheckQualifiedMemberReference(Expr *BaseExpr, QualType BaseType,
3879 const CXXScopeSpec &SS,
3880 const LookupResult &R);
3882 ExprResult ActOnDependentMemberExpr(Expr *Base, QualType BaseType,
3883 bool IsArrow, SourceLocation OpLoc,
3884 const CXXScopeSpec &SS,
3885 SourceLocation TemplateKWLoc,
3886 NamedDecl *FirstQualifierInScope,
3887 const DeclarationNameInfo &NameInfo,
3888 const TemplateArgumentListInfo *TemplateArgs);
3890 ExprResult ActOnMemberAccessExpr(Scope *S, Expr *Base,
3891 SourceLocation OpLoc,
3892 tok::TokenKind OpKind,
3894 SourceLocation TemplateKWLoc,
3895 UnqualifiedId &Member,
3898 void ActOnDefaultCtorInitializers(Decl *CDtorDecl);
3899 bool ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
3900 FunctionDecl *FDecl,
3901 const FunctionProtoType *Proto,
3902 ArrayRef<Expr *> Args,
3903 SourceLocation RParenLoc,
3904 bool ExecConfig = false);
3905 void CheckStaticArrayArgument(SourceLocation CallLoc,
3907 const Expr *ArgExpr);
3909 /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
3910 /// This provides the location of the left/right parens and a list of comma
3912 ExprResult ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
3913 MultiExprArg ArgExprs, SourceLocation RParenLoc,
3914 Expr *ExecConfig = nullptr,
3915 bool IsExecConfig = false);
3916 ExprResult BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
3917 SourceLocation LParenLoc,
3918 ArrayRef<Expr *> Arg,
3919 SourceLocation RParenLoc,
3920 Expr *Config = nullptr,
3921 bool IsExecConfig = false);
3923 ExprResult ActOnCUDAExecConfigExpr(Scope *S, SourceLocation LLLLoc,
3924 MultiExprArg ExecConfig,
3925 SourceLocation GGGLoc);
3927 ExprResult ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
3928 Declarator &D, ParsedType &Ty,
3929 SourceLocation RParenLoc, Expr *CastExpr);
3930 ExprResult BuildCStyleCastExpr(SourceLocation LParenLoc,
3932 SourceLocation RParenLoc,
3934 CastKind PrepareScalarCast(ExprResult &src, QualType destType);
3936 /// \brief Build an altivec or OpenCL literal.
3937 ExprResult BuildVectorLiteral(SourceLocation LParenLoc,
3938 SourceLocation RParenLoc, Expr *E,
3939 TypeSourceInfo *TInfo);
3941 ExprResult MaybeConvertParenListExprToParenExpr(Scope *S, Expr *ME);
3943 ExprResult ActOnCompoundLiteral(SourceLocation LParenLoc,
3945 SourceLocation RParenLoc,
3948 ExprResult BuildCompoundLiteralExpr(SourceLocation LParenLoc,
3949 TypeSourceInfo *TInfo,
3950 SourceLocation RParenLoc,
3953 ExprResult ActOnInitList(SourceLocation LBraceLoc,
3954 MultiExprArg InitArgList,
3955 SourceLocation RBraceLoc);
3957 ExprResult ActOnDesignatedInitializer(Designation &Desig,
3963 static BinaryOperatorKind ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind);
3966 ExprResult ActOnBinOp(Scope *S, SourceLocation TokLoc,
3967 tok::TokenKind Kind, Expr *LHSExpr, Expr *RHSExpr);
3968 ExprResult BuildBinOp(Scope *S, SourceLocation OpLoc,
3969 BinaryOperatorKind Opc, Expr *LHSExpr, Expr *RHSExpr);
3970 ExprResult CreateBuiltinBinOp(SourceLocation OpLoc, BinaryOperatorKind Opc,
3971 Expr *LHSExpr, Expr *RHSExpr);
3973 /// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
3974 /// in the case of a the GNU conditional expr extension.
3975 ExprResult ActOnConditionalOp(SourceLocation QuestionLoc,
3976 SourceLocation ColonLoc,
3977 Expr *CondExpr, Expr *LHSExpr, Expr *RHSExpr);
3979 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
3980 ExprResult ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
3981 LabelDecl *TheDecl);
3983 void ActOnStartStmtExpr();
3984 ExprResult ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
3985 SourceLocation RPLoc); // "({..})"
3986 void ActOnStmtExprError();
3988 // __builtin_offsetof(type, identifier(.identifier|[expr])*)
3989 struct OffsetOfComponent {
3990 SourceLocation LocStart, LocEnd;
3991 bool isBrackets; // true if [expr], false if .ident
3993 IdentifierInfo *IdentInfo;
3998 /// __builtin_offsetof(type, a.b[123][456].c)
3999 ExprResult BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
4000 TypeSourceInfo *TInfo,
4001 ArrayRef<OffsetOfComponent> Components,
4002 SourceLocation RParenLoc);
4003 ExprResult ActOnBuiltinOffsetOf(Scope *S,
4004 SourceLocation BuiltinLoc,
4005 SourceLocation TypeLoc,
4006 ParsedType ParsedArgTy,
4007 ArrayRef<OffsetOfComponent> Components,
4008 SourceLocation RParenLoc);
4010 // __builtin_choose_expr(constExpr, expr1, expr2)
4011 ExprResult ActOnChooseExpr(SourceLocation BuiltinLoc,
4012 Expr *CondExpr, Expr *LHSExpr,
4013 Expr *RHSExpr, SourceLocation RPLoc);
4015 // __builtin_va_arg(expr, type)
4016 ExprResult ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty,
4017 SourceLocation RPLoc);
4018 ExprResult BuildVAArgExpr(SourceLocation BuiltinLoc, Expr *E,
4019 TypeSourceInfo *TInfo, SourceLocation RPLoc);
4022 ExprResult ActOnGNUNullExpr(SourceLocation TokenLoc);
4024 bool CheckCaseExpression(Expr *E);
4026 /// \brief Describes the result of an "if-exists" condition check.
4027 enum IfExistsResult {
4028 /// \brief The symbol exists.
4031 /// \brief The symbol does not exist.
4034 /// \brief The name is a dependent name, so the results will differ
4035 /// from one instantiation to the next.
4038 /// \brief An error occurred.
4043 CheckMicrosoftIfExistsSymbol(Scope *S, CXXScopeSpec &SS,
4044 const DeclarationNameInfo &TargetNameInfo);
4047 CheckMicrosoftIfExistsSymbol(Scope *S, SourceLocation KeywordLoc,
4048 bool IsIfExists, CXXScopeSpec &SS,
4049 UnqualifiedId &Name);
4051 StmtResult BuildMSDependentExistsStmt(SourceLocation KeywordLoc,
4053 NestedNameSpecifierLoc QualifierLoc,
4054 DeclarationNameInfo NameInfo,
4056 StmtResult ActOnMSDependentExistsStmt(SourceLocation KeywordLoc,
4058 CXXScopeSpec &SS, UnqualifiedId &Name,
4061 //===------------------------- "Block" Extension ------------------------===//
4063 /// ActOnBlockStart - This callback is invoked when a block literal is
4065 void ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope);
4067 /// ActOnBlockArguments - This callback allows processing of block arguments.
4068 /// If there are no arguments, this is still invoked.
4069 void ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
4072 /// ActOnBlockError - If there is an error parsing a block, this callback
4073 /// is invoked to pop the information about the block from the action impl.
4074 void ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope);
4076 /// ActOnBlockStmtExpr - This is called when the body of a block statement
4077 /// literal was successfully completed. ^(int x){...}
4078 ExprResult ActOnBlockStmtExpr(SourceLocation CaretLoc, Stmt *Body,
4081 //===---------------------------- Clang Extensions ----------------------===//
4083 /// __builtin_convertvector(...)
4084 ExprResult ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy,
4085 SourceLocation BuiltinLoc,
4086 SourceLocation RParenLoc);
4088 //===---------------------------- OpenCL Features -----------------------===//
4090 /// __builtin_astype(...)
4091 ExprResult ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
4092 SourceLocation BuiltinLoc,
4093 SourceLocation RParenLoc);
4095 //===---------------------------- C++ Features --------------------------===//
4097 // Act on C++ namespaces
4098 Decl *ActOnStartNamespaceDef(Scope *S, SourceLocation InlineLoc,
4099 SourceLocation NamespaceLoc,
4100 SourceLocation IdentLoc,
4101 IdentifierInfo *Ident,
4102 SourceLocation LBrace,
4103 AttributeList *AttrList,
4104 UsingDirectiveDecl * &UsingDecl);
4105 void ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace);
4107 NamespaceDecl *getStdNamespace() const;
4108 NamespaceDecl *getOrCreateStdNamespace();
4110 CXXRecordDecl *getStdBadAlloc() const;
4112 /// \brief Tests whether Ty is an instance of std::initializer_list and, if
4113 /// it is and Element is not NULL, assigns the element type to Element.
4114 bool isStdInitializerList(QualType Ty, QualType *Element);
4116 /// \brief Looks for the std::initializer_list template and instantiates it
4117 /// with Element, or emits an error if it's not found.
4119 /// \returns The instantiated template, or null on error.
4120 QualType BuildStdInitializerList(QualType Element, SourceLocation Loc);
4122 /// \brief Determine whether Ctor is an initializer-list constructor, as
4123 /// defined in [dcl.init.list]p2.
4124 bool isInitListConstructor(const CXXConstructorDecl *Ctor);
4126 Decl *ActOnUsingDirective(Scope *CurScope,
4127 SourceLocation UsingLoc,
4128 SourceLocation NamespcLoc,
4130 SourceLocation IdentLoc,
4131 IdentifierInfo *NamespcName,
4132 AttributeList *AttrList);
4134 void PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir);
4136 Decl *ActOnNamespaceAliasDef(Scope *CurScope,
4137 SourceLocation NamespaceLoc,
4138 SourceLocation AliasLoc,
4139 IdentifierInfo *Alias,
4141 SourceLocation IdentLoc,
4142 IdentifierInfo *Ident);
4144 void HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow);
4145 bool CheckUsingShadowDecl(UsingDecl *UD, NamedDecl *Target,
4146 const LookupResult &PreviousDecls,
4147 UsingShadowDecl *&PrevShadow);
4148 UsingShadowDecl *BuildUsingShadowDecl(Scope *S, UsingDecl *UD,
4150 UsingShadowDecl *PrevDecl);
4152 bool CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
4153 bool HasTypenameKeyword,
4154 const CXXScopeSpec &SS,
4155 SourceLocation NameLoc,
4156 const LookupResult &Previous);
4157 bool CheckUsingDeclQualifier(SourceLocation UsingLoc,
4158 const CXXScopeSpec &SS,
4159 const DeclarationNameInfo &NameInfo,
4160 SourceLocation NameLoc);
4162 NamedDecl *BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
4163 SourceLocation UsingLoc,
4165 DeclarationNameInfo NameInfo,
4166 AttributeList *AttrList,
4167 bool IsInstantiation,
4168 bool HasTypenameKeyword,
4169 SourceLocation TypenameLoc);
4171 bool CheckInheritingConstructorUsingDecl(UsingDecl *UD);
4173 Decl *ActOnUsingDeclaration(Scope *CurScope,
4175 bool HasUsingKeyword,
4176 SourceLocation UsingLoc,
4178 UnqualifiedId &Name,
4179 AttributeList *AttrList,
4180 bool HasTypenameKeyword,
4181 SourceLocation TypenameLoc);
4182 Decl *ActOnAliasDeclaration(Scope *CurScope,
4184 MultiTemplateParamsArg TemplateParams,
4185 SourceLocation UsingLoc,
4186 UnqualifiedId &Name,
4187 AttributeList *AttrList,
4189 Decl *DeclFromDeclSpec);
4191 /// BuildCXXConstructExpr - Creates a complete call to a constructor,
4192 /// including handling of its default argument expressions.
4194 /// \param ConstructKind - a CXXConstructExpr::ConstructionKind
4196 BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
4197 CXXConstructorDecl *Constructor, MultiExprArg Exprs,
4198 bool HadMultipleCandidates, bool IsListInitialization,
4199 bool IsStdInitListInitialization,
4200 bool RequiresZeroInit, unsigned ConstructKind,
4201 SourceRange ParenRange);
4203 // FIXME: Can we remove this and have the above BuildCXXConstructExpr check if
4204 // the constructor can be elidable?
4206 BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
4207 CXXConstructorDecl *Constructor, bool Elidable,
4208 MultiExprArg Exprs, bool HadMultipleCandidates,
4209 bool IsListInitialization,
4210 bool IsStdInitListInitialization, bool RequiresZeroInit,
4211 unsigned ConstructKind, SourceRange ParenRange);
4213 ExprResult BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field);
4215 /// BuildCXXDefaultArgExpr - Creates a CXXDefaultArgExpr, instantiating
4216 /// the default expr if needed.
4217 ExprResult BuildCXXDefaultArgExpr(SourceLocation CallLoc,
4219 ParmVarDecl *Param);
4221 /// FinalizeVarWithDestructor - Prepare for calling destructor on the
4222 /// constructed variable.
4223 void FinalizeVarWithDestructor(VarDecl *VD, const RecordType *DeclInitType);
4225 /// \brief Helper class that collects exception specifications for
4226 /// implicitly-declared special member functions.
4227 class ImplicitExceptionSpecification {
4228 // Pointer to allow copying
4230 // We order exception specifications thus:
4231 // noexcept is the most restrictive, but is only used in C++11.
4232 // throw() comes next.
4233 // Then a throw(collected exceptions)
4234 // Finally no specification, which is expressed as noexcept(false).
4235 // throw(...) is used instead if any called function uses it.
4236 ExceptionSpecificationType ComputedEST;
4237 llvm::SmallPtrSet<CanQualType, 4> ExceptionsSeen;
4238 SmallVector<QualType, 4> Exceptions;
4240 void ClearExceptions() {
4241 ExceptionsSeen.clear();
4246 explicit ImplicitExceptionSpecification(Sema &Self)
4247 : Self(&Self), ComputedEST(EST_BasicNoexcept) {
4248 if (!Self.getLangOpts().CPlusPlus11)
4249 ComputedEST = EST_DynamicNone;
4252 /// \brief Get the computed exception specification type.
4253 ExceptionSpecificationType getExceptionSpecType() const {
4254 assert(ComputedEST != EST_ComputedNoexcept &&
4255 "noexcept(expr) should not be a possible result");
4259 /// \brief The number of exceptions in the exception specification.
4260 unsigned size() const { return Exceptions.size(); }
4262 /// \brief The set of exceptions in the exception specification.
4263 const QualType *data() const { return Exceptions.data(); }
4265 /// \brief Integrate another called method into the collected data.
4266 void CalledDecl(SourceLocation CallLoc, const CXXMethodDecl *Method);
4268 /// \brief Integrate an invoked expression into the collected data.
4269 void CalledExpr(Expr *E);
4271 /// \brief Overwrite an EPI's exception specification with this
4272 /// computed exception specification.
4273 FunctionProtoType::ExceptionSpecInfo getExceptionSpec() const {
4274 FunctionProtoType::ExceptionSpecInfo ESI;
4275 ESI.Type = getExceptionSpecType();
4276 if (ESI.Type == EST_Dynamic) {
4277 ESI.Exceptions = Exceptions;
4278 } else if (ESI.Type == EST_None) {
4279 /// C++11 [except.spec]p14:
4280 /// The exception-specification is noexcept(false) if the set of
4281 /// potential exceptions of the special member function contains "any"
4282 ESI.Type = EST_ComputedNoexcept;
4283 ESI.NoexceptExpr = Self->ActOnCXXBoolLiteral(SourceLocation(),
4284 tok::kw_false).get();
4290 /// \brief Determine what sort of exception specification a defaulted
4291 /// copy constructor of a class will have.
4292 ImplicitExceptionSpecification
4293 ComputeDefaultedDefaultCtorExceptionSpec(SourceLocation Loc,
4296 /// \brief Determine what sort of exception specification a defaulted
4297 /// default constructor of a class will have, and whether the parameter
4299 ImplicitExceptionSpecification
4300 ComputeDefaultedCopyCtorExceptionSpec(CXXMethodDecl *MD);
4302 /// \brief Determine what sort of exception specification a defautled
4303 /// copy assignment operator of a class will have, and whether the
4304 /// parameter will be const.
4305 ImplicitExceptionSpecification
4306 ComputeDefaultedCopyAssignmentExceptionSpec(CXXMethodDecl *MD);
4308 /// \brief Determine what sort of exception specification a defaulted move
4309 /// constructor of a class will have.
4310 ImplicitExceptionSpecification
4311 ComputeDefaultedMoveCtorExceptionSpec(CXXMethodDecl *MD);
4313 /// \brief Determine what sort of exception specification a defaulted move
4314 /// assignment operator of a class will have.
4315 ImplicitExceptionSpecification
4316 ComputeDefaultedMoveAssignmentExceptionSpec(CXXMethodDecl *MD);
4318 /// \brief Determine what sort of exception specification a defaulted
4319 /// destructor of a class will have.
4320 ImplicitExceptionSpecification
4321 ComputeDefaultedDtorExceptionSpec(CXXMethodDecl *MD);
4323 /// \brief Determine what sort of exception specification an inheriting
4324 /// constructor of a class will have.
4325 ImplicitExceptionSpecification
4326 ComputeInheritingCtorExceptionSpec(CXXConstructorDecl *CD);
4328 /// \brief Evaluate the implicit exception specification for a defaulted
4329 /// special member function.
4330 void EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD);
4332 /// \brief Check the given exception-specification and update the
4333 /// exception specification information with the results.
4334 void checkExceptionSpecification(bool IsTopLevel,
4335 ExceptionSpecificationType EST,
4336 ArrayRef<ParsedType> DynamicExceptions,
4337 ArrayRef<SourceRange> DynamicExceptionRanges,
4339 SmallVectorImpl<QualType> &Exceptions,
4340 FunctionProtoType::ExceptionSpecInfo &ESI);
4342 /// \brief Determine if we're in a case where we need to (incorrectly) eagerly
4343 /// parse an exception specification to work around a libstdc++ bug.
4344 bool isLibstdcxxEagerExceptionSpecHack(const Declarator &D);
4346 /// \brief Add an exception-specification to the given member function
4347 /// (or member function template). The exception-specification was parsed
4348 /// after the method itself was declared.
4349 void actOnDelayedExceptionSpecification(Decl *Method,
4350 ExceptionSpecificationType EST,
4351 SourceRange SpecificationRange,
4352 ArrayRef<ParsedType> DynamicExceptions,
4353 ArrayRef<SourceRange> DynamicExceptionRanges,
4354 Expr *NoexceptExpr);
4356 /// \brief Determine if a special member function should have a deleted
4357 /// definition when it is defaulted.
4358 bool ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
4359 bool Diagnose = false);
4361 /// \brief Declare the implicit default constructor for the given class.
4363 /// \param ClassDecl The class declaration into which the implicit
4364 /// default constructor will be added.
4366 /// \returns The implicitly-declared default constructor.
4367 CXXConstructorDecl *DeclareImplicitDefaultConstructor(
4368 CXXRecordDecl *ClassDecl);
4370 /// DefineImplicitDefaultConstructor - Checks for feasibility of
4371 /// defining this constructor as the default constructor.
4372 void DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
4373 CXXConstructorDecl *Constructor);
4375 /// \brief Declare the implicit destructor for the given class.
4377 /// \param ClassDecl The class declaration into which the implicit
4378 /// destructor will be added.
4380 /// \returns The implicitly-declared destructor.
4381 CXXDestructorDecl *DeclareImplicitDestructor(CXXRecordDecl *ClassDecl);
4383 /// DefineImplicitDestructor - Checks for feasibility of
4384 /// defining this destructor as the default destructor.
4385 void DefineImplicitDestructor(SourceLocation CurrentLocation,
4386 CXXDestructorDecl *Destructor);
4388 /// \brief Build an exception spec for destructors that don't have one.
4390 /// C++11 says that user-defined destructors with no exception spec get one
4391 /// that looks as if the destructor was implicitly declared.
4392 void AdjustDestructorExceptionSpec(CXXRecordDecl *ClassDecl,
4393 CXXDestructorDecl *Destructor);
4395 /// \brief Declare all inheriting constructors for the given class.
4397 /// \param ClassDecl The class declaration into which the inheriting
4398 /// constructors will be added.
4399 void DeclareInheritingConstructors(CXXRecordDecl *ClassDecl);
4401 /// \brief Define the specified inheriting constructor.
4402 void DefineInheritingConstructor(SourceLocation UseLoc,
4403 CXXConstructorDecl *Constructor);
4405 /// \brief Declare the implicit copy constructor for the given class.
4407 /// \param ClassDecl The class declaration into which the implicit
4408 /// copy constructor will be added.
4410 /// \returns The implicitly-declared copy constructor.
4411 CXXConstructorDecl *DeclareImplicitCopyConstructor(CXXRecordDecl *ClassDecl);
4413 /// DefineImplicitCopyConstructor - Checks for feasibility of
4414 /// defining this constructor as the copy constructor.
4415 void DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
4416 CXXConstructorDecl *Constructor);
4418 /// \brief Declare the implicit move constructor for the given class.
4420 /// \param ClassDecl The Class declaration into which the implicit
4421 /// move constructor will be added.
4423 /// \returns The implicitly-declared move constructor, or NULL if it wasn't
4425 CXXConstructorDecl *DeclareImplicitMoveConstructor(CXXRecordDecl *ClassDecl);
4427 /// DefineImplicitMoveConstructor - Checks for feasibility of
4428 /// defining this constructor as the move constructor.
4429 void DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
4430 CXXConstructorDecl *Constructor);
4432 /// \brief Declare the implicit copy assignment operator for the given class.
4434 /// \param ClassDecl The class declaration into which the implicit
4435 /// copy assignment operator will be added.
4437 /// \returns The implicitly-declared copy assignment operator.
4438 CXXMethodDecl *DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl);
4440 /// \brief Defines an implicitly-declared copy assignment operator.
4441 void DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
4442 CXXMethodDecl *MethodDecl);
4444 /// \brief Declare the implicit move assignment operator for the given class.
4446 /// \param ClassDecl The Class declaration into which the implicit
4447 /// move assignment operator will be added.
4449 /// \returns The implicitly-declared move assignment operator, or NULL if it
4450 /// wasn't declared.
4451 CXXMethodDecl *DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl);
4453 /// \brief Defines an implicitly-declared move assignment operator.
4454 void DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
4455 CXXMethodDecl *MethodDecl);
4457 /// \brief Force the declaration of any implicitly-declared members of this
4459 void ForceDeclarationOfImplicitMembers(CXXRecordDecl *Class);
4461 /// \brief Determine whether the given function is an implicitly-deleted
4462 /// special member function.
4463 bool isImplicitlyDeleted(FunctionDecl *FD);
4465 /// \brief Check whether 'this' shows up in the type of a static member
4466 /// function after the (naturally empty) cv-qualifier-seq would be.
4468 /// \returns true if an error occurred.
4469 bool checkThisInStaticMemberFunctionType(CXXMethodDecl *Method);
4471 /// \brief Whether this' shows up in the exception specification of a static
4472 /// member function.
4473 bool checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method);
4475 /// \brief Check whether 'this' shows up in the attributes of the given
4476 /// static member function.
4478 /// \returns true if an error occurred.
4479 bool checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method);
4481 /// MaybeBindToTemporary - If the passed in expression has a record type with
4482 /// a non-trivial destructor, this will return CXXBindTemporaryExpr. Otherwise
4483 /// it simply returns the passed in expression.
4484 ExprResult MaybeBindToTemporary(Expr *E);
4486 bool CompleteConstructorCall(CXXConstructorDecl *Constructor,
4487 MultiExprArg ArgsPtr,
4489 SmallVectorImpl<Expr*> &ConvertedArgs,
4490 bool AllowExplicit = false,
4491 bool IsListInitialization = false);
4493 ParsedType getInheritingConstructorName(CXXScopeSpec &SS,
4494 SourceLocation NameLoc,
4495 IdentifierInfo &Name);
4497 ParsedType getDestructorName(SourceLocation TildeLoc,
4498 IdentifierInfo &II, SourceLocation NameLoc,
4499 Scope *S, CXXScopeSpec &SS,
4500 ParsedType ObjectType,
4501 bool EnteringContext);
4503 ParsedType getDestructorType(const DeclSpec& DS, ParsedType ObjectType);
4505 // Checks that reinterpret casts don't have undefined behavior.
4506 void CheckCompatibleReinterpretCast(QualType SrcType, QualType DestType,
4507 bool IsDereference, SourceRange Range);
4509 /// ActOnCXXNamedCast - Parse {dynamic,static,reinterpret,const}_cast's.
4510 ExprResult ActOnCXXNamedCast(SourceLocation OpLoc,
4511 tok::TokenKind Kind,
4512 SourceLocation LAngleBracketLoc,
4514 SourceLocation RAngleBracketLoc,
4515 SourceLocation LParenLoc,
4517 SourceLocation RParenLoc);
4519 ExprResult BuildCXXNamedCast(SourceLocation OpLoc,
4520 tok::TokenKind Kind,
4523 SourceRange AngleBrackets,
4524 SourceRange Parens);
4526 ExprResult BuildCXXTypeId(QualType TypeInfoType,
4527 SourceLocation TypeidLoc,
4528 TypeSourceInfo *Operand,
4529 SourceLocation RParenLoc);
4530 ExprResult BuildCXXTypeId(QualType TypeInfoType,
4531 SourceLocation TypeidLoc,
4533 SourceLocation RParenLoc);
4535 /// ActOnCXXTypeid - Parse typeid( something ).
4536 ExprResult ActOnCXXTypeid(SourceLocation OpLoc,
4537 SourceLocation LParenLoc, bool isType,
4539 SourceLocation RParenLoc);
4541 ExprResult BuildCXXUuidof(QualType TypeInfoType,
4542 SourceLocation TypeidLoc,
4543 TypeSourceInfo *Operand,
4544 SourceLocation RParenLoc);
4545 ExprResult BuildCXXUuidof(QualType TypeInfoType,
4546 SourceLocation TypeidLoc,
4548 SourceLocation RParenLoc);
4550 /// ActOnCXXUuidof - Parse __uuidof( something ).
4551 ExprResult ActOnCXXUuidof(SourceLocation OpLoc,
4552 SourceLocation LParenLoc, bool isType,
4554 SourceLocation RParenLoc);
4556 /// \brief Handle a C++1z fold-expression: ( expr op ... op expr ).
4557 ExprResult ActOnCXXFoldExpr(SourceLocation LParenLoc, Expr *LHS,
4558 tok::TokenKind Operator,
4559 SourceLocation EllipsisLoc, Expr *RHS,
4560 SourceLocation RParenLoc);
4561 ExprResult BuildCXXFoldExpr(SourceLocation LParenLoc, Expr *LHS,
4562 BinaryOperatorKind Operator,
4563 SourceLocation EllipsisLoc, Expr *RHS,
4564 SourceLocation RParenLoc);
4565 ExprResult BuildEmptyCXXFoldExpr(SourceLocation EllipsisLoc,
4566 BinaryOperatorKind Operator);
4568 //// ActOnCXXThis - Parse 'this' pointer.
4569 ExprResult ActOnCXXThis(SourceLocation loc);
4571 /// \brief Try to retrieve the type of the 'this' pointer.
4573 /// \returns The type of 'this', if possible. Otherwise, returns a NULL type.
4574 QualType getCurrentThisType();
4576 /// \brief When non-NULL, the C++ 'this' expression is allowed despite the
4577 /// current context not being a non-static member function. In such cases,
4578 /// this provides the type used for 'this'.
4579 QualType CXXThisTypeOverride;
4581 /// \brief RAII object used to temporarily allow the C++ 'this' expression
4582 /// to be used, with the given qualifiers on the current class type.
4583 class CXXThisScopeRAII {
4585 QualType OldCXXThisTypeOverride;
4589 /// \brief Introduce a new scope where 'this' may be allowed (when enabled),
4590 /// using the given declaration (which is either a class template or a
4591 /// class) along with the given qualifiers.
4592 /// along with the qualifiers placed on '*this'.
4593 CXXThisScopeRAII(Sema &S, Decl *ContextDecl, unsigned CXXThisTypeQuals,
4594 bool Enabled = true);
4596 ~CXXThisScopeRAII();
4599 /// \brief Make sure the value of 'this' is actually available in the current
4600 /// context, if it is a potentially evaluated context.
4602 /// \param Loc The location at which the capture of 'this' occurs.
4604 /// \param Explicit Whether 'this' is explicitly captured in a lambda
4607 /// \param FunctionScopeIndexToStopAt If non-null, it points to the index
4608 /// of the FunctionScopeInfo stack beyond which we do not attempt to capture.
4609 /// This is useful when enclosing lambdas must speculatively capture
4610 /// 'this' that may or may not be used in certain specializations of
4611 /// a nested generic lambda (depending on whether the name resolves to
4612 /// a non-static member function or a static function).
4613 /// \return returns 'true' if failed, 'false' if success.
4614 bool CheckCXXThisCapture(SourceLocation Loc, bool Explicit = false,
4615 bool BuildAndDiagnose = true,
4616 const unsigned *const FunctionScopeIndexToStopAt = nullptr);
4618 /// \brief Determine whether the given type is the type of *this that is used
4619 /// outside of the body of a member function for a type that is currently
4621 bool isThisOutsideMemberFunctionBody(QualType BaseType);
4623 /// ActOnCXXBoolLiteral - Parse {true,false} literals.
4624 ExprResult ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind);
4627 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
4628 ExprResult ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind);
4630 /// ActOnCXXNullPtrLiteral - Parse 'nullptr'.
4631 ExprResult ActOnCXXNullPtrLiteral(SourceLocation Loc);
4633 //// ActOnCXXThrow - Parse throw expressions.
4634 ExprResult ActOnCXXThrow(Scope *S, SourceLocation OpLoc, Expr *expr);
4635 ExprResult BuildCXXThrow(SourceLocation OpLoc, Expr *Ex,
4636 bool IsThrownVarInScope);
4637 bool CheckCXXThrowOperand(SourceLocation ThrowLoc, QualType ThrowTy, Expr *E);
4639 /// ActOnCXXTypeConstructExpr - Parse construction of a specified type.
4640 /// Can be interpreted either as function-style casting ("int(x)")
4641 /// or class type construction ("ClassType(x,y,z)")
4642 /// or creation of a value-initialized type ("int()").
4643 ExprResult ActOnCXXTypeConstructExpr(ParsedType TypeRep,
4644 SourceLocation LParenLoc,
4646 SourceLocation RParenLoc);
4648 ExprResult BuildCXXTypeConstructExpr(TypeSourceInfo *Type,
4649 SourceLocation LParenLoc,
4651 SourceLocation RParenLoc);
4653 /// ActOnCXXNew - Parsed a C++ 'new' expression.
4654 ExprResult ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
4655 SourceLocation PlacementLParen,
4656 MultiExprArg PlacementArgs,
4657 SourceLocation PlacementRParen,
4658 SourceRange TypeIdParens, Declarator &D,
4660 ExprResult BuildCXXNew(SourceRange Range, bool UseGlobal,
4661 SourceLocation PlacementLParen,
4662 MultiExprArg PlacementArgs,
4663 SourceLocation PlacementRParen,
4664 SourceRange TypeIdParens,
4666 TypeSourceInfo *AllocTypeInfo,
4668 SourceRange DirectInitRange,
4670 bool TypeMayContainAuto = true);
4672 bool CheckAllocatedType(QualType AllocType, SourceLocation Loc,
4674 bool FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,
4675 bool UseGlobal, QualType AllocType, bool IsArray,
4676 MultiExprArg PlaceArgs,
4677 FunctionDecl *&OperatorNew,
4678 FunctionDecl *&OperatorDelete);
4679 bool FindAllocationOverload(SourceLocation StartLoc, SourceRange Range,
4680 DeclarationName Name, MultiExprArg Args,
4682 bool AllowMissing, FunctionDecl *&Operator,
4683 bool Diagnose = true);
4684 void DeclareGlobalNewDelete();
4685 void DeclareGlobalAllocationFunction(DeclarationName Name, QualType Return,
4687 QualType Param2 = QualType(),
4688 bool addRestrictAttr = false);
4690 bool FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD,
4691 DeclarationName Name, FunctionDecl* &Operator,
4692 bool Diagnose = true);
4693 FunctionDecl *FindUsualDeallocationFunction(SourceLocation StartLoc,
4694 bool CanProvideSize,
4695 DeclarationName Name);
4697 /// ActOnCXXDelete - Parsed a C++ 'delete' expression
4698 ExprResult ActOnCXXDelete(SourceLocation StartLoc,
4699 bool UseGlobal, bool ArrayForm,
4702 DeclResult ActOnCXXConditionDeclaration(Scope *S, Declarator &D);
4703 ExprResult CheckConditionVariable(VarDecl *ConditionVar,
4704 SourceLocation StmtLoc,
4705 bool ConvertToBoolean);
4707 ExprResult ActOnNoexceptExpr(SourceLocation KeyLoc, SourceLocation LParen,
4708 Expr *Operand, SourceLocation RParen);
4709 ExprResult BuildCXXNoexceptExpr(SourceLocation KeyLoc, Expr *Operand,
4710 SourceLocation RParen);
4712 /// \brief Parsed one of the type trait support pseudo-functions.
4713 ExprResult ActOnTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
4714 ArrayRef<ParsedType> Args,
4715 SourceLocation RParenLoc);
4716 ExprResult BuildTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
4717 ArrayRef<TypeSourceInfo *> Args,
4718 SourceLocation RParenLoc);
4720 /// ActOnArrayTypeTrait - Parsed one of the bianry type trait support
4721 /// pseudo-functions.
4722 ExprResult ActOnArrayTypeTrait(ArrayTypeTrait ATT,
4723 SourceLocation KWLoc,
4726 SourceLocation RParen);
4728 ExprResult BuildArrayTypeTrait(ArrayTypeTrait ATT,
4729 SourceLocation KWLoc,
4730 TypeSourceInfo *TSInfo,
4732 SourceLocation RParen);
4734 /// ActOnExpressionTrait - Parsed one of the unary type trait support
4735 /// pseudo-functions.
4736 ExprResult ActOnExpressionTrait(ExpressionTrait OET,
4737 SourceLocation KWLoc,
4739 SourceLocation RParen);
4741 ExprResult BuildExpressionTrait(ExpressionTrait OET,
4742 SourceLocation KWLoc,
4744 SourceLocation RParen);
4746 ExprResult ActOnStartCXXMemberReference(Scope *S,
4748 SourceLocation OpLoc,
4749 tok::TokenKind OpKind,
4750 ParsedType &ObjectType,
4751 bool &MayBePseudoDestructor);
4753 ExprResult BuildPseudoDestructorExpr(Expr *Base,
4754 SourceLocation OpLoc,
4755 tok::TokenKind OpKind,
4756 const CXXScopeSpec &SS,
4757 TypeSourceInfo *ScopeType,
4758 SourceLocation CCLoc,
4759 SourceLocation TildeLoc,
4760 PseudoDestructorTypeStorage DestroyedType);
4762 ExprResult ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
4763 SourceLocation OpLoc,
4764 tok::TokenKind OpKind,
4766 UnqualifiedId &FirstTypeName,
4767 SourceLocation CCLoc,
4768 SourceLocation TildeLoc,
4769 UnqualifiedId &SecondTypeName);
4771 ExprResult ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
4772 SourceLocation OpLoc,
4773 tok::TokenKind OpKind,
4774 SourceLocation TildeLoc,
4775 const DeclSpec& DS);
4777 /// MaybeCreateExprWithCleanups - If the current full-expression
4778 /// requires any cleanups, surround it with a ExprWithCleanups node.
4779 /// Otherwise, just returns the passed-in expression.
4780 Expr *MaybeCreateExprWithCleanups(Expr *SubExpr);
4781 Stmt *MaybeCreateStmtWithCleanups(Stmt *SubStmt);
4782 ExprResult MaybeCreateExprWithCleanups(ExprResult SubExpr);
4784 ExprResult ActOnFinishFullExpr(Expr *Expr) {
4785 return ActOnFinishFullExpr(Expr, Expr ? Expr->getExprLoc()
4786 : SourceLocation());
4788 ExprResult ActOnFinishFullExpr(Expr *Expr, SourceLocation CC,
4789 bool DiscardedValue = false,
4790 bool IsConstexpr = false,
4791 bool IsLambdaInitCaptureInitializer = false);
4792 StmtResult ActOnFinishFullStmt(Stmt *Stmt);
4794 // Marks SS invalid if it represents an incomplete type.
4795 bool RequireCompleteDeclContext(CXXScopeSpec &SS, DeclContext *DC);
4797 DeclContext *computeDeclContext(QualType T);
4798 DeclContext *computeDeclContext(const CXXScopeSpec &SS,
4799 bool EnteringContext = false);
4800 bool isDependentScopeSpecifier(const CXXScopeSpec &SS);
4801 CXXRecordDecl *getCurrentInstantiationOf(NestedNameSpecifier *NNS);
4803 /// \brief The parser has parsed a global nested-name-specifier '::'.
4805 /// \param CCLoc The location of the '::'.
4807 /// \param SS The nested-name-specifier, which will be updated in-place
4808 /// to reflect the parsed nested-name-specifier.
4810 /// \returns true if an error occurred, false otherwise.
4811 bool ActOnCXXGlobalScopeSpecifier(SourceLocation CCLoc, CXXScopeSpec &SS);
4813 /// \brief The parser has parsed a '__super' nested-name-specifier.
4815 /// \param SuperLoc The location of the '__super' keyword.
4817 /// \param ColonColonLoc The location of the '::'.
4819 /// \param SS The nested-name-specifier, which will be updated in-place
4820 /// to reflect the parsed nested-name-specifier.
4822 /// \returns true if an error occurred, false otherwise.
4823 bool ActOnSuperScopeSpecifier(SourceLocation SuperLoc,
4824 SourceLocation ColonColonLoc, CXXScopeSpec &SS);
4826 bool isAcceptableNestedNameSpecifier(const NamedDecl *SD,
4827 bool *CanCorrect = nullptr);
4828 NamedDecl *FindFirstQualifierInScope(Scope *S, NestedNameSpecifier *NNS);
4830 bool isNonTypeNestedNameSpecifier(Scope *S, CXXScopeSpec &SS,
4831 SourceLocation IdLoc,
4833 ParsedType ObjectType);
4835 bool BuildCXXNestedNameSpecifier(Scope *S,
4836 IdentifierInfo &Identifier,
4837 SourceLocation IdentifierLoc,
4838 SourceLocation CCLoc,
4839 QualType ObjectType,
4840 bool EnteringContext,
4842 NamedDecl *ScopeLookupResult,
4843 bool ErrorRecoveryLookup,
4844 bool *IsCorrectedToColon = nullptr);
4846 /// \brief The parser has parsed a nested-name-specifier 'identifier::'.
4848 /// \param S The scope in which this nested-name-specifier occurs.
4850 /// \param Identifier The identifier preceding the '::'.
4852 /// \param IdentifierLoc The location of the identifier.
4854 /// \param CCLoc The location of the '::'.
4856 /// \param ObjectType The type of the object, if we're parsing
4857 /// nested-name-specifier in a member access expression.
4859 /// \param EnteringContext Whether we're entering the context nominated by
4860 /// this nested-name-specifier.
4862 /// \param SS The nested-name-specifier, which is both an input
4863 /// parameter (the nested-name-specifier before this type) and an
4864 /// output parameter (containing the full nested-name-specifier,
4865 /// including this new type).
4867 /// \param ErrorRecoveryLookup If true, then this method is called to improve
4868 /// error recovery. In this case do not emit error message.
4870 /// \param IsCorrectedToColon If not null, suggestions to replace '::' -> ':'
4871 /// are allowed. The bool value pointed by this parameter is set to 'true'
4872 /// if the identifier is treated as if it was followed by ':', not '::'.
4874 /// \returns true if an error occurred, false otherwise.
4875 bool ActOnCXXNestedNameSpecifier(Scope *S,
4876 IdentifierInfo &Identifier,
4877 SourceLocation IdentifierLoc,
4878 SourceLocation CCLoc,
4879 ParsedType ObjectType,
4880 bool EnteringContext,
4882 bool ErrorRecoveryLookup = false,
4883 bool *IsCorrectedToColon = nullptr);
4885 ExprResult ActOnDecltypeExpression(Expr *E);
4887 bool ActOnCXXNestedNameSpecifierDecltype(CXXScopeSpec &SS,
4889 SourceLocation ColonColonLoc);
4891 bool IsInvalidUnlessNestedName(Scope *S, CXXScopeSpec &SS,
4892 IdentifierInfo &Identifier,
4893 SourceLocation IdentifierLoc,
4894 SourceLocation ColonLoc,
4895 ParsedType ObjectType,
4896 bool EnteringContext);
4898 /// \brief The parser has parsed a nested-name-specifier
4899 /// 'template[opt] template-name < template-args >::'.
4901 /// \param S The scope in which this nested-name-specifier occurs.
4903 /// \param SS The nested-name-specifier, which is both an input
4904 /// parameter (the nested-name-specifier before this type) and an
4905 /// output parameter (containing the full nested-name-specifier,
4906 /// including this new type).
4908 /// \param TemplateKWLoc the location of the 'template' keyword, if any.
4909 /// \param TemplateName the template name.
4910 /// \param TemplateNameLoc The location of the template name.
4911 /// \param LAngleLoc The location of the opening angle bracket ('<').
4912 /// \param TemplateArgs The template arguments.
4913 /// \param RAngleLoc The location of the closing angle bracket ('>').
4914 /// \param CCLoc The location of the '::'.
4916 /// \param EnteringContext Whether we're entering the context of the
4917 /// nested-name-specifier.
4920 /// \returns true if an error occurred, false otherwise.
4921 bool ActOnCXXNestedNameSpecifier(Scope *S,
4923 SourceLocation TemplateKWLoc,
4924 TemplateTy TemplateName,
4925 SourceLocation TemplateNameLoc,
4926 SourceLocation LAngleLoc,
4927 ASTTemplateArgsPtr TemplateArgs,
4928 SourceLocation RAngleLoc,
4929 SourceLocation CCLoc,
4930 bool EnteringContext);
4932 /// \brief Given a C++ nested-name-specifier, produce an annotation value
4933 /// that the parser can use later to reconstruct the given
4934 /// nested-name-specifier.
4936 /// \param SS A nested-name-specifier.
4938 /// \returns A pointer containing all of the information in the
4939 /// nested-name-specifier \p SS.
4940 void *SaveNestedNameSpecifierAnnotation(CXXScopeSpec &SS);
4942 /// \brief Given an annotation pointer for a nested-name-specifier, restore
4943 /// the nested-name-specifier structure.
4945 /// \param Annotation The annotation pointer, produced by
4946 /// \c SaveNestedNameSpecifierAnnotation().
4948 /// \param AnnotationRange The source range corresponding to the annotation.
4950 /// \param SS The nested-name-specifier that will be updated with the contents
4951 /// of the annotation pointer.
4952 void RestoreNestedNameSpecifierAnnotation(void *Annotation,
4953 SourceRange AnnotationRange,
4956 bool ShouldEnterDeclaratorScope(Scope *S, const CXXScopeSpec &SS);
4958 /// ActOnCXXEnterDeclaratorScope - Called when a C++ scope specifier (global
4959 /// scope or nested-name-specifier) is parsed, part of a declarator-id.
4960 /// After this method is called, according to [C++ 3.4.3p3], names should be
4961 /// looked up in the declarator-id's scope, until the declarator is parsed and
4962 /// ActOnCXXExitDeclaratorScope is called.
4963 /// The 'SS' should be a non-empty valid CXXScopeSpec.
4964 bool ActOnCXXEnterDeclaratorScope(Scope *S, CXXScopeSpec &SS);
4966 /// ActOnCXXExitDeclaratorScope - Called when a declarator that previously
4967 /// invoked ActOnCXXEnterDeclaratorScope(), is finished. 'SS' is the same
4968 /// CXXScopeSpec that was passed to ActOnCXXEnterDeclaratorScope as well.
4969 /// Used to indicate that names should revert to being looked up in the
4971 void ActOnCXXExitDeclaratorScope(Scope *S, const CXXScopeSpec &SS);
4973 /// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse an
4974 /// initializer for the declaration 'Dcl'.
4975 /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
4976 /// static data member of class X, names should be looked up in the scope of
4978 void ActOnCXXEnterDeclInitializer(Scope *S, Decl *Dcl);
4980 /// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
4981 /// initializer for the declaration 'Dcl'.
4982 void ActOnCXXExitDeclInitializer(Scope *S, Decl *Dcl);
4984 /// \brief Create a new lambda closure type.
4985 CXXRecordDecl *createLambdaClosureType(SourceRange IntroducerRange,
4986 TypeSourceInfo *Info,
4987 bool KnownDependent,
4988 LambdaCaptureDefault CaptureDefault);
4990 /// \brief Start the definition of a lambda expression.
4991 CXXMethodDecl *startLambdaDefinition(CXXRecordDecl *Class,
4992 SourceRange IntroducerRange,
4993 TypeSourceInfo *MethodType,
4994 SourceLocation EndLoc,
4995 ArrayRef<ParmVarDecl *> Params);
4997 /// \brief Endow the lambda scope info with the relevant properties.
4998 void buildLambdaScope(sema::LambdaScopeInfo *LSI,
4999 CXXMethodDecl *CallOperator,
5000 SourceRange IntroducerRange,
5001 LambdaCaptureDefault CaptureDefault,
5002 SourceLocation CaptureDefaultLoc,
5003 bool ExplicitParams,
5004 bool ExplicitResultType,
5007 /// \brief Perform initialization analysis of the init-capture and perform
5008 /// any implicit conversions such as an lvalue-to-rvalue conversion if
5009 /// not being used to initialize a reference.
5010 ParsedType actOnLambdaInitCaptureInitialization(
5011 SourceLocation Loc, bool ByRef, IdentifierInfo *Id,
5012 LambdaCaptureInitKind InitKind, Expr *&Init) {
5013 return ParsedType::make(buildLambdaInitCaptureInitialization(
5014 Loc, ByRef, Id, InitKind != LambdaCaptureInitKind::CopyInit, Init));
5016 QualType buildLambdaInitCaptureInitialization(SourceLocation Loc, bool ByRef,
5018 bool DirectInit, Expr *&Init);
5020 /// \brief Create a dummy variable within the declcontext of the lambda's
5021 /// call operator, for name lookup purposes for a lambda init capture.
5023 /// CodeGen handles emission of lambda captures, ignoring these dummy
5024 /// variables appropriately.
5025 VarDecl *createLambdaInitCaptureVarDecl(SourceLocation Loc,
5026 QualType InitCaptureType,
5028 unsigned InitStyle, Expr *Init);
5030 /// \brief Build the implicit field for an init-capture.
5031 FieldDecl *buildInitCaptureField(sema::LambdaScopeInfo *LSI, VarDecl *Var);
5033 /// \brief Note that we have finished the explicit captures for the
5035 void finishLambdaExplicitCaptures(sema::LambdaScopeInfo *LSI);
5037 /// \brief Introduce the lambda parameters into scope.
5038 void addLambdaParameters(CXXMethodDecl *CallOperator, Scope *CurScope);
5040 /// \brief Deduce a block or lambda's return type based on the return
5041 /// statements present in the body.
5042 void deduceClosureReturnType(sema::CapturingScopeInfo &CSI);
5044 /// ActOnStartOfLambdaDefinition - This is called just before we start
5045 /// parsing the body of a lambda; it analyzes the explicit captures and
5046 /// arguments, and sets up various data-structures for the body of the
5048 void ActOnStartOfLambdaDefinition(LambdaIntroducer &Intro,
5049 Declarator &ParamInfo, Scope *CurScope);
5051 /// ActOnLambdaError - If there is an error parsing a lambda, this callback
5052 /// is invoked to pop the information about the lambda.
5053 void ActOnLambdaError(SourceLocation StartLoc, Scope *CurScope,
5054 bool IsInstantiation = false);
5056 /// ActOnLambdaExpr - This is called when the body of a lambda expression
5057 /// was successfully completed.
5058 ExprResult ActOnLambdaExpr(SourceLocation StartLoc, Stmt *Body,
5061 /// \brief Complete a lambda-expression having processed and attached the
5063 ExprResult BuildLambdaExpr(SourceLocation StartLoc, SourceLocation EndLoc,
5064 sema::LambdaScopeInfo *LSI);
5066 /// \brief Define the "body" of the conversion from a lambda object to a
5067 /// function pointer.
5069 /// This routine doesn't actually define a sensible body; rather, it fills
5070 /// in the initialization expression needed to copy the lambda object into
5071 /// the block, and IR generation actually generates the real body of the
5072 /// block pointer conversion.
5073 void DefineImplicitLambdaToFunctionPointerConversion(
5074 SourceLocation CurrentLoc, CXXConversionDecl *Conv);
5076 /// \brief Define the "body" of the conversion from a lambda object to a
5079 /// This routine doesn't actually define a sensible body; rather, it fills
5080 /// in the initialization expression needed to copy the lambda object into
5081 /// the block, and IR generation actually generates the real body of the
5082 /// block pointer conversion.
5083 void DefineImplicitLambdaToBlockPointerConversion(SourceLocation CurrentLoc,
5084 CXXConversionDecl *Conv);
5086 ExprResult BuildBlockForLambdaConversion(SourceLocation CurrentLocation,
5087 SourceLocation ConvLocation,
5088 CXXConversionDecl *Conv,
5091 // ParseObjCStringLiteral - Parse Objective-C string literals.
5092 ExprResult ParseObjCStringLiteral(SourceLocation *AtLocs,
5093 ArrayRef<Expr *> Strings);
5095 ExprResult BuildObjCStringLiteral(SourceLocation AtLoc, StringLiteral *S);
5097 /// BuildObjCNumericLiteral - builds an ObjCBoxedExpr AST node for the
5098 /// numeric literal expression. Type of the expression will be "NSNumber *"
5099 /// or "id" if NSNumber is unavailable.
5100 ExprResult BuildObjCNumericLiteral(SourceLocation AtLoc, Expr *Number);
5101 ExprResult ActOnObjCBoolLiteral(SourceLocation AtLoc, SourceLocation ValueLoc,
5103 ExprResult BuildObjCArrayLiteral(SourceRange SR, MultiExprArg Elements);
5105 /// BuildObjCBoxedExpr - builds an ObjCBoxedExpr AST node for the
5106 /// '@' prefixed parenthesized expression. The type of the expression will
5107 /// either be "NSNumber *", "NSString *" or "NSValue *" depending on the type
5108 /// of ValueType, which is allowed to be a built-in numeric type, "char *",
5109 /// "const char *" or C structure with attribute 'objc_boxable'.
5110 ExprResult BuildObjCBoxedExpr(SourceRange SR, Expr *ValueExpr);
5112 ExprResult BuildObjCSubscriptExpression(SourceLocation RB, Expr *BaseExpr,
5114 ObjCMethodDecl *getterMethod,
5115 ObjCMethodDecl *setterMethod);
5117 ExprResult BuildObjCDictionaryLiteral(SourceRange SR,
5118 MutableArrayRef<ObjCDictionaryElement> Elements);
5120 ExprResult BuildObjCEncodeExpression(SourceLocation AtLoc,
5121 TypeSourceInfo *EncodedTypeInfo,
5122 SourceLocation RParenLoc);
5123 ExprResult BuildCXXMemberCallExpr(Expr *Exp, NamedDecl *FoundDecl,
5124 CXXConversionDecl *Method,
5125 bool HadMultipleCandidates);
5127 ExprResult ParseObjCEncodeExpression(SourceLocation AtLoc,
5128 SourceLocation EncodeLoc,
5129 SourceLocation LParenLoc,
5131 SourceLocation RParenLoc);
5133 /// ParseObjCSelectorExpression - Build selector expression for \@selector
5134 ExprResult ParseObjCSelectorExpression(Selector Sel,
5135 SourceLocation AtLoc,
5136 SourceLocation SelLoc,
5137 SourceLocation LParenLoc,
5138 SourceLocation RParenLoc,
5139 bool WarnMultipleSelectors);
5141 /// ParseObjCProtocolExpression - Build protocol expression for \@protocol
5142 ExprResult ParseObjCProtocolExpression(IdentifierInfo * ProtocolName,
5143 SourceLocation AtLoc,
5144 SourceLocation ProtoLoc,
5145 SourceLocation LParenLoc,
5146 SourceLocation ProtoIdLoc,
5147 SourceLocation RParenLoc);
5149 //===--------------------------------------------------------------------===//
5152 Decl *ActOnStartLinkageSpecification(Scope *S,
5153 SourceLocation ExternLoc,
5155 SourceLocation LBraceLoc);
5156 Decl *ActOnFinishLinkageSpecification(Scope *S,
5158 SourceLocation RBraceLoc);
5161 //===--------------------------------------------------------------------===//
5164 bool isCurrentClassName(const IdentifierInfo &II, Scope *S,
5165 const CXXScopeSpec *SS = nullptr);
5166 bool isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS);
5168 bool ActOnAccessSpecifier(AccessSpecifier Access,
5169 SourceLocation ASLoc,
5170 SourceLocation ColonLoc,
5171 AttributeList *Attrs = nullptr);
5173 NamedDecl *ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS,
5175 MultiTemplateParamsArg TemplateParameterLists,
5176 Expr *BitfieldWidth, const VirtSpecifiers &VS,
5177 InClassInitStyle InitStyle);
5179 void ActOnStartCXXInClassMemberInitializer();
5180 void ActOnFinishCXXInClassMemberInitializer(Decl *VarDecl,
5181 SourceLocation EqualLoc,
5184 MemInitResult ActOnMemInitializer(Decl *ConstructorD,
5187 IdentifierInfo *MemberOrBase,
5188 ParsedType TemplateTypeTy,
5190 SourceLocation IdLoc,
5191 SourceLocation LParenLoc,
5192 ArrayRef<Expr *> Args,
5193 SourceLocation RParenLoc,
5194 SourceLocation EllipsisLoc);
5196 MemInitResult ActOnMemInitializer(Decl *ConstructorD,
5199 IdentifierInfo *MemberOrBase,
5200 ParsedType TemplateTypeTy,
5202 SourceLocation IdLoc,
5204 SourceLocation EllipsisLoc);
5206 MemInitResult BuildMemInitializer(Decl *ConstructorD,
5209 IdentifierInfo *MemberOrBase,
5210 ParsedType TemplateTypeTy,
5212 SourceLocation IdLoc,
5214 SourceLocation EllipsisLoc);
5216 MemInitResult BuildMemberInitializer(ValueDecl *Member,
5218 SourceLocation IdLoc);
5220 MemInitResult BuildBaseInitializer(QualType BaseType,
5221 TypeSourceInfo *BaseTInfo,
5223 CXXRecordDecl *ClassDecl,
5224 SourceLocation EllipsisLoc);
5226 MemInitResult BuildDelegatingInitializer(TypeSourceInfo *TInfo,
5228 CXXRecordDecl *ClassDecl);
5230 bool SetDelegatingInitializer(CXXConstructorDecl *Constructor,
5231 CXXCtorInitializer *Initializer);
5233 bool SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
5234 ArrayRef<CXXCtorInitializer *> Initializers = None);
5236 void SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation);
5239 /// MarkBaseAndMemberDestructorsReferenced - Given a record decl,
5240 /// mark all the non-trivial destructors of its members and bases as
5242 void MarkBaseAndMemberDestructorsReferenced(SourceLocation Loc,
5243 CXXRecordDecl *Record);
5245 /// \brief The list of classes whose vtables have been used within
5246 /// this translation unit, and the source locations at which the
5247 /// first use occurred.
5248 typedef std::pair<CXXRecordDecl*, SourceLocation> VTableUse;
5250 /// \brief The list of vtables that are required but have not yet been
5252 SmallVector<VTableUse, 16> VTableUses;
5254 /// \brief The set of classes whose vtables have been used within
5255 /// this translation unit, and a bit that will be true if the vtable is
5256 /// required to be emitted (otherwise, it should be emitted only if needed
5257 /// by code generation).
5258 llvm::DenseMap<CXXRecordDecl *, bool> VTablesUsed;
5260 /// \brief Load any externally-stored vtable uses.
5261 void LoadExternalVTableUses();
5263 /// \brief Note that the vtable for the given class was used at the
5265 void MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
5266 bool DefinitionRequired = false);
5268 /// \brief Mark the exception specifications of all virtual member functions
5269 /// in the given class as needed.
5270 void MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
5271 const CXXRecordDecl *RD);
5273 /// MarkVirtualMembersReferenced - Will mark all members of the given
5274 /// CXXRecordDecl referenced.
5275 void MarkVirtualMembersReferenced(SourceLocation Loc,
5276 const CXXRecordDecl *RD);
5278 /// \brief Define all of the vtables that have been used in this
5279 /// translation unit and reference any virtual members used by those
5282 /// \returns true if any work was done, false otherwise.
5283 bool DefineUsedVTables();
5285 void AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl);
5287 void ActOnMemInitializers(Decl *ConstructorDecl,
5288 SourceLocation ColonLoc,
5289 ArrayRef<CXXCtorInitializer*> MemInits,
5292 void checkClassLevelDLLAttribute(CXXRecordDecl *Class);
5293 void propagateDLLAttrToBaseClassTemplate(
5294 CXXRecordDecl *Class, Attr *ClassAttr,
5295 ClassTemplateSpecializationDecl *BaseTemplateSpec,
5296 SourceLocation BaseLoc);
5297 void CheckCompletedCXXClass(CXXRecordDecl *Record);
5298 void ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
5300 SourceLocation LBrac,
5301 SourceLocation RBrac,
5302 AttributeList *AttrList);
5303 void ActOnFinishCXXMemberDecls();
5304 void ActOnFinishCXXNonNestedClass(Decl *D);
5306 void ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param);
5307 unsigned ActOnReenterTemplateScope(Scope *S, Decl *Template);
5308 void ActOnStartDelayedMemberDeclarations(Scope *S, Decl *Record);
5309 void ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *Method);
5310 void ActOnDelayedCXXMethodParameter(Scope *S, Decl *Param);
5311 void ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *Record);
5312 void ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *Method);
5313 void ActOnFinishDelayedMemberInitializers(Decl *Record);
5314 void MarkAsLateParsedTemplate(FunctionDecl *FD, Decl *FnD,
5315 CachedTokens &Toks);
5316 void UnmarkAsLateParsedTemplate(FunctionDecl *FD);
5317 bool IsInsideALocalClassWithinATemplateFunction();
5319 Decl *ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
5321 Expr *AssertMessageExpr,
5322 SourceLocation RParenLoc);
5323 Decl *BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
5325 StringLiteral *AssertMessageExpr,
5326 SourceLocation RParenLoc,
5329 FriendDecl *CheckFriendTypeDecl(SourceLocation LocStart,
5330 SourceLocation FriendLoc,
5331 TypeSourceInfo *TSInfo);
5332 Decl *ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
5333 MultiTemplateParamsArg TemplateParams);
5334 NamedDecl *ActOnFriendFunctionDecl(Scope *S, Declarator &D,
5335 MultiTemplateParamsArg TemplateParams);
5337 QualType CheckConstructorDeclarator(Declarator &D, QualType R,
5339 void CheckConstructor(CXXConstructorDecl *Constructor);
5340 QualType CheckDestructorDeclarator(Declarator &D, QualType R,
5342 bool CheckDestructor(CXXDestructorDecl *Destructor);
5343 void CheckConversionDeclarator(Declarator &D, QualType &R,
5345 Decl *ActOnConversionDeclarator(CXXConversionDecl *Conversion);
5347 void CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD);
5348 void CheckExplicitlyDefaultedMemberExceptionSpec(CXXMethodDecl *MD,
5349 const FunctionProtoType *T);
5350 void CheckDelayedMemberExceptionSpecs();
5352 //===--------------------------------------------------------------------===//
5353 // C++ Derived Classes
5356 /// ActOnBaseSpecifier - Parsed a base specifier
5357 CXXBaseSpecifier *CheckBaseSpecifier(CXXRecordDecl *Class,
5358 SourceRange SpecifierRange,
5359 bool Virtual, AccessSpecifier Access,
5360 TypeSourceInfo *TInfo,
5361 SourceLocation EllipsisLoc);
5363 BaseResult ActOnBaseSpecifier(Decl *classdecl,
5364 SourceRange SpecifierRange,
5365 ParsedAttributes &Attrs,
5366 bool Virtual, AccessSpecifier Access,
5367 ParsedType basetype,
5368 SourceLocation BaseLoc,
5369 SourceLocation EllipsisLoc);
5371 bool AttachBaseSpecifiers(CXXRecordDecl *Class,
5372 MutableArrayRef<CXXBaseSpecifier *> Bases);
5373 void ActOnBaseSpecifiers(Decl *ClassDecl,
5374 MutableArrayRef<CXXBaseSpecifier *> Bases);
5376 bool IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base);
5377 bool IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base,
5378 CXXBasePaths &Paths);
5380 // FIXME: I don't like this name.
5381 void BuildBasePathArray(const CXXBasePaths &Paths, CXXCastPath &BasePath);
5383 bool CheckDerivedToBaseConversion(QualType Derived, QualType Base,
5384 SourceLocation Loc, SourceRange Range,
5385 CXXCastPath *BasePath = nullptr,
5386 bool IgnoreAccess = false);
5387 bool CheckDerivedToBaseConversion(QualType Derived, QualType Base,
5388 unsigned InaccessibleBaseID,
5389 unsigned AmbigiousBaseConvID,
5390 SourceLocation Loc, SourceRange Range,
5391 DeclarationName Name,
5392 CXXCastPath *BasePath,
5393 bool IgnoreAccess = false);
5395 std::string getAmbiguousPathsDisplayString(CXXBasePaths &Paths);
5397 bool CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
5398 const CXXMethodDecl *Old);
5400 /// CheckOverridingFunctionReturnType - Checks whether the return types are
5401 /// covariant, according to C++ [class.virtual]p5.
5402 bool CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
5403 const CXXMethodDecl *Old);
5405 /// CheckOverridingFunctionExceptionSpec - Checks whether the exception
5406 /// spec is a subset of base spec.
5407 bool CheckOverridingFunctionExceptionSpec(const CXXMethodDecl *New,
5408 const CXXMethodDecl *Old);
5410 bool CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange);
5412 /// CheckOverrideControl - Check C++11 override control semantics.
5413 void CheckOverrideControl(NamedDecl *D);
5415 /// DiagnoseAbsenceOfOverrideControl - Diagnose if 'override' keyword was
5416 /// not used in the declaration of an overriding method.
5417 void DiagnoseAbsenceOfOverrideControl(NamedDecl *D);
5419 /// CheckForFunctionMarkedFinal - Checks whether a virtual member function
5420 /// overrides a virtual member function marked 'final', according to
5421 /// C++11 [class.virtual]p4.
5422 bool CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
5423 const CXXMethodDecl *Old);
5426 //===--------------------------------------------------------------------===//
5427 // C++ Access Control
5437 bool SetMemberAccessSpecifier(NamedDecl *MemberDecl,
5438 NamedDecl *PrevMemberDecl,
5439 AccessSpecifier LexicalAS);
5441 AccessResult CheckUnresolvedMemberAccess(UnresolvedMemberExpr *E,
5442 DeclAccessPair FoundDecl);
5443 AccessResult CheckUnresolvedLookupAccess(UnresolvedLookupExpr *E,
5444 DeclAccessPair FoundDecl);
5445 AccessResult CheckAllocationAccess(SourceLocation OperatorLoc,
5446 SourceRange PlacementRange,
5447 CXXRecordDecl *NamingClass,
5448 DeclAccessPair FoundDecl,
5449 bool Diagnose = true);
5450 AccessResult CheckConstructorAccess(SourceLocation Loc,
5451 CXXConstructorDecl *D,
5452 const InitializedEntity &Entity,
5453 AccessSpecifier Access,
5454 bool IsCopyBindingRefToTemp = false);
5455 AccessResult CheckConstructorAccess(SourceLocation Loc,
5456 CXXConstructorDecl *D,
5457 const InitializedEntity &Entity,
5458 AccessSpecifier Access,
5459 const PartialDiagnostic &PDiag);
5460 AccessResult CheckDestructorAccess(SourceLocation Loc,
5461 CXXDestructorDecl *Dtor,
5462 const PartialDiagnostic &PDiag,
5463 QualType objectType = QualType());
5464 AccessResult CheckFriendAccess(NamedDecl *D);
5465 AccessResult CheckMemberAccess(SourceLocation UseLoc,
5466 CXXRecordDecl *NamingClass,
5467 DeclAccessPair Found);
5468 AccessResult CheckMemberOperatorAccess(SourceLocation Loc,
5471 DeclAccessPair FoundDecl);
5472 AccessResult CheckAddressOfMemberAccess(Expr *OvlExpr,
5473 DeclAccessPair FoundDecl);
5474 AccessResult CheckBaseClassAccess(SourceLocation AccessLoc,
5475 QualType Base, QualType Derived,
5476 const CXXBasePath &Path,
5478 bool ForceCheck = false,
5479 bool ForceUnprivileged = false);
5480 void CheckLookupAccess(const LookupResult &R);
5481 bool IsSimplyAccessible(NamedDecl *decl, DeclContext *Ctx);
5482 bool isSpecialMemberAccessibleForDeletion(CXXMethodDecl *decl,
5483 AccessSpecifier access,
5484 QualType objectType);
5486 void HandleDependentAccessCheck(const DependentDiagnostic &DD,
5487 const MultiLevelTemplateArgumentList &TemplateArgs);
5488 void PerformDependentDiagnostics(const DeclContext *Pattern,
5489 const MultiLevelTemplateArgumentList &TemplateArgs);
5491 void HandleDelayedAccessCheck(sema::DelayedDiagnostic &DD, Decl *Ctx);
5493 /// \brief When true, access checking violations are treated as SFINAE
5494 /// failures rather than hard errors.
5495 bool AccessCheckingSFINAE;
5497 enum AbstractDiagSelID {
5501 AbstractVariableType,
5504 AbstractSynthesizedIvarType,
5508 bool isAbstractType(SourceLocation Loc, QualType T);
5509 bool RequireNonAbstractType(SourceLocation Loc, QualType T,
5510 TypeDiagnoser &Diagnoser);
5511 template <typename... Ts>
5512 bool RequireNonAbstractType(SourceLocation Loc, QualType T, unsigned DiagID,
5513 const Ts &...Args) {
5514 BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
5515 return RequireNonAbstractType(Loc, T, Diagnoser);
5518 void DiagnoseAbstractType(const CXXRecordDecl *RD);
5520 //===--------------------------------------------------------------------===//
5521 // C++ Overloaded Operators [C++ 13.5]
5524 bool CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl);
5526 bool CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl);
5528 //===--------------------------------------------------------------------===//
5529 // C++ Templates [C++ 14]
5531 void FilterAcceptableTemplateNames(LookupResult &R,
5532 bool AllowFunctionTemplates = true);
5533 bool hasAnyAcceptableTemplateNames(LookupResult &R,
5534 bool AllowFunctionTemplates = true);
5536 void LookupTemplateName(LookupResult &R, Scope *S, CXXScopeSpec &SS,
5537 QualType ObjectType, bool EnteringContext,
5538 bool &MemberOfUnknownSpecialization);
5540 TemplateNameKind isTemplateName(Scope *S,
5542 bool hasTemplateKeyword,
5543 UnqualifiedId &Name,
5544 ParsedType ObjectType,
5545 bool EnteringContext,
5546 TemplateTy &Template,
5547 bool &MemberOfUnknownSpecialization);
5549 bool DiagnoseUnknownTemplateName(const IdentifierInfo &II,
5550 SourceLocation IILoc,
5552 const CXXScopeSpec *SS,
5553 TemplateTy &SuggestedTemplate,
5554 TemplateNameKind &SuggestedKind);
5556 void DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl);
5557 TemplateDecl *AdjustDeclIfTemplate(Decl *&Decl);
5559 Decl *ActOnTypeParameter(Scope *S, bool Typename,
5560 SourceLocation EllipsisLoc,
5561 SourceLocation KeyLoc,
5562 IdentifierInfo *ParamName,
5563 SourceLocation ParamNameLoc,
5564 unsigned Depth, unsigned Position,
5565 SourceLocation EqualLoc,
5566 ParsedType DefaultArg);
5568 QualType CheckNonTypeTemplateParameterType(QualType T, SourceLocation Loc);
5569 Decl *ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
5572 SourceLocation EqualLoc,
5574 Decl *ActOnTemplateTemplateParameter(Scope *S,
5575 SourceLocation TmpLoc,
5576 TemplateParameterList *Params,
5577 SourceLocation EllipsisLoc,
5578 IdentifierInfo *ParamName,
5579 SourceLocation ParamNameLoc,
5582 SourceLocation EqualLoc,
5583 ParsedTemplateArgument DefaultArg);
5585 TemplateParameterList *
5586 ActOnTemplateParameterList(unsigned Depth,
5587 SourceLocation ExportLoc,
5588 SourceLocation TemplateLoc,
5589 SourceLocation LAngleLoc,
5590 ArrayRef<Decl *> Params,
5591 SourceLocation RAngleLoc);
5593 /// \brief The context in which we are checking a template parameter list.
5594 enum TemplateParamListContext {
5597 TPC_FunctionTemplate,
5598 TPC_ClassTemplateMember,
5599 TPC_FriendClassTemplate,
5600 TPC_FriendFunctionTemplate,
5601 TPC_FriendFunctionTemplateDefinition,
5602 TPC_TypeAliasTemplate
5605 bool CheckTemplateParameterList(TemplateParameterList *NewParams,
5606 TemplateParameterList *OldParams,
5607 TemplateParamListContext TPC);
5608 TemplateParameterList *MatchTemplateParametersToScopeSpecifier(
5609 SourceLocation DeclStartLoc, SourceLocation DeclLoc,
5610 const CXXScopeSpec &SS, TemplateIdAnnotation *TemplateId,
5611 ArrayRef<TemplateParameterList *> ParamLists,
5612 bool IsFriend, bool &IsExplicitSpecialization, bool &Invalid);
5614 DeclResult CheckClassTemplate(Scope *S, unsigned TagSpec, TagUseKind TUK,
5615 SourceLocation KWLoc, CXXScopeSpec &SS,
5616 IdentifierInfo *Name, SourceLocation NameLoc,
5617 AttributeList *Attr,
5618 TemplateParameterList *TemplateParams,
5620 SourceLocation ModulePrivateLoc,
5621 SourceLocation FriendLoc,
5622 unsigned NumOuterTemplateParamLists,
5623 TemplateParameterList **OuterTemplateParamLists,
5624 SkipBodyInfo *SkipBody = nullptr);
5626 void translateTemplateArguments(const ASTTemplateArgsPtr &In,
5627 TemplateArgumentListInfo &Out);
5629 void NoteAllFoundTemplates(TemplateName Name);
5631 QualType CheckTemplateIdType(TemplateName Template,
5632 SourceLocation TemplateLoc,
5633 TemplateArgumentListInfo &TemplateArgs);
5636 ActOnTemplateIdType(CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
5637 TemplateTy Template, SourceLocation TemplateLoc,
5638 SourceLocation LAngleLoc,
5639 ASTTemplateArgsPtr TemplateArgs,
5640 SourceLocation RAngleLoc,
5641 bool IsCtorOrDtorName = false);
5643 /// \brief Parsed an elaborated-type-specifier that refers to a template-id,
5644 /// such as \c class T::template apply<U>.
5645 TypeResult ActOnTagTemplateIdType(TagUseKind TUK,
5646 TypeSpecifierType TagSpec,
5647 SourceLocation TagLoc,
5649 SourceLocation TemplateKWLoc,
5650 TemplateTy TemplateD,
5651 SourceLocation TemplateLoc,
5652 SourceLocation LAngleLoc,
5653 ASTTemplateArgsPtr TemplateArgsIn,
5654 SourceLocation RAngleLoc);
5656 DeclResult ActOnVarTemplateSpecialization(
5657 Scope *S, Declarator &D, TypeSourceInfo *DI,
5658 SourceLocation TemplateKWLoc, TemplateParameterList *TemplateParams,
5659 StorageClass SC, bool IsPartialSpecialization);
5661 DeclResult CheckVarTemplateId(VarTemplateDecl *Template,
5662 SourceLocation TemplateLoc,
5663 SourceLocation TemplateNameLoc,
5664 const TemplateArgumentListInfo &TemplateArgs);
5666 ExprResult CheckVarTemplateId(const CXXScopeSpec &SS,
5667 const DeclarationNameInfo &NameInfo,
5668 VarTemplateDecl *Template,
5669 SourceLocation TemplateLoc,
5670 const TemplateArgumentListInfo *TemplateArgs);
5672 ExprResult BuildTemplateIdExpr(const CXXScopeSpec &SS,
5673 SourceLocation TemplateKWLoc,
5676 const TemplateArgumentListInfo *TemplateArgs);
5678 ExprResult BuildQualifiedTemplateIdExpr(CXXScopeSpec &SS,
5679 SourceLocation TemplateKWLoc,
5680 const DeclarationNameInfo &NameInfo,
5681 const TemplateArgumentListInfo *TemplateArgs);
5683 TemplateNameKind ActOnDependentTemplateName(Scope *S,
5685 SourceLocation TemplateKWLoc,
5686 UnqualifiedId &Name,
5687 ParsedType ObjectType,
5688 bool EnteringContext,
5689 TemplateTy &Template);
5692 ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec, TagUseKind TUK,
5693 SourceLocation KWLoc,
5694 SourceLocation ModulePrivateLoc,
5695 TemplateIdAnnotation &TemplateId,
5696 AttributeList *Attr,
5697 MultiTemplateParamsArg TemplateParameterLists,
5698 SkipBodyInfo *SkipBody = nullptr);
5700 Decl *ActOnTemplateDeclarator(Scope *S,
5701 MultiTemplateParamsArg TemplateParameterLists,
5705 CheckSpecializationInstantiationRedecl(SourceLocation NewLoc,
5706 TemplateSpecializationKind NewTSK,
5707 NamedDecl *PrevDecl,
5708 TemplateSpecializationKind PrevTSK,
5709 SourceLocation PrevPtOfInstantiation,
5712 bool CheckDependentFunctionTemplateSpecialization(FunctionDecl *FD,
5713 const TemplateArgumentListInfo &ExplicitTemplateArgs,
5714 LookupResult &Previous);
5716 bool CheckFunctionTemplateSpecialization(FunctionDecl *FD,
5717 TemplateArgumentListInfo *ExplicitTemplateArgs,
5718 LookupResult &Previous);
5719 bool CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous);
5722 ActOnExplicitInstantiation(Scope *S,
5723 SourceLocation ExternLoc,
5724 SourceLocation TemplateLoc,
5726 SourceLocation KWLoc,
5727 const CXXScopeSpec &SS,
5728 TemplateTy Template,
5729 SourceLocation TemplateNameLoc,
5730 SourceLocation LAngleLoc,
5731 ASTTemplateArgsPtr TemplateArgs,
5732 SourceLocation RAngleLoc,
5733 AttributeList *Attr);
5736 ActOnExplicitInstantiation(Scope *S,
5737 SourceLocation ExternLoc,
5738 SourceLocation TemplateLoc,
5740 SourceLocation KWLoc,
5742 IdentifierInfo *Name,
5743 SourceLocation NameLoc,
5744 AttributeList *Attr);
5746 DeclResult ActOnExplicitInstantiation(Scope *S,
5747 SourceLocation ExternLoc,
5748 SourceLocation TemplateLoc,
5752 SubstDefaultTemplateArgumentIfAvailable(TemplateDecl *Template,
5753 SourceLocation TemplateLoc,
5754 SourceLocation RAngleLoc,
5756 SmallVectorImpl<TemplateArgument>
5758 bool &HasDefaultArg);
5760 /// \brief Specifies the context in which a particular template
5761 /// argument is being checked.
5762 enum CheckTemplateArgumentKind {
5763 /// \brief The template argument was specified in the code or was
5764 /// instantiated with some deduced template arguments.
5767 /// \brief The template argument was deduced via template argument
5771 /// \brief The template argument was deduced from an array bound
5772 /// via template argument deduction.
5773 CTAK_DeducedFromArrayBound
5776 bool CheckTemplateArgument(NamedDecl *Param,
5777 TemplateArgumentLoc &Arg,
5778 NamedDecl *Template,
5779 SourceLocation TemplateLoc,
5780 SourceLocation RAngleLoc,
5781 unsigned ArgumentPackIndex,
5782 SmallVectorImpl<TemplateArgument> &Converted,
5783 CheckTemplateArgumentKind CTAK = CTAK_Specified);
5785 /// \brief Check that the given template arguments can be be provided to
5786 /// the given template, converting the arguments along the way.
5788 /// \param Template The template to which the template arguments are being
5791 /// \param TemplateLoc The location of the template name in the source.
5793 /// \param TemplateArgs The list of template arguments. If the template is
5794 /// a template template parameter, this function may extend the set of
5795 /// template arguments to also include substituted, defaulted template
5798 /// \param PartialTemplateArgs True if the list of template arguments is
5799 /// intentionally partial, e.g., because we're checking just the initial
5800 /// set of template arguments.
5802 /// \param Converted Will receive the converted, canonicalized template
5805 /// \returns true if an error occurred, false otherwise.
5806 bool CheckTemplateArgumentList(TemplateDecl *Template,
5807 SourceLocation TemplateLoc,
5808 TemplateArgumentListInfo &TemplateArgs,
5809 bool PartialTemplateArgs,
5810 SmallVectorImpl<TemplateArgument> &Converted);
5812 bool CheckTemplateTypeArgument(TemplateTypeParmDecl *Param,
5813 TemplateArgumentLoc &Arg,
5814 SmallVectorImpl<TemplateArgument> &Converted);
5816 bool CheckTemplateArgument(TemplateTypeParmDecl *Param,
5817 TypeSourceInfo *Arg);
5818 ExprResult CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
5819 QualType InstantiatedParamType, Expr *Arg,
5820 TemplateArgument &Converted,
5821 CheckTemplateArgumentKind CTAK = CTAK_Specified);
5822 bool CheckTemplateArgument(TemplateTemplateParmDecl *Param,
5823 TemplateArgumentLoc &Arg,
5824 unsigned ArgumentPackIndex);
5827 BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg,
5829 SourceLocation Loc);
5831 BuildExpressionFromIntegralTemplateArgument(const TemplateArgument &Arg,
5832 SourceLocation Loc);
5834 /// \brief Enumeration describing how template parameter lists are compared
5836 enum TemplateParameterListEqualKind {
5837 /// \brief We are matching the template parameter lists of two templates
5838 /// that might be redeclarations.
5841 /// template<typename T> struct X;
5842 /// template<typename T> struct X;
5846 /// \brief We are matching the template parameter lists of two template
5847 /// template parameters as part of matching the template parameter lists
5848 /// of two templates that might be redeclarations.
5851 /// template<template<int I> class TT> struct X;
5852 /// template<template<int Value> class Other> struct X;
5854 TPL_TemplateTemplateParmMatch,
5856 /// \brief We are matching the template parameter lists of a template
5857 /// template argument against the template parameter lists of a template
5858 /// template parameter.
5861 /// template<template<int Value> class Metafun> struct X;
5862 /// template<int Value> struct integer_c;
5863 /// X<integer_c> xic;
5865 TPL_TemplateTemplateArgumentMatch
5868 bool TemplateParameterListsAreEqual(TemplateParameterList *New,
5869 TemplateParameterList *Old,
5871 TemplateParameterListEqualKind Kind,
5872 SourceLocation TemplateArgLoc
5873 = SourceLocation());
5875 bool CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams);
5877 /// \brief Called when the parser has parsed a C++ typename
5878 /// specifier, e.g., "typename T::type".
5880 /// \param S The scope in which this typename type occurs.
5881 /// \param TypenameLoc the location of the 'typename' keyword
5882 /// \param SS the nested-name-specifier following the typename (e.g., 'T::').
5883 /// \param II the identifier we're retrieving (e.g., 'type' in the example).
5884 /// \param IdLoc the location of the identifier.
5886 ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
5887 const CXXScopeSpec &SS, const IdentifierInfo &II,
5888 SourceLocation IdLoc);
5890 /// \brief Called when the parser has parsed a C++ typename
5891 /// specifier that ends in a template-id, e.g.,
5892 /// "typename MetaFun::template apply<T1, T2>".
5894 /// \param S The scope in which this typename type occurs.
5895 /// \param TypenameLoc the location of the 'typename' keyword
5896 /// \param SS the nested-name-specifier following the typename (e.g., 'T::').
5897 /// \param TemplateLoc the location of the 'template' keyword, if any.
5898 /// \param TemplateName The template name.
5899 /// \param TemplateNameLoc The location of the template name.
5900 /// \param LAngleLoc The location of the opening angle bracket ('<').
5901 /// \param TemplateArgs The template arguments.
5902 /// \param RAngleLoc The location of the closing angle bracket ('>').
5904 ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
5905 const CXXScopeSpec &SS,
5906 SourceLocation TemplateLoc,
5907 TemplateTy TemplateName,
5908 SourceLocation TemplateNameLoc,
5909 SourceLocation LAngleLoc,
5910 ASTTemplateArgsPtr TemplateArgs,
5911 SourceLocation RAngleLoc);
5913 QualType CheckTypenameType(ElaboratedTypeKeyword Keyword,
5914 SourceLocation KeywordLoc,
5915 NestedNameSpecifierLoc QualifierLoc,
5916 const IdentifierInfo &II,
5917 SourceLocation IILoc);
5919 TypeSourceInfo *RebuildTypeInCurrentInstantiation(TypeSourceInfo *T,
5921 DeclarationName Name);
5922 bool RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS);
5924 ExprResult RebuildExprInCurrentInstantiation(Expr *E);
5925 bool RebuildTemplateParamsInCurrentInstantiation(
5926 TemplateParameterList *Params);
5929 getTemplateArgumentBindingsText(const TemplateParameterList *Params,
5930 const TemplateArgumentList &Args);
5933 getTemplateArgumentBindingsText(const TemplateParameterList *Params,
5934 const TemplateArgument *Args,
5937 //===--------------------------------------------------------------------===//
5938 // C++ Variadic Templates (C++0x [temp.variadic])
5939 //===--------------------------------------------------------------------===//
5941 /// Determine whether an unexpanded parameter pack might be permitted in this
5942 /// location. Useful for error recovery.
5943 bool isUnexpandedParameterPackPermitted();
5945 /// \brief The context in which an unexpanded parameter pack is
5946 /// being diagnosed.
5948 /// Note that the values of this enumeration line up with the first
5949 /// argument to the \c err_unexpanded_parameter_pack diagnostic.
5950 enum UnexpandedParameterPackContext {
5951 /// \brief An arbitrary expression.
5952 UPPC_Expression = 0,
5954 /// \brief The base type of a class type.
5957 /// \brief The type of an arbitrary declaration.
5958 UPPC_DeclarationType,
5960 /// \brief The type of a data member.
5961 UPPC_DataMemberType,
5963 /// \brief The size of a bit-field.
5966 /// \brief The expression in a static assertion.
5967 UPPC_StaticAssertExpression,
5969 /// \brief The fixed underlying type of an enumeration.
5970 UPPC_FixedUnderlyingType,
5972 /// \brief The enumerator value.
5973 UPPC_EnumeratorValue,
5975 /// \brief A using declaration.
5976 UPPC_UsingDeclaration,
5978 /// \brief A friend declaration.
5979 UPPC_FriendDeclaration,
5981 /// \brief A declaration qualifier.
5982 UPPC_DeclarationQualifier,
5984 /// \brief An initializer.
5987 /// \brief A default argument.
5988 UPPC_DefaultArgument,
5990 /// \brief The type of a non-type template parameter.
5991 UPPC_NonTypeTemplateParameterType,
5993 /// \brief The type of an exception.
5996 /// \brief Partial specialization.
5997 UPPC_PartialSpecialization,
5999 /// \brief Microsoft __if_exists.
6002 /// \brief Microsoft __if_not_exists.
6005 /// \brief Lambda expression.
6008 /// \brief Block expression,
6012 /// \brief Diagnose unexpanded parameter packs.
6014 /// \param Loc The location at which we should emit the diagnostic.
6016 /// \param UPPC The context in which we are diagnosing unexpanded
6017 /// parameter packs.
6019 /// \param Unexpanded the set of unexpanded parameter packs.
6021 /// \returns true if an error occurred, false otherwise.
6022 bool DiagnoseUnexpandedParameterPacks(SourceLocation Loc,
6023 UnexpandedParameterPackContext UPPC,
6024 ArrayRef<UnexpandedParameterPack> Unexpanded);
6026 /// \brief If the given type contains an unexpanded parameter pack,
6027 /// diagnose the error.
6029 /// \param Loc The source location where a diagnostc should be emitted.
6031 /// \param T The type that is being checked for unexpanded parameter
6034 /// \returns true if an error occurred, false otherwise.
6035 bool DiagnoseUnexpandedParameterPack(SourceLocation Loc, TypeSourceInfo *T,
6036 UnexpandedParameterPackContext UPPC);
6038 /// \brief If the given expression contains an unexpanded parameter
6039 /// pack, diagnose the error.
6041 /// \param E The expression that is being checked for unexpanded
6042 /// parameter packs.
6044 /// \returns true if an error occurred, false otherwise.
6045 bool DiagnoseUnexpandedParameterPack(Expr *E,
6046 UnexpandedParameterPackContext UPPC = UPPC_Expression);
6048 /// \brief If the given nested-name-specifier contains an unexpanded
6049 /// parameter pack, diagnose the error.
6051 /// \param SS The nested-name-specifier that is being checked for
6052 /// unexpanded parameter packs.
6054 /// \returns true if an error occurred, false otherwise.
6055 bool DiagnoseUnexpandedParameterPack(const CXXScopeSpec &SS,
6056 UnexpandedParameterPackContext UPPC);
6058 /// \brief If the given name contains an unexpanded parameter pack,
6059 /// diagnose the error.
6061 /// \param NameInfo The name (with source location information) that
6062 /// is being checked for unexpanded parameter packs.
6064 /// \returns true if an error occurred, false otherwise.
6065 bool DiagnoseUnexpandedParameterPack(const DeclarationNameInfo &NameInfo,
6066 UnexpandedParameterPackContext UPPC);
6068 /// \brief If the given template name contains an unexpanded parameter pack,
6069 /// diagnose the error.
6071 /// \param Loc The location of the template name.
6073 /// \param Template The template name that is being checked for unexpanded
6074 /// parameter packs.
6076 /// \returns true if an error occurred, false otherwise.
6077 bool DiagnoseUnexpandedParameterPack(SourceLocation Loc,
6078 TemplateName Template,
6079 UnexpandedParameterPackContext UPPC);
6081 /// \brief If the given template argument contains an unexpanded parameter
6082 /// pack, diagnose the error.
6084 /// \param Arg The template argument that is being checked for unexpanded
6085 /// parameter packs.
6087 /// \returns true if an error occurred, false otherwise.
6088 bool DiagnoseUnexpandedParameterPack(TemplateArgumentLoc Arg,
6089 UnexpandedParameterPackContext UPPC);
6091 /// \brief Collect the set of unexpanded parameter packs within the given
6092 /// template argument.
6094 /// \param Arg The template argument that will be traversed to find
6095 /// unexpanded parameter packs.
6096 void collectUnexpandedParameterPacks(TemplateArgument Arg,
6097 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
6099 /// \brief Collect the set of unexpanded parameter packs within the given
6100 /// template argument.
6102 /// \param Arg The template argument that will be traversed to find
6103 /// unexpanded parameter packs.
6104 void collectUnexpandedParameterPacks(TemplateArgumentLoc Arg,
6105 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
6107 /// \brief Collect the set of unexpanded parameter packs within the given
6110 /// \param T The type that will be traversed to find
6111 /// unexpanded parameter packs.
6112 void collectUnexpandedParameterPacks(QualType T,
6113 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
6115 /// \brief Collect the set of unexpanded parameter packs within the given
6118 /// \param TL The type that will be traversed to find
6119 /// unexpanded parameter packs.
6120 void collectUnexpandedParameterPacks(TypeLoc TL,
6121 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
6123 /// \brief Collect the set of unexpanded parameter packs within the given
6124 /// nested-name-specifier.
6126 /// \param SS The nested-name-specifier that will be traversed to find
6127 /// unexpanded parameter packs.
6128 void collectUnexpandedParameterPacks(CXXScopeSpec &SS,
6129 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
6131 /// \brief Collect the set of unexpanded parameter packs within the given
6134 /// \param NameInfo The name that will be traversed to find
6135 /// unexpanded parameter packs.
6136 void collectUnexpandedParameterPacks(const DeclarationNameInfo &NameInfo,
6137 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
6139 /// \brief Invoked when parsing a template argument followed by an
6140 /// ellipsis, which creates a pack expansion.
6142 /// \param Arg The template argument preceding the ellipsis, which
6143 /// may already be invalid.
6145 /// \param EllipsisLoc The location of the ellipsis.
6146 ParsedTemplateArgument ActOnPackExpansion(const ParsedTemplateArgument &Arg,
6147 SourceLocation EllipsisLoc);
6149 /// \brief Invoked when parsing a type followed by an ellipsis, which
6150 /// creates a pack expansion.
6152 /// \param Type The type preceding the ellipsis, which will become
6153 /// the pattern of the pack expansion.
6155 /// \param EllipsisLoc The location of the ellipsis.
6156 TypeResult ActOnPackExpansion(ParsedType Type, SourceLocation EllipsisLoc);
6158 /// \brief Construct a pack expansion type from the pattern of the pack
6160 TypeSourceInfo *CheckPackExpansion(TypeSourceInfo *Pattern,
6161 SourceLocation EllipsisLoc,
6162 Optional<unsigned> NumExpansions);
6164 /// \brief Construct a pack expansion type from the pattern of the pack
6166 QualType CheckPackExpansion(QualType Pattern,
6167 SourceRange PatternRange,
6168 SourceLocation EllipsisLoc,
6169 Optional<unsigned> NumExpansions);
6171 /// \brief Invoked when parsing an expression followed by an ellipsis, which
6172 /// creates a pack expansion.
6174 /// \param Pattern The expression preceding the ellipsis, which will become
6175 /// the pattern of the pack expansion.
6177 /// \param EllipsisLoc The location of the ellipsis.
6178 ExprResult ActOnPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc);
6180 /// \brief Invoked when parsing an expression followed by an ellipsis, which
6181 /// creates a pack expansion.
6183 /// \param Pattern The expression preceding the ellipsis, which will become
6184 /// the pattern of the pack expansion.
6186 /// \param EllipsisLoc The location of the ellipsis.
6187 ExprResult CheckPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc,
6188 Optional<unsigned> NumExpansions);
6190 /// \brief Determine whether we could expand a pack expansion with the
6191 /// given set of parameter packs into separate arguments by repeatedly
6192 /// transforming the pattern.
6194 /// \param EllipsisLoc The location of the ellipsis that identifies the
6197 /// \param PatternRange The source range that covers the entire pattern of
6198 /// the pack expansion.
6200 /// \param Unexpanded The set of unexpanded parameter packs within the
6203 /// \param ShouldExpand Will be set to \c true if the transformer should
6204 /// expand the corresponding pack expansions into separate arguments. When
6205 /// set, \c NumExpansions must also be set.
6207 /// \param RetainExpansion Whether the caller should add an unexpanded
6208 /// pack expansion after all of the expanded arguments. This is used
6209 /// when extending explicitly-specified template argument packs per
6210 /// C++0x [temp.arg.explicit]p9.
6212 /// \param NumExpansions The number of separate arguments that will be in
6213 /// the expanded form of the corresponding pack expansion. This is both an
6214 /// input and an output parameter, which can be set by the caller if the
6215 /// number of expansions is known a priori (e.g., due to a prior substitution)
6216 /// and will be set by the callee when the number of expansions is known.
6217 /// The callee must set this value when \c ShouldExpand is \c true; it may
6218 /// set this value in other cases.
6220 /// \returns true if an error occurred (e.g., because the parameter packs
6221 /// are to be instantiated with arguments of different lengths), false
6222 /// otherwise. If false, \c ShouldExpand (and possibly \c NumExpansions)
6224 bool CheckParameterPacksForExpansion(SourceLocation EllipsisLoc,
6225 SourceRange PatternRange,
6226 ArrayRef<UnexpandedParameterPack> Unexpanded,
6227 const MultiLevelTemplateArgumentList &TemplateArgs,
6229 bool &RetainExpansion,
6230 Optional<unsigned> &NumExpansions);
6232 /// \brief Determine the number of arguments in the given pack expansion
6235 /// This routine assumes that the number of arguments in the expansion is
6236 /// consistent across all of the unexpanded parameter packs in its pattern.
6238 /// Returns an empty Optional if the type can't be expanded.
6239 Optional<unsigned> getNumArgumentsInExpansion(QualType T,
6240 const MultiLevelTemplateArgumentList &TemplateArgs);
6242 /// \brief Determine whether the given declarator contains any unexpanded
6243 /// parameter packs.
6245 /// This routine is used by the parser to disambiguate function declarators
6246 /// with an ellipsis prior to the ')', e.g.,
6252 /// To determine whether we have an (unnamed) function parameter pack or
6253 /// a variadic function.
6255 /// \returns true if the declarator contains any unexpanded parameter packs,
6256 /// false otherwise.
6257 bool containsUnexpandedParameterPacks(Declarator &D);
6259 /// \brief Returns the pattern of the pack expansion for a template argument.
6261 /// \param OrigLoc The template argument to expand.
6263 /// \param Ellipsis Will be set to the location of the ellipsis.
6265 /// \param NumExpansions Will be set to the number of expansions that will
6266 /// be generated from this pack expansion, if known a priori.
6267 TemplateArgumentLoc getTemplateArgumentPackExpansionPattern(
6268 TemplateArgumentLoc OrigLoc,
6269 SourceLocation &Ellipsis,
6270 Optional<unsigned> &NumExpansions) const;
6272 //===--------------------------------------------------------------------===//
6273 // C++ Template Argument Deduction (C++ [temp.deduct])
6274 //===--------------------------------------------------------------------===//
6276 QualType adjustCCAndNoReturn(QualType ArgFunctionType, QualType FunctionType);
6278 /// \brief Describes the result of template argument deduction.
6280 /// The TemplateDeductionResult enumeration describes the result of
6281 /// template argument deduction, as returned from
6282 /// DeduceTemplateArguments(). The separate TemplateDeductionInfo
6283 /// structure provides additional information about the results of
6284 /// template argument deduction, e.g., the deduced template argument
6285 /// list (if successful) or the specific template parameters or
6286 /// deduced arguments that were involved in the failure.
6287 enum TemplateDeductionResult {
6288 /// \brief Template argument deduction was successful.
6290 /// \brief The declaration was invalid; do nothing.
6292 /// \brief Template argument deduction exceeded the maximum template
6293 /// instantiation depth (which has already been diagnosed).
6294 TDK_InstantiationDepth,
6295 /// \brief Template argument deduction did not deduce a value
6296 /// for every template parameter.
6298 /// \brief Template argument deduction produced inconsistent
6299 /// deduced values for the given template parameter.
6301 /// \brief Template argument deduction failed due to inconsistent
6302 /// cv-qualifiers on a template parameter type that would
6303 /// otherwise be deduced, e.g., we tried to deduce T in "const T"
6304 /// but were given a non-const "X".
6306 /// \brief Substitution of the deduced template argument values
6307 /// resulted in an error.
6308 TDK_SubstitutionFailure,
6309 /// \brief After substituting deduced template arguments, a dependent
6310 /// parameter type did not match the corresponding argument.
6311 TDK_DeducedMismatch,
6312 /// \brief A non-depnedent component of the parameter did not match the
6313 /// corresponding component of the argument.
6314 TDK_NonDeducedMismatch,
6315 /// \brief When performing template argument deduction for a function
6316 /// template, there were too many call arguments.
6317 TDK_TooManyArguments,
6318 /// \brief When performing template argument deduction for a function
6319 /// template, there were too few call arguments.
6320 TDK_TooFewArguments,
6321 /// \brief The explicitly-specified template arguments were not valid
6322 /// template arguments for the given template.
6323 TDK_InvalidExplicitArguments,
6324 /// \brief The arguments included an overloaded function name that could
6325 /// not be resolved to a suitable function.
6326 TDK_FailedOverloadResolution,
6327 /// \brief Deduction failed; that's all we know.
6328 TDK_MiscellaneousDeductionFailure
6331 TemplateDeductionResult
6332 DeduceTemplateArguments(ClassTemplatePartialSpecializationDecl *Partial,
6333 const TemplateArgumentList &TemplateArgs,
6334 sema::TemplateDeductionInfo &Info);
6336 TemplateDeductionResult
6337 DeduceTemplateArguments(VarTemplatePartialSpecializationDecl *Partial,
6338 const TemplateArgumentList &TemplateArgs,
6339 sema::TemplateDeductionInfo &Info);
6341 TemplateDeductionResult SubstituteExplicitTemplateArguments(
6342 FunctionTemplateDecl *FunctionTemplate,
6343 TemplateArgumentListInfo &ExplicitTemplateArgs,
6344 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
6345 SmallVectorImpl<QualType> &ParamTypes, QualType *FunctionType,
6346 sema::TemplateDeductionInfo &Info);
6348 /// brief A function argument from which we performed template argument
6349 // deduction for a call.
6350 struct OriginalCallArg {
6351 OriginalCallArg(QualType OriginalParamType,
6353 QualType OriginalArgType)
6354 : OriginalParamType(OriginalParamType), ArgIdx(ArgIdx),
6355 OriginalArgType(OriginalArgType) { }
6357 QualType OriginalParamType;
6359 QualType OriginalArgType;
6362 TemplateDeductionResult
6363 FinishTemplateArgumentDeduction(FunctionTemplateDecl *FunctionTemplate,
6364 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
6365 unsigned NumExplicitlySpecified,
6366 FunctionDecl *&Specialization,
6367 sema::TemplateDeductionInfo &Info,
6368 SmallVectorImpl<OriginalCallArg> const *OriginalCallArgs = nullptr,
6369 bool PartialOverloading = false);
6371 TemplateDeductionResult
6372 DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
6373 TemplateArgumentListInfo *ExplicitTemplateArgs,
6374 ArrayRef<Expr *> Args,
6375 FunctionDecl *&Specialization,
6376 sema::TemplateDeductionInfo &Info,
6377 bool PartialOverloading = false);
6379 TemplateDeductionResult
6380 DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
6381 TemplateArgumentListInfo *ExplicitTemplateArgs,
6382 QualType ArgFunctionType,
6383 FunctionDecl *&Specialization,
6384 sema::TemplateDeductionInfo &Info,
6385 bool InOverloadResolution = false);
6387 TemplateDeductionResult
6388 DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
6390 CXXConversionDecl *&Specialization,
6391 sema::TemplateDeductionInfo &Info);
6393 TemplateDeductionResult
6394 DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
6395 TemplateArgumentListInfo *ExplicitTemplateArgs,
6396 FunctionDecl *&Specialization,
6397 sema::TemplateDeductionInfo &Info,
6398 bool InOverloadResolution = false);
6400 /// \brief Substitute Replacement for \p auto in \p TypeWithAuto
6401 QualType SubstAutoType(QualType TypeWithAuto, QualType Replacement);
6402 /// \brief Substitute Replacement for auto in TypeWithAuto
6403 TypeSourceInfo* SubstAutoTypeSourceInfo(TypeSourceInfo *TypeWithAuto,
6404 QualType Replacement);
6406 /// \brief Result type of DeduceAutoType.
6407 enum DeduceAutoResult {
6410 DAR_FailedAlreadyDiagnosed
6413 DeduceAutoResult DeduceAutoType(TypeSourceInfo *AutoType, Expr *&Initializer,
6415 DeduceAutoResult DeduceAutoType(TypeLoc AutoTypeLoc, Expr *&Initializer,
6417 void DiagnoseAutoDeductionFailure(VarDecl *VDecl, Expr *Init);
6418 bool DeduceReturnType(FunctionDecl *FD, SourceLocation Loc,
6419 bool Diagnose = true);
6421 QualType deduceVarTypeFromInitializer(VarDecl *VDecl, DeclarationName Name,
6422 QualType Type, TypeSourceInfo *TSI,
6423 SourceRange Range, bool DirectInit,
6426 TypeLoc getReturnTypeLoc(FunctionDecl *FD) const;
6428 bool DeduceFunctionTypeFromReturnExpr(FunctionDecl *FD,
6429 SourceLocation ReturnLoc,
6430 Expr *&RetExpr, AutoType *AT);
6432 FunctionTemplateDecl *getMoreSpecializedTemplate(FunctionTemplateDecl *FT1,
6433 FunctionTemplateDecl *FT2,
6435 TemplatePartialOrderingContext TPOC,
6436 unsigned NumCallArguments1,
6437 unsigned NumCallArguments2);
6438 UnresolvedSetIterator
6439 getMostSpecialized(UnresolvedSetIterator SBegin, UnresolvedSetIterator SEnd,
6440 TemplateSpecCandidateSet &FailedCandidates,
6442 const PartialDiagnostic &NoneDiag,
6443 const PartialDiagnostic &AmbigDiag,
6444 const PartialDiagnostic &CandidateDiag,
6445 bool Complain = true, QualType TargetType = QualType());
6447 ClassTemplatePartialSpecializationDecl *
6448 getMoreSpecializedPartialSpecialization(
6449 ClassTemplatePartialSpecializationDecl *PS1,
6450 ClassTemplatePartialSpecializationDecl *PS2,
6451 SourceLocation Loc);
6453 VarTemplatePartialSpecializationDecl *getMoreSpecializedPartialSpecialization(
6454 VarTemplatePartialSpecializationDecl *PS1,
6455 VarTemplatePartialSpecializationDecl *PS2, SourceLocation Loc);
6457 void MarkUsedTemplateParameters(const TemplateArgumentList &TemplateArgs,
6460 llvm::SmallBitVector &Used);
6461 void MarkDeducedTemplateParameters(
6462 const FunctionTemplateDecl *FunctionTemplate,
6463 llvm::SmallBitVector &Deduced) {
6464 return MarkDeducedTemplateParameters(Context, FunctionTemplate, Deduced);
6466 static void MarkDeducedTemplateParameters(ASTContext &Ctx,
6467 const FunctionTemplateDecl *FunctionTemplate,
6468 llvm::SmallBitVector &Deduced);
6470 //===--------------------------------------------------------------------===//
6471 // C++ Template Instantiation
6474 MultiLevelTemplateArgumentList
6475 getTemplateInstantiationArgs(NamedDecl *D,
6476 const TemplateArgumentList *Innermost = nullptr,
6477 bool RelativeToPrimary = false,
6478 const FunctionDecl *Pattern = nullptr);
6480 /// \brief A template instantiation that is currently in progress.
6481 struct ActiveTemplateInstantiation {
6482 /// \brief The kind of template instantiation we are performing
6483 enum InstantiationKind {
6484 /// We are instantiating a template declaration. The entity is
6485 /// the declaration we're instantiating (e.g., a CXXRecordDecl).
6486 TemplateInstantiation,
6488 /// We are instantiating a default argument for a template
6489 /// parameter. The Entity is the template, and
6490 /// TemplateArgs/NumTemplateArguments provides the template
6491 /// arguments as specified.
6492 /// FIXME: Use a TemplateArgumentList
6493 DefaultTemplateArgumentInstantiation,
6495 /// We are instantiating a default argument for a function.
6496 /// The Entity is the ParmVarDecl, and TemplateArgs/NumTemplateArgs
6497 /// provides the template arguments as specified.
6498 DefaultFunctionArgumentInstantiation,
6500 /// We are substituting explicit template arguments provided for
6501 /// a function template. The entity is a FunctionTemplateDecl.
6502 ExplicitTemplateArgumentSubstitution,
6504 /// We are substituting template argument determined as part of
6505 /// template argument deduction for either a class template
6506 /// partial specialization or a function template. The
6507 /// Entity is either a ClassTemplatePartialSpecializationDecl or
6508 /// a FunctionTemplateDecl.
6509 DeducedTemplateArgumentSubstitution,
6511 /// We are substituting prior template arguments into a new
6512 /// template parameter. The template parameter itself is either a
6513 /// NonTypeTemplateParmDecl or a TemplateTemplateParmDecl.
6514 PriorTemplateArgumentSubstitution,
6516 /// We are checking the validity of a default template argument that
6517 /// has been used when naming a template-id.
6518 DefaultTemplateArgumentChecking,
6520 /// We are instantiating the exception specification for a function
6521 /// template which was deferred until it was needed.
6522 ExceptionSpecInstantiation
6525 /// \brief The point of instantiation within the source code.
6526 SourceLocation PointOfInstantiation;
6528 /// \brief The template (or partial specialization) in which we are
6529 /// performing the instantiation, for substitutions of prior template
6531 NamedDecl *Template;
6533 /// \brief The entity that is being instantiated.
6536 /// \brief The list of template arguments we are substituting, if they
6537 /// are not part of the entity.
6538 const TemplateArgument *TemplateArgs;
6540 /// \brief The number of template arguments in TemplateArgs.
6541 unsigned NumTemplateArgs;
6543 /// \brief The template deduction info object associated with the
6544 /// substitution or checking of explicit or deduced template arguments.
6545 sema::TemplateDeductionInfo *DeductionInfo;
6547 /// \brief The source range that covers the construct that cause
6548 /// the instantiation, e.g., the template-id that causes a class
6549 /// template instantiation.
6550 SourceRange InstantiationRange;
6552 ActiveTemplateInstantiation()
6553 : Kind(TemplateInstantiation), Template(nullptr), Entity(nullptr),
6554 TemplateArgs(nullptr), NumTemplateArgs(0), DeductionInfo(nullptr) {}
6556 /// \brief Determines whether this template is an actual instantiation
6557 /// that should be counted toward the maximum instantiation depth.
6558 bool isInstantiationRecord() const;
6560 friend bool operator==(const ActiveTemplateInstantiation &X,
6561 const ActiveTemplateInstantiation &Y) {
6562 if (X.Kind != Y.Kind)
6565 if (X.Entity != Y.Entity)
6569 case TemplateInstantiation:
6570 case ExceptionSpecInstantiation:
6573 case PriorTemplateArgumentSubstitution:
6574 case DefaultTemplateArgumentChecking:
6575 return X.Template == Y.Template && X.TemplateArgs == Y.TemplateArgs;
6577 case DefaultTemplateArgumentInstantiation:
6578 case ExplicitTemplateArgumentSubstitution:
6579 case DeducedTemplateArgumentSubstitution:
6580 case DefaultFunctionArgumentInstantiation:
6581 return X.TemplateArgs == Y.TemplateArgs;
6585 llvm_unreachable("Invalid InstantiationKind!");
6588 friend bool operator!=(const ActiveTemplateInstantiation &X,
6589 const ActiveTemplateInstantiation &Y) {
6594 /// \brief List of active template instantiations.
6596 /// This vector is treated as a stack. As one template instantiation
6597 /// requires another template instantiation, additional
6598 /// instantiations are pushed onto the stack up to a
6599 /// user-configurable limit LangOptions::InstantiationDepth.
6600 SmallVector<ActiveTemplateInstantiation, 16>
6601 ActiveTemplateInstantiations;
6603 /// \brief Extra modules inspected when performing a lookup during a template
6604 /// instantiation. Computed lazily.
6605 SmallVector<Module*, 16> ActiveTemplateInstantiationLookupModules;
6607 /// \brief Cache of additional modules that should be used for name lookup
6608 /// within the current template instantiation. Computed lazily; use
6609 /// getLookupModules() to get a complete set.
6610 llvm::DenseSet<Module*> LookupModulesCache;
6612 /// \brief Get the set of additional modules that should be checked during
6613 /// name lookup. A module and its imports become visible when instanting a
6614 /// template defined within it.
6615 llvm::DenseSet<Module*> &getLookupModules();
6617 /// \brief Whether we are in a SFINAE context that is not associated with
6618 /// template instantiation.
6620 /// This is used when setting up a SFINAE trap (\c see SFINAETrap) outside
6621 /// of a template instantiation or template argument deduction.
6622 bool InNonInstantiationSFINAEContext;
6624 /// \brief The number of ActiveTemplateInstantiation entries in
6625 /// \c ActiveTemplateInstantiations that are not actual instantiations and,
6626 /// therefore, should not be counted as part of the instantiation depth.
6627 unsigned NonInstantiationEntries;
6629 /// \brief The last template from which a template instantiation
6630 /// error or warning was produced.
6632 /// This value is used to suppress printing of redundant template
6633 /// instantiation backtraces when there are multiple errors in the
6634 /// same instantiation. FIXME: Does this belong in Sema? It's tough
6635 /// to implement it anywhere else.
6636 ActiveTemplateInstantiation LastTemplateInstantiationErrorContext;
6638 /// \brief The current index into pack expansion arguments that will be
6639 /// used for substitution of parameter packs.
6641 /// The pack expansion index will be -1 to indicate that parameter packs
6642 /// should be instantiated as themselves. Otherwise, the index specifies
6643 /// which argument within the parameter pack will be used for substitution.
6644 int ArgumentPackSubstitutionIndex;
6646 /// \brief RAII object used to change the argument pack substitution index
6647 /// within a \c Sema object.
6649 /// See \c ArgumentPackSubstitutionIndex for more information.
6650 class ArgumentPackSubstitutionIndexRAII {
6652 int OldSubstitutionIndex;
6655 ArgumentPackSubstitutionIndexRAII(Sema &Self, int NewSubstitutionIndex)
6656 : Self(Self), OldSubstitutionIndex(Self.ArgumentPackSubstitutionIndex) {
6657 Self.ArgumentPackSubstitutionIndex = NewSubstitutionIndex;
6660 ~ArgumentPackSubstitutionIndexRAII() {
6661 Self.ArgumentPackSubstitutionIndex = OldSubstitutionIndex;
6665 friend class ArgumentPackSubstitutionRAII;
6667 /// \brief For each declaration that involved template argument deduction, the
6668 /// set of diagnostics that were suppressed during that template argument
6671 /// FIXME: Serialize this structure to the AST file.
6672 typedef llvm::DenseMap<Decl *, SmallVector<PartialDiagnosticAt, 1> >
6673 SuppressedDiagnosticsMap;
6674 SuppressedDiagnosticsMap SuppressedDiagnostics;
6676 /// \brief A stack object to be created when performing template
6679 /// Construction of an object of type \c InstantiatingTemplate
6680 /// pushes the current instantiation onto the stack of active
6681 /// instantiations. If the size of this stack exceeds the maximum
6682 /// number of recursive template instantiations, construction
6683 /// produces an error and evaluates true.
6685 /// Destruction of this object will pop the named instantiation off
6687 struct InstantiatingTemplate {
6688 /// \brief Note that we are instantiating a class template,
6689 /// function template, variable template, alias template,
6690 /// or a member thereof.
6691 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
6693 SourceRange InstantiationRange = SourceRange());
6695 struct ExceptionSpecification {};
6696 /// \brief Note that we are instantiating an exception specification
6697 /// of a function template.
6698 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
6699 FunctionDecl *Entity, ExceptionSpecification,
6700 SourceRange InstantiationRange = SourceRange());
6702 /// \brief Note that we are instantiating a default argument in a
6704 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
6705 TemplateDecl *Template,
6706 ArrayRef<TemplateArgument> TemplateArgs,
6707 SourceRange InstantiationRange = SourceRange());
6709 /// \brief Note that we are instantiating a default argument in a
6711 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
6712 FunctionTemplateDecl *FunctionTemplate,
6713 ArrayRef<TemplateArgument> TemplateArgs,
6714 ActiveTemplateInstantiation::InstantiationKind Kind,
6715 sema::TemplateDeductionInfo &DeductionInfo,
6716 SourceRange InstantiationRange = SourceRange());
6718 /// \brief Note that we are instantiating as part of template
6719 /// argument deduction for a class template partial
6721 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
6722 ClassTemplatePartialSpecializationDecl *PartialSpec,
6723 ArrayRef<TemplateArgument> TemplateArgs,
6724 sema::TemplateDeductionInfo &DeductionInfo,
6725 SourceRange InstantiationRange = SourceRange());
6727 /// \brief Note that we are instantiating as part of template
6728 /// argument deduction for a variable template partial
6730 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
6731 VarTemplatePartialSpecializationDecl *PartialSpec,
6732 ArrayRef<TemplateArgument> TemplateArgs,
6733 sema::TemplateDeductionInfo &DeductionInfo,
6734 SourceRange InstantiationRange = SourceRange());
6736 /// \brief Note that we are instantiating a default argument for a function
6738 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
6740 ArrayRef<TemplateArgument> TemplateArgs,
6741 SourceRange InstantiationRange = SourceRange());
6743 /// \brief Note that we are substituting prior template arguments into a
6744 /// non-type parameter.
6745 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
6746 NamedDecl *Template,
6747 NonTypeTemplateParmDecl *Param,
6748 ArrayRef<TemplateArgument> TemplateArgs,
6749 SourceRange InstantiationRange);
6751 /// \brief Note that we are substituting prior template arguments into a
6752 /// template template parameter.
6753 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
6754 NamedDecl *Template,
6755 TemplateTemplateParmDecl *Param,
6756 ArrayRef<TemplateArgument> TemplateArgs,
6757 SourceRange InstantiationRange);
6759 /// \brief Note that we are checking the default template argument
6760 /// against the template parameter for a given template-id.
6761 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
6762 TemplateDecl *Template,
6764 ArrayRef<TemplateArgument> TemplateArgs,
6765 SourceRange InstantiationRange);
6768 /// \brief Note that we have finished instantiating this template.
6771 ~InstantiatingTemplate() { Clear(); }
6773 /// \brief Determines whether we have exceeded the maximum
6774 /// recursive template instantiations.
6775 bool isInvalid() const { return Invalid; }
6780 bool SavedInNonInstantiationSFINAEContext;
6781 bool CheckInstantiationDepth(SourceLocation PointOfInstantiation,
6782 SourceRange InstantiationRange);
6784 InstantiatingTemplate(
6785 Sema &SemaRef, ActiveTemplateInstantiation::InstantiationKind Kind,
6786 SourceLocation PointOfInstantiation, SourceRange InstantiationRange,
6787 Decl *Entity, NamedDecl *Template = nullptr,
6788 ArrayRef<TemplateArgument> TemplateArgs = None,
6789 sema::TemplateDeductionInfo *DeductionInfo = nullptr);
6791 InstantiatingTemplate(const InstantiatingTemplate&) = delete;
6793 InstantiatingTemplate&
6794 operator=(const InstantiatingTemplate&) = delete;
6797 void PrintInstantiationStack();
6799 /// \brief Determines whether we are currently in a context where
6800 /// template argument substitution failures are not considered
6803 /// \returns An empty \c Optional if we're not in a SFINAE context.
6804 /// Otherwise, contains a pointer that, if non-NULL, contains the nearest
6805 /// template-deduction context object, which can be used to capture
6806 /// diagnostics that will be suppressed.
6807 Optional<sema::TemplateDeductionInfo *> isSFINAEContext() const;
6809 /// \brief Determines whether we are currently in a context that
6810 /// is not evaluated as per C++ [expr] p5.
6811 bool isUnevaluatedContext() const {
6812 assert(!ExprEvalContexts.empty() &&
6813 "Must be in an expression evaluation context");
6814 return ExprEvalContexts.back().isUnevaluated();
6817 /// \brief RAII class used to determine whether SFINAE has
6818 /// trapped any errors that occur during template argument
6822 unsigned PrevSFINAEErrors;
6823 bool PrevInNonInstantiationSFINAEContext;
6824 bool PrevAccessCheckingSFINAE;
6827 explicit SFINAETrap(Sema &SemaRef, bool AccessCheckingSFINAE = false)
6828 : SemaRef(SemaRef), PrevSFINAEErrors(SemaRef.NumSFINAEErrors),
6829 PrevInNonInstantiationSFINAEContext(
6830 SemaRef.InNonInstantiationSFINAEContext),
6831 PrevAccessCheckingSFINAE(SemaRef.AccessCheckingSFINAE)
6833 if (!SemaRef.isSFINAEContext())
6834 SemaRef.InNonInstantiationSFINAEContext = true;
6835 SemaRef.AccessCheckingSFINAE = AccessCheckingSFINAE;
6839 SemaRef.NumSFINAEErrors = PrevSFINAEErrors;
6840 SemaRef.InNonInstantiationSFINAEContext
6841 = PrevInNonInstantiationSFINAEContext;
6842 SemaRef.AccessCheckingSFINAE = PrevAccessCheckingSFINAE;
6845 /// \brief Determine whether any SFINAE errors have been trapped.
6846 bool hasErrorOccurred() const {
6847 return SemaRef.NumSFINAEErrors > PrevSFINAEErrors;
6851 /// \brief RAII class used to indicate that we are performing provisional
6852 /// semantic analysis to determine the validity of a construct, so
6853 /// typo-correction and diagnostics in the immediate context (not within
6854 /// implicitly-instantiated templates) should be suppressed.
6855 class TentativeAnalysisScope {
6857 // FIXME: Using a SFINAETrap for this is a hack.
6859 bool PrevDisableTypoCorrection;
6861 explicit TentativeAnalysisScope(Sema &SemaRef)
6862 : SemaRef(SemaRef), Trap(SemaRef, true),
6863 PrevDisableTypoCorrection(SemaRef.DisableTypoCorrection) {
6864 SemaRef.DisableTypoCorrection = true;
6866 ~TentativeAnalysisScope() {
6867 SemaRef.DisableTypoCorrection = PrevDisableTypoCorrection;
6871 /// \brief The current instantiation scope used to store local
6873 LocalInstantiationScope *CurrentInstantiationScope;
6875 /// \brief Tracks whether we are in a context where typo correction is
6877 bool DisableTypoCorrection;
6879 /// \brief The number of typos corrected by CorrectTypo.
6880 unsigned TyposCorrected;
6882 typedef llvm::SmallSet<SourceLocation, 2> SrcLocSet;
6883 typedef llvm::DenseMap<IdentifierInfo *, SrcLocSet> IdentifierSourceLocations;
6885 /// \brief A cache containing identifiers for which typo correction failed and
6886 /// their locations, so that repeated attempts to correct an identifier in a
6887 /// given location are ignored if typo correction already failed for it.
6888 IdentifierSourceLocations TypoCorrectionFailures;
6890 /// \brief Worker object for performing CFG-based warnings.
6891 sema::AnalysisBasedWarnings AnalysisWarnings;
6892 threadSafety::BeforeSet *ThreadSafetyDeclCache;
6894 /// \brief An entity for which implicit template instantiation is required.
6896 /// The source location associated with the declaration is the first place in
6897 /// the source code where the declaration was "used". It is not necessarily
6898 /// the point of instantiation (which will be either before or after the
6899 /// namespace-scope declaration that triggered this implicit instantiation),
6900 /// However, it is the location that diagnostics should generally refer to,
6901 /// because users will need to know what code triggered the instantiation.
6902 typedef std::pair<ValueDecl *, SourceLocation> PendingImplicitInstantiation;
6904 /// \brief The queue of implicit template instantiations that are required
6905 /// but have not yet been performed.
6906 std::deque<PendingImplicitInstantiation> PendingInstantiations;
6908 class SavePendingInstantiationsAndVTableUsesRAII {
6910 SavePendingInstantiationsAndVTableUsesRAII(Sema &S, bool Enabled)
6911 : S(S), Enabled(Enabled) {
6912 if (!Enabled) return;
6914 SavedPendingInstantiations.swap(S.PendingInstantiations);
6915 SavedVTableUses.swap(S.VTableUses);
6918 ~SavePendingInstantiationsAndVTableUsesRAII() {
6919 if (!Enabled) return;
6921 // Restore the set of pending vtables.
6922 assert(S.VTableUses.empty() &&
6923 "VTableUses should be empty before it is discarded.");
6924 S.VTableUses.swap(SavedVTableUses);
6926 // Restore the set of pending implicit instantiations.
6927 assert(S.PendingInstantiations.empty() &&
6928 "PendingInstantiations should be empty before it is discarded.");
6929 S.PendingInstantiations.swap(SavedPendingInstantiations);
6934 SmallVector<VTableUse, 16> SavedVTableUses;
6935 std::deque<PendingImplicitInstantiation> SavedPendingInstantiations;
6939 /// \brief The queue of implicit template instantiations that are required
6940 /// and must be performed within the current local scope.
6942 /// This queue is only used for member functions of local classes in
6943 /// templates, which must be instantiated in the same scope as their
6944 /// enclosing function, so that they can reference function-local
6945 /// types, static variables, enumerators, etc.
6946 std::deque<PendingImplicitInstantiation> PendingLocalImplicitInstantiations;
6948 class SavePendingLocalImplicitInstantiationsRAII {
6950 SavePendingLocalImplicitInstantiationsRAII(Sema &S): S(S) {
6951 SavedPendingLocalImplicitInstantiations.swap(
6952 S.PendingLocalImplicitInstantiations);
6955 ~SavePendingLocalImplicitInstantiationsRAII() {
6956 assert(S.PendingLocalImplicitInstantiations.empty() &&
6957 "there shouldn't be any pending local implicit instantiations");
6958 SavedPendingLocalImplicitInstantiations.swap(
6959 S.PendingLocalImplicitInstantiations);
6964 std::deque<PendingImplicitInstantiation>
6965 SavedPendingLocalImplicitInstantiations;
6968 void PerformPendingInstantiations(bool LocalOnly = false);
6970 TypeSourceInfo *SubstType(TypeSourceInfo *T,
6971 const MultiLevelTemplateArgumentList &TemplateArgs,
6972 SourceLocation Loc, DeclarationName Entity);
6974 QualType SubstType(QualType T,
6975 const MultiLevelTemplateArgumentList &TemplateArgs,
6976 SourceLocation Loc, DeclarationName Entity);
6978 TypeSourceInfo *SubstType(TypeLoc TL,
6979 const MultiLevelTemplateArgumentList &TemplateArgs,
6980 SourceLocation Loc, DeclarationName Entity);
6982 TypeSourceInfo *SubstFunctionDeclType(TypeSourceInfo *T,
6983 const MultiLevelTemplateArgumentList &TemplateArgs,
6985 DeclarationName Entity,
6986 CXXRecordDecl *ThisContext,
6987 unsigned ThisTypeQuals);
6988 void SubstExceptionSpec(FunctionDecl *New, const FunctionProtoType *Proto,
6989 const MultiLevelTemplateArgumentList &Args);
6990 ParmVarDecl *SubstParmVarDecl(ParmVarDecl *D,
6991 const MultiLevelTemplateArgumentList &TemplateArgs,
6992 int indexAdjustment,
6993 Optional<unsigned> NumExpansions,
6994 bool ExpectParameterPack);
6995 bool SubstParmTypes(SourceLocation Loc,
6996 ParmVarDecl **Params, unsigned NumParams,
6997 const MultiLevelTemplateArgumentList &TemplateArgs,
6998 SmallVectorImpl<QualType> &ParamTypes,
6999 SmallVectorImpl<ParmVarDecl *> *OutParams = nullptr);
7000 ExprResult SubstExpr(Expr *E,
7001 const MultiLevelTemplateArgumentList &TemplateArgs);
7003 /// \brief Substitute the given template arguments into a list of
7004 /// expressions, expanding pack expansions if required.
7006 /// \param Exprs The list of expressions to substitute into.
7008 /// \param IsCall Whether this is some form of call, in which case
7009 /// default arguments will be dropped.
7011 /// \param TemplateArgs The set of template arguments to substitute.
7013 /// \param Outputs Will receive all of the substituted arguments.
7015 /// \returns true if an error occurred, false otherwise.
7016 bool SubstExprs(ArrayRef<Expr *> Exprs, bool IsCall,
7017 const MultiLevelTemplateArgumentList &TemplateArgs,
7018 SmallVectorImpl<Expr *> &Outputs);
7020 StmtResult SubstStmt(Stmt *S,
7021 const MultiLevelTemplateArgumentList &TemplateArgs);
7023 Decl *SubstDecl(Decl *D, DeclContext *Owner,
7024 const MultiLevelTemplateArgumentList &TemplateArgs);
7026 ExprResult SubstInitializer(Expr *E,
7027 const MultiLevelTemplateArgumentList &TemplateArgs,
7028 bool CXXDirectInit);
7031 SubstBaseSpecifiers(CXXRecordDecl *Instantiation,
7032 CXXRecordDecl *Pattern,
7033 const MultiLevelTemplateArgumentList &TemplateArgs);
7036 InstantiateClass(SourceLocation PointOfInstantiation,
7037 CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern,
7038 const MultiLevelTemplateArgumentList &TemplateArgs,
7039 TemplateSpecializationKind TSK,
7040 bool Complain = true);
7042 bool InstantiateEnum(SourceLocation PointOfInstantiation,
7043 EnumDecl *Instantiation, EnumDecl *Pattern,
7044 const MultiLevelTemplateArgumentList &TemplateArgs,
7045 TemplateSpecializationKind TSK);
7047 bool InstantiateInClassInitializer(
7048 SourceLocation PointOfInstantiation, FieldDecl *Instantiation,
7049 FieldDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs);
7051 struct LateInstantiatedAttribute {
7052 const Attr *TmplAttr;
7053 LocalInstantiationScope *Scope;
7056 LateInstantiatedAttribute(const Attr *A, LocalInstantiationScope *S,
7058 : TmplAttr(A), Scope(S), NewDecl(D)
7061 typedef SmallVector<LateInstantiatedAttribute, 16> LateInstantiatedAttrVec;
7063 void InstantiateAttrs(const MultiLevelTemplateArgumentList &TemplateArgs,
7064 const Decl *Pattern, Decl *Inst,
7065 LateInstantiatedAttrVec *LateAttrs = nullptr,
7066 LocalInstantiationScope *OuterMostScope = nullptr);
7069 InstantiateClassTemplateSpecialization(SourceLocation PointOfInstantiation,
7070 ClassTemplateSpecializationDecl *ClassTemplateSpec,
7071 TemplateSpecializationKind TSK,
7072 bool Complain = true);
7074 void InstantiateClassMembers(SourceLocation PointOfInstantiation,
7075 CXXRecordDecl *Instantiation,
7076 const MultiLevelTemplateArgumentList &TemplateArgs,
7077 TemplateSpecializationKind TSK);
7079 void InstantiateClassTemplateSpecializationMembers(
7080 SourceLocation PointOfInstantiation,
7081 ClassTemplateSpecializationDecl *ClassTemplateSpec,
7082 TemplateSpecializationKind TSK);
7084 NestedNameSpecifierLoc
7085 SubstNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS,
7086 const MultiLevelTemplateArgumentList &TemplateArgs);
7089 SubstDeclarationNameInfo(const DeclarationNameInfo &NameInfo,
7090 const MultiLevelTemplateArgumentList &TemplateArgs);
7092 SubstTemplateName(NestedNameSpecifierLoc QualifierLoc, TemplateName Name,
7094 const MultiLevelTemplateArgumentList &TemplateArgs);
7095 bool Subst(const TemplateArgumentLoc *Args, unsigned NumArgs,
7096 TemplateArgumentListInfo &Result,
7097 const MultiLevelTemplateArgumentList &TemplateArgs);
7099 void InstantiateExceptionSpec(SourceLocation PointOfInstantiation,
7100 FunctionDecl *Function);
7101 void InstantiateFunctionDefinition(SourceLocation PointOfInstantiation,
7102 FunctionDecl *Function,
7103 bool Recursive = false,
7104 bool DefinitionRequired = false);
7105 VarTemplateSpecializationDecl *BuildVarTemplateInstantiation(
7106 VarTemplateDecl *VarTemplate, VarDecl *FromVar,
7107 const TemplateArgumentList &TemplateArgList,
7108 const TemplateArgumentListInfo &TemplateArgsInfo,
7109 SmallVectorImpl<TemplateArgument> &Converted,
7110 SourceLocation PointOfInstantiation, void *InsertPos,
7111 LateInstantiatedAttrVec *LateAttrs = nullptr,
7112 LocalInstantiationScope *StartingScope = nullptr);
7113 VarTemplateSpecializationDecl *CompleteVarTemplateSpecializationDecl(
7114 VarTemplateSpecializationDecl *VarSpec, VarDecl *PatternDecl,
7115 const MultiLevelTemplateArgumentList &TemplateArgs);
7117 BuildVariableInstantiation(VarDecl *NewVar, VarDecl *OldVar,
7118 const MultiLevelTemplateArgumentList &TemplateArgs,
7119 LateInstantiatedAttrVec *LateAttrs,
7121 LocalInstantiationScope *StartingScope,
7122 bool InstantiatingVarTemplate = false);
7123 void InstantiateVariableInitializer(
7124 VarDecl *Var, VarDecl *OldVar,
7125 const MultiLevelTemplateArgumentList &TemplateArgs);
7126 void InstantiateVariableDefinition(SourceLocation PointOfInstantiation,
7127 VarDecl *Var, bool Recursive = false,
7128 bool DefinitionRequired = false);
7129 void InstantiateStaticDataMemberDefinition(
7130 SourceLocation PointOfInstantiation,
7132 bool Recursive = false,
7133 bool DefinitionRequired = false);
7135 void InstantiateMemInitializers(CXXConstructorDecl *New,
7136 const CXXConstructorDecl *Tmpl,
7137 const MultiLevelTemplateArgumentList &TemplateArgs);
7139 NamedDecl *FindInstantiatedDecl(SourceLocation Loc, NamedDecl *D,
7140 const MultiLevelTemplateArgumentList &TemplateArgs);
7141 DeclContext *FindInstantiatedContext(SourceLocation Loc, DeclContext *DC,
7142 const MultiLevelTemplateArgumentList &TemplateArgs);
7144 // Objective-C declarations.
7145 enum ObjCContainerKind {
7152 OCK_CategoryImplementation
7154 ObjCContainerKind getObjCContainerKind() const;
7156 DeclResult actOnObjCTypeParam(Scope *S,
7157 ObjCTypeParamVariance variance,
7158 SourceLocation varianceLoc,
7160 IdentifierInfo *paramName,
7161 SourceLocation paramLoc,
7162 SourceLocation colonLoc,
7163 ParsedType typeBound);
7165 ObjCTypeParamList *actOnObjCTypeParamList(Scope *S, SourceLocation lAngleLoc,
7166 ArrayRef<Decl *> typeParams,
7167 SourceLocation rAngleLoc);
7168 void popObjCTypeParamList(Scope *S, ObjCTypeParamList *typeParamList);
7170 Decl *ActOnStartClassInterface(Scope *S,
7171 SourceLocation AtInterfaceLoc,
7172 IdentifierInfo *ClassName,
7173 SourceLocation ClassLoc,
7174 ObjCTypeParamList *typeParamList,
7175 IdentifierInfo *SuperName,
7176 SourceLocation SuperLoc,
7177 ArrayRef<ParsedType> SuperTypeArgs,
7178 SourceRange SuperTypeArgsRange,
7179 Decl * const *ProtoRefs,
7180 unsigned NumProtoRefs,
7181 const SourceLocation *ProtoLocs,
7182 SourceLocation EndProtoLoc,
7183 AttributeList *AttrList);
7185 void ActOnSuperClassOfClassInterface(Scope *S,
7186 SourceLocation AtInterfaceLoc,
7187 ObjCInterfaceDecl *IDecl,
7188 IdentifierInfo *ClassName,
7189 SourceLocation ClassLoc,
7190 IdentifierInfo *SuperName,
7191 SourceLocation SuperLoc,
7192 ArrayRef<ParsedType> SuperTypeArgs,
7193 SourceRange SuperTypeArgsRange);
7195 void ActOnTypedefedProtocols(SmallVectorImpl<Decl *> &ProtocolRefs,
7196 IdentifierInfo *SuperName,
7197 SourceLocation SuperLoc);
7199 Decl *ActOnCompatibilityAlias(
7200 SourceLocation AtCompatibilityAliasLoc,
7201 IdentifierInfo *AliasName, SourceLocation AliasLocation,
7202 IdentifierInfo *ClassName, SourceLocation ClassLocation);
7204 bool CheckForwardProtocolDeclarationForCircularDependency(
7205 IdentifierInfo *PName,
7206 SourceLocation &PLoc, SourceLocation PrevLoc,
7207 const ObjCList<ObjCProtocolDecl> &PList);
7209 Decl *ActOnStartProtocolInterface(
7210 SourceLocation AtProtoInterfaceLoc,
7211 IdentifierInfo *ProtocolName, SourceLocation ProtocolLoc,
7212 Decl * const *ProtoRefNames, unsigned NumProtoRefs,
7213 const SourceLocation *ProtoLocs,
7214 SourceLocation EndProtoLoc,
7215 AttributeList *AttrList);
7217 Decl *ActOnStartCategoryInterface(SourceLocation AtInterfaceLoc,
7218 IdentifierInfo *ClassName,
7219 SourceLocation ClassLoc,
7220 ObjCTypeParamList *typeParamList,
7221 IdentifierInfo *CategoryName,
7222 SourceLocation CategoryLoc,
7223 Decl * const *ProtoRefs,
7224 unsigned NumProtoRefs,
7225 const SourceLocation *ProtoLocs,
7226 SourceLocation EndProtoLoc);
7228 Decl *ActOnStartClassImplementation(
7229 SourceLocation AtClassImplLoc,
7230 IdentifierInfo *ClassName, SourceLocation ClassLoc,
7231 IdentifierInfo *SuperClassname,
7232 SourceLocation SuperClassLoc);
7234 Decl *ActOnStartCategoryImplementation(SourceLocation AtCatImplLoc,
7235 IdentifierInfo *ClassName,
7236 SourceLocation ClassLoc,
7237 IdentifierInfo *CatName,
7238 SourceLocation CatLoc);
7240 DeclGroupPtrTy ActOnFinishObjCImplementation(Decl *ObjCImpDecl,
7241 ArrayRef<Decl *> Decls);
7243 DeclGroupPtrTy ActOnForwardClassDeclaration(SourceLocation Loc,
7244 IdentifierInfo **IdentList,
7245 SourceLocation *IdentLocs,
7246 ArrayRef<ObjCTypeParamList *> TypeParamLists,
7249 DeclGroupPtrTy ActOnForwardProtocolDeclaration(SourceLocation AtProtoclLoc,
7250 ArrayRef<IdentifierLocPair> IdentList,
7251 AttributeList *attrList);
7253 void FindProtocolDeclaration(bool WarnOnDeclarations, bool ForObjCContainer,
7254 ArrayRef<IdentifierLocPair> ProtocolId,
7255 SmallVectorImpl<Decl *> &Protocols);
7257 /// Given a list of identifiers (and their locations), resolve the
7258 /// names to either Objective-C protocol qualifiers or type
7259 /// arguments, as appropriate.
7260 void actOnObjCTypeArgsOrProtocolQualifiers(
7262 ParsedType baseType,
7263 SourceLocation lAngleLoc,
7264 ArrayRef<IdentifierInfo *> identifiers,
7265 ArrayRef<SourceLocation> identifierLocs,
7266 SourceLocation rAngleLoc,
7267 SourceLocation &typeArgsLAngleLoc,
7268 SmallVectorImpl<ParsedType> &typeArgs,
7269 SourceLocation &typeArgsRAngleLoc,
7270 SourceLocation &protocolLAngleLoc,
7271 SmallVectorImpl<Decl *> &protocols,
7272 SourceLocation &protocolRAngleLoc,
7273 bool warnOnIncompleteProtocols);
7275 /// Build a an Objective-C protocol-qualified 'id' type where no
7276 /// base type was specified.
7277 TypeResult actOnObjCProtocolQualifierType(
7278 SourceLocation lAngleLoc,
7279 ArrayRef<Decl *> protocols,
7280 ArrayRef<SourceLocation> protocolLocs,
7281 SourceLocation rAngleLoc);
7283 /// Build a specialized and/or protocol-qualified Objective-C type.
7284 TypeResult actOnObjCTypeArgsAndProtocolQualifiers(
7287 ParsedType BaseType,
7288 SourceLocation TypeArgsLAngleLoc,
7289 ArrayRef<ParsedType> TypeArgs,
7290 SourceLocation TypeArgsRAngleLoc,
7291 SourceLocation ProtocolLAngleLoc,
7292 ArrayRef<Decl *> Protocols,
7293 ArrayRef<SourceLocation> ProtocolLocs,
7294 SourceLocation ProtocolRAngleLoc);
7296 /// Build an Objective-C object pointer type.
7297 QualType BuildObjCObjectType(QualType BaseType,
7299 SourceLocation TypeArgsLAngleLoc,
7300 ArrayRef<TypeSourceInfo *> TypeArgs,
7301 SourceLocation TypeArgsRAngleLoc,
7302 SourceLocation ProtocolLAngleLoc,
7303 ArrayRef<ObjCProtocolDecl *> Protocols,
7304 ArrayRef<SourceLocation> ProtocolLocs,
7305 SourceLocation ProtocolRAngleLoc,
7306 bool FailOnError = false);
7308 /// Check the application of the Objective-C '__kindof' qualifier to
7310 bool checkObjCKindOfType(QualType &type, SourceLocation loc);
7312 /// Ensure attributes are consistent with type.
7313 /// \param [in, out] Attributes The attributes to check; they will
7314 /// be modified to be consistent with \p PropertyTy.
7315 void CheckObjCPropertyAttributes(Decl *PropertyPtrTy,
7317 unsigned &Attributes,
7318 bool propertyInPrimaryClass);
7320 /// Process the specified property declaration and create decls for the
7321 /// setters and getters as needed.
7322 /// \param property The property declaration being processed
7323 void ProcessPropertyDecl(ObjCPropertyDecl *property);
7326 void DiagnosePropertyMismatch(ObjCPropertyDecl *Property,
7327 ObjCPropertyDecl *SuperProperty,
7328 const IdentifierInfo *Name,
7329 bool OverridingProtocolProperty);
7331 void DiagnoseClassExtensionDupMethods(ObjCCategoryDecl *CAT,
7332 ObjCInterfaceDecl *ID);
7334 Decl *ActOnAtEnd(Scope *S, SourceRange AtEnd,
7335 ArrayRef<Decl *> allMethods = None,
7336 ArrayRef<DeclGroupPtrTy> allTUVars = None);
7338 Decl *ActOnProperty(Scope *S, SourceLocation AtLoc,
7339 SourceLocation LParenLoc,
7340 FieldDeclarator &FD, ObjCDeclSpec &ODS,
7341 Selector GetterSel, Selector SetterSel,
7342 tok::ObjCKeywordKind MethodImplKind,
7343 DeclContext *lexicalDC = nullptr);
7345 Decl *ActOnPropertyImplDecl(Scope *S,
7346 SourceLocation AtLoc,
7347 SourceLocation PropertyLoc,
7349 IdentifierInfo *PropertyId,
7350 IdentifierInfo *PropertyIvar,
7351 SourceLocation PropertyIvarLoc);
7353 enum ObjCSpecialMethodKind {
7359 OSMK_NonRetainingInit
7362 struct ObjCArgInfo {
7363 IdentifierInfo *Name;
7364 SourceLocation NameLoc;
7365 // The Type is null if no type was specified, and the DeclSpec is invalid
7368 ObjCDeclSpec DeclSpec;
7370 /// ArgAttrs - Attribute list for this argument.
7371 AttributeList *ArgAttrs;
7374 Decl *ActOnMethodDeclaration(
7376 SourceLocation BeginLoc, // location of the + or -.
7377 SourceLocation EndLoc, // location of the ; or {.
7378 tok::TokenKind MethodType,
7379 ObjCDeclSpec &ReturnQT, ParsedType ReturnType,
7380 ArrayRef<SourceLocation> SelectorLocs, Selector Sel,
7381 // optional arguments. The number of types/arguments is obtained
7382 // from the Sel.getNumArgs().
7383 ObjCArgInfo *ArgInfo,
7384 DeclaratorChunk::ParamInfo *CParamInfo, unsigned CNumArgs, // c-style args
7385 AttributeList *AttrList, tok::ObjCKeywordKind MethodImplKind,
7386 bool isVariadic, bool MethodDefinition);
7388 ObjCMethodDecl *LookupMethodInQualifiedType(Selector Sel,
7389 const ObjCObjectPointerType *OPT,
7391 ObjCMethodDecl *LookupMethodInObjectType(Selector Sel, QualType Ty,
7394 bool CheckARCMethodDecl(ObjCMethodDecl *method);
7395 bool inferObjCARCLifetime(ValueDecl *decl);
7398 HandleExprPropertyRefExpr(const ObjCObjectPointerType *OPT,
7400 SourceLocation OpLoc,
7401 DeclarationName MemberName,
7402 SourceLocation MemberLoc,
7403 SourceLocation SuperLoc, QualType SuperType,
7407 ActOnClassPropertyRefExpr(IdentifierInfo &receiverName,
7408 IdentifierInfo &propertyName,
7409 SourceLocation receiverNameLoc,
7410 SourceLocation propertyNameLoc);
7412 ObjCMethodDecl *tryCaptureObjCSelf(SourceLocation Loc);
7414 /// \brief Describes the kind of message expression indicated by a message
7415 /// send that starts with an identifier.
7416 enum ObjCMessageKind {
7417 /// \brief The message is sent to 'super'.
7419 /// \brief The message is an instance message.
7420 ObjCInstanceMessage,
7421 /// \brief The message is a class message, and the identifier is a type
7426 ObjCMessageKind getObjCMessageKind(Scope *S,
7427 IdentifierInfo *Name,
7428 SourceLocation NameLoc,
7430 bool HasTrailingDot,
7431 ParsedType &ReceiverType);
7433 ExprResult ActOnSuperMessage(Scope *S, SourceLocation SuperLoc,
7435 SourceLocation LBracLoc,
7436 ArrayRef<SourceLocation> SelectorLocs,
7437 SourceLocation RBracLoc,
7440 ExprResult BuildClassMessage(TypeSourceInfo *ReceiverTypeInfo,
7441 QualType ReceiverType,
7442 SourceLocation SuperLoc,
7444 ObjCMethodDecl *Method,
7445 SourceLocation LBracLoc,
7446 ArrayRef<SourceLocation> SelectorLocs,
7447 SourceLocation RBracLoc,
7449 bool isImplicit = false);
7451 ExprResult BuildClassMessageImplicit(QualType ReceiverType,
7452 bool isSuperReceiver,
7455 ObjCMethodDecl *Method,
7458 ExprResult ActOnClassMessage(Scope *S,
7459 ParsedType Receiver,
7461 SourceLocation LBracLoc,
7462 ArrayRef<SourceLocation> SelectorLocs,
7463 SourceLocation RBracLoc,
7466 ExprResult BuildInstanceMessage(Expr *Receiver,
7467 QualType ReceiverType,
7468 SourceLocation SuperLoc,
7470 ObjCMethodDecl *Method,
7471 SourceLocation LBracLoc,
7472 ArrayRef<SourceLocation> SelectorLocs,
7473 SourceLocation RBracLoc,
7475 bool isImplicit = false);
7477 ExprResult BuildInstanceMessageImplicit(Expr *Receiver,
7478 QualType ReceiverType,
7481 ObjCMethodDecl *Method,
7484 ExprResult ActOnInstanceMessage(Scope *S,
7487 SourceLocation LBracLoc,
7488 ArrayRef<SourceLocation> SelectorLocs,
7489 SourceLocation RBracLoc,
7492 ExprResult BuildObjCBridgedCast(SourceLocation LParenLoc,
7493 ObjCBridgeCastKind Kind,
7494 SourceLocation BridgeKeywordLoc,
7495 TypeSourceInfo *TSInfo,
7498 ExprResult ActOnObjCBridgedCast(Scope *S,
7499 SourceLocation LParenLoc,
7500 ObjCBridgeCastKind Kind,
7501 SourceLocation BridgeKeywordLoc,
7503 SourceLocation RParenLoc,
7506 void CheckTollFreeBridgeCast(QualType castType, Expr *castExpr);
7508 void CheckObjCBridgeRelatedCast(QualType castType, Expr *castExpr);
7510 bool CheckTollFreeBridgeStaticCast(QualType castType, Expr *castExpr,
7513 bool checkObjCBridgeRelatedComponents(SourceLocation Loc,
7514 QualType DestType, QualType SrcType,
7515 ObjCInterfaceDecl *&RelatedClass,
7516 ObjCMethodDecl *&ClassMethod,
7517 ObjCMethodDecl *&InstanceMethod,
7518 TypedefNameDecl *&TDNDecl,
7519 bool CfToNs, bool Diagnose = true);
7521 bool CheckObjCBridgeRelatedConversions(SourceLocation Loc,
7522 QualType DestType, QualType SrcType,
7523 Expr *&SrcExpr, bool Diagnose = true);
7525 bool ConversionToObjCStringLiteralCheck(QualType DstType, Expr *&SrcExpr,
7526 bool Diagnose = true);
7528 bool checkInitMethod(ObjCMethodDecl *method, QualType receiverTypeIfCall);
7530 /// \brief Check whether the given new method is a valid override of the
7531 /// given overridden method, and set any properties that should be inherited.
7532 void CheckObjCMethodOverride(ObjCMethodDecl *NewMethod,
7533 const ObjCMethodDecl *Overridden);
7535 /// \brief Describes the compatibility of a result type with its method.
7536 enum ResultTypeCompatibilityKind {
7542 void CheckObjCMethodOverrides(ObjCMethodDecl *ObjCMethod,
7543 ObjCInterfaceDecl *CurrentClass,
7544 ResultTypeCompatibilityKind RTC);
7546 enum PragmaOptionsAlignKind {
7547 POAK_Native, // #pragma options align=native
7548 POAK_Natural, // #pragma options align=natural
7549 POAK_Packed, // #pragma options align=packed
7550 POAK_Power, // #pragma options align=power
7551 POAK_Mac68k, // #pragma options align=mac68k
7552 POAK_Reset // #pragma options align=reset
7555 /// ActOnPragmaOptionsAlign - Called on well formed \#pragma options align.
7556 void ActOnPragmaOptionsAlign(PragmaOptionsAlignKind Kind,
7557 SourceLocation PragmaLoc);
7559 enum PragmaPackKind {
7560 PPK_Default, // #pragma pack([n])
7561 PPK_Show, // #pragma pack(show), only supported by MSVC.
7562 PPK_Push, // #pragma pack(push, [identifier], [n])
7563 PPK_Pop // #pragma pack(pop, [identifier], [n])
7566 enum PragmaMSStructKind {
7567 PMSST_OFF, // #pragms ms_struct off
7568 PMSST_ON // #pragms ms_struct on
7571 enum PragmaMSCommentKind {
7573 PCK_Linker, // #pragma comment(linker, ...)
7574 PCK_Lib, // #pragma comment(lib, ...)
7575 PCK_Compiler, // #pragma comment(compiler, ...)
7576 PCK_ExeStr, // #pragma comment(exestr, ...)
7577 PCK_User // #pragma comment(user, ...)
7580 /// ActOnPragmaPack - Called on well formed \#pragma pack(...).
7581 void ActOnPragmaPack(PragmaPackKind Kind,
7582 IdentifierInfo *Name,
7584 SourceLocation PragmaLoc,
7585 SourceLocation LParenLoc,
7586 SourceLocation RParenLoc);
7588 /// ActOnPragmaMSStruct - Called on well formed \#pragma ms_struct [on|off].
7589 void ActOnPragmaMSStruct(PragmaMSStructKind Kind);
7591 /// ActOnPragmaMSComment - Called on well formed
7592 /// \#pragma comment(kind, "arg").
7593 void ActOnPragmaMSComment(PragmaMSCommentKind Kind, StringRef Arg);
7595 /// ActOnPragmaMSPointersToMembers - called on well formed \#pragma
7596 /// pointers_to_members(representation method[, general purpose
7597 /// representation]).
7598 void ActOnPragmaMSPointersToMembers(
7599 LangOptions::PragmaMSPointersToMembersKind Kind,
7600 SourceLocation PragmaLoc);
7602 /// \brief Called on well formed \#pragma vtordisp().
7603 void ActOnPragmaMSVtorDisp(PragmaVtorDispKind Kind, SourceLocation PragmaLoc,
7604 MSVtorDispAttr::Mode Value);
7606 enum PragmaSectionKind {
7613 bool UnifySection(StringRef SectionName,
7615 DeclaratorDecl *TheDecl);
7616 bool UnifySection(StringRef SectionName,
7618 SourceLocation PragmaSectionLocation);
7620 /// \brief Called on well formed \#pragma bss_seg/data_seg/const_seg/code_seg.
7621 void ActOnPragmaMSSeg(SourceLocation PragmaLocation,
7622 PragmaMsStackAction Action,
7623 llvm::StringRef StackSlotLabel,
7624 StringLiteral *SegmentName,
7625 llvm::StringRef PragmaName);
7627 /// \brief Called on well formed \#pragma section().
7628 void ActOnPragmaMSSection(SourceLocation PragmaLocation,
7629 int SectionFlags, StringLiteral *SegmentName);
7631 /// \brief Called on well-formed \#pragma init_seg().
7632 void ActOnPragmaMSInitSeg(SourceLocation PragmaLocation,
7633 StringLiteral *SegmentName);
7635 /// \brief Called on #pragma clang __debug dump II
7636 void ActOnPragmaDump(Scope *S, SourceLocation Loc, IdentifierInfo *II);
7638 /// ActOnPragmaDetectMismatch - Call on well-formed \#pragma detect_mismatch
7639 void ActOnPragmaDetectMismatch(StringRef Name, StringRef Value);
7641 /// ActOnPragmaUnused - Called on well-formed '\#pragma unused'.
7642 void ActOnPragmaUnused(const Token &Identifier,
7644 SourceLocation PragmaLoc);
7646 /// ActOnPragmaVisibility - Called on well formed \#pragma GCC visibility... .
7647 void ActOnPragmaVisibility(const IdentifierInfo* VisType,
7648 SourceLocation PragmaLoc);
7650 NamedDecl *DeclClonePragmaWeak(NamedDecl *ND, IdentifierInfo *II,
7651 SourceLocation Loc);
7652 void DeclApplyPragmaWeak(Scope *S, NamedDecl *ND, WeakInfo &W);
7654 /// ActOnPragmaWeakID - Called on well formed \#pragma weak ident.
7655 void ActOnPragmaWeakID(IdentifierInfo* WeakName,
7656 SourceLocation PragmaLoc,
7657 SourceLocation WeakNameLoc);
7659 /// ActOnPragmaRedefineExtname - Called on well formed
7660 /// \#pragma redefine_extname oldname newname.
7661 void ActOnPragmaRedefineExtname(IdentifierInfo* WeakName,
7662 IdentifierInfo* AliasName,
7663 SourceLocation PragmaLoc,
7664 SourceLocation WeakNameLoc,
7665 SourceLocation AliasNameLoc);
7667 /// ActOnPragmaWeakAlias - Called on well formed \#pragma weak ident = ident.
7668 void ActOnPragmaWeakAlias(IdentifierInfo* WeakName,
7669 IdentifierInfo* AliasName,
7670 SourceLocation PragmaLoc,
7671 SourceLocation WeakNameLoc,
7672 SourceLocation AliasNameLoc);
7674 /// ActOnPragmaFPContract - Called on well formed
7675 /// \#pragma {STDC,OPENCL} FP_CONTRACT
7676 void ActOnPragmaFPContract(tok::OnOffSwitch OOS);
7678 /// AddAlignmentAttributesForRecord - Adds any needed alignment attributes to
7679 /// a the record decl, to handle '\#pragma pack' and '\#pragma options align'.
7680 void AddAlignmentAttributesForRecord(RecordDecl *RD);
7682 /// AddMsStructLayoutForRecord - Adds ms_struct layout attribute to record.
7683 void AddMsStructLayoutForRecord(RecordDecl *RD);
7685 /// FreePackedContext - Deallocate and null out PackContext.
7686 void FreePackedContext();
7688 /// PushNamespaceVisibilityAttr - Note that we've entered a
7689 /// namespace with a visibility attribute.
7690 void PushNamespaceVisibilityAttr(const VisibilityAttr *Attr,
7691 SourceLocation Loc);
7693 /// AddPushedVisibilityAttribute - If '\#pragma GCC visibility' was used,
7694 /// add an appropriate visibility attribute.
7695 void AddPushedVisibilityAttribute(Decl *RD);
7697 /// PopPragmaVisibility - Pop the top element of the visibility stack; used
7698 /// for '\#pragma GCC visibility' and visibility attributes on namespaces.
7699 void PopPragmaVisibility(bool IsNamespaceEnd, SourceLocation EndLoc);
7701 /// FreeVisContext - Deallocate and null out VisContext.
7702 void FreeVisContext();
7704 /// AddCFAuditedAttribute - Check whether we're currently within
7705 /// '\#pragma clang arc_cf_code_audited' and, if so, consider adding
7706 /// the appropriate attribute.
7707 void AddCFAuditedAttribute(Decl *D);
7709 /// \brief Called on well formed \#pragma clang optimize.
7710 void ActOnPragmaOptimize(bool On, SourceLocation PragmaLoc);
7712 /// \brief Get the location for the currently active "\#pragma clang optimize
7713 /// off". If this location is invalid, then the state of the pragma is "on".
7714 SourceLocation getOptimizeOffPragmaLocation() const {
7715 return OptimizeOffPragmaLocation;
7718 /// \brief Only called on function definitions; if there is a pragma in scope
7719 /// with the effect of a range-based optnone, consider marking the function
7720 /// with attribute optnone.
7721 void AddRangeBasedOptnone(FunctionDecl *FD);
7723 /// \brief Adds the 'optnone' attribute to the function declaration if there
7724 /// are no conflicts; Loc represents the location causing the 'optnone'
7725 /// attribute to be added (usually because of a pragma).
7726 void AddOptnoneAttributeIfNoConflicts(FunctionDecl *FD, SourceLocation Loc);
7728 /// AddAlignedAttr - Adds an aligned attribute to a particular declaration.
7729 void AddAlignedAttr(SourceRange AttrRange, Decl *D, Expr *E,
7730 unsigned SpellingListIndex, bool IsPackExpansion);
7731 void AddAlignedAttr(SourceRange AttrRange, Decl *D, TypeSourceInfo *T,
7732 unsigned SpellingListIndex, bool IsPackExpansion);
7734 /// AddAssumeAlignedAttr - Adds an assume_aligned attribute to a particular
7736 void AddAssumeAlignedAttr(SourceRange AttrRange, Decl *D, Expr *E, Expr *OE,
7737 unsigned SpellingListIndex);
7739 /// AddAlignValueAttr - Adds an align_value attribute to a particular
7741 void AddAlignValueAttr(SourceRange AttrRange, Decl *D, Expr *E,
7742 unsigned SpellingListIndex);
7744 /// AddLaunchBoundsAttr - Adds a launch_bounds attribute to a particular
7746 void AddLaunchBoundsAttr(SourceRange AttrRange, Decl *D, Expr *MaxThreads,
7747 Expr *MinBlocks, unsigned SpellingListIndex);
7749 //===--------------------------------------------------------------------===//
7750 // C++ Coroutines TS
7752 ExprResult ActOnCoawaitExpr(Scope *S, SourceLocation KwLoc, Expr *E);
7753 ExprResult ActOnCoyieldExpr(Scope *S, SourceLocation KwLoc, Expr *E);
7754 StmtResult ActOnCoreturnStmt(SourceLocation KwLoc, Expr *E);
7756 ExprResult BuildCoawaitExpr(SourceLocation KwLoc, Expr *E);
7757 ExprResult BuildCoyieldExpr(SourceLocation KwLoc, Expr *E);
7758 StmtResult BuildCoreturnStmt(SourceLocation KwLoc, Expr *E);
7760 void CheckCompletedCoroutineBody(FunctionDecl *FD, Stmt *&Body);
7762 //===--------------------------------------------------------------------===//
7763 // OpenMP directives and clauses.
7766 void *VarDataSharingAttributesStack;
7767 /// \brief Initialization of data-sharing attributes stack.
7768 void InitDataSharingAttributesStack();
7769 void DestroyDataSharingAttributesStack();
7771 VerifyPositiveIntegerConstantInClause(Expr *Op, OpenMPClauseKind CKind,
7772 bool StrictlyPositive = true);
7775 /// \brief Return true if the provided declaration \a VD should be captured by
7776 /// reference in the provided scope \a RSI. This will take into account the
7777 /// semantics of the directive and associated clauses.
7778 bool IsOpenMPCapturedByRef(VarDecl *VD,
7779 const sema::CapturedRegionScopeInfo *RSI);
7781 /// \brief Check if the specified variable is used in one of the private
7782 /// clauses (private, firstprivate, lastprivate, reduction etc.) in OpenMP
7784 bool IsOpenMPCapturedVar(VarDecl *VD);
7786 /// \brief Check if the specified variable is used in 'private' clause.
7787 /// \param Level Relative level of nested OpenMP construct for that the check
7789 bool isOpenMPPrivateVar(VarDecl *VD, unsigned Level);
7791 /// \brief Check if the specified variable is captured by 'target' directive.
7792 /// \param Level Relative level of nested OpenMP construct for that the check
7794 bool isOpenMPTargetCapturedVar(VarDecl *VD, unsigned Level);
7796 ExprResult PerformOpenMPImplicitIntegerConversion(SourceLocation OpLoc,
7798 /// \brief Called on start of new data sharing attribute block.
7799 void StartOpenMPDSABlock(OpenMPDirectiveKind K,
7800 const DeclarationNameInfo &DirName, Scope *CurScope,
7801 SourceLocation Loc);
7802 /// \brief Start analysis of clauses.
7803 void StartOpenMPClause(OpenMPClauseKind K);
7804 /// \brief End analysis of clauses.
7805 void EndOpenMPClause();
7806 /// \brief Called on end of data sharing attribute block.
7807 void EndOpenMPDSABlock(Stmt *CurDirective);
7809 /// \brief Check if the current region is an OpenMP loop region and if it is,
7810 /// mark loop control variable, used in \p Init for loop initialization, as
7811 /// private by default.
7812 /// \param Init First part of the for loop.
7813 void ActOnOpenMPLoopInitialization(SourceLocation ForLoc, Stmt *Init);
7815 // OpenMP directives and clauses.
7816 /// \brief Called on correct id-expression from the '#pragma omp
7818 ExprResult ActOnOpenMPIdExpression(Scope *CurScope,
7819 CXXScopeSpec &ScopeSpec,
7820 const DeclarationNameInfo &Id);
7821 /// \brief Called on well-formed '#pragma omp threadprivate'.
7822 DeclGroupPtrTy ActOnOpenMPThreadprivateDirective(
7824 ArrayRef<Expr *> VarList);
7825 /// \brief Builds a new OpenMPThreadPrivateDecl and checks its correctness.
7826 OMPThreadPrivateDecl *CheckOMPThreadPrivateDecl(
7828 ArrayRef<Expr *> VarList);
7830 /// \brief Initialization of captured region for OpenMP region.
7831 void ActOnOpenMPRegionStart(OpenMPDirectiveKind DKind, Scope *CurScope);
7832 /// \brief End of OpenMP region.
7834 /// \param S Statement associated with the current OpenMP region.
7835 /// \param Clauses List of clauses for the current OpenMP region.
7837 /// \returns Statement for finished OpenMP region.
7838 StmtResult ActOnOpenMPRegionEnd(StmtResult S, ArrayRef<OMPClause *> Clauses);
7839 StmtResult ActOnOpenMPExecutableDirective(
7840 OpenMPDirectiveKind Kind, const DeclarationNameInfo &DirName,
7841 OpenMPDirectiveKind CancelRegion, ArrayRef<OMPClause *> Clauses,
7842 Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc);
7843 /// \brief Called on well-formed '\#pragma omp parallel' after parsing
7844 /// of the associated statement.
7845 StmtResult ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses,
7847 SourceLocation StartLoc,
7848 SourceLocation EndLoc);
7849 /// \brief Called on well-formed '\#pragma omp simd' after parsing
7850 /// of the associated statement.
7851 StmtResult ActOnOpenMPSimdDirective(
7852 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7853 SourceLocation EndLoc,
7854 llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA);
7855 /// \brief Called on well-formed '\#pragma omp for' after parsing
7856 /// of the associated statement.
7857 StmtResult ActOnOpenMPForDirective(
7858 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7859 SourceLocation EndLoc,
7860 llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA);
7861 /// \brief Called on well-formed '\#pragma omp for simd' after parsing
7862 /// of the associated statement.
7863 StmtResult ActOnOpenMPForSimdDirective(
7864 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7865 SourceLocation EndLoc,
7866 llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA);
7867 /// \brief Called on well-formed '\#pragma omp sections' after parsing
7868 /// of the associated statement.
7869 StmtResult ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses,
7870 Stmt *AStmt, SourceLocation StartLoc,
7871 SourceLocation EndLoc);
7872 /// \brief Called on well-formed '\#pragma omp section' after parsing of the
7873 /// associated statement.
7874 StmtResult ActOnOpenMPSectionDirective(Stmt *AStmt, SourceLocation StartLoc,
7875 SourceLocation EndLoc);
7876 /// \brief Called on well-formed '\#pragma omp single' after parsing of the
7877 /// associated statement.
7878 StmtResult ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses,
7879 Stmt *AStmt, SourceLocation StartLoc,
7880 SourceLocation EndLoc);
7881 /// \brief Called on well-formed '\#pragma omp master' after parsing of the
7882 /// associated statement.
7883 StmtResult ActOnOpenMPMasterDirective(Stmt *AStmt, SourceLocation StartLoc,
7884 SourceLocation EndLoc);
7885 /// \brief Called on well-formed '\#pragma omp critical' after parsing of the
7886 /// associated statement.
7887 StmtResult ActOnOpenMPCriticalDirective(const DeclarationNameInfo &DirName,
7888 ArrayRef<OMPClause *> Clauses,
7889 Stmt *AStmt, SourceLocation StartLoc,
7890 SourceLocation EndLoc);
7891 /// \brief Called on well-formed '\#pragma omp parallel for' after parsing
7892 /// of the associated statement.
7893 StmtResult ActOnOpenMPParallelForDirective(
7894 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7895 SourceLocation EndLoc,
7896 llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA);
7897 /// \brief Called on well-formed '\#pragma omp parallel for simd' after
7898 /// parsing of the associated statement.
7899 StmtResult ActOnOpenMPParallelForSimdDirective(
7900 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7901 SourceLocation EndLoc,
7902 llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA);
7903 /// \brief Called on well-formed '\#pragma omp parallel sections' after
7904 /// parsing of the associated statement.
7905 StmtResult ActOnOpenMPParallelSectionsDirective(ArrayRef<OMPClause *> Clauses,
7907 SourceLocation StartLoc,
7908 SourceLocation EndLoc);
7909 /// \brief Called on well-formed '\#pragma omp task' after parsing of the
7910 /// associated statement.
7911 StmtResult ActOnOpenMPTaskDirective(ArrayRef<OMPClause *> Clauses,
7912 Stmt *AStmt, SourceLocation StartLoc,
7913 SourceLocation EndLoc);
7914 /// \brief Called on well-formed '\#pragma omp taskyield'.
7915 StmtResult ActOnOpenMPTaskyieldDirective(SourceLocation StartLoc,
7916 SourceLocation EndLoc);
7917 /// \brief Called on well-formed '\#pragma omp barrier'.
7918 StmtResult ActOnOpenMPBarrierDirective(SourceLocation StartLoc,
7919 SourceLocation EndLoc);
7920 /// \brief Called on well-formed '\#pragma omp taskwait'.
7921 StmtResult ActOnOpenMPTaskwaitDirective(SourceLocation StartLoc,
7922 SourceLocation EndLoc);
7923 /// \brief Called on well-formed '\#pragma omp taskgroup'.
7924 StmtResult ActOnOpenMPTaskgroupDirective(Stmt *AStmt, SourceLocation StartLoc,
7925 SourceLocation EndLoc);
7926 /// \brief Called on well-formed '\#pragma omp flush'.
7927 StmtResult ActOnOpenMPFlushDirective(ArrayRef<OMPClause *> Clauses,
7928 SourceLocation StartLoc,
7929 SourceLocation EndLoc);
7930 /// \brief Called on well-formed '\#pragma omp ordered' after parsing of the
7931 /// associated statement.
7932 StmtResult ActOnOpenMPOrderedDirective(ArrayRef<OMPClause *> Clauses,
7933 Stmt *AStmt, SourceLocation StartLoc,
7934 SourceLocation EndLoc);
7935 /// \brief Called on well-formed '\#pragma omp atomic' after parsing of the
7936 /// associated statement.
7937 StmtResult ActOnOpenMPAtomicDirective(ArrayRef<OMPClause *> Clauses,
7938 Stmt *AStmt, SourceLocation StartLoc,
7939 SourceLocation EndLoc);
7940 /// \brief Called on well-formed '\#pragma omp target' after parsing of the
7941 /// associated statement.
7942 StmtResult ActOnOpenMPTargetDirective(ArrayRef<OMPClause *> Clauses,
7943 Stmt *AStmt, SourceLocation StartLoc,
7944 SourceLocation EndLoc);
7945 /// \brief Called on well-formed '\#pragma omp target data' after parsing of
7946 /// the associated statement.
7947 StmtResult ActOnOpenMPTargetDataDirective(ArrayRef<OMPClause *> Clauses,
7948 Stmt *AStmt, SourceLocation StartLoc,
7949 SourceLocation EndLoc);
7950 /// \brief Called on well-formed '\#pragma omp teams' after parsing of the
7951 /// associated statement.
7952 StmtResult ActOnOpenMPTeamsDirective(ArrayRef<OMPClause *> Clauses,
7953 Stmt *AStmt, SourceLocation StartLoc,
7954 SourceLocation EndLoc);
7955 /// \brief Called on well-formed '\#pragma omp cancellation point'.
7957 ActOnOpenMPCancellationPointDirective(SourceLocation StartLoc,
7958 SourceLocation EndLoc,
7959 OpenMPDirectiveKind CancelRegion);
7960 /// \brief Called on well-formed '\#pragma omp cancel'.
7961 StmtResult ActOnOpenMPCancelDirective(ArrayRef<OMPClause *> Clauses,
7962 SourceLocation StartLoc,
7963 SourceLocation EndLoc,
7964 OpenMPDirectiveKind CancelRegion);
7965 /// \brief Called on well-formed '\#pragma omp taskloop' after parsing of the
7966 /// associated statement.
7967 StmtResult ActOnOpenMPTaskLoopDirective(
7968 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7969 SourceLocation EndLoc,
7970 llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA);
7971 /// \brief Called on well-formed '\#pragma omp taskloop simd' after parsing of
7972 /// the associated statement.
7973 StmtResult ActOnOpenMPTaskLoopSimdDirective(
7974 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7975 SourceLocation EndLoc,
7976 llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA);
7977 /// \brief Called on well-formed '\#pragma omp distribute' after parsing
7978 /// of the associated statement.
7979 StmtResult ActOnOpenMPDistributeDirective(
7980 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7981 SourceLocation EndLoc,
7982 llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA);
7984 OMPClause *ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind,
7986 SourceLocation StartLoc,
7987 SourceLocation LParenLoc,
7988 SourceLocation EndLoc);
7989 /// \brief Called on well-formed 'if' clause.
7990 OMPClause *ActOnOpenMPIfClause(OpenMPDirectiveKind NameModifier,
7991 Expr *Condition, SourceLocation StartLoc,
7992 SourceLocation LParenLoc,
7993 SourceLocation NameModifierLoc,
7994 SourceLocation ColonLoc,
7995 SourceLocation EndLoc);
7996 /// \brief Called on well-formed 'final' clause.
7997 OMPClause *ActOnOpenMPFinalClause(Expr *Condition, SourceLocation StartLoc,
7998 SourceLocation LParenLoc,
7999 SourceLocation EndLoc);
8000 /// \brief Called on well-formed 'num_threads' clause.
8001 OMPClause *ActOnOpenMPNumThreadsClause(Expr *NumThreads,
8002 SourceLocation StartLoc,
8003 SourceLocation LParenLoc,
8004 SourceLocation EndLoc);
8005 /// \brief Called on well-formed 'safelen' clause.
8006 OMPClause *ActOnOpenMPSafelenClause(Expr *Length,
8007 SourceLocation StartLoc,
8008 SourceLocation LParenLoc,
8009 SourceLocation EndLoc);
8010 /// \brief Called on well-formed 'simdlen' clause.
8011 OMPClause *ActOnOpenMPSimdlenClause(Expr *Length, SourceLocation StartLoc,
8012 SourceLocation LParenLoc,
8013 SourceLocation EndLoc);
8014 /// \brief Called on well-formed 'collapse' clause.
8015 OMPClause *ActOnOpenMPCollapseClause(Expr *NumForLoops,
8016 SourceLocation StartLoc,
8017 SourceLocation LParenLoc,
8018 SourceLocation EndLoc);
8019 /// \brief Called on well-formed 'ordered' clause.
8021 ActOnOpenMPOrderedClause(SourceLocation StartLoc, SourceLocation EndLoc,
8022 SourceLocation LParenLoc = SourceLocation(),
8023 Expr *NumForLoops = nullptr);
8024 /// \brief Called on well-formed 'grainsize' clause.
8025 OMPClause *ActOnOpenMPGrainsizeClause(Expr *Size, SourceLocation StartLoc,
8026 SourceLocation LParenLoc,
8027 SourceLocation EndLoc);
8028 /// \brief Called on well-formed 'num_tasks' clause.
8029 OMPClause *ActOnOpenMPNumTasksClause(Expr *NumTasks, SourceLocation StartLoc,
8030 SourceLocation LParenLoc,
8031 SourceLocation EndLoc);
8032 /// \brief Called on well-formed 'hint' clause.
8033 OMPClause *ActOnOpenMPHintClause(Expr *Hint, SourceLocation StartLoc,
8034 SourceLocation LParenLoc,
8035 SourceLocation EndLoc);
8037 OMPClause *ActOnOpenMPSimpleClause(OpenMPClauseKind Kind,
8039 SourceLocation ArgumentLoc,
8040 SourceLocation StartLoc,
8041 SourceLocation LParenLoc,
8042 SourceLocation EndLoc);
8043 /// \brief Called on well-formed 'default' clause.
8044 OMPClause *ActOnOpenMPDefaultClause(OpenMPDefaultClauseKind Kind,
8045 SourceLocation KindLoc,
8046 SourceLocation StartLoc,
8047 SourceLocation LParenLoc,
8048 SourceLocation EndLoc);
8049 /// \brief Called on well-formed 'proc_bind' clause.
8050 OMPClause *ActOnOpenMPProcBindClause(OpenMPProcBindClauseKind Kind,
8051 SourceLocation KindLoc,
8052 SourceLocation StartLoc,
8053 SourceLocation LParenLoc,
8054 SourceLocation EndLoc);
8056 OMPClause *ActOnOpenMPSingleExprWithArgClause(
8057 OpenMPClauseKind Kind, ArrayRef<unsigned> Arguments, Expr *Expr,
8058 SourceLocation StartLoc, SourceLocation LParenLoc,
8059 ArrayRef<SourceLocation> ArgumentsLoc, SourceLocation DelimLoc,
8060 SourceLocation EndLoc);
8061 /// \brief Called on well-formed 'schedule' clause.
8062 OMPClause *ActOnOpenMPScheduleClause(
8063 OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2,
8064 OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
8065 SourceLocation LParenLoc, SourceLocation M1Loc, SourceLocation M2Loc,
8066 SourceLocation KindLoc, SourceLocation CommaLoc, SourceLocation EndLoc);
8068 OMPClause *ActOnOpenMPClause(OpenMPClauseKind Kind, SourceLocation StartLoc,
8069 SourceLocation EndLoc);
8070 /// \brief Called on well-formed 'nowait' clause.
8071 OMPClause *ActOnOpenMPNowaitClause(SourceLocation StartLoc,
8072 SourceLocation EndLoc);
8073 /// \brief Called on well-formed 'untied' clause.
8074 OMPClause *ActOnOpenMPUntiedClause(SourceLocation StartLoc,
8075 SourceLocation EndLoc);
8076 /// \brief Called on well-formed 'mergeable' clause.
8077 OMPClause *ActOnOpenMPMergeableClause(SourceLocation StartLoc,
8078 SourceLocation EndLoc);
8079 /// \brief Called on well-formed 'read' clause.
8080 OMPClause *ActOnOpenMPReadClause(SourceLocation StartLoc,
8081 SourceLocation EndLoc);
8082 /// \brief Called on well-formed 'write' clause.
8083 OMPClause *ActOnOpenMPWriteClause(SourceLocation StartLoc,
8084 SourceLocation EndLoc);
8085 /// \brief Called on well-formed 'update' clause.
8086 OMPClause *ActOnOpenMPUpdateClause(SourceLocation StartLoc,
8087 SourceLocation EndLoc);
8088 /// \brief Called on well-formed 'capture' clause.
8089 OMPClause *ActOnOpenMPCaptureClause(SourceLocation StartLoc,
8090 SourceLocation EndLoc);
8091 /// \brief Called on well-formed 'seq_cst' clause.
8092 OMPClause *ActOnOpenMPSeqCstClause(SourceLocation StartLoc,
8093 SourceLocation EndLoc);
8094 /// \brief Called on well-formed 'threads' clause.
8095 OMPClause *ActOnOpenMPThreadsClause(SourceLocation StartLoc,
8096 SourceLocation EndLoc);
8097 /// \brief Called on well-formed 'simd' clause.
8098 OMPClause *ActOnOpenMPSIMDClause(SourceLocation StartLoc,
8099 SourceLocation EndLoc);
8100 /// \brief Called on well-formed 'nogroup' clause.
8101 OMPClause *ActOnOpenMPNogroupClause(SourceLocation StartLoc,
8102 SourceLocation EndLoc);
8104 OMPClause *ActOnOpenMPVarListClause(
8105 OpenMPClauseKind Kind, ArrayRef<Expr *> Vars, Expr *TailExpr,
8106 SourceLocation StartLoc, SourceLocation LParenLoc,
8107 SourceLocation ColonLoc, SourceLocation EndLoc,
8108 CXXScopeSpec &ReductionIdScopeSpec,
8109 const DeclarationNameInfo &ReductionId, OpenMPDependClauseKind DepKind,
8110 OpenMPLinearClauseKind LinKind, OpenMPMapClauseKind MapTypeModifier,
8111 OpenMPMapClauseKind MapType, SourceLocation DepLinMapLoc);
8112 /// \brief Called on well-formed 'private' clause.
8113 OMPClause *ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList,
8114 SourceLocation StartLoc,
8115 SourceLocation LParenLoc,
8116 SourceLocation EndLoc);
8117 /// \brief Called on well-formed 'firstprivate' clause.
8118 OMPClause *ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList,
8119 SourceLocation StartLoc,
8120 SourceLocation LParenLoc,
8121 SourceLocation EndLoc);
8122 /// \brief Called on well-formed 'lastprivate' clause.
8123 OMPClause *ActOnOpenMPLastprivateClause(ArrayRef<Expr *> VarList,
8124 SourceLocation StartLoc,
8125 SourceLocation LParenLoc,
8126 SourceLocation EndLoc);
8127 /// \brief Called on well-formed 'shared' clause.
8128 OMPClause *ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList,
8129 SourceLocation StartLoc,
8130 SourceLocation LParenLoc,
8131 SourceLocation EndLoc);
8132 /// \brief Called on well-formed 'reduction' clause.
8134 ActOnOpenMPReductionClause(ArrayRef<Expr *> VarList, SourceLocation StartLoc,
8135 SourceLocation LParenLoc, SourceLocation ColonLoc,
8136 SourceLocation EndLoc,
8137 CXXScopeSpec &ReductionIdScopeSpec,
8138 const DeclarationNameInfo &ReductionId);
8139 /// \brief Called on well-formed 'linear' clause.
8141 ActOnOpenMPLinearClause(ArrayRef<Expr *> VarList, Expr *Step,
8142 SourceLocation StartLoc, SourceLocation LParenLoc,
8143 OpenMPLinearClauseKind LinKind, SourceLocation LinLoc,
8144 SourceLocation ColonLoc, SourceLocation EndLoc);
8145 /// \brief Called on well-formed 'aligned' clause.
8146 OMPClause *ActOnOpenMPAlignedClause(ArrayRef<Expr *> VarList,
8148 SourceLocation StartLoc,
8149 SourceLocation LParenLoc,
8150 SourceLocation ColonLoc,
8151 SourceLocation EndLoc);
8152 /// \brief Called on well-formed 'copyin' clause.
8153 OMPClause *ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList,
8154 SourceLocation StartLoc,
8155 SourceLocation LParenLoc,
8156 SourceLocation EndLoc);
8157 /// \brief Called on well-formed 'copyprivate' clause.
8158 OMPClause *ActOnOpenMPCopyprivateClause(ArrayRef<Expr *> VarList,
8159 SourceLocation StartLoc,
8160 SourceLocation LParenLoc,
8161 SourceLocation EndLoc);
8162 /// \brief Called on well-formed 'flush' pseudo clause.
8163 OMPClause *ActOnOpenMPFlushClause(ArrayRef<Expr *> VarList,
8164 SourceLocation StartLoc,
8165 SourceLocation LParenLoc,
8166 SourceLocation EndLoc);
8167 /// \brief Called on well-formed 'depend' clause.
8169 ActOnOpenMPDependClause(OpenMPDependClauseKind DepKind, SourceLocation DepLoc,
8170 SourceLocation ColonLoc, ArrayRef<Expr *> VarList,
8171 SourceLocation StartLoc, SourceLocation LParenLoc,
8172 SourceLocation EndLoc);
8173 /// \brief Called on well-formed 'device' clause.
8174 OMPClause *ActOnOpenMPDeviceClause(Expr *Device, SourceLocation StartLoc,
8175 SourceLocation LParenLoc,
8176 SourceLocation EndLoc);
8177 /// \brief Called on well-formed 'map' clause.
8178 OMPClause *ActOnOpenMPMapClause(
8179 OpenMPMapClauseKind MapTypeModifier, OpenMPMapClauseKind MapType,
8180 SourceLocation MapLoc, SourceLocation ColonLoc, ArrayRef<Expr *> VarList,
8181 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc);
8182 /// \brief Called on well-formed 'num_teams' clause.
8183 OMPClause *ActOnOpenMPNumTeamsClause(Expr *NumTeams, SourceLocation StartLoc,
8184 SourceLocation LParenLoc,
8185 SourceLocation EndLoc);
8186 /// \brief Called on well-formed 'thread_limit' clause.
8187 OMPClause *ActOnOpenMPThreadLimitClause(Expr *ThreadLimit,
8188 SourceLocation StartLoc,
8189 SourceLocation LParenLoc,
8190 SourceLocation EndLoc);
8191 /// \brief Called on well-formed 'priority' clause.
8192 OMPClause *ActOnOpenMPPriorityClause(Expr *Priority, SourceLocation StartLoc,
8193 SourceLocation LParenLoc,
8194 SourceLocation EndLoc);
8196 /// \brief The kind of conversion being performed.
8197 enum CheckedConversionKind {
8198 /// \brief An implicit conversion.
8199 CCK_ImplicitConversion,
8200 /// \brief A C-style cast.
8202 /// \brief A functional-style cast.
8204 /// \brief A cast other than a C-style cast.
8208 /// ImpCastExprToType - If Expr is not of type 'Type', insert an implicit
8209 /// cast. If there is already an implicit cast, merge into the existing one.
8210 /// If isLvalue, the result of the cast is an lvalue.
8211 ExprResult ImpCastExprToType(Expr *E, QualType Type, CastKind CK,
8212 ExprValueKind VK = VK_RValue,
8213 const CXXCastPath *BasePath = nullptr,
8214 CheckedConversionKind CCK
8215 = CCK_ImplicitConversion);
8217 /// ScalarTypeToBooleanCastKind - Returns the cast kind corresponding
8218 /// to the conversion from scalar type ScalarTy to the Boolean type.
8219 static CastKind ScalarTypeToBooleanCastKind(QualType ScalarTy);
8221 /// IgnoredValueConversions - Given that an expression's result is
8222 /// syntactically ignored, perform any conversions that are
8224 ExprResult IgnoredValueConversions(Expr *E);
8226 // UsualUnaryConversions - promotes integers (C99 6.3.1.1p2) and converts
8227 // functions and arrays to their respective pointers (C99 6.3.2.1).
8228 ExprResult UsualUnaryConversions(Expr *E);
8230 /// CallExprUnaryConversions - a special case of an unary conversion
8231 /// performed on a function designator of a call expression.
8232 ExprResult CallExprUnaryConversions(Expr *E);
8234 // DefaultFunctionArrayConversion - converts functions and arrays
8235 // to their respective pointers (C99 6.3.2.1).
8236 ExprResult DefaultFunctionArrayConversion(Expr *E, bool Diagnose = true);
8238 // DefaultFunctionArrayLvalueConversion - converts functions and
8239 // arrays to their respective pointers and performs the
8240 // lvalue-to-rvalue conversion.
8241 ExprResult DefaultFunctionArrayLvalueConversion(Expr *E,
8242 bool Diagnose = true);
8244 // DefaultLvalueConversion - performs lvalue-to-rvalue conversion on
8245 // the operand. This is DefaultFunctionArrayLvalueConversion,
8246 // except that it assumes the operand isn't of function or array
8248 ExprResult DefaultLvalueConversion(Expr *E);
8250 // DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
8251 // do not have a prototype. Integer promotions are performed on each
8252 // argument, and arguments that have type float are promoted to double.
8253 ExprResult DefaultArgumentPromotion(Expr *E);
8255 // Used for emitting the right warning by DefaultVariadicArgumentPromotion
8256 enum VariadicCallType {
8260 VariadicConstructor,
8261 VariadicDoesNotApply
8264 VariadicCallType getVariadicCallType(FunctionDecl *FDecl,
8265 const FunctionProtoType *Proto,
8268 // Used for determining in which context a type is allowed to be passed to a
8278 // Determines which VarArgKind fits an expression.
8279 VarArgKind isValidVarArgType(const QualType &Ty);
8281 /// Check to see if the given expression is a valid argument to a variadic
8282 /// function, issuing a diagnostic if not.
8283 void checkVariadicArgument(const Expr *E, VariadicCallType CT);
8285 /// Check to see if a given expression could have '.c_str()' called on it.
8286 bool hasCStrMethod(const Expr *E);
8288 /// GatherArgumentsForCall - Collector argument expressions for various
8289 /// form of call prototypes.
8290 bool GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl,
8291 const FunctionProtoType *Proto,
8292 unsigned FirstParam, ArrayRef<Expr *> Args,
8293 SmallVectorImpl<Expr *> &AllArgs,
8294 VariadicCallType CallType = VariadicDoesNotApply,
8295 bool AllowExplicit = false,
8296 bool IsListInitialization = false);
8298 // DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
8299 // will create a runtime trap if the resulting type is not a POD type.
8300 ExprResult DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
8301 FunctionDecl *FDecl);
8303 // UsualArithmeticConversions - performs the UsualUnaryConversions on it's
8304 // operands and then handles various conversions that are common to binary
8305 // operators (C99 6.3.1.8). If both operands aren't arithmetic, this
8306 // routine returns the first non-arithmetic type found. The client is
8307 // responsible for emitting appropriate error diagnostics.
8308 QualType UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
8309 bool IsCompAssign = false);
8311 /// AssignConvertType - All of the 'assignment' semantic checks return this
8312 /// enum to indicate whether the assignment was allowed. These checks are
8313 /// done for simple assignments, as well as initialization, return from
8314 /// function, argument passing, etc. The query is phrased in terms of a
8315 /// source and destination type.
8316 enum AssignConvertType {
8317 /// Compatible - the types are compatible according to the standard.
8320 /// PointerToInt - The assignment converts a pointer to an int, which we
8321 /// accept as an extension.
8324 /// IntToPointer - The assignment converts an int to a pointer, which we
8325 /// accept as an extension.
8328 /// FunctionVoidPointer - The assignment is between a function pointer and
8329 /// void*, which the standard doesn't allow, but we accept as an extension.
8330 FunctionVoidPointer,
8332 /// IncompatiblePointer - The assignment is between two pointers types that
8333 /// are not compatible, but we accept them as an extension.
8334 IncompatiblePointer,
8336 /// IncompatiblePointer - The assignment is between two pointers types which
8337 /// point to integers which have a different sign, but are otherwise
8338 /// identical. This is a subset of the above, but broken out because it's by
8339 /// far the most common case of incompatible pointers.
8340 IncompatiblePointerSign,
8342 /// CompatiblePointerDiscardsQualifiers - The assignment discards
8343 /// c/v/r qualifiers, which we accept as an extension.
8344 CompatiblePointerDiscardsQualifiers,
8346 /// IncompatiblePointerDiscardsQualifiers - The assignment
8347 /// discards qualifiers that we don't permit to be discarded,
8348 /// like address spaces.
8349 IncompatiblePointerDiscardsQualifiers,
8351 /// IncompatibleNestedPointerQualifiers - The assignment is between two
8352 /// nested pointer types, and the qualifiers other than the first two
8353 /// levels differ e.g. char ** -> const char **, but we accept them as an
8355 IncompatibleNestedPointerQualifiers,
8357 /// IncompatibleVectors - The assignment is between two vector types that
8358 /// have the same size, which we accept as an extension.
8359 IncompatibleVectors,
8361 /// IntToBlockPointer - The assignment converts an int to a block
8362 /// pointer. We disallow this.
8365 /// IncompatibleBlockPointer - The assignment is between two block
8366 /// pointers types that are not compatible.
8367 IncompatibleBlockPointer,
8369 /// IncompatibleObjCQualifiedId - The assignment is between a qualified
8370 /// id type and something else (that is incompatible with it). For example,
8371 /// "id <XXX>" = "Foo *", where "Foo *" doesn't implement the XXX protocol.
8372 IncompatibleObjCQualifiedId,
8374 /// IncompatibleObjCWeakRef - Assigning a weak-unavailable object to an
8375 /// object with __weak qualifier.
8376 IncompatibleObjCWeakRef,
8378 /// Incompatible - We reject this conversion outright, it is invalid to
8379 /// represent it in the AST.
8383 /// DiagnoseAssignmentResult - Emit a diagnostic, if required, for the
8384 /// assignment conversion type specified by ConvTy. This returns true if the
8385 /// conversion was invalid or false if the conversion was accepted.
8386 bool DiagnoseAssignmentResult(AssignConvertType ConvTy,
8388 QualType DstType, QualType SrcType,
8389 Expr *SrcExpr, AssignmentAction Action,
8390 bool *Complained = nullptr);
8392 /// IsValueInFlagEnum - Determine if a value is allowed as part of a flag
8393 /// enum. If AllowMask is true, then we also allow the complement of a valid
8394 /// value, to be used as a mask.
8395 bool IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
8396 bool AllowMask) const;
8398 /// DiagnoseAssignmentEnum - Warn if assignment to enum is a constant
8399 /// integer not in the range of enum values.
8400 void DiagnoseAssignmentEnum(QualType DstType, QualType SrcType,
8403 /// CheckAssignmentConstraints - Perform type checking for assignment,
8404 /// argument passing, variable initialization, and function return values.
8406 AssignConvertType CheckAssignmentConstraints(SourceLocation Loc,
8410 /// Check assignment constraints and optionally prepare for a conversion of
8411 /// the RHS to the LHS type. The conversion is prepared for if ConvertRHS
8413 AssignConvertType CheckAssignmentConstraints(QualType LHSType,
8416 bool ConvertRHS = true);
8418 // CheckSingleAssignmentConstraints - Currently used by
8419 // CheckAssignmentOperands, and ActOnReturnStmt. Prior to type checking,
8420 // this routine performs the default function/array converions, if ConvertRHS
8422 AssignConvertType CheckSingleAssignmentConstraints(QualType LHSType,
8424 bool Diagnose = true,
8425 bool DiagnoseCFAudited = false,
8426 bool ConvertRHS = true);
8428 // \brief If the lhs type is a transparent union, check whether we
8429 // can initialize the transparent union with the given expression.
8430 AssignConvertType CheckTransparentUnionArgumentConstraints(QualType ArgType,
8433 bool IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType);
8435 bool CheckExceptionSpecCompatibility(Expr *From, QualType ToType);
8437 ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
8438 AssignmentAction Action,
8439 bool AllowExplicit = false);
8440 ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
8441 AssignmentAction Action,
8443 ImplicitConversionSequence& ICS);
8444 ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
8445 const ImplicitConversionSequence& ICS,
8446 AssignmentAction Action,
8447 CheckedConversionKind CCK
8448 = CCK_ImplicitConversion);
8449 ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
8450 const StandardConversionSequence& SCS,
8451 AssignmentAction Action,
8452 CheckedConversionKind CCK);
8454 /// the following "Check" methods will return a valid/converted QualType
8455 /// or a null QualType (indicating an error diagnostic was issued).
8457 /// type checking binary operators (subroutines of CreateBuiltinBinOp).
8458 QualType InvalidOperands(SourceLocation Loc, ExprResult &LHS,
8460 QualType CheckPointerToMemberOperands( // C++ 5.5
8461 ExprResult &LHS, ExprResult &RHS, ExprValueKind &VK,
8462 SourceLocation OpLoc, bool isIndirect);
8463 QualType CheckMultiplyDivideOperands( // C99 6.5.5
8464 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign,
8466 QualType CheckRemainderOperands( // C99 6.5.5
8467 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
8468 bool IsCompAssign = false);
8469 QualType CheckAdditionOperands( // C99 6.5.6
8470 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
8471 BinaryOperatorKind Opc, QualType* CompLHSTy = nullptr);
8472 QualType CheckSubtractionOperands( // C99 6.5.6
8473 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
8474 QualType* CompLHSTy = nullptr);
8475 QualType CheckShiftOperands( // C99 6.5.7
8476 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
8477 BinaryOperatorKind Opc, bool IsCompAssign = false);
8478 QualType CheckCompareOperands( // C99 6.5.8/9
8479 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
8480 BinaryOperatorKind Opc, bool isRelational);
8481 QualType CheckBitwiseOperands( // C99 6.5.[10...12]
8482 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
8483 bool IsCompAssign = false);
8484 QualType CheckLogicalOperands( // C99 6.5.[13,14]
8485 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
8486 BinaryOperatorKind Opc);
8487 // CheckAssignmentOperands is used for both simple and compound assignment.
8488 // For simple assignment, pass both expressions and a null converted type.
8489 // For compound assignment, pass both expressions and the converted type.
8490 QualType CheckAssignmentOperands( // C99 6.5.16.[1,2]
8491 Expr *LHSExpr, ExprResult &RHS, SourceLocation Loc, QualType CompoundType);
8493 ExprResult checkPseudoObjectIncDec(Scope *S, SourceLocation OpLoc,
8494 UnaryOperatorKind Opcode, Expr *Op);
8495 ExprResult checkPseudoObjectAssignment(Scope *S, SourceLocation OpLoc,
8496 BinaryOperatorKind Opcode,
8497 Expr *LHS, Expr *RHS);
8498 ExprResult checkPseudoObjectRValue(Expr *E);
8499 Expr *recreateSyntacticForm(PseudoObjectExpr *E);
8501 QualType CheckConditionalOperands( // C99 6.5.15
8502 ExprResult &Cond, ExprResult &LHS, ExprResult &RHS,
8503 ExprValueKind &VK, ExprObjectKind &OK, SourceLocation QuestionLoc);
8504 QualType CXXCheckConditionalOperands( // C++ 5.16
8505 ExprResult &cond, ExprResult &lhs, ExprResult &rhs,
8506 ExprValueKind &VK, ExprObjectKind &OK, SourceLocation questionLoc);
8507 QualType FindCompositePointerType(SourceLocation Loc, Expr *&E1, Expr *&E2,
8508 bool *NonStandardCompositeType = nullptr);
8509 QualType FindCompositePointerType(SourceLocation Loc,
8510 ExprResult &E1, ExprResult &E2,
8511 bool *NonStandardCompositeType = nullptr) {
8512 Expr *E1Tmp = E1.get(), *E2Tmp = E2.get();
8513 QualType Composite = FindCompositePointerType(Loc, E1Tmp, E2Tmp,
8514 NonStandardCompositeType);
8520 QualType FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
8521 SourceLocation QuestionLoc);
8523 bool DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
8524 SourceLocation QuestionLoc);
8526 void DiagnoseAlwaysNonNullPointer(Expr *E,
8527 Expr::NullPointerConstantKind NullType,
8528 bool IsEqual, SourceRange Range);
8530 /// type checking for vector binary operators.
8531 QualType CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
8532 SourceLocation Loc, bool IsCompAssign,
8533 bool AllowBothBool, bool AllowBoolConversion);
8534 QualType GetSignedVectorType(QualType V);
8535 QualType CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
8536 SourceLocation Loc, bool isRelational);
8537 QualType CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
8538 SourceLocation Loc);
8540 bool areLaxCompatibleVectorTypes(QualType srcType, QualType destType);
8541 bool isLaxVectorConversion(QualType srcType, QualType destType);
8543 /// type checking declaration initializers (C99 6.7.8)
8544 bool CheckForConstantInitializer(Expr *e, QualType t);
8546 // type checking C++ declaration initializers (C++ [dcl.init]).
8548 /// ReferenceCompareResult - Expresses the result of comparing two
8549 /// types (cv1 T1 and cv2 T2) to determine their compatibility for the
8550 /// purposes of initialization by reference (C++ [dcl.init.ref]p4).
8551 enum ReferenceCompareResult {
8552 /// Ref_Incompatible - The two types are incompatible, so direct
8553 /// reference binding is not possible.
8554 Ref_Incompatible = 0,
8555 /// Ref_Related - The two types are reference-related, which means
8556 /// that their unqualified forms (T1 and T2) are either the same
8557 /// or T1 is a base class of T2.
8559 /// Ref_Compatible_With_Added_Qualification - The two types are
8560 /// reference-compatible with added qualification, meaning that
8561 /// they are reference-compatible and the qualifiers on T1 (cv1)
8562 /// are greater than the qualifiers on T2 (cv2).
8563 Ref_Compatible_With_Added_Qualification,
8564 /// Ref_Compatible - The two types are reference-compatible and
8565 /// have equivalent qualifiers (cv1 == cv2).
8569 ReferenceCompareResult CompareReferenceRelationship(SourceLocation Loc,
8570 QualType T1, QualType T2,
8571 bool &DerivedToBase,
8572 bool &ObjCConversion,
8573 bool &ObjCLifetimeConversion);
8575 ExprResult checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
8576 Expr *CastExpr, CastKind &CastKind,
8577 ExprValueKind &VK, CXXCastPath &Path);
8579 /// \brief Force an expression with unknown-type to an expression of the
8581 ExprResult forceUnknownAnyToType(Expr *E, QualType ToType);
8583 /// \brief Type-check an expression that's being passed to an
8584 /// __unknown_anytype parameter.
8585 ExprResult checkUnknownAnyArg(SourceLocation callLoc,
8586 Expr *result, QualType ¶mType);
8588 // CheckVectorCast - check type constraints for vectors.
8589 // Since vectors are an extension, there are no C standard reference for this.
8590 // We allow casting between vectors and integer datatypes of the same size.
8591 // returns true if the cast is invalid
8592 bool CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
8595 /// \brief Prepare `SplattedExpr` for a vector splat operation, adding
8596 /// implicit casts if necessary.
8597 ExprResult prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr);
8599 // CheckExtVectorCast - check type constraints for extended vectors.
8600 // Since vectors are an extension, there are no C standard reference for this.
8601 // We allow casting between vectors and integer datatypes of the same size,
8602 // or vectors and the element type of that vector.
8603 // returns the cast expr
8604 ExprResult CheckExtVectorCast(SourceRange R, QualType DestTy, Expr *CastExpr,
8607 ExprResult BuildCXXFunctionalCastExpr(TypeSourceInfo *TInfo,
8608 SourceLocation LParenLoc,
8610 SourceLocation RParenLoc);
8612 enum ARCConversionResult { ACR_okay, ACR_unbridged };
8614 /// \brief Checks for invalid conversions and casts between
8615 /// retainable pointers and other pointer kinds.
8616 ARCConversionResult CheckObjCARCConversion(SourceRange castRange,
8617 QualType castType, Expr *&op,
8618 CheckedConversionKind CCK,
8619 bool Diagnose = true,
8620 bool DiagnoseCFAudited = false,
8621 BinaryOperatorKind Opc = BO_PtrMemD
8624 Expr *stripARCUnbridgedCast(Expr *e);
8625 void diagnoseARCUnbridgedCast(Expr *e);
8627 bool CheckObjCARCUnavailableWeakConversion(QualType castType,
8630 /// checkRetainCycles - Check whether an Objective-C message send
8631 /// might create an obvious retain cycle.
8632 void checkRetainCycles(ObjCMessageExpr *msg);
8633 void checkRetainCycles(Expr *receiver, Expr *argument);
8634 void checkRetainCycles(VarDecl *Var, Expr *Init);
8636 /// checkUnsafeAssigns - Check whether +1 expr is being assigned
8637 /// to weak/__unsafe_unretained type.
8638 bool checkUnsafeAssigns(SourceLocation Loc, QualType LHS, Expr *RHS);
8640 /// checkUnsafeExprAssigns - Check whether +1 expr is being assigned
8641 /// to weak/__unsafe_unretained expression.
8642 void checkUnsafeExprAssigns(SourceLocation Loc, Expr *LHS, Expr *RHS);
8644 /// CheckMessageArgumentTypes - Check types in an Obj-C message send.
8645 /// \param Method - May be null.
8646 /// \param [out] ReturnType - The return type of the send.
8647 /// \return true iff there were any incompatible types.
8648 bool CheckMessageArgumentTypes(QualType ReceiverType,
8649 MultiExprArg Args, Selector Sel,
8650 ArrayRef<SourceLocation> SelectorLocs,
8651 ObjCMethodDecl *Method, bool isClassMessage,
8652 bool isSuperMessage,
8653 SourceLocation lbrac, SourceLocation rbrac,
8654 SourceRange RecRange,
8655 QualType &ReturnType, ExprValueKind &VK);
8657 /// \brief Determine the result of a message send expression based on
8658 /// the type of the receiver, the method expected to receive the message,
8659 /// and the form of the message send.
8660 QualType getMessageSendResultType(QualType ReceiverType,
8661 ObjCMethodDecl *Method,
8662 bool isClassMessage, bool isSuperMessage);
8664 /// \brief If the given expression involves a message send to a method
8665 /// with a related result type, emit a note describing what happened.
8666 void EmitRelatedResultTypeNote(const Expr *E);
8668 /// \brief Given that we had incompatible pointer types in a return
8669 /// statement, check whether we're in a method with a related result
8670 /// type, and if so, emit a note describing what happened.
8671 void EmitRelatedResultTypeNoteForReturn(QualType destType);
8673 /// CheckBooleanCondition - Diagnose problems involving the use of
8674 /// the given expression as a boolean condition (e.g. in an if
8675 /// statement). Also performs the standard function and array
8676 /// decays, possibly changing the input variable.
8678 /// \param Loc - A location associated with the condition, e.g. the
8680 /// \return true iff there were any errors
8681 ExprResult CheckBooleanCondition(Expr *E, SourceLocation Loc);
8683 ExprResult ActOnBooleanCondition(Scope *S, SourceLocation Loc,
8686 /// DiagnoseAssignmentAsCondition - Given that an expression is
8687 /// being used as a boolean condition, warn if it's an assignment.
8688 void DiagnoseAssignmentAsCondition(Expr *E);
8690 /// \brief Redundant parentheses over an equality comparison can indicate
8691 /// that the user intended an assignment used as condition.
8692 void DiagnoseEqualityWithExtraParens(ParenExpr *ParenE);
8694 /// CheckCXXBooleanCondition - Returns true if conversion to bool is invalid.
8695 ExprResult CheckCXXBooleanCondition(Expr *CondExpr);
8697 /// ConvertIntegerToTypeWarnOnOverflow - Convert the specified APInt to have
8698 /// the specified width and sign. If an overflow occurs, detect it and emit
8699 /// the specified diagnostic.
8700 void ConvertIntegerToTypeWarnOnOverflow(llvm::APSInt &OldVal,
8701 unsigned NewWidth, bool NewSign,
8702 SourceLocation Loc, unsigned DiagID);
8704 /// Checks that the Objective-C declaration is declared in the global scope.
8705 /// Emits an error and marks the declaration as invalid if it's not declared
8706 /// in the global scope.
8707 bool CheckObjCDeclScope(Decl *D);
8709 /// \brief Abstract base class used for diagnosing integer constant
8710 /// expression violations.
8711 class VerifyICEDiagnoser {
8715 VerifyICEDiagnoser(bool Suppress = false) : Suppress(Suppress) { }
8717 virtual void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) =0;
8718 virtual void diagnoseFold(Sema &S, SourceLocation Loc, SourceRange SR);
8719 virtual ~VerifyICEDiagnoser() { }
8722 /// VerifyIntegerConstantExpression - Verifies that an expression is an ICE,
8723 /// and reports the appropriate diagnostics. Returns false on success.
8724 /// Can optionally return the value of the expression.
8725 ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
8726 VerifyICEDiagnoser &Diagnoser,
8727 bool AllowFold = true);
8728 ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
8730 bool AllowFold = true);
8731 ExprResult VerifyIntegerConstantExpression(Expr *E,
8732 llvm::APSInt *Result = nullptr);
8734 /// VerifyBitField - verifies that a bit field expression is an ICE and has
8735 /// the correct width, and that the field type is valid.
8736 /// Returns false on success.
8737 /// Can optionally return whether the bit-field is of width 0
8738 ExprResult VerifyBitField(SourceLocation FieldLoc, IdentifierInfo *FieldName,
8739 QualType FieldTy, bool IsMsStruct,
8740 Expr *BitWidth, bool *ZeroWidth = nullptr);
8742 enum CUDAFunctionTarget {
8750 CUDAFunctionTarget IdentifyCUDATarget(const FunctionDecl *D);
8752 enum CUDAFunctionPreference {
8753 CFP_Never, // Invalid caller/callee combination.
8754 CFP_LastResort, // Lowest priority. Only in effect if
8755 // LangOpts.CUDADisableTargetCallChecks is true.
8756 CFP_Fallback, // Low priority caller/callee combination
8757 CFP_Best, // Preferred caller/callee combination
8760 /// Identifies relative preference of a given Caller/Callee
8761 /// combination, based on their host/device attributes.
8762 /// \param Caller function which needs address of \p Callee.
8763 /// nullptr in case of global context.
8764 /// \param Callee target function
8766 /// \returns preference value for particular Caller/Callee combination.
8767 CUDAFunctionPreference IdentifyCUDAPreference(const FunctionDecl *Caller,
8768 const FunctionDecl *Callee);
8770 bool CheckCUDATarget(const FunctionDecl *Caller, const FunctionDecl *Callee);
8772 /// Finds a function in \p Matches with highest calling priority
8773 /// from \p Caller context and erases all functions with lower
8774 /// calling priority.
8775 void EraseUnwantedCUDAMatches(const FunctionDecl *Caller,
8776 SmallVectorImpl<FunctionDecl *> &Matches);
8777 void EraseUnwantedCUDAMatches(const FunctionDecl *Caller,
8778 SmallVectorImpl<DeclAccessPair> &Matches);
8779 void EraseUnwantedCUDAMatches(
8780 const FunctionDecl *Caller,
8781 SmallVectorImpl<std::pair<DeclAccessPair, FunctionDecl *>> &Matches);
8783 /// Given a implicit special member, infer its CUDA target from the
8784 /// calls it needs to make to underlying base/field special members.
8785 /// \param ClassDecl the class for which the member is being created.
8786 /// \param CSM the kind of special member.
8787 /// \param MemberDecl the special member itself.
8788 /// \param ConstRHS true if this is a copy operation with a const object on
8790 /// \param Diagnose true if this call should emit diagnostics.
8791 /// \return true if there was an error inferring.
8792 /// The result of this call is implicit CUDA target attribute(s) attached to
8793 /// the member declaration.
8794 bool inferCUDATargetForImplicitSpecialMember(CXXRecordDecl *ClassDecl,
8795 CXXSpecialMember CSM,
8796 CXXMethodDecl *MemberDecl,
8800 /// \name Code completion
8802 /// \brief Describes the context in which code completion occurs.
8803 enum ParserCompletionContext {
8804 /// \brief Code completion occurs at top-level or namespace context.
8806 /// \brief Code completion occurs within a class, struct, or union.
8808 /// \brief Code completion occurs within an Objective-C interface, protocol,
8811 /// \brief Code completion occurs within an Objective-C implementation or
8812 /// category implementation
8813 PCC_ObjCImplementation,
8814 /// \brief Code completion occurs within the list of instance variables
8815 /// in an Objective-C interface, protocol, category, or implementation.
8816 PCC_ObjCInstanceVariableList,
8817 /// \brief Code completion occurs following one or more template
8820 /// \brief Code completion occurs following one or more template
8821 /// headers within a class.
8823 /// \brief Code completion occurs within an expression.
8825 /// \brief Code completion occurs within a statement, which may
8826 /// also be an expression or a declaration.
8828 /// \brief Code completion occurs at the beginning of the
8829 /// initialization statement (or expression) in a for loop.
8831 /// \brief Code completion occurs within the condition of an if,
8832 /// while, switch, or for statement.
8834 /// \brief Code completion occurs within the body of a function on a
8835 /// recovery path, where we do not have a specific handle on our position
8837 PCC_RecoveryInFunction,
8838 /// \brief Code completion occurs where only a type is permitted.
8840 /// \brief Code completion occurs in a parenthesized expression, which
8841 /// might also be a type cast.
8842 PCC_ParenthesizedExpression,
8843 /// \brief Code completion occurs within a sequence of declaration
8844 /// specifiers within a function, method, or block.
8845 PCC_LocalDeclarationSpecifiers
8848 void CodeCompleteModuleImport(SourceLocation ImportLoc, ModuleIdPath Path);
8849 void CodeCompleteOrdinaryName(Scope *S,
8850 ParserCompletionContext CompletionContext);
8851 void CodeCompleteDeclSpec(Scope *S, DeclSpec &DS,
8852 bool AllowNonIdentifiers,
8853 bool AllowNestedNameSpecifiers);
8855 struct CodeCompleteExpressionData;
8856 void CodeCompleteExpression(Scope *S,
8857 const CodeCompleteExpressionData &Data);
8858 void CodeCompleteMemberReferenceExpr(Scope *S, Expr *Base,
8859 SourceLocation OpLoc,
8861 void CodeCompletePostfixExpression(Scope *S, ExprResult LHS);
8862 void CodeCompleteTag(Scope *S, unsigned TagSpec);
8863 void CodeCompleteTypeQualifiers(DeclSpec &DS);
8864 void CodeCompleteCase(Scope *S);
8865 void CodeCompleteCall(Scope *S, Expr *Fn, ArrayRef<Expr *> Args);
8866 void CodeCompleteConstructor(Scope *S, QualType Type, SourceLocation Loc,
8867 ArrayRef<Expr *> Args);
8868 void CodeCompleteInitializer(Scope *S, Decl *D);
8869 void CodeCompleteReturn(Scope *S);
8870 void CodeCompleteAfterIf(Scope *S);
8871 void CodeCompleteAssignmentRHS(Scope *S, Expr *LHS);
8873 void CodeCompleteQualifiedId(Scope *S, CXXScopeSpec &SS,
8874 bool EnteringContext);
8875 void CodeCompleteUsing(Scope *S);
8876 void CodeCompleteUsingDirective(Scope *S);
8877 void CodeCompleteNamespaceDecl(Scope *S);
8878 void CodeCompleteNamespaceAliasDecl(Scope *S);
8879 void CodeCompleteOperatorName(Scope *S);
8880 void CodeCompleteConstructorInitializer(
8882 ArrayRef<CXXCtorInitializer *> Initializers);
8884 void CodeCompleteLambdaIntroducer(Scope *S, LambdaIntroducer &Intro,
8885 bool AfterAmpersand);
8887 void CodeCompleteObjCAtDirective(Scope *S);
8888 void CodeCompleteObjCAtVisibility(Scope *S);
8889 void CodeCompleteObjCAtStatement(Scope *S);
8890 void CodeCompleteObjCAtExpression(Scope *S);
8891 void CodeCompleteObjCPropertyFlags(Scope *S, ObjCDeclSpec &ODS);
8892 void CodeCompleteObjCPropertyGetter(Scope *S);
8893 void CodeCompleteObjCPropertySetter(Scope *S);
8894 void CodeCompleteObjCPassingType(Scope *S, ObjCDeclSpec &DS,
8896 void CodeCompleteObjCMessageReceiver(Scope *S);
8897 void CodeCompleteObjCSuperMessage(Scope *S, SourceLocation SuperLoc,
8898 ArrayRef<IdentifierInfo *> SelIdents,
8899 bool AtArgumentExpression);
8900 void CodeCompleteObjCClassMessage(Scope *S, ParsedType Receiver,
8901 ArrayRef<IdentifierInfo *> SelIdents,
8902 bool AtArgumentExpression,
8903 bool IsSuper = false);
8904 void CodeCompleteObjCInstanceMessage(Scope *S, Expr *Receiver,
8905 ArrayRef<IdentifierInfo *> SelIdents,
8906 bool AtArgumentExpression,
8907 ObjCInterfaceDecl *Super = nullptr);
8908 void CodeCompleteObjCForCollection(Scope *S,
8909 DeclGroupPtrTy IterationVar);
8910 void CodeCompleteObjCSelector(Scope *S,
8911 ArrayRef<IdentifierInfo *> SelIdents);
8912 void CodeCompleteObjCProtocolReferences(
8913 ArrayRef<IdentifierLocPair> Protocols);
8914 void CodeCompleteObjCProtocolDecl(Scope *S);
8915 void CodeCompleteObjCInterfaceDecl(Scope *S);
8916 void CodeCompleteObjCSuperclass(Scope *S,
8917 IdentifierInfo *ClassName,
8918 SourceLocation ClassNameLoc);
8919 void CodeCompleteObjCImplementationDecl(Scope *S);
8920 void CodeCompleteObjCInterfaceCategory(Scope *S,
8921 IdentifierInfo *ClassName,
8922 SourceLocation ClassNameLoc);
8923 void CodeCompleteObjCImplementationCategory(Scope *S,
8924 IdentifierInfo *ClassName,
8925 SourceLocation ClassNameLoc);
8926 void CodeCompleteObjCPropertyDefinition(Scope *S);
8927 void CodeCompleteObjCPropertySynthesizeIvar(Scope *S,
8928 IdentifierInfo *PropertyName);
8929 void CodeCompleteObjCMethodDecl(Scope *S,
8930 bool IsInstanceMethod,
8931 ParsedType ReturnType);
8932 void CodeCompleteObjCMethodDeclSelector(Scope *S,
8933 bool IsInstanceMethod,
8934 bool AtParameterName,
8935 ParsedType ReturnType,
8936 ArrayRef<IdentifierInfo *> SelIdents);
8937 void CodeCompletePreprocessorDirective(bool InConditional);
8938 void CodeCompleteInPreprocessorConditionalExclusion(Scope *S);
8939 void CodeCompletePreprocessorMacroName(bool IsDefinition);
8940 void CodeCompletePreprocessorExpression();
8941 void CodeCompletePreprocessorMacroArgument(Scope *S,
8942 IdentifierInfo *Macro,
8943 MacroInfo *MacroInfo,
8945 void CodeCompleteNaturalLanguage();
8946 void GatherGlobalCodeCompletions(CodeCompletionAllocator &Allocator,
8947 CodeCompletionTUInfo &CCTUInfo,
8948 SmallVectorImpl<CodeCompletionResult> &Results);
8951 //===--------------------------------------------------------------------===//
8952 // Extra semantic analysis beyond the C type system
8955 SourceLocation getLocationOfStringLiteralByte(const StringLiteral *SL,
8956 unsigned ByteNo) const;
8959 void CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
8960 const ArraySubscriptExpr *ASE=nullptr,
8961 bool AllowOnePastEnd=true, bool IndexNegated=false);
8962 void CheckArrayAccess(const Expr *E);
8963 // Used to grab the relevant information from a FormatAttr and a
8964 // FunctionDeclaration.
8965 struct FormatStringInfo {
8967 unsigned FirstDataArg;
8971 static bool getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
8972 FormatStringInfo *FSI);
8973 bool CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
8974 const FunctionProtoType *Proto);
8975 bool CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation loc,
8976 ArrayRef<const Expr *> Args);
8977 bool CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
8978 const FunctionProtoType *Proto);
8979 bool CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto);
8980 void CheckConstructorCall(FunctionDecl *FDecl,
8981 ArrayRef<const Expr *> Args,
8982 const FunctionProtoType *Proto,
8983 SourceLocation Loc);
8985 void checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
8986 ArrayRef<const Expr *> Args, bool IsMemberFunction,
8987 SourceLocation Loc, SourceRange Range,
8988 VariadicCallType CallType);
8990 bool CheckObjCString(Expr *Arg);
8992 ExprResult CheckBuiltinFunctionCall(FunctionDecl *FDecl,
8993 unsigned BuiltinID, CallExpr *TheCall);
8995 bool CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
8997 bool CheckNeonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
8998 bool CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
9000 bool CheckAArch64BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
9001 bool CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
9002 bool CheckSystemZBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
9003 bool CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
9004 bool CheckPPCBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
9006 bool SemaBuiltinVAStartImpl(CallExpr *TheCall);
9007 bool SemaBuiltinVAStart(CallExpr *TheCall);
9008 bool SemaBuiltinMSVAStart(CallExpr *TheCall);
9009 bool SemaBuiltinVAStartARM(CallExpr *Call);
9010 bool SemaBuiltinUnorderedCompare(CallExpr *TheCall);
9011 bool SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs);
9014 // Used by C++ template instantiation.
9015 ExprResult SemaBuiltinShuffleVector(CallExpr *TheCall);
9016 ExprResult SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
9017 SourceLocation BuiltinLoc,
9018 SourceLocation RParenLoc);
9021 bool SemaBuiltinPrefetch(CallExpr *TheCall);
9022 bool SemaBuiltinAssume(CallExpr *TheCall);
9023 bool SemaBuiltinAssumeAligned(CallExpr *TheCall);
9024 bool SemaBuiltinLongjmp(CallExpr *TheCall);
9025 bool SemaBuiltinSetjmp(CallExpr *TheCall);
9026 ExprResult SemaBuiltinAtomicOverloaded(ExprResult TheCallResult);
9027 ExprResult SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult);
9028 ExprResult SemaAtomicOpsOverloaded(ExprResult TheCallResult,
9029 AtomicExpr::AtomicOp Op);
9030 bool SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
9031 llvm::APSInt &Result);
9032 bool SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
9034 bool SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall,
9035 int ArgNum, unsigned ExpectedFieldNum,
9038 enum FormatStringType {
9049 static FormatStringType GetFormatStringType(const FormatAttr *Format);
9051 void CheckFormatString(const StringLiteral *FExpr, const Expr *OrigFormatExpr,
9052 ArrayRef<const Expr *> Args, bool HasVAListArg,
9053 unsigned format_idx, unsigned firstDataArg,
9054 FormatStringType Type, bool inFunctionCall,
9055 VariadicCallType CallType,
9056 llvm::SmallBitVector &CheckedVarArgs);
9058 bool FormatStringHasSArg(const StringLiteral *FExpr);
9060 static bool GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx);
9063 bool CheckFormatArguments(const FormatAttr *Format,
9064 ArrayRef<const Expr *> Args,
9066 VariadicCallType CallType,
9067 SourceLocation Loc, SourceRange Range,
9068 llvm::SmallBitVector &CheckedVarArgs);
9069 bool CheckFormatArguments(ArrayRef<const Expr *> Args,
9070 bool HasVAListArg, unsigned format_idx,
9071 unsigned firstDataArg, FormatStringType Type,
9072 VariadicCallType CallType,
9073 SourceLocation Loc, SourceRange range,
9074 llvm::SmallBitVector &CheckedVarArgs);
9076 void CheckAbsoluteValueFunction(const CallExpr *Call,
9077 const FunctionDecl *FDecl,
9078 IdentifierInfo *FnInfo);
9080 void CheckMemaccessArguments(const CallExpr *Call,
9082 IdentifierInfo *FnName);
9084 void CheckStrlcpycatArguments(const CallExpr *Call,
9085 IdentifierInfo *FnName);
9087 void CheckStrncatArguments(const CallExpr *Call,
9088 IdentifierInfo *FnName);
9090 void CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
9091 SourceLocation ReturnLoc,
9092 bool isObjCMethod = false,
9093 const AttrVec *Attrs = nullptr,
9094 const FunctionDecl *FD = nullptr);
9096 void CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr* RHS);
9097 void CheckImplicitConversions(Expr *E, SourceLocation CC = SourceLocation());
9098 void CheckBoolLikeConversion(Expr *E, SourceLocation CC);
9099 void CheckForIntOverflow(Expr *E);
9100 void CheckUnsequencedOperations(Expr *E);
9102 /// \brief Perform semantic checks on a completed expression. This will either
9103 /// be a full-expression or a default argument expression.
9104 void CheckCompletedExpr(Expr *E, SourceLocation CheckLoc = SourceLocation(),
9105 bool IsConstexpr = false);
9107 void CheckBitFieldInitialization(SourceLocation InitLoc, FieldDecl *Field,
9110 /// \brief Check if the given expression contains 'break' or 'continue'
9111 /// statement that produces control flow different from GCC.
9112 void CheckBreakContinueBinding(Expr *E);
9114 /// \brief Check whether receiver is mutable ObjC container which
9115 /// attempts to add itself into the container
9116 void CheckObjCCircularContainer(ObjCMessageExpr *Message);
9118 void AnalyzeDeleteExprMismatch(const CXXDeleteExpr *DE);
9119 void AnalyzeDeleteExprMismatch(FieldDecl *Field, SourceLocation DeleteLoc,
9120 bool DeleteWasArrayForm);
9122 /// \brief Register a magic integral constant to be used as a type tag.
9123 void RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
9124 uint64_t MagicValue, QualType Type,
9125 bool LayoutCompatible, bool MustBeNull);
9127 struct TypeTagData {
9130 TypeTagData(QualType Type, bool LayoutCompatible, bool MustBeNull) :
9131 Type(Type), LayoutCompatible(LayoutCompatible),
9132 MustBeNull(MustBeNull)
9137 /// If true, \c Type should be compared with other expression's types for
9138 /// layout-compatibility.
9139 unsigned LayoutCompatible : 1;
9140 unsigned MustBeNull : 1;
9143 /// A pair of ArgumentKind identifier and magic value. This uniquely
9144 /// identifies the magic value.
9145 typedef std::pair<const IdentifierInfo *, uint64_t> TypeTagMagicValue;
9148 /// \brief A map from magic value to type information.
9149 std::unique_ptr<llvm::DenseMap<TypeTagMagicValue, TypeTagData>>
9150 TypeTagForDatatypeMagicValues;
9152 /// \brief Peform checks on a call of a function with argument_with_type_tag
9153 /// or pointer_with_type_tag attributes.
9154 void CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
9155 const Expr * const *ExprArgs);
9157 /// \brief The parser's current scope.
9159 /// The parser maintains this state here.
9162 mutable IdentifierInfo *Ident_super;
9163 mutable IdentifierInfo *Ident___float128;
9165 /// Nullability type specifiers.
9166 IdentifierInfo *Ident__Nonnull = nullptr;
9167 IdentifierInfo *Ident__Nullable = nullptr;
9168 IdentifierInfo *Ident__Null_unspecified = nullptr;
9170 IdentifierInfo *Ident_NSError = nullptr;
9173 friend class Parser;
9174 friend class InitializationSequence;
9175 friend class ASTReader;
9176 friend class ASTDeclReader;
9177 friend class ASTWriter;
9180 /// Retrieve the keyword associated
9181 IdentifierInfo *getNullabilityKeyword(NullabilityKind nullability);
9183 /// The struct behind the CFErrorRef pointer.
9184 RecordDecl *CFError = nullptr;
9186 /// Retrieve the identifier "NSError".
9187 IdentifierInfo *getNSErrorIdent();
9189 /// \brief Retrieve the parser's current scope.
9191 /// This routine must only be used when it is certain that semantic analysis
9192 /// and the parser are in precisely the same context, which is not the case
9193 /// when, e.g., we are performing any kind of template instantiation.
9194 /// Therefore, the only safe places to use this scope are in the parser
9195 /// itself and in routines directly invoked from the parser and *never* from
9196 /// template substitution or instantiation.
9197 Scope *getCurScope() const { return CurScope; }
9199 void incrementMSManglingNumber() const {
9200 return CurScope->incrementMSManglingNumber();
9203 IdentifierInfo *getSuperIdentifier() const;
9204 IdentifierInfo *getFloat128Identifier() const;
9206 Decl *getObjCDeclContext() const;
9208 DeclContext *getCurLexicalContext() const {
9209 return OriginalLexicalContext ? OriginalLexicalContext : CurContext;
9212 AvailabilityResult getCurContextAvailability() const;
9214 const DeclContext *getCurObjCLexicalContext() const {
9215 const DeclContext *DC = getCurLexicalContext();
9216 // A category implicitly has the attribute of the interface.
9217 if (const ObjCCategoryDecl *CatD = dyn_cast<ObjCCategoryDecl>(DC))
9218 DC = CatD->getClassInterface();
9222 /// \brief To be used for checking whether the arguments being passed to
9223 /// function exceeds the number of parameters expected for it.
9224 static bool TooManyArguments(size_t NumParams, size_t NumArgs,
9225 bool PartialOverloading = false) {
9226 // We check whether we're just after a comma in code-completion.
9227 if (NumArgs > 0 && PartialOverloading)
9228 return NumArgs + 1 > NumParams; // If so, we view as an extra argument.
9229 return NumArgs > NumParams;
9232 // Emitting members of dllexported classes is delayed until the class
9233 // (including field initializers) is fully parsed.
9234 SmallVector<CXXRecordDecl*, 4> DelayedDllExportClasses;
9237 /// \brief RAII object that enters a new expression evaluation context.
9238 class EnterExpressionEvaluationContext {
9242 EnterExpressionEvaluationContext(Sema &Actions,
9243 Sema::ExpressionEvaluationContext NewContext,
9244 Decl *LambdaContextDecl = nullptr,
9245 bool IsDecltype = false)
9246 : Actions(Actions) {
9247 Actions.PushExpressionEvaluationContext(NewContext, LambdaContextDecl,
9250 EnterExpressionEvaluationContext(Sema &Actions,
9251 Sema::ExpressionEvaluationContext NewContext,
9252 Sema::ReuseLambdaContextDecl_t,
9253 bool IsDecltype = false)
9254 : Actions(Actions) {
9255 Actions.PushExpressionEvaluationContext(NewContext,
9256 Sema::ReuseLambdaContextDecl,
9260 ~EnterExpressionEvaluationContext() {
9261 Actions.PopExpressionEvaluationContext();
9265 DeductionFailureInfo
9266 MakeDeductionFailureInfo(ASTContext &Context, Sema::TemplateDeductionResult TDK,
9267 sema::TemplateDeductionInfo &Info);
9269 /// \brief Contains a late templated function.
9270 /// Will be parsed at the end of the translation unit, used by Sema & Parser.
9271 struct LateParsedTemplate {
9273 /// \brief The template function declaration to be late parsed.
9277 } // end namespace clang