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;
81 class CXXDestructorDecl;
82 class CXXFieldCollector;
83 class CXXMemberCallExpr;
89 class ClassTemplateDecl;
90 class ClassTemplatePartialSpecializationDecl;
91 class ClassTemplateSpecializationDecl;
92 class VarTemplatePartialSpecializationDecl;
93 class CodeCompleteConsumer;
94 class CodeCompletionAllocator;
95 class CodeCompletionTUInfo;
96 class CodeCompletionResult;
101 class DeclaratorDecl;
102 class DeducedTemplateArgument;
103 class DependentDiagnostic;
104 class DesignatedInitExpr;
107 class EnumConstantDecl;
110 class ExternalSemaSource;
114 class FunctionProtoType;
115 class FunctionTemplateDecl;
116 class ImplicitConversionSequence;
118 class InitializationKind;
119 class InitializationSequence;
120 class InitializedEntity;
121 class IntegerLiteral;
125 class LocalInstantiationScope;
128 typedef ArrayRef<std::pair<IdentifierInfo *, SourceLocation>> ModuleIdPath;
130 class MultiLevelTemplateArgumentList;
132 class ObjCCategoryDecl;
133 class ObjCCategoryImplDecl;
134 class ObjCCompatibleAliasDecl;
135 class ObjCContainerDecl;
137 class ObjCImplementationDecl;
138 class ObjCInterfaceDecl;
140 template <class T> class ObjCList;
141 class ObjCMessageExpr;
142 class ObjCMethodDecl;
143 class ObjCPropertyDecl;
144 class ObjCProtocolDecl;
145 class OMPThreadPrivateDecl;
147 class OverloadCandidateSet;
152 class PseudoDestructorTypeStorage;
153 class PseudoObjectExpr;
155 class StandardConversionSequence;
159 class TemplateArgument;
160 class TemplateArgumentList;
161 class TemplateArgumentLoc;
163 class TemplateParameterList;
164 class TemplatePartialOrderingContext;
165 class TemplateTemplateParmDecl;
169 class TypedefNameDecl;
171 class TypoCorrectionConsumer;
173 class UnresolvedLookupExpr;
174 class UnresolvedMemberExpr;
175 class UnresolvedSetImpl;
176 class UnresolvedSetIterator;
178 class UsingShadowDecl;
181 class VarTemplateSpecializationDecl;
182 class VisibilityAttr;
183 class VisibleDeclConsumer;
184 class IndirectFieldDecl;
185 struct DeductionFailureInfo;
186 class TemplateSpecCandidateSet;
189 class AccessedEntity;
190 class BlockScopeInfo;
191 class CapturedRegionScopeInfo;
192 class CapturingScopeInfo;
193 class CompoundScopeInfo;
194 class DelayedDiagnostic;
195 class DelayedDiagnosticPool;
196 class FunctionScopeInfo;
197 class LambdaScopeInfo;
198 class PossiblyUnreachableDiag;
199 class TemplateDeductionInfo;
202 // FIXME: No way to easily map from TemplateTypeParmTypes to
203 // TemplateTypeParmDecls, so we have this horrible PointerUnion.
204 typedef std::pair<llvm::PointerUnion<const TemplateTypeParmType*, NamedDecl*>,
205 SourceLocation> UnexpandedParameterPack;
207 /// Sema - This implements semantic analysis and AST building for C.
209 Sema(const Sema &) LLVM_DELETED_FUNCTION;
210 void operator=(const Sema &) LLVM_DELETED_FUNCTION;
212 ///\brief Source of additional semantic information.
213 ExternalSemaSource *ExternalSource;
215 ///\brief Whether Sema has generated a multiplexer and has to delete it.
216 bool isMultiplexExternalSource;
218 static bool mightHaveNonExternalLinkage(const DeclaratorDecl *FD);
221 shouldLinkPossiblyHiddenDecl(const NamedDecl *Old, const NamedDecl *New) {
222 // We are about to link these. It is now safe to compute the linkage of
223 // the new decl. If the new decl has external linkage, we will
224 // link it with the hidden decl (which also has external linkage) and
225 // it will keep having external linkage. If it has internal linkage, we
226 // will not link it. Since it has no previous decls, it will remain
227 // with internal linkage.
228 return !Old->isHidden() || New->isExternallyVisible();
232 typedef OpaquePtr<DeclGroupRef> DeclGroupPtrTy;
233 typedef OpaquePtr<TemplateName> TemplateTy;
234 typedef OpaquePtr<QualType> TypeTy;
236 OpenCLOptions OpenCLFeatures;
237 FPOptions FPFeatures;
239 const LangOptions &LangOpts;
242 ASTConsumer &Consumer;
243 DiagnosticsEngine &Diags;
244 SourceManager &SourceMgr;
246 /// \brief Flag indicating whether or not to collect detailed statistics.
249 /// \brief Code-completion consumer.
250 CodeCompleteConsumer *CodeCompleter;
252 /// CurContext - This is the current declaration context of parsing.
253 DeclContext *CurContext;
255 /// \brief Generally null except when we temporarily switch decl contexts,
256 /// like in \see ActOnObjCTemporaryExitContainerContext.
257 DeclContext *OriginalLexicalContext;
259 /// VAListTagName - The declaration name corresponding to __va_list_tag.
260 /// This is used as part of a hack to omit that class from ADL results.
261 DeclarationName VAListTagName;
263 /// PackContext - Manages the stack for \#pragma pack. An alignment
264 /// of 0 indicates default alignment.
265 void *PackContext; // Really a "PragmaPackStack*"
267 bool MSStructPragmaOn; // True when \#pragma ms_struct on
269 /// \brief Controls member pointer representation format under the MS ABI.
270 LangOptions::PragmaMSPointersToMembersKind
271 MSPointerToMemberRepresentationMethod;
273 enum PragmaVtorDispKind {
274 PVDK_Push, ///< #pragma vtordisp(push, mode)
275 PVDK_Set, ///< #pragma vtordisp(mode)
276 PVDK_Pop, ///< #pragma vtordisp(pop)
277 PVDK_Reset ///< #pragma vtordisp()
280 enum PragmaMsStackAction {
281 PSK_Reset, // #pragma ()
282 PSK_Set, // #pragma ("name")
283 PSK_Push, // #pragma (push[, id])
284 PSK_Push_Set, // #pragma (push[, id], "name")
285 PSK_Pop, // #pragma (pop[, id])
286 PSK_Pop_Set, // #pragma (pop[, id], "name")
289 /// \brief Whether to insert vtordisps prior to virtual bases in the Microsoft
290 /// C++ ABI. Possible values are 0, 1, and 2, which mean:
292 /// 0: Suppress all vtordisps
293 /// 1: Insert vtordisps in the presence of vbase overrides and non-trivial
295 /// 2: Always insert vtordisps to support RTTI on partially constructed
298 /// The stack always has at least one element in it.
299 SmallVector<MSVtorDispAttr::Mode, 2> VtorDispModeStack;
301 /// \brief Source location for newly created implicit MSInheritanceAttrs
302 SourceLocation ImplicitMSInheritanceAttrLoc;
304 template<typename ValueType>
307 llvm::StringRef StackSlotLabel;
309 SourceLocation PragmaLocation;
310 Slot(llvm::StringRef StackSlotLabel,
312 SourceLocation PragmaLocation)
313 : StackSlotLabel(StackSlotLabel), Value(Value),
314 PragmaLocation(PragmaLocation) {}
316 void Act(SourceLocation PragmaLocation,
317 PragmaMsStackAction Action,
318 llvm::StringRef StackSlotLabel,
320 explicit PragmaStack(const ValueType &Value)
321 : CurrentValue(Value) {}
322 SmallVector<Slot, 2> Stack;
323 ValueType CurrentValue;
324 SourceLocation CurrentPragmaLocation;
326 // FIXME: We should serialize / deserialize these if they occur in a PCH (but
327 // we shouldn't do so if they're in a module).
328 PragmaStack<StringLiteral *> DataSegStack;
329 PragmaStack<StringLiteral *> BSSSegStack;
330 PragmaStack<StringLiteral *> ConstSegStack;
331 PragmaStack<StringLiteral *> CodeSegStack;
333 /// Last section used with #pragma init_seg.
334 StringLiteral *CurInitSeg;
335 SourceLocation CurInitSegLoc;
337 /// VisContext - Manages the stack for \#pragma GCC visibility.
338 void *VisContext; // Really a "PragmaVisStack*"
340 /// \brief This represents the last location of a "#pragma clang optimize off"
341 /// directive if such a directive has not been closed by an "on" yet. If
342 /// optimizations are currently "on", this is set to an invalid location.
343 SourceLocation OptimizeOffPragmaLocation;
345 /// \brief Flag indicating if Sema is building a recovery call expression.
347 /// This flag is used to avoid building recovery call expressions
348 /// if Sema is already doing so, which would cause infinite recursions.
349 bool IsBuildingRecoveryCallExpr;
351 /// ExprNeedsCleanups - True if the current evaluation context
352 /// requires cleanups to be run at its conclusion.
353 bool ExprNeedsCleanups;
355 /// ExprCleanupObjects - This is the stack of objects requiring
356 /// cleanup that are created by the current full expression. The
357 /// element type here is ExprWithCleanups::Object.
358 SmallVector<BlockDecl*, 8> ExprCleanupObjects;
360 /// \brief Store a list of either DeclRefExprs or MemberExprs
361 /// that contain a reference to a variable (constant) that may or may not
362 /// be odr-used in this Expr, and we won't know until all lvalue-to-rvalue
363 /// and discarded value conversions have been applied to all subexpressions
364 /// of the enclosing full expression. This is cleared at the end of each
366 llvm::SmallPtrSet<Expr*, 2> MaybeODRUseExprs;
368 /// \brief Stack containing information about each of the nested
369 /// function, block, and method scopes that are currently active.
371 /// This array is never empty. Clients should ignore the first
372 /// element, which is used to cache a single FunctionScopeInfo
373 /// that's used to parse every top-level function.
374 SmallVector<sema::FunctionScopeInfo *, 4> FunctionScopes;
376 typedef LazyVector<TypedefNameDecl *, ExternalSemaSource,
377 &ExternalSemaSource::ReadExtVectorDecls, 2, 2>
380 /// ExtVectorDecls - This is a list all the extended vector types. This allows
381 /// us to associate a raw vector type with one of the ext_vector type names.
382 /// This is only necessary for issuing pretty diagnostics.
383 ExtVectorDeclsType ExtVectorDecls;
385 /// FieldCollector - Collects CXXFieldDecls during parsing of C++ classes.
386 std::unique_ptr<CXXFieldCollector> FieldCollector;
388 typedef llvm::SmallSetVector<const NamedDecl*, 16> NamedDeclSetType;
390 /// \brief Set containing all declared private fields that are not used.
391 NamedDeclSetType UnusedPrivateFields;
393 /// \brief Set containing all typedefs that are likely unused.
394 llvm::SmallSetVector<const TypedefNameDecl *, 4>
395 UnusedLocalTypedefNameCandidates;
397 typedef llvm::SmallPtrSet<const CXXRecordDecl*, 8> RecordDeclSetTy;
399 /// PureVirtualClassDiagSet - a set of class declarations which we have
400 /// emitted a list of pure virtual functions. Used to prevent emitting the
401 /// same list more than once.
402 std::unique_ptr<RecordDeclSetTy> PureVirtualClassDiagSet;
404 /// ParsingInitForAutoVars - a set of declarations with auto types for which
405 /// we are currently parsing the initializer.
406 llvm::SmallPtrSet<const Decl*, 4> ParsingInitForAutoVars;
408 /// \brief A mapping from external names to the most recent
409 /// locally-scoped extern "C" declaration with that name.
411 /// This map contains external declarations introduced in local
415 /// extern "C" void f() {
416 /// void foo(int, int);
420 /// Here, the name "foo" will be associated with the declaration of
421 /// "foo" within f. This name is not visible outside of
422 /// "f". However, we still find it in two cases:
424 /// - If we are declaring another global or extern "C" entity with
425 /// the name "foo", we can find "foo" as a previous declaration,
426 /// so that the types of this external declaration can be checked
427 /// for compatibility.
429 /// - If we would implicitly declare "foo" (e.g., due to a call to
430 /// "foo" in C when no prototype or definition is visible), then
431 /// we find this declaration of "foo" and complain that it is
433 llvm::DenseMap<DeclarationName, NamedDecl *> LocallyScopedExternCDecls;
435 /// \brief Look for a locally scoped extern "C" declaration by the given name.
436 NamedDecl *findLocallyScopedExternCDecl(DeclarationName Name);
438 typedef LazyVector<VarDecl *, ExternalSemaSource,
439 &ExternalSemaSource::ReadTentativeDefinitions, 2, 2>
440 TentativeDefinitionsType;
442 /// \brief All the tentative definitions encountered in the TU.
443 TentativeDefinitionsType TentativeDefinitions;
445 typedef LazyVector<const DeclaratorDecl *, ExternalSemaSource,
446 &ExternalSemaSource::ReadUnusedFileScopedDecls, 2, 2>
447 UnusedFileScopedDeclsType;
449 /// \brief The set of file scoped decls seen so far that have not been used
450 /// and must warn if not used. Only contains the first declaration.
451 UnusedFileScopedDeclsType UnusedFileScopedDecls;
453 typedef LazyVector<CXXConstructorDecl *, ExternalSemaSource,
454 &ExternalSemaSource::ReadDelegatingConstructors, 2, 2>
455 DelegatingCtorDeclsType;
457 /// \brief All the delegating constructors seen so far in the file, used for
458 /// cycle detection at the end of the TU.
459 DelegatingCtorDeclsType DelegatingCtorDecls;
461 /// \brief All the overriding functions seen during a class definition
462 /// that had their exception spec checks delayed, plus the overridden
464 SmallVector<std::pair<const CXXMethodDecl*, const CXXMethodDecl*>, 2>
465 DelayedExceptionSpecChecks;
467 /// \brief All the members seen during a class definition which were both
468 /// explicitly defaulted and had explicitly-specified exception
469 /// specifications, along with the function type containing their
470 /// user-specified exception specification. Those exception specifications
471 /// were overridden with the default specifications, but we still need to
472 /// check whether they are compatible with the default specification, and
473 /// we can't do that until the nesting set of class definitions is complete.
474 SmallVector<std::pair<CXXMethodDecl*, const FunctionProtoType*>, 2>
475 DelayedDefaultedMemberExceptionSpecs;
477 typedef llvm::DenseMap<const FunctionDecl *, LateParsedTemplate *>
478 LateParsedTemplateMapT;
479 LateParsedTemplateMapT LateParsedTemplateMap;
481 /// \brief Callback to the parser to parse templated functions when needed.
482 typedef void LateTemplateParserCB(void *P, LateParsedTemplate &LPT);
483 typedef void LateTemplateParserCleanupCB(void *P);
484 LateTemplateParserCB *LateTemplateParser;
485 LateTemplateParserCleanupCB *LateTemplateParserCleanup;
488 void SetLateTemplateParser(LateTemplateParserCB *LTP,
489 LateTemplateParserCleanupCB *LTPCleanup,
491 LateTemplateParser = LTP;
492 LateTemplateParserCleanup = LTPCleanup;
496 class DelayedDiagnostics;
498 class DelayedDiagnosticsState {
499 sema::DelayedDiagnosticPool *SavedPool;
500 friend class Sema::DelayedDiagnostics;
502 typedef DelayedDiagnosticsState ParsingDeclState;
503 typedef DelayedDiagnosticsState ProcessingContextState;
505 /// A class which encapsulates the logic for delaying diagnostics
506 /// during parsing and other processing.
507 class DelayedDiagnostics {
508 /// \brief The current pool of diagnostics into which delayed
509 /// diagnostics should go.
510 sema::DelayedDiagnosticPool *CurPool;
513 DelayedDiagnostics() : CurPool(nullptr) {}
515 /// Adds a delayed diagnostic.
516 void add(const sema::DelayedDiagnostic &diag); // in DelayedDiagnostic.h
518 /// Determines whether diagnostics should be delayed.
519 bool shouldDelayDiagnostics() { return CurPool != nullptr; }
521 /// Returns the current delayed-diagnostics pool.
522 sema::DelayedDiagnosticPool *getCurrentPool() const {
526 /// Enter a new scope. Access and deprecation diagnostics will be
527 /// collected in this pool.
528 DelayedDiagnosticsState push(sema::DelayedDiagnosticPool &pool) {
529 DelayedDiagnosticsState state;
530 state.SavedPool = CurPool;
535 /// Leave a delayed-diagnostic state that was previously pushed.
536 /// Do not emit any of the diagnostics. This is performed as part
537 /// of the bookkeeping of popping a pool "properly".
538 void popWithoutEmitting(DelayedDiagnosticsState state) {
539 CurPool = state.SavedPool;
542 /// Enter a new scope where access and deprecation diagnostics are
544 DelayedDiagnosticsState pushUndelayed() {
545 DelayedDiagnosticsState state;
546 state.SavedPool = CurPool;
551 /// Undo a previous pushUndelayed().
552 void popUndelayed(DelayedDiagnosticsState state) {
553 assert(CurPool == nullptr);
554 CurPool = state.SavedPool;
556 } DelayedDiagnostics;
558 /// A RAII object to temporarily push a declaration context.
562 DeclContext *SavedContext;
563 ProcessingContextState SavedContextState;
564 QualType SavedCXXThisTypeOverride;
567 ContextRAII(Sema &S, DeclContext *ContextToPush, bool NewThisContext = true)
568 : S(S), SavedContext(S.CurContext),
569 SavedContextState(S.DelayedDiagnostics.pushUndelayed()),
570 SavedCXXThisTypeOverride(S.CXXThisTypeOverride)
572 assert(ContextToPush && "pushing null context");
573 S.CurContext = ContextToPush;
575 S.CXXThisTypeOverride = QualType();
579 if (!SavedContext) return;
580 S.CurContext = SavedContext;
581 S.DelayedDiagnostics.popUndelayed(SavedContextState);
582 S.CXXThisTypeOverride = SavedCXXThisTypeOverride;
583 SavedContext = nullptr;
591 /// \brief RAII object to handle the state changes required to synthesize
593 class SynthesizedFunctionScope {
595 Sema::ContextRAII SavedContext;
598 SynthesizedFunctionScope(Sema &S, DeclContext *DC)
599 : S(S), SavedContext(S, DC)
601 S.PushFunctionScope();
602 S.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated);
605 ~SynthesizedFunctionScope() {
606 S.PopExpressionEvaluationContext();
607 S.PopFunctionScopeInfo();
611 /// WeakUndeclaredIdentifiers - Identifiers contained in
612 /// \#pragma weak before declared. rare. may alias another
613 /// identifier, declared or undeclared
614 llvm::DenseMap<IdentifierInfo*,WeakInfo> WeakUndeclaredIdentifiers;
616 /// ExtnameUndeclaredIdentifiers - Identifiers contained in
617 /// \#pragma redefine_extname before declared. Used in Solaris system headers
618 /// to define functions that occur in multiple standards to call the version
619 /// in the currently selected standard.
620 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*> ExtnameUndeclaredIdentifiers;
623 /// \brief Load weak undeclared identifiers from the external source.
624 void LoadExternalWeakUndeclaredIdentifiers();
626 /// WeakTopLevelDecl - Translation-unit scoped declarations generated by
627 /// \#pragma weak during processing of other Decls.
628 /// I couldn't figure out a clean way to generate these in-line, so
629 /// we store them here and handle separately -- which is a hack.
630 /// It would be best to refactor this.
631 SmallVector<Decl*,2> WeakTopLevelDecl;
633 IdentifierResolver IdResolver;
635 /// Translation Unit Scope - useful to Objective-C actions that need
636 /// to lookup file scope declarations in the "ordinary" C decl namespace.
637 /// For example, user-defined classes, built-in "id" type, etc.
640 /// \brief The C++ "std" namespace, where the standard library resides.
641 LazyDeclPtr StdNamespace;
643 /// \brief The C++ "std::bad_alloc" class, which is defined by the C++
644 /// standard library.
645 LazyDeclPtr StdBadAlloc;
647 /// \brief The C++ "std::initializer_list" template, which is defined in
648 /// \<initializer_list>.
649 ClassTemplateDecl *StdInitializerList;
651 /// \brief The C++ "type_info" declaration, which is defined in \<typeinfo>.
652 RecordDecl *CXXTypeInfoDecl;
654 /// \brief The MSVC "_GUID" struct, which is defined in MSVC header files.
655 RecordDecl *MSVCGuidDecl;
657 /// \brief Caches identifiers/selectors for NSFoundation APIs.
658 std::unique_ptr<NSAPI> NSAPIObj;
660 /// \brief The declaration of the Objective-C NSNumber class.
661 ObjCInterfaceDecl *NSNumberDecl;
663 /// \brief Pointer to NSNumber type (NSNumber *).
664 QualType NSNumberPointer;
666 /// \brief The Objective-C NSNumber methods used to create NSNumber literals.
667 ObjCMethodDecl *NSNumberLiteralMethods[NSAPI::NumNSNumberLiteralMethods];
669 /// \brief The declaration of the Objective-C NSString class.
670 ObjCInterfaceDecl *NSStringDecl;
672 /// \brief Pointer to NSString type (NSString *).
673 QualType NSStringPointer;
675 /// \brief The declaration of the stringWithUTF8String: method.
676 ObjCMethodDecl *StringWithUTF8StringMethod;
678 /// \brief The declaration of the Objective-C NSArray class.
679 ObjCInterfaceDecl *NSArrayDecl;
681 /// \brief The declaration of the arrayWithObjects:count: method.
682 ObjCMethodDecl *ArrayWithObjectsMethod;
684 /// \brief The declaration of the Objective-C NSDictionary class.
685 ObjCInterfaceDecl *NSDictionaryDecl;
687 /// \brief The declaration of the dictionaryWithObjects:forKeys:count: method.
688 ObjCMethodDecl *DictionaryWithObjectsMethod;
690 /// \brief id<NSCopying> type.
691 QualType QIDNSCopying;
693 /// \brief will hold 'respondsToSelector:'
694 Selector RespondsToSelectorSel;
696 /// \brief counter for internal MS Asm label names.
697 unsigned MSAsmLabelNameCounter;
699 /// A flag to remember whether the implicit forms of operator new and delete
700 /// have been declared.
701 bool GlobalNewDeleteDeclared;
703 /// A flag to indicate that we're in a context that permits abstract
704 /// references to fields. This is really a
705 bool AllowAbstractFieldReference;
707 /// \brief Describes how the expressions currently being parsed are
708 /// evaluated at run-time, if at all.
709 enum ExpressionEvaluationContext {
710 /// \brief The current expression and its subexpressions occur within an
711 /// unevaluated operand (C++11 [expr]p7), such as the subexpression of
712 /// \c sizeof, where the type of the expression may be significant but
713 /// no code will be generated to evaluate the value of the expression at
717 /// \brief The current expression occurs within an unevaluated
718 /// operand that unconditionally permits abstract references to
719 /// fields, such as a SIZE operator in MS-style inline assembly.
722 /// \brief The current context is "potentially evaluated" in C++11 terms,
723 /// but the expression is evaluated at compile-time (like the values of
724 /// cases in a switch statement).
727 /// \brief The current expression is potentially evaluated at run time,
728 /// which means that code may be generated to evaluate the value of the
729 /// expression at run time.
730 PotentiallyEvaluated,
732 /// \brief The current expression is potentially evaluated, but any
733 /// declarations referenced inside that expression are only used if
734 /// in fact the current expression is used.
736 /// This value is used when parsing default function arguments, for which
737 /// we would like to provide diagnostics (e.g., passing non-POD arguments
738 /// through varargs) but do not want to mark declarations as "referenced"
739 /// until the default argument is used.
740 PotentiallyEvaluatedIfUsed
743 /// \brief Data structure used to record current or nested
744 /// expression evaluation contexts.
745 struct ExpressionEvaluationContextRecord {
746 /// \brief The expression evaluation context.
747 ExpressionEvaluationContext Context;
749 /// \brief Whether the enclosing context needed a cleanup.
750 bool ParentNeedsCleanups;
752 /// \brief Whether we are in a decltype expression.
755 /// \brief The number of active cleanup objects when we entered
756 /// this expression evaluation context.
757 unsigned NumCleanupObjects;
759 /// \brief The number of typos encountered during this expression evaluation
760 /// context (i.e. the number of TypoExprs created).
763 llvm::SmallPtrSet<Expr*, 2> SavedMaybeODRUseExprs;
765 /// \brief The lambdas that are present within this context, if it
766 /// is indeed an unevaluated context.
767 SmallVector<LambdaExpr *, 2> Lambdas;
769 /// \brief The declaration that provides context for lambda expressions
770 /// and block literals if the normal declaration context does not
771 /// suffice, e.g., in a default function argument.
772 Decl *ManglingContextDecl;
774 /// \brief The context information used to mangle lambda expressions
775 /// and block literals within this context.
777 /// This mangling information is allocated lazily, since most contexts
778 /// do not have lambda expressions or block literals.
779 IntrusiveRefCntPtr<MangleNumberingContext> MangleNumbering;
781 /// \brief If we are processing a decltype type, a set of call expressions
782 /// for which we have deferred checking the completeness of the return type.
783 SmallVector<CallExpr *, 8> DelayedDecltypeCalls;
785 /// \brief If we are processing a decltype type, a set of temporary binding
786 /// expressions for which we have deferred checking the destructor.
787 SmallVector<CXXBindTemporaryExpr *, 8> DelayedDecltypeBinds;
789 ExpressionEvaluationContextRecord(ExpressionEvaluationContext Context,
790 unsigned NumCleanupObjects,
791 bool ParentNeedsCleanups,
792 Decl *ManglingContextDecl,
794 : Context(Context), ParentNeedsCleanups(ParentNeedsCleanups),
795 IsDecltype(IsDecltype), NumCleanupObjects(NumCleanupObjects),
797 ManglingContextDecl(ManglingContextDecl), MangleNumbering() { }
799 /// \brief Retrieve the mangling numbering context, used to consistently
800 /// number constructs like lambdas for mangling.
801 MangleNumberingContext &getMangleNumberingContext(ASTContext &Ctx);
803 bool isUnevaluated() const {
804 return Context == Unevaluated || Context == UnevaluatedAbstract;
808 /// A stack of expression evaluation contexts.
809 SmallVector<ExpressionEvaluationContextRecord, 8> ExprEvalContexts;
811 /// \brief Compute the mangling number context for a lambda expression or
814 /// \param DC - The DeclContext containing the lambda expression or
816 /// \param[out] ManglingContextDecl - Returns the ManglingContextDecl
817 /// associated with the context, if relevant.
818 MangleNumberingContext *getCurrentMangleNumberContext(
819 const DeclContext *DC,
820 Decl *&ManglingContextDecl);
823 /// SpecialMemberOverloadResult - The overloading result for a special member
826 /// This is basically a wrapper around PointerIntPair. The lowest bits of the
827 /// integer are used to determine whether overload resolution succeeded.
828 class SpecialMemberOverloadResult : public llvm::FastFoldingSetNode {
837 llvm::PointerIntPair<CXXMethodDecl*, 2> Pair;
840 SpecialMemberOverloadResult(const llvm::FoldingSetNodeID &ID)
841 : FastFoldingSetNode(ID)
844 CXXMethodDecl *getMethod() const { return Pair.getPointer(); }
845 void setMethod(CXXMethodDecl *MD) { Pair.setPointer(MD); }
847 Kind getKind() const { return static_cast<Kind>(Pair.getInt()); }
848 void setKind(Kind K) { Pair.setInt(K); }
851 /// \brief A cache of special member function overload resolution results
853 llvm::FoldingSet<SpecialMemberOverloadResult> SpecialMemberCache;
855 /// \brief The kind of translation unit we are processing.
857 /// When we're processing a complete translation unit, Sema will perform
858 /// end-of-translation-unit semantic tasks (such as creating
859 /// initializers for tentative definitions in C) once parsing has
860 /// completed. Modules and precompiled headers perform different kinds of
862 TranslationUnitKind TUKind;
864 llvm::BumpPtrAllocator BumpAlloc;
866 /// \brief The number of SFINAE diagnostics that have been trapped.
867 unsigned NumSFINAEErrors;
869 typedef llvm::DenseMap<ParmVarDecl *, llvm::TinyPtrVector<ParmVarDecl *>>
870 UnparsedDefaultArgInstantiationsMap;
872 /// \brief A mapping from parameters with unparsed default arguments to the
873 /// set of instantiations of each parameter.
875 /// This mapping is a temporary data structure used when parsing
876 /// nested class templates or nested classes of class templates,
877 /// where we might end up instantiating an inner class before the
878 /// default arguments of its methods have been parsed.
879 UnparsedDefaultArgInstantiationsMap UnparsedDefaultArgInstantiations;
881 // Contains the locations of the beginning of unparsed default
882 // argument locations.
883 llvm::DenseMap<ParmVarDecl *, SourceLocation> UnparsedDefaultArgLocs;
885 /// UndefinedInternals - all the used, undefined objects which require a
886 /// definition in this translation unit.
887 llvm::DenseMap<NamedDecl *, SourceLocation> UndefinedButUsed;
889 /// Obtain a sorted list of functions that are undefined but ODR-used.
890 void getUndefinedButUsed(
891 SmallVectorImpl<std::pair<NamedDecl *, SourceLocation> > &Undefined);
893 typedef std::pair<ObjCMethodList, ObjCMethodList> GlobalMethods;
894 typedef llvm::DenseMap<Selector, GlobalMethods> GlobalMethodPool;
896 /// Method Pool - allows efficient lookup when typechecking messages to "id".
897 /// We need to maintain a list, since selectors can have differing signatures
898 /// across classes. In Cocoa, this happens to be extremely uncommon (only 1%
899 /// of selectors are "overloaded").
900 /// At the head of the list it is recorded whether there were 0, 1, or >= 2
901 /// methods inside categories with a particular selector.
902 GlobalMethodPool MethodPool;
904 /// Method selectors used in a \@selector expression. Used for implementation
906 llvm::DenseMap<Selector, SourceLocation> ReferencedSelectors;
908 /// Kinds of C++ special members.
909 enum CXXSpecialMember {
910 CXXDefaultConstructor,
919 typedef std::pair<CXXRecordDecl*, CXXSpecialMember> SpecialMemberDecl;
921 /// The C++ special members which we are currently in the process of
922 /// declaring. If this process recursively triggers the declaration of the
923 /// same special member, we should act as if it is not yet declared.
924 llvm::SmallSet<SpecialMemberDecl, 4> SpecialMembersBeingDeclared;
926 void ReadMethodPool(Selector Sel);
928 /// Private Helper predicate to check for 'self'.
929 bool isSelfExpr(Expr *RExpr);
930 bool isSelfExpr(Expr *RExpr, const ObjCMethodDecl *Method);
932 /// \brief Cause the active diagnostic on the DiagosticsEngine to be
933 /// emitted. This is closely coupled to the SemaDiagnosticBuilder class and
934 /// should not be used elsewhere.
935 void EmitCurrentDiagnostic(unsigned DiagID);
937 /// Records and restores the FP_CONTRACT state on entry/exit of compound
939 class FPContractStateRAII {
941 FPContractStateRAII(Sema& S)
942 : S(S), OldFPContractState(S.FPFeatures.fp_contract) {}
943 ~FPContractStateRAII() {
944 S.FPFeatures.fp_contract = OldFPContractState;
948 bool OldFPContractState : 1;
951 void addImplicitTypedef(StringRef Name, QualType T);
954 Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer,
955 TranslationUnitKind TUKind = TU_Complete,
956 CodeCompleteConsumer *CompletionConsumer = nullptr);
959 /// \brief Perform initialization that occurs after the parser has been
960 /// initialized but before it parses anything.
963 const LangOptions &getLangOpts() const { return LangOpts; }
964 OpenCLOptions &getOpenCLOptions() { return OpenCLFeatures; }
965 FPOptions &getFPOptions() { return FPFeatures; }
967 DiagnosticsEngine &getDiagnostics() const { return Diags; }
968 SourceManager &getSourceManager() const { return SourceMgr; }
969 Preprocessor &getPreprocessor() const { return PP; }
970 ASTContext &getASTContext() const { return Context; }
971 ASTConsumer &getASTConsumer() const { return Consumer; }
972 ASTMutationListener *getASTMutationListener() const;
973 ExternalSemaSource* getExternalSource() const { return ExternalSource; }
975 ///\brief Registers an external source. If an external source already exists,
976 /// creates a multiplex external source and appends to it.
978 ///\param[in] E - A non-null external sema source.
980 void addExternalSource(ExternalSemaSource *E);
982 void PrintStats() const;
984 /// \brief Helper class that creates diagnostics with optional
985 /// template instantiation stacks.
987 /// This class provides a wrapper around the basic DiagnosticBuilder
988 /// class that emits diagnostics. SemaDiagnosticBuilder is
989 /// responsible for emitting the diagnostic (as DiagnosticBuilder
990 /// does) and, if the diagnostic comes from inside a template
991 /// instantiation, printing the template instantiation stack as
993 class SemaDiagnosticBuilder : public DiagnosticBuilder {
998 SemaDiagnosticBuilder(DiagnosticBuilder &DB, Sema &SemaRef, unsigned DiagID)
999 : DiagnosticBuilder(DB), SemaRef(SemaRef), DiagID(DiagID) { }
1001 ~SemaDiagnosticBuilder() {
1002 // If we aren't active, there is nothing to do.
1003 if (!isActive()) return;
1005 // Otherwise, we need to emit the diagnostic. First flush the underlying
1006 // DiagnosticBuilder data, and clear the diagnostic builder itself so it
1007 // won't emit the diagnostic in its own destructor.
1009 // This seems wasteful, in that as written the DiagnosticBuilder dtor will
1010 // do its own needless checks to see if the diagnostic needs to be
1011 // emitted. However, because we take care to ensure that the builder
1012 // objects never escape, a sufficiently smart compiler will be able to
1013 // eliminate that code.
1017 // Dispatch to Sema to emit the diagnostic.
1018 SemaRef.EmitCurrentDiagnostic(DiagID);
1021 /// Teach operator<< to produce an object of the correct type.
1022 template<typename T>
1023 friend const SemaDiagnosticBuilder &operator<<(
1024 const SemaDiagnosticBuilder &Diag, const T &Value) {
1025 const DiagnosticBuilder &BaseDiag = Diag;
1031 /// \brief Emit a diagnostic.
1032 SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID) {
1033 DiagnosticBuilder DB = Diags.Report(Loc, DiagID);
1034 return SemaDiagnosticBuilder(DB, *this, DiagID);
1037 /// \brief Emit a partial diagnostic.
1038 SemaDiagnosticBuilder Diag(SourceLocation Loc, const PartialDiagnostic& PD);
1040 /// \brief Build a partial diagnostic.
1041 PartialDiagnostic PDiag(unsigned DiagID = 0); // in SemaInternal.h
1043 bool findMacroSpelling(SourceLocation &loc, StringRef name);
1045 /// \brief Get a string to suggest for zero-initialization of a type.
1047 getFixItZeroInitializerForType(QualType T, SourceLocation Loc) const;
1048 std::string getFixItZeroLiteralForType(QualType T, SourceLocation Loc) const;
1050 /// \brief Calls \c Lexer::getLocForEndOfToken()
1051 SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset = 0);
1053 /// \brief Retrieve the module loader associated with the preprocessor.
1054 ModuleLoader &getModuleLoader() const;
1056 void emitAndClearUnusedLocalTypedefWarnings();
1058 void ActOnEndOfTranslationUnit();
1060 void CheckDelegatingCtorCycles();
1062 Scope *getScopeForContext(DeclContext *Ctx);
1064 void PushFunctionScope();
1065 void PushBlockScope(Scope *BlockScope, BlockDecl *Block);
1066 sema::LambdaScopeInfo *PushLambdaScope();
1068 /// \brief This is used to inform Sema what the current TemplateParameterDepth
1069 /// is during Parsing. Currently it is used to pass on the depth
1070 /// when parsing generic lambda 'auto' parameters.
1071 void RecordParsingTemplateParameterDepth(unsigned Depth);
1073 void PushCapturedRegionScope(Scope *RegionScope, CapturedDecl *CD,
1075 CapturedRegionKind K);
1077 PopFunctionScopeInfo(const sema::AnalysisBasedWarnings::Policy *WP = nullptr,
1078 const Decl *D = nullptr,
1079 const BlockExpr *blkExpr = nullptr);
1081 sema::FunctionScopeInfo *getCurFunction() const {
1082 return FunctionScopes.back();
1085 sema::FunctionScopeInfo *getEnclosingFunction() const {
1086 if (FunctionScopes.empty())
1089 for (int e = FunctionScopes.size()-1; e >= 0; --e) {
1090 if (isa<sema::BlockScopeInfo>(FunctionScopes[e]))
1092 return FunctionScopes[e];
1097 template <typename ExprT>
1098 void recordUseOfEvaluatedWeak(const ExprT *E, bool IsRead=true) {
1099 if (!isUnevaluatedContext())
1100 getCurFunction()->recordUseOfWeak(E, IsRead);
1103 void PushCompoundScope();
1104 void PopCompoundScope();
1106 sema::CompoundScopeInfo &getCurCompoundScope() const;
1108 bool hasAnyUnrecoverableErrorsInThisFunction() const;
1110 /// \brief Retrieve the current block, if any.
1111 sema::BlockScopeInfo *getCurBlock();
1113 /// \brief Retrieve the current lambda scope info, if any.
1114 sema::LambdaScopeInfo *getCurLambda();
1116 /// \brief Retrieve the current generic lambda info, if any.
1117 sema::LambdaScopeInfo *getCurGenericLambda();
1119 /// \brief Retrieve the current captured region, if any.
1120 sema::CapturedRegionScopeInfo *getCurCapturedRegion();
1122 /// WeakTopLevelDeclDecls - access to \#pragma weak-generated Decls
1123 SmallVectorImpl<Decl *> &WeakTopLevelDecls() { return WeakTopLevelDecl; }
1125 void ActOnComment(SourceRange Comment);
1127 //===--------------------------------------------------------------------===//
1128 // Type Analysis / Processing: SemaType.cpp.
1131 QualType BuildQualifiedType(QualType T, SourceLocation Loc, Qualifiers Qs,
1132 const DeclSpec *DS = nullptr);
1133 QualType BuildQualifiedType(QualType T, SourceLocation Loc, unsigned CVRA,
1134 const DeclSpec *DS = nullptr);
1135 QualType BuildPointerType(QualType T,
1136 SourceLocation Loc, DeclarationName Entity);
1137 QualType BuildReferenceType(QualType T, bool LValueRef,
1138 SourceLocation Loc, DeclarationName Entity);
1139 QualType BuildArrayType(QualType T, ArrayType::ArraySizeModifier ASM,
1140 Expr *ArraySize, unsigned Quals,
1141 SourceRange Brackets, DeclarationName Entity);
1142 QualType BuildExtVectorType(QualType T, Expr *ArraySize,
1143 SourceLocation AttrLoc);
1145 bool CheckFunctionReturnType(QualType T, SourceLocation Loc);
1147 /// \brief Build a function type.
1149 /// This routine checks the function type according to C++ rules and
1150 /// under the assumption that the result type and parameter types have
1151 /// just been instantiated from a template. It therefore duplicates
1152 /// some of the behavior of GetTypeForDeclarator, but in a much
1153 /// simpler form that is only suitable for this narrow use case.
1155 /// \param T The return type of the function.
1157 /// \param ParamTypes The parameter types of the function. This array
1158 /// will be modified to account for adjustments to the types of the
1159 /// function parameters.
1161 /// \param Loc The location of the entity whose type involves this
1162 /// function type or, if there is no such entity, the location of the
1163 /// type that will have function type.
1165 /// \param Entity The name of the entity that involves the function
1168 /// \param EPI Extra information about the function type. Usually this will
1169 /// be taken from an existing function with the same prototype.
1171 /// \returns A suitable function type, if there are no errors. The
1172 /// unqualified type will always be a FunctionProtoType.
1173 /// Otherwise, returns a NULL type.
1174 QualType BuildFunctionType(QualType T,
1175 MutableArrayRef<QualType> ParamTypes,
1176 SourceLocation Loc, DeclarationName Entity,
1177 const FunctionProtoType::ExtProtoInfo &EPI);
1179 QualType BuildMemberPointerType(QualType T, QualType Class,
1181 DeclarationName Entity);
1182 QualType BuildBlockPointerType(QualType T,
1183 SourceLocation Loc, DeclarationName Entity);
1184 QualType BuildParenType(QualType T);
1185 QualType BuildAtomicType(QualType T, SourceLocation Loc);
1187 TypeSourceInfo *GetTypeForDeclarator(Declarator &D, Scope *S);
1188 TypeSourceInfo *GetTypeForDeclaratorCast(Declarator &D, QualType FromTy);
1189 TypeSourceInfo *GetTypeSourceInfoForDeclarator(Declarator &D, QualType T,
1190 TypeSourceInfo *ReturnTypeInfo);
1192 /// \brief Package the given type and TSI into a ParsedType.
1193 ParsedType CreateParsedType(QualType T, TypeSourceInfo *TInfo);
1194 DeclarationNameInfo GetNameForDeclarator(Declarator &D);
1195 DeclarationNameInfo GetNameFromUnqualifiedId(const UnqualifiedId &Name);
1196 static QualType GetTypeFromParser(ParsedType Ty,
1197 TypeSourceInfo **TInfo = nullptr);
1198 CanThrowResult canThrow(const Expr *E);
1199 const FunctionProtoType *ResolveExceptionSpec(SourceLocation Loc,
1200 const FunctionProtoType *FPT);
1201 void UpdateExceptionSpec(FunctionDecl *FD,
1202 const FunctionProtoType::ExceptionSpecInfo &ESI);
1203 bool CheckSpecifiedExceptionType(QualType &T, const SourceRange &Range);
1204 bool CheckDistantExceptionSpec(QualType T);
1205 bool CheckEquivalentExceptionSpec(FunctionDecl *Old, FunctionDecl *New);
1206 bool CheckEquivalentExceptionSpec(
1207 const FunctionProtoType *Old, SourceLocation OldLoc,
1208 const FunctionProtoType *New, SourceLocation NewLoc);
1209 bool CheckEquivalentExceptionSpec(
1210 const PartialDiagnostic &DiagID, const PartialDiagnostic & NoteID,
1211 const FunctionProtoType *Old, SourceLocation OldLoc,
1212 const FunctionProtoType *New, SourceLocation NewLoc,
1213 bool *MissingExceptionSpecification = nullptr,
1214 bool *MissingEmptyExceptionSpecification = nullptr,
1215 bool AllowNoexceptAllMatchWithNoSpec = false,
1216 bool IsOperatorNew = false);
1217 bool CheckExceptionSpecSubset(
1218 const PartialDiagnostic &DiagID, const PartialDiagnostic & NoteID,
1219 const FunctionProtoType *Superset, SourceLocation SuperLoc,
1220 const FunctionProtoType *Subset, SourceLocation SubLoc);
1221 bool CheckParamExceptionSpec(const PartialDiagnostic & NoteID,
1222 const FunctionProtoType *Target, SourceLocation TargetLoc,
1223 const FunctionProtoType *Source, SourceLocation SourceLoc);
1225 TypeResult ActOnTypeName(Scope *S, Declarator &D);
1227 /// \brief The parser has parsed the context-sensitive type 'instancetype'
1228 /// in an Objective-C message declaration. Return the appropriate type.
1229 ParsedType ActOnObjCInstanceType(SourceLocation Loc);
1231 /// \brief Abstract class used to diagnose incomplete types.
1232 struct TypeDiagnoser {
1235 TypeDiagnoser(bool Suppressed = false) : Suppressed(Suppressed) { }
1237 virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) = 0;
1238 virtual ~TypeDiagnoser() {}
1241 static int getPrintable(int I) { return I; }
1242 static unsigned getPrintable(unsigned I) { return I; }
1243 static bool getPrintable(bool B) { return B; }
1244 static const char * getPrintable(const char *S) { return S; }
1245 static StringRef getPrintable(StringRef S) { return S; }
1246 static const std::string &getPrintable(const std::string &S) { return S; }
1247 static const IdentifierInfo *getPrintable(const IdentifierInfo *II) {
1250 static DeclarationName getPrintable(DeclarationName N) { return N; }
1251 static QualType getPrintable(QualType T) { return T; }
1252 static SourceRange getPrintable(SourceRange R) { return R; }
1253 static SourceRange getPrintable(SourceLocation L) { return L; }
1254 static SourceRange getPrintable(const Expr *E) { return E->getSourceRange(); }
1255 static SourceRange getPrintable(TypeLoc TL) { return TL.getSourceRange();}
1257 template<typename T1>
1258 class BoundTypeDiagnoser1 : public TypeDiagnoser {
1263 BoundTypeDiagnoser1(unsigned DiagID, const T1 &Arg1)
1264 : TypeDiagnoser(DiagID == 0), DiagID(DiagID), Arg1(Arg1) { }
1265 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
1266 if (Suppressed) return;
1267 S.Diag(Loc, DiagID) << getPrintable(Arg1) << T;
1270 virtual ~BoundTypeDiagnoser1() { }
1273 template<typename T1, typename T2>
1274 class BoundTypeDiagnoser2 : public TypeDiagnoser {
1280 BoundTypeDiagnoser2(unsigned DiagID, const T1 &Arg1,
1282 : TypeDiagnoser(DiagID == 0), DiagID(DiagID), Arg1(Arg1),
1285 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
1286 if (Suppressed) return;
1287 S.Diag(Loc, DiagID) << getPrintable(Arg1) << getPrintable(Arg2) << T;
1290 virtual ~BoundTypeDiagnoser2() { }
1293 template<typename T1, typename T2, typename T3>
1294 class BoundTypeDiagnoser3 : public TypeDiagnoser {
1301 BoundTypeDiagnoser3(unsigned DiagID, const T1 &Arg1,
1302 const T2 &Arg2, const T3 &Arg3)
1303 : TypeDiagnoser(DiagID == 0), DiagID(DiagID), Arg1(Arg1),
1304 Arg2(Arg2), Arg3(Arg3) { }
1306 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
1307 if (Suppressed) return;
1309 << getPrintable(Arg1) << getPrintable(Arg2) << getPrintable(Arg3) << T;
1312 virtual ~BoundTypeDiagnoser3() { }
1316 bool RequireCompleteTypeImpl(SourceLocation Loc, QualType T,
1317 TypeDiagnoser &Diagnoser);
1319 bool RequireCompleteType(SourceLocation Loc, QualType T,
1320 TypeDiagnoser &Diagnoser);
1321 bool RequireCompleteType(SourceLocation Loc, QualType T,
1324 template<typename T1>
1325 bool RequireCompleteType(SourceLocation Loc, QualType T,
1326 unsigned DiagID, const T1 &Arg1) {
1327 BoundTypeDiagnoser1<T1> Diagnoser(DiagID, Arg1);
1328 return RequireCompleteType(Loc, T, Diagnoser);
1331 template<typename T1, typename T2>
1332 bool RequireCompleteType(SourceLocation Loc, QualType T,
1333 unsigned DiagID, const T1 &Arg1, const T2 &Arg2) {
1334 BoundTypeDiagnoser2<T1, T2> Diagnoser(DiagID, Arg1, Arg2);
1335 return RequireCompleteType(Loc, T, Diagnoser);
1338 template<typename T1, typename T2, typename T3>
1339 bool RequireCompleteType(SourceLocation Loc, QualType T,
1340 unsigned DiagID, const T1 &Arg1, const T2 &Arg2,
1342 BoundTypeDiagnoser3<T1, T2, T3> Diagnoser(DiagID, Arg1, Arg2,
1344 return RequireCompleteType(Loc, T, Diagnoser);
1347 bool RequireCompleteExprType(Expr *E, TypeDiagnoser &Diagnoser);
1348 bool RequireCompleteExprType(Expr *E, unsigned DiagID);
1350 template<typename T1>
1351 bool RequireCompleteExprType(Expr *E, unsigned DiagID, const T1 &Arg1) {
1352 BoundTypeDiagnoser1<T1> Diagnoser(DiagID, Arg1);
1353 return RequireCompleteExprType(E, Diagnoser);
1356 template<typename T1, typename T2>
1357 bool RequireCompleteExprType(Expr *E, unsigned DiagID, const T1 &Arg1,
1359 BoundTypeDiagnoser2<T1, T2> Diagnoser(DiagID, Arg1, Arg2);
1360 return RequireCompleteExprType(E, Diagnoser);
1363 template<typename T1, typename T2, typename T3>
1364 bool RequireCompleteExprType(Expr *E, unsigned DiagID, const T1 &Arg1,
1365 const T2 &Arg2, const T3 &Arg3) {
1366 BoundTypeDiagnoser3<T1, T2, T3> Diagnoser(DiagID, Arg1, Arg2,
1368 return RequireCompleteExprType(E, Diagnoser);
1371 bool RequireLiteralType(SourceLocation Loc, QualType T,
1372 TypeDiagnoser &Diagnoser);
1373 bool RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID);
1375 template<typename T1>
1376 bool RequireLiteralType(SourceLocation Loc, QualType T,
1377 unsigned DiagID, const T1 &Arg1) {
1378 BoundTypeDiagnoser1<T1> Diagnoser(DiagID, Arg1);
1379 return RequireLiteralType(Loc, T, Diagnoser);
1382 template<typename T1, typename T2>
1383 bool RequireLiteralType(SourceLocation Loc, QualType T,
1384 unsigned DiagID, const T1 &Arg1, const T2 &Arg2) {
1385 BoundTypeDiagnoser2<T1, T2> Diagnoser(DiagID, Arg1, Arg2);
1386 return RequireLiteralType(Loc, T, Diagnoser);
1389 template<typename T1, typename T2, typename T3>
1390 bool RequireLiteralType(SourceLocation Loc, QualType T,
1391 unsigned DiagID, const T1 &Arg1, const T2 &Arg2,
1393 BoundTypeDiagnoser3<T1, T2, T3> Diagnoser(DiagID, Arg1, Arg2,
1395 return RequireLiteralType(Loc, T, Diagnoser);
1398 QualType getElaboratedType(ElaboratedTypeKeyword Keyword,
1399 const CXXScopeSpec &SS, QualType T);
1401 QualType BuildTypeofExprType(Expr *E, SourceLocation Loc);
1402 /// If AsUnevaluated is false, E is treated as though it were an evaluated
1403 /// context, such as when building a type for decltype(auto).
1404 QualType BuildDecltypeType(Expr *E, SourceLocation Loc,
1405 bool AsUnevaluated = true);
1406 QualType BuildUnaryTransformType(QualType BaseType,
1407 UnaryTransformType::UTTKind UKind,
1408 SourceLocation Loc);
1410 //===--------------------------------------------------------------------===//
1411 // Symbol table / Decl tracking callbacks: SemaDecl.cpp.
1414 /// List of decls defined in a function prototype. This contains EnumConstants
1415 /// that incorrectly end up in translation unit scope because there is no
1416 /// function to pin them on. ActOnFunctionDeclarator reads this list and patches
1417 /// them into the FunctionDecl.
1418 std::vector<NamedDecl*> DeclsInPrototypeScope;
1420 DeclGroupPtrTy ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType = nullptr);
1422 void DiagnoseUseOfUnimplementedSelectors();
1424 bool isSimpleTypeSpecifier(tok::TokenKind Kind) const;
1426 ParsedType getTypeName(const IdentifierInfo &II, SourceLocation NameLoc,
1427 Scope *S, CXXScopeSpec *SS = nullptr,
1428 bool isClassName = false,
1429 bool HasTrailingDot = false,
1430 ParsedType ObjectType = ParsedType(),
1431 bool IsCtorOrDtorName = false,
1432 bool WantNontrivialTypeSourceInfo = false,
1433 IdentifierInfo **CorrectedII = nullptr);
1434 TypeSpecifierType isTagName(IdentifierInfo &II, Scope *S);
1435 bool isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S);
1436 void DiagnoseUnknownTypeName(IdentifierInfo *&II,
1437 SourceLocation IILoc,
1440 ParsedType &SuggestedType,
1441 bool AllowClassTemplates = false);
1443 /// \brief For compatibility with MSVC, we delay parsing of some default
1444 /// template type arguments until instantiation time. Emits a warning and
1445 /// returns a synthesized DependentNameType that isn't really dependent on any
1446 /// other template arguments.
1447 ParsedType ActOnDelayedDefaultTemplateArg(const IdentifierInfo &II,
1448 SourceLocation NameLoc);
1450 /// \brief Describes the result of the name lookup and resolution performed
1451 /// by \c ClassifyName().
1452 enum NameClassificationKind {
1458 NC_NestedNameSpecifier,
1464 class NameClassification {
1465 NameClassificationKind Kind;
1467 TemplateName Template;
1469 const IdentifierInfo *Keyword;
1471 explicit NameClassification(NameClassificationKind Kind) : Kind(Kind) {}
1474 NameClassification(ExprResult Expr) : Kind(NC_Expression), Expr(Expr) {}
1476 NameClassification(ParsedType Type) : Kind(NC_Type), Type(Type) {}
1478 NameClassification(const IdentifierInfo *Keyword)
1479 : Kind(NC_Keyword), Keyword(Keyword) { }
1481 static NameClassification Error() {
1482 return NameClassification(NC_Error);
1485 static NameClassification Unknown() {
1486 return NameClassification(NC_Unknown);
1489 static NameClassification NestedNameSpecifier() {
1490 return NameClassification(NC_NestedNameSpecifier);
1493 static NameClassification TypeTemplate(TemplateName Name) {
1494 NameClassification Result(NC_TypeTemplate);
1495 Result.Template = Name;
1499 static NameClassification VarTemplate(TemplateName Name) {
1500 NameClassification Result(NC_VarTemplate);
1501 Result.Template = Name;
1505 static NameClassification FunctionTemplate(TemplateName Name) {
1506 NameClassification Result(NC_FunctionTemplate);
1507 Result.Template = Name;
1511 NameClassificationKind getKind() const { return Kind; }
1513 ParsedType getType() const {
1514 assert(Kind == NC_Type);
1518 ExprResult getExpression() const {
1519 assert(Kind == NC_Expression);
1523 TemplateName getTemplateName() const {
1524 assert(Kind == NC_TypeTemplate || Kind == NC_FunctionTemplate ||
1525 Kind == NC_VarTemplate);
1529 TemplateNameKind getTemplateNameKind() const {
1531 case NC_TypeTemplate:
1532 return TNK_Type_template;
1533 case NC_FunctionTemplate:
1534 return TNK_Function_template;
1535 case NC_VarTemplate:
1536 return TNK_Var_template;
1538 llvm_unreachable("unsupported name classification.");
1543 /// \brief Perform name lookup on the given name, classifying it based on
1544 /// the results of name lookup and the following token.
1546 /// This routine is used by the parser to resolve identifiers and help direct
1547 /// parsing. When the identifier cannot be found, this routine will attempt
1548 /// to correct the typo and classify based on the resulting name.
1550 /// \param S The scope in which we're performing name lookup.
1552 /// \param SS The nested-name-specifier that precedes the name.
1554 /// \param Name The identifier. If typo correction finds an alternative name,
1555 /// this pointer parameter will be updated accordingly.
1557 /// \param NameLoc The location of the identifier.
1559 /// \param NextToken The token following the identifier. Used to help
1560 /// disambiguate the name.
1562 /// \param IsAddressOfOperand True if this name is the operand of a unary
1563 /// address of ('&') expression, assuming it is classified as an
1566 /// \param CCC The correction callback, if typo correction is desired.
1568 ClassifyName(Scope *S, CXXScopeSpec &SS, IdentifierInfo *&Name,
1569 SourceLocation NameLoc, const Token &NextToken,
1570 bool IsAddressOfOperand,
1571 std::unique_ptr<CorrectionCandidateCallback> CCC = nullptr);
1573 Decl *ActOnDeclarator(Scope *S, Declarator &D);
1575 NamedDecl *HandleDeclarator(Scope *S, Declarator &D,
1576 MultiTemplateParamsArg TemplateParameterLists);
1577 void RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S);
1578 bool DiagnoseClassNameShadow(DeclContext *DC, DeclarationNameInfo Info);
1579 bool diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
1580 DeclarationName Name,
1581 SourceLocation Loc);
1583 diagnoseIgnoredQualifiers(unsigned DiagID, unsigned Quals,
1584 SourceLocation FallbackLoc,
1585 SourceLocation ConstQualLoc = SourceLocation(),
1586 SourceLocation VolatileQualLoc = SourceLocation(),
1587 SourceLocation RestrictQualLoc = SourceLocation(),
1588 SourceLocation AtomicQualLoc = SourceLocation());
1590 static bool adjustContextForLocalExternDecl(DeclContext *&DC);
1591 void DiagnoseFunctionSpecifiers(const DeclSpec &DS);
1592 void CheckShadow(Scope *S, VarDecl *D, const LookupResult& R);
1593 void CheckShadow(Scope *S, VarDecl *D);
1594 void CheckCastAlign(Expr *Op, QualType T, SourceRange TRange);
1595 void CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *D);
1596 NamedDecl* ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
1597 TypeSourceInfo *TInfo,
1598 LookupResult &Previous);
1599 NamedDecl* ActOnTypedefNameDecl(Scope* S, DeclContext* DC, TypedefNameDecl *D,
1600 LookupResult &Previous, bool &Redeclaration);
1601 NamedDecl *ActOnVariableDeclarator(Scope *S, Declarator &D, DeclContext *DC,
1602 TypeSourceInfo *TInfo,
1603 LookupResult &Previous,
1604 MultiTemplateParamsArg TemplateParamLists,
1606 // Returns true if the variable declaration is a redeclaration
1607 bool CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous);
1608 void CheckVariableDeclarationType(VarDecl *NewVD);
1609 void CheckCompleteVariableDeclaration(VarDecl *var);
1610 void MaybeSuggestAddingStaticToDecl(const FunctionDecl *D);
1612 NamedDecl* ActOnFunctionDeclarator(Scope* S, Declarator& D, DeclContext* DC,
1613 TypeSourceInfo *TInfo,
1614 LookupResult &Previous,
1615 MultiTemplateParamsArg TemplateParamLists,
1617 bool AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD);
1619 bool CheckConstexprFunctionDecl(const FunctionDecl *FD);
1620 bool CheckConstexprFunctionBody(const FunctionDecl *FD, Stmt *Body);
1622 void DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD);
1623 void FindHiddenVirtualMethods(CXXMethodDecl *MD,
1624 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods);
1625 void NoteHiddenVirtualMethods(CXXMethodDecl *MD,
1626 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods);
1627 // Returns true if the function declaration is a redeclaration
1628 bool CheckFunctionDeclaration(Scope *S,
1629 FunctionDecl *NewFD, LookupResult &Previous,
1630 bool IsExplicitSpecialization);
1631 void CheckMain(FunctionDecl *FD, const DeclSpec &D);
1632 void CheckMSVCRTEntryPoint(FunctionDecl *FD);
1633 Decl *ActOnParamDeclarator(Scope *S, Declarator &D);
1634 ParmVarDecl *BuildParmVarDeclForTypedef(DeclContext *DC,
1637 ParmVarDecl *CheckParameter(DeclContext *DC, SourceLocation StartLoc,
1638 SourceLocation NameLoc, IdentifierInfo *Name,
1639 QualType T, TypeSourceInfo *TSInfo,
1641 void ActOnParamDefaultArgument(Decl *param,
1642 SourceLocation EqualLoc,
1644 void ActOnParamUnparsedDefaultArgument(Decl *param,
1645 SourceLocation EqualLoc,
1646 SourceLocation ArgLoc);
1647 void ActOnParamDefaultArgumentError(Decl *param, SourceLocation EqualLoc);
1648 bool SetParamDefaultArgument(ParmVarDecl *Param, Expr *DefaultArg,
1649 SourceLocation EqualLoc);
1651 void AddInitializerToDecl(Decl *dcl, Expr *init, bool DirectInit,
1652 bool TypeMayContainAuto);
1653 void ActOnUninitializedDecl(Decl *dcl, bool TypeMayContainAuto);
1654 void ActOnInitializerError(Decl *Dcl);
1655 void ActOnCXXForRangeDecl(Decl *D);
1656 StmtResult ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc,
1657 IdentifierInfo *Ident,
1658 ParsedAttributes &Attrs,
1659 SourceLocation AttrEnd);
1660 void SetDeclDeleted(Decl *dcl, SourceLocation DelLoc);
1661 void SetDeclDefaulted(Decl *dcl, SourceLocation DefaultLoc);
1662 void FinalizeDeclaration(Decl *D);
1663 DeclGroupPtrTy FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
1664 ArrayRef<Decl *> Group);
1665 DeclGroupPtrTy BuildDeclaratorGroup(MutableArrayRef<Decl *> Group,
1666 bool TypeMayContainAuto = true);
1668 /// Should be called on all declarations that might have attached
1669 /// documentation comments.
1670 void ActOnDocumentableDecl(Decl *D);
1671 void ActOnDocumentableDecls(ArrayRef<Decl *> Group);
1673 void ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
1674 SourceLocation LocAfterDecls);
1675 void CheckForFunctionRedefinition(FunctionDecl *FD,
1676 const FunctionDecl *EffectiveDefinition =
1678 Decl *ActOnStartOfFunctionDef(Scope *S, Declarator &D);
1679 Decl *ActOnStartOfFunctionDef(Scope *S, Decl *D);
1680 void ActOnStartOfObjCMethodDef(Scope *S, Decl *D);
1681 bool isObjCMethodDecl(Decl *D) {
1682 return D && isa<ObjCMethodDecl>(D);
1685 /// \brief Determine whether we can delay parsing the body of a function or
1686 /// function template until it is used, assuming we don't care about emitting
1687 /// code for that function.
1689 /// This will be \c false if we may need the body of the function in the
1690 /// middle of parsing an expression (where it's impractical to switch to
1691 /// parsing a different function), for instance, if it's constexpr in C++11
1692 /// or has an 'auto' return type in C++14. These cases are essentially bugs.
1693 bool canDelayFunctionBody(const Declarator &D);
1695 /// \brief Determine whether we can skip parsing the body of a function
1696 /// definition, assuming we don't care about analyzing its body or emitting
1697 /// code for that function.
1699 /// This will be \c false only if we may need the body of the function in
1700 /// order to parse the rest of the program (for instance, if it is
1701 /// \c constexpr in C++11 or has an 'auto' return type in C++14).
1702 bool canSkipFunctionBody(Decl *D);
1704 void computeNRVO(Stmt *Body, sema::FunctionScopeInfo *Scope);
1705 Decl *ActOnFinishFunctionBody(Decl *Decl, Stmt *Body);
1706 Decl *ActOnFinishFunctionBody(Decl *Decl, Stmt *Body, bool IsInstantiation);
1707 Decl *ActOnSkippedFunctionBody(Decl *Decl);
1708 void ActOnFinishInlineMethodDef(CXXMethodDecl *D);
1710 /// ActOnFinishDelayedAttribute - Invoked when we have finished parsing an
1711 /// attribute for which parsing is delayed.
1712 void ActOnFinishDelayedAttribute(Scope *S, Decl *D, ParsedAttributes &Attrs);
1714 /// \brief Diagnose any unused parameters in the given sequence of
1715 /// ParmVarDecl pointers.
1716 void DiagnoseUnusedParameters(ParmVarDecl * const *Begin,
1717 ParmVarDecl * const *End);
1719 /// \brief Diagnose whether the size of parameters or return value of a
1720 /// function or obj-c method definition is pass-by-value and larger than a
1721 /// specified threshold.
1722 void DiagnoseSizeOfParametersAndReturnValue(ParmVarDecl * const *Begin,
1723 ParmVarDecl * const *End,
1727 void DiagnoseInvalidJumps(Stmt *Body);
1728 Decl *ActOnFileScopeAsmDecl(Expr *expr,
1729 SourceLocation AsmLoc,
1730 SourceLocation RParenLoc);
1732 /// \brief Handle a C++11 empty-declaration and attribute-declaration.
1733 Decl *ActOnEmptyDeclaration(Scope *S,
1734 AttributeList *AttrList,
1735 SourceLocation SemiLoc);
1737 /// \brief The parser has processed a module import declaration.
1739 /// \param AtLoc The location of the '@' symbol, if any.
1741 /// \param ImportLoc The location of the 'import' keyword.
1743 /// \param Path The module access path.
1744 DeclResult ActOnModuleImport(SourceLocation AtLoc, SourceLocation ImportLoc,
1747 /// \brief The parser has processed a module import translated from a
1748 /// #include or similar preprocessing directive.
1749 void ActOnModuleInclude(SourceLocation DirectiveLoc, Module *Mod);
1751 /// \brief Create an implicit import of the given module at the given
1752 /// source location, for error recovery, if possible.
1754 /// This routine is typically used when an entity found by name lookup
1755 /// is actually hidden within a module that we know about but the user
1756 /// has forgotten to import.
1757 void createImplicitModuleImportForErrorRecovery(SourceLocation Loc,
1760 /// \brief Retrieve a suitable printing policy.
1761 PrintingPolicy getPrintingPolicy() const {
1762 return getPrintingPolicy(Context, PP);
1765 /// \brief Retrieve a suitable printing policy.
1766 static PrintingPolicy getPrintingPolicy(const ASTContext &Ctx,
1767 const Preprocessor &PP);
1770 void ActOnPopScope(SourceLocation Loc, Scope *S);
1771 void ActOnTranslationUnitScope(Scope *S);
1773 Decl *ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS,
1775 Decl *ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS,
1777 MultiTemplateParamsArg TemplateParams,
1778 bool IsExplicitInstantiation = false);
1780 Decl *BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
1783 const PrintingPolicy &Policy);
1785 Decl *BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
1786 RecordDecl *Record);
1788 bool isAcceptableTagRedeclaration(const TagDecl *Previous,
1789 TagTypeKind NewTag, bool isDefinition,
1790 SourceLocation NewTagLoc,
1791 const IdentifierInfo &Name);
1794 TUK_Reference, // Reference to a tag: 'struct foo *X;'
1795 TUK_Declaration, // Fwd decl of a tag: 'struct foo;'
1796 TUK_Definition, // Definition of a tag: 'struct foo { int X; } Y;'
1797 TUK_Friend // Friend declaration: 'friend struct foo;'
1800 Decl *ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
1801 SourceLocation KWLoc, CXXScopeSpec &SS,
1802 IdentifierInfo *Name, SourceLocation NameLoc,
1803 AttributeList *Attr, AccessSpecifier AS,
1804 SourceLocation ModulePrivateLoc,
1805 MultiTemplateParamsArg TemplateParameterLists,
1806 bool &OwnedDecl, bool &IsDependent,
1807 SourceLocation ScopedEnumKWLoc,
1808 bool ScopedEnumUsesClassTag, TypeResult UnderlyingType,
1809 bool IsTypeSpecifier);
1811 Decl *ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
1812 unsigned TagSpec, SourceLocation TagLoc,
1814 IdentifierInfo *Name, SourceLocation NameLoc,
1815 AttributeList *Attr,
1816 MultiTemplateParamsArg TempParamLists);
1818 TypeResult ActOnDependentTag(Scope *S,
1821 const CXXScopeSpec &SS,
1822 IdentifierInfo *Name,
1823 SourceLocation TagLoc,
1824 SourceLocation NameLoc);
1826 void ActOnDefs(Scope *S, Decl *TagD, SourceLocation DeclStart,
1827 IdentifierInfo *ClassName,
1828 SmallVectorImpl<Decl *> &Decls);
1829 Decl *ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
1830 Declarator &D, Expr *BitfieldWidth);
1832 FieldDecl *HandleField(Scope *S, RecordDecl *TagD, SourceLocation DeclStart,
1833 Declarator &D, Expr *BitfieldWidth,
1834 InClassInitStyle InitStyle,
1835 AccessSpecifier AS);
1836 MSPropertyDecl *HandleMSProperty(Scope *S, RecordDecl *TagD,
1837 SourceLocation DeclStart,
1838 Declarator &D, Expr *BitfieldWidth,
1839 InClassInitStyle InitStyle,
1841 AttributeList *MSPropertyAttr);
1843 FieldDecl *CheckFieldDecl(DeclarationName Name, QualType T,
1844 TypeSourceInfo *TInfo,
1845 RecordDecl *Record, SourceLocation Loc,
1846 bool Mutable, Expr *BitfieldWidth,
1847 InClassInitStyle InitStyle,
1848 SourceLocation TSSL,
1849 AccessSpecifier AS, NamedDecl *PrevDecl,
1850 Declarator *D = nullptr);
1852 bool CheckNontrivialField(FieldDecl *FD);
1853 void DiagnoseNontrivial(const CXXRecordDecl *Record, CXXSpecialMember CSM);
1854 bool SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
1855 bool Diagnose = false);
1856 CXXSpecialMember getSpecialMember(const CXXMethodDecl *MD);
1857 void ActOnLastBitfield(SourceLocation DeclStart,
1858 SmallVectorImpl<Decl *> &AllIvarDecls);
1859 Decl *ActOnIvar(Scope *S, SourceLocation DeclStart,
1860 Declarator &D, Expr *BitfieldWidth,
1861 tok::ObjCKeywordKind visibility);
1863 // This is used for both record definitions and ObjC interface declarations.
1864 void ActOnFields(Scope* S, SourceLocation RecLoc, Decl *TagDecl,
1865 ArrayRef<Decl *> Fields,
1866 SourceLocation LBrac, SourceLocation RBrac,
1867 AttributeList *AttrList);
1869 /// ActOnTagStartDefinition - Invoked when we have entered the
1870 /// scope of a tag's definition (e.g., for an enumeration, class,
1871 /// struct, or union).
1872 void ActOnTagStartDefinition(Scope *S, Decl *TagDecl);
1874 Decl *ActOnObjCContainerStartDefinition(Decl *IDecl);
1876 /// ActOnStartCXXMemberDeclarations - Invoked when we have parsed a
1877 /// C++ record definition's base-specifiers clause and are starting its
1878 /// member declarations.
1879 void ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagDecl,
1880 SourceLocation FinalLoc,
1881 bool IsFinalSpelledSealed,
1882 SourceLocation LBraceLoc);
1884 /// ActOnTagFinishDefinition - Invoked once we have finished parsing
1885 /// the definition of a tag (enumeration, class, struct, or union).
1886 void ActOnTagFinishDefinition(Scope *S, Decl *TagDecl,
1887 SourceLocation RBraceLoc);
1889 void ActOnObjCContainerFinishDefinition();
1891 /// \brief Invoked when we must temporarily exit the objective-c container
1892 /// scope for parsing/looking-up C constructs.
1894 /// Must be followed by a call to \see ActOnObjCReenterContainerContext
1895 void ActOnObjCTemporaryExitContainerContext(DeclContext *DC);
1896 void ActOnObjCReenterContainerContext(DeclContext *DC);
1898 /// ActOnTagDefinitionError - Invoked when there was an unrecoverable
1899 /// error parsing the definition of a tag.
1900 void ActOnTagDefinitionError(Scope *S, Decl *TagDecl);
1902 EnumConstantDecl *CheckEnumConstant(EnumDecl *Enum,
1903 EnumConstantDecl *LastEnumConst,
1904 SourceLocation IdLoc,
1907 bool CheckEnumUnderlyingType(TypeSourceInfo *TI);
1908 bool CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
1909 QualType EnumUnderlyingTy, const EnumDecl *Prev);
1911 Decl *ActOnEnumConstant(Scope *S, Decl *EnumDecl, Decl *LastEnumConstant,
1912 SourceLocation IdLoc, IdentifierInfo *Id,
1913 AttributeList *Attrs,
1914 SourceLocation EqualLoc, Expr *Val);
1915 void ActOnEnumBody(SourceLocation EnumLoc, SourceLocation LBraceLoc,
1916 SourceLocation RBraceLoc, Decl *EnumDecl,
1917 ArrayRef<Decl *> Elements,
1918 Scope *S, AttributeList *Attr);
1920 DeclContext *getContainingDC(DeclContext *DC);
1922 /// Set the current declaration context until it gets popped.
1923 void PushDeclContext(Scope *S, DeclContext *DC);
1924 void PopDeclContext();
1926 /// EnterDeclaratorContext - Used when we must lookup names in the context
1927 /// of a declarator's nested name specifier.
1928 void EnterDeclaratorContext(Scope *S, DeclContext *DC);
1929 void ExitDeclaratorContext(Scope *S);
1931 /// Push the parameters of D, which must be a function, into scope.
1932 void ActOnReenterFunctionContext(Scope* S, Decl* D);
1933 void ActOnExitFunctionContext();
1935 DeclContext *getFunctionLevelDeclContext();
1937 /// getCurFunctionDecl - If inside of a function body, this returns a pointer
1938 /// to the function decl for the function being parsed. If we're currently
1939 /// in a 'block', this returns the containing context.
1940 FunctionDecl *getCurFunctionDecl();
1942 /// getCurMethodDecl - If inside of a method body, this returns a pointer to
1943 /// the method decl for the method being parsed. If we're currently
1944 /// in a 'block', this returns the containing context.
1945 ObjCMethodDecl *getCurMethodDecl();
1947 /// getCurFunctionOrMethodDecl - Return the Decl for the current ObjC method
1948 /// or C function we're in, otherwise return null. If we're currently
1949 /// in a 'block', this returns the containing context.
1950 NamedDecl *getCurFunctionOrMethodDecl();
1952 /// Add this decl to the scope shadowed decl chains.
1953 void PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext = true);
1955 /// \brief Make the given externally-produced declaration visible at the
1956 /// top level scope.
1958 /// \param D The externally-produced declaration to push.
1960 /// \param Name The name of the externally-produced declaration.
1961 void pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name);
1963 /// isDeclInScope - If 'Ctx' is a function/method, isDeclInScope returns true
1964 /// if 'D' is in Scope 'S', otherwise 'S' is ignored and isDeclInScope returns
1965 /// true if 'D' belongs to the given declaration context.
1967 /// \param AllowInlineNamespace If \c true, allow the declaration to be in the
1968 /// enclosing namespace set of the context, rather than contained
1969 /// directly within it.
1970 bool isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S = nullptr,
1971 bool AllowInlineNamespace = false);
1973 /// Finds the scope corresponding to the given decl context, if it
1974 /// happens to be an enclosing scope. Otherwise return NULL.
1975 static Scope *getScopeForDeclContext(Scope *S, DeclContext *DC);
1977 /// Subroutines of ActOnDeclarator().
1978 TypedefDecl *ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
1979 TypeSourceInfo *TInfo);
1980 bool isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New);
1982 /// Attribute merging methods. Return true if a new attribute was added.
1983 AvailabilityAttr *mergeAvailabilityAttr(NamedDecl *D, SourceRange Range,
1984 IdentifierInfo *Platform,
1985 VersionTuple Introduced,
1986 VersionTuple Deprecated,
1987 VersionTuple Obsoleted,
1991 unsigned AttrSpellingListIndex);
1992 TypeVisibilityAttr *mergeTypeVisibilityAttr(Decl *D, SourceRange Range,
1993 TypeVisibilityAttr::VisibilityType Vis,
1994 unsigned AttrSpellingListIndex);
1995 VisibilityAttr *mergeVisibilityAttr(Decl *D, SourceRange Range,
1996 VisibilityAttr::VisibilityType Vis,
1997 unsigned AttrSpellingListIndex);
1998 DLLImportAttr *mergeDLLImportAttr(Decl *D, SourceRange Range,
1999 unsigned AttrSpellingListIndex);
2000 DLLExportAttr *mergeDLLExportAttr(Decl *D, SourceRange Range,
2001 unsigned AttrSpellingListIndex);
2003 mergeMSInheritanceAttr(Decl *D, SourceRange Range, bool BestCase,
2004 unsigned AttrSpellingListIndex,
2005 MSInheritanceAttr::Spelling SemanticSpelling);
2006 FormatAttr *mergeFormatAttr(Decl *D, SourceRange Range,
2007 IdentifierInfo *Format, int FormatIdx,
2008 int FirstArg, unsigned AttrSpellingListIndex);
2009 SectionAttr *mergeSectionAttr(Decl *D, SourceRange Range, StringRef Name,
2010 unsigned AttrSpellingListIndex);
2011 AlwaysInlineAttr *mergeAlwaysInlineAttr(Decl *D, SourceRange Range,
2012 IdentifierInfo *Ident,
2013 unsigned AttrSpellingListIndex);
2014 MinSizeAttr *mergeMinSizeAttr(Decl *D, SourceRange Range,
2015 unsigned AttrSpellingListIndex);
2016 OptimizeNoneAttr *mergeOptimizeNoneAttr(Decl *D, SourceRange Range,
2017 unsigned AttrSpellingListIndex);
2019 /// \brief Describes the kind of merge to perform for availability
2020 /// attributes (including "deprecated", "unavailable", and "availability").
2021 enum AvailabilityMergeKind {
2022 /// \brief Don't merge availability attributes at all.
2024 /// \brief Merge availability attributes for a redeclaration, which requires
2027 /// \brief Merge availability attributes for an override, which requires
2028 /// an exact match or a weakening of constraints.
2032 void mergeDeclAttributes(NamedDecl *New, Decl *Old,
2033 AvailabilityMergeKind AMK = AMK_Redeclaration);
2034 void MergeTypedefNameDecl(TypedefNameDecl *New, LookupResult &OldDecls);
2035 bool MergeFunctionDecl(FunctionDecl *New, NamedDecl *&Old, Scope *S,
2036 bool MergeTypeWithOld);
2037 bool MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
2038 Scope *S, bool MergeTypeWithOld);
2039 void mergeObjCMethodDecls(ObjCMethodDecl *New, ObjCMethodDecl *Old);
2040 void MergeVarDecl(VarDecl *New, LookupResult &Previous);
2041 void MergeVarDeclTypes(VarDecl *New, VarDecl *Old, bool MergeTypeWithOld);
2042 void MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old);
2043 bool MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old, Scope *S);
2045 // AssignmentAction - This is used by all the assignment diagnostic functions
2046 // to represent what is actually causing the operation
2047 enum AssignmentAction {
2055 AA_Passing_CFAudited
2058 /// C++ Overloading.
2060 /// This is a legitimate overload: the existing declarations are
2061 /// functions or function templates with different signatures.
2064 /// This is not an overload because the signature exactly matches
2065 /// an existing declaration.
2068 /// This is not an overload because the lookup results contain a
2072 OverloadKind CheckOverload(Scope *S,
2074 const LookupResult &OldDecls,
2075 NamedDecl *&OldDecl,
2076 bool IsForUsingDecl);
2077 bool IsOverload(FunctionDecl *New, FunctionDecl *Old, bool IsForUsingDecl);
2079 /// \brief Checks availability of the function depending on the current
2080 /// function context.Inside an unavailable function,unavailability is ignored.
2082 /// \returns true if \p FD is unavailable and current context is inside
2083 /// an available function, false otherwise.
2084 bool isFunctionConsideredUnavailable(FunctionDecl *FD);
2086 ImplicitConversionSequence
2087 TryImplicitConversion(Expr *From, QualType ToType,
2088 bool SuppressUserConversions,
2090 bool InOverloadResolution,
2092 bool AllowObjCWritebackConversion);
2094 bool IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType);
2095 bool IsFloatingPointPromotion(QualType FromType, QualType ToType);
2096 bool IsComplexPromotion(QualType FromType, QualType ToType);
2097 bool IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
2098 bool InOverloadResolution,
2099 QualType& ConvertedType, bool &IncompatibleObjC);
2100 bool isObjCPointerConversion(QualType FromType, QualType ToType,
2101 QualType& ConvertedType, bool &IncompatibleObjC);
2102 bool isObjCWritebackConversion(QualType FromType, QualType ToType,
2103 QualType &ConvertedType);
2104 bool IsBlockPointerConversion(QualType FromType, QualType ToType,
2105 QualType& ConvertedType);
2106 bool FunctionParamTypesAreEqual(const FunctionProtoType *OldType,
2107 const FunctionProtoType *NewType,
2108 unsigned *ArgPos = nullptr);
2109 void HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
2110 QualType FromType, QualType ToType);
2112 CastKind PrepareCastToObjCObjectPointer(ExprResult &E);
2113 bool CheckPointerConversion(Expr *From, QualType ToType,
2115 CXXCastPath& BasePath,
2116 bool IgnoreBaseAccess);
2117 bool IsMemberPointerConversion(Expr *From, QualType FromType, QualType ToType,
2118 bool InOverloadResolution,
2119 QualType &ConvertedType);
2120 bool CheckMemberPointerConversion(Expr *From, QualType ToType,
2122 CXXCastPath &BasePath,
2123 bool IgnoreBaseAccess);
2124 bool IsQualificationConversion(QualType FromType, QualType ToType,
2125 bool CStyle, bool &ObjCLifetimeConversion);
2126 bool IsNoReturnConversion(QualType FromType, QualType ToType,
2127 QualType &ResultTy);
2128 bool DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType);
2129 bool isSameOrCompatibleFunctionType(CanQualType Param, CanQualType Arg);
2131 ExprResult PerformMoveOrCopyInitialization(const InitializedEntity &Entity,
2132 const VarDecl *NRVOCandidate,
2133 QualType ResultType,
2135 bool AllowNRVO = true);
2137 bool CanPerformCopyInitialization(const InitializedEntity &Entity,
2139 ExprResult PerformCopyInitialization(const InitializedEntity &Entity,
2140 SourceLocation EqualLoc,
2142 bool TopLevelOfInitList = false,
2143 bool AllowExplicit = false);
2144 ExprResult PerformObjectArgumentInitialization(Expr *From,
2145 NestedNameSpecifier *Qualifier,
2146 NamedDecl *FoundDecl,
2147 CXXMethodDecl *Method);
2149 ExprResult PerformContextuallyConvertToBool(Expr *From);
2150 ExprResult PerformContextuallyConvertToObjCPointer(Expr *From);
2152 /// Contexts in which a converted constant expression is required.
2154 CCEK_CaseValue, ///< Expression in a case label.
2155 CCEK_Enumerator, ///< Enumerator value with fixed underlying type.
2156 CCEK_TemplateArg, ///< Value of a non-type template parameter.
2157 CCEK_NewExpr ///< Constant expression in a noptr-new-declarator.
2159 ExprResult CheckConvertedConstantExpression(Expr *From, QualType T,
2160 llvm::APSInt &Value, CCEKind CCE);
2161 ExprResult CheckConvertedConstantExpression(Expr *From, QualType T,
2162 APValue &Value, CCEKind CCE);
2164 /// \brief Abstract base class used to perform a contextual implicit
2165 /// conversion from an expression to any type passing a filter.
2166 class ContextualImplicitConverter {
2169 bool SuppressConversion;
2171 ContextualImplicitConverter(bool Suppress = false,
2172 bool SuppressConversion = false)
2173 : Suppress(Suppress), SuppressConversion(SuppressConversion) {}
2175 /// \brief Determine whether the specified type is a valid destination type
2176 /// for this conversion.
2177 virtual bool match(QualType T) = 0;
2179 /// \brief Emits a diagnostic complaining that the expression does not have
2180 /// integral or enumeration type.
2181 virtual SemaDiagnosticBuilder
2182 diagnoseNoMatch(Sema &S, SourceLocation Loc, QualType T) = 0;
2184 /// \brief Emits a diagnostic when the expression has incomplete class type.
2185 virtual SemaDiagnosticBuilder
2186 diagnoseIncomplete(Sema &S, SourceLocation Loc, QualType T) = 0;
2188 /// \brief Emits a diagnostic when the only matching conversion function
2190 virtual SemaDiagnosticBuilder diagnoseExplicitConv(
2191 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) = 0;
2193 /// \brief Emits a note for the explicit conversion function.
2194 virtual SemaDiagnosticBuilder
2195 noteExplicitConv(Sema &S, CXXConversionDecl *Conv, QualType ConvTy) = 0;
2197 /// \brief Emits a diagnostic when there are multiple possible conversion
2199 virtual SemaDiagnosticBuilder
2200 diagnoseAmbiguous(Sema &S, SourceLocation Loc, QualType T) = 0;
2202 /// \brief Emits a note for one of the candidate conversions.
2203 virtual SemaDiagnosticBuilder
2204 noteAmbiguous(Sema &S, CXXConversionDecl *Conv, QualType ConvTy) = 0;
2206 /// \brief Emits a diagnostic when we picked a conversion function
2207 /// (for cases when we are not allowed to pick a conversion function).
2208 virtual SemaDiagnosticBuilder diagnoseConversion(
2209 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) = 0;
2211 virtual ~ContextualImplicitConverter() {}
2214 class ICEConvertDiagnoser : public ContextualImplicitConverter {
2215 bool AllowScopedEnumerations;
2218 ICEConvertDiagnoser(bool AllowScopedEnumerations,
2219 bool Suppress, bool SuppressConversion)
2220 : ContextualImplicitConverter(Suppress, SuppressConversion),
2221 AllowScopedEnumerations(AllowScopedEnumerations) {}
2223 /// Match an integral or (possibly scoped) enumeration type.
2224 bool match(QualType T) override;
2226 SemaDiagnosticBuilder
2227 diagnoseNoMatch(Sema &S, SourceLocation Loc, QualType T) override {
2228 return diagnoseNotInt(S, Loc, T);
2231 /// \brief Emits a diagnostic complaining that the expression does not have
2232 /// integral or enumeration type.
2233 virtual SemaDiagnosticBuilder
2234 diagnoseNotInt(Sema &S, SourceLocation Loc, QualType T) = 0;
2237 /// Perform a contextual implicit conversion.
2238 ExprResult PerformContextualImplicitConversion(
2239 SourceLocation Loc, Expr *FromE, ContextualImplicitConverter &Converter);
2242 enum ObjCSubscriptKind {
2247 ObjCSubscriptKind CheckSubscriptingKind(Expr *FromE);
2249 // Note that LK_String is intentionally after the other literals, as
2250 // this is used for diagnostics logic.
2251 enum ObjCLiteralKind {
2260 ObjCLiteralKind CheckLiteralKind(Expr *FromE);
2262 ExprResult PerformObjectMemberConversion(Expr *From,
2263 NestedNameSpecifier *Qualifier,
2264 NamedDecl *FoundDecl,
2267 // Members have to be NamespaceDecl* or TranslationUnitDecl*.
2268 // TODO: make this is a typesafe union.
2269 typedef llvm::SmallPtrSet<DeclContext *, 16> AssociatedNamespaceSet;
2270 typedef llvm::SmallPtrSet<CXXRecordDecl *, 16> AssociatedClassSet;
2272 void AddOverloadCandidate(FunctionDecl *Function,
2273 DeclAccessPair FoundDecl,
2274 ArrayRef<Expr *> Args,
2275 OverloadCandidateSet& CandidateSet,
2276 bool SuppressUserConversions = false,
2277 bool PartialOverloading = false,
2278 bool AllowExplicit = false);
2279 void AddFunctionCandidates(const UnresolvedSetImpl &Functions,
2280 ArrayRef<Expr *> Args,
2281 OverloadCandidateSet &CandidateSet,
2282 bool SuppressUserConversions = false,
2283 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr);
2284 void AddMethodCandidate(DeclAccessPair FoundDecl,
2285 QualType ObjectType,
2286 Expr::Classification ObjectClassification,
2287 ArrayRef<Expr *> Args,
2288 OverloadCandidateSet& CandidateSet,
2289 bool SuppressUserConversion = false);
2290 void AddMethodCandidate(CXXMethodDecl *Method,
2291 DeclAccessPair FoundDecl,
2292 CXXRecordDecl *ActingContext, QualType ObjectType,
2293 Expr::Classification ObjectClassification,
2294 ArrayRef<Expr *> Args,
2295 OverloadCandidateSet& CandidateSet,
2296 bool SuppressUserConversions = false);
2297 void AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
2298 DeclAccessPair FoundDecl,
2299 CXXRecordDecl *ActingContext,
2300 TemplateArgumentListInfo *ExplicitTemplateArgs,
2301 QualType ObjectType,
2302 Expr::Classification ObjectClassification,
2303 ArrayRef<Expr *> Args,
2304 OverloadCandidateSet& CandidateSet,
2305 bool SuppressUserConversions = false);
2306 void AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
2307 DeclAccessPair FoundDecl,
2308 TemplateArgumentListInfo *ExplicitTemplateArgs,
2309 ArrayRef<Expr *> Args,
2310 OverloadCandidateSet& CandidateSet,
2311 bool SuppressUserConversions = false);
2312 void AddConversionCandidate(CXXConversionDecl *Conversion,
2313 DeclAccessPair FoundDecl,
2314 CXXRecordDecl *ActingContext,
2315 Expr *From, QualType ToType,
2316 OverloadCandidateSet& CandidateSet,
2317 bool AllowObjCConversionOnExplicit);
2318 void AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
2319 DeclAccessPair FoundDecl,
2320 CXXRecordDecl *ActingContext,
2321 Expr *From, QualType ToType,
2322 OverloadCandidateSet &CandidateSet,
2323 bool AllowObjCConversionOnExplicit);
2324 void AddSurrogateCandidate(CXXConversionDecl *Conversion,
2325 DeclAccessPair FoundDecl,
2326 CXXRecordDecl *ActingContext,
2327 const FunctionProtoType *Proto,
2328 Expr *Object, ArrayRef<Expr *> Args,
2329 OverloadCandidateSet& CandidateSet);
2330 void AddMemberOperatorCandidates(OverloadedOperatorKind Op,
2331 SourceLocation OpLoc, ArrayRef<Expr *> Args,
2332 OverloadCandidateSet& CandidateSet,
2333 SourceRange OpRange = SourceRange());
2334 void AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
2335 ArrayRef<Expr *> Args,
2336 OverloadCandidateSet& CandidateSet,
2337 bool IsAssignmentOperator = false,
2338 unsigned NumContextualBoolArguments = 0);
2339 void AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
2340 SourceLocation OpLoc, ArrayRef<Expr *> Args,
2341 OverloadCandidateSet& CandidateSet);
2342 void AddArgumentDependentLookupCandidates(DeclarationName Name,
2344 ArrayRef<Expr *> Args,
2345 TemplateArgumentListInfo *ExplicitTemplateArgs,
2346 OverloadCandidateSet& CandidateSet,
2347 bool PartialOverloading = false);
2349 // Emit as a 'note' the specific overload candidate
2350 void NoteOverloadCandidate(FunctionDecl *Fn, QualType DestType = QualType());
2352 // Emit as a series of 'note's all template and non-templates
2353 // identified by the expression Expr
2354 void NoteAllOverloadCandidates(Expr* E, QualType DestType = QualType());
2356 /// Check the enable_if expressions on the given function. Returns the first
2357 /// failing attribute, or NULL if they were all successful.
2358 EnableIfAttr *CheckEnableIf(FunctionDecl *Function, ArrayRef<Expr *> Args,
2359 bool MissingImplicitThis = false);
2361 // [PossiblyAFunctionType] --> [Return]
2362 // NonFunctionType --> NonFunctionType
2364 // R (*)(A) --> R (A)
2365 // R (&)(A) --> R (A)
2366 // R (S::*)(A) --> R (A)
2367 QualType ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType);
2370 ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
2371 QualType TargetType,
2373 DeclAccessPair &Found,
2374 bool *pHadMultipleCandidates = nullptr);
2377 ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
2378 bool Complain = false,
2379 DeclAccessPair *Found = nullptr);
2381 bool ResolveAndFixSingleFunctionTemplateSpecialization(
2382 ExprResult &SrcExpr,
2383 bool DoFunctionPointerConverion = false,
2384 bool Complain = false,
2385 const SourceRange& OpRangeForComplaining = SourceRange(),
2386 QualType DestTypeForComplaining = QualType(),
2387 unsigned DiagIDForComplaining = 0);
2390 Expr *FixOverloadedFunctionReference(Expr *E,
2391 DeclAccessPair FoundDecl,
2393 ExprResult FixOverloadedFunctionReference(ExprResult,
2394 DeclAccessPair FoundDecl,
2397 void AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
2398 ArrayRef<Expr *> Args,
2399 OverloadCandidateSet &CandidateSet,
2400 bool PartialOverloading = false);
2402 // An enum used to represent the different possible results of building a
2403 // range-based for loop.
2404 enum ForRangeStatus {
2406 FRS_NoViableFunction,
2407 FRS_DiagnosticIssued
2410 // An enum to represent whether something is dealing with a call to begin()
2411 // or a call to end() in a range-based for loop.
2412 enum BeginEndFunction {
2417 ForRangeStatus BuildForRangeBeginEndCall(Scope *S, SourceLocation Loc,
2418 SourceLocation RangeLoc,
2420 BeginEndFunction BEF,
2421 const DeclarationNameInfo &NameInfo,
2422 LookupResult &MemberLookup,
2423 OverloadCandidateSet *CandidateSet,
2424 Expr *Range, ExprResult *CallExpr);
2426 ExprResult BuildOverloadedCallExpr(Scope *S, Expr *Fn,
2427 UnresolvedLookupExpr *ULE,
2428 SourceLocation LParenLoc,
2430 SourceLocation RParenLoc,
2432 bool AllowTypoCorrection=true);
2434 bool buildOverloadedCallSet(Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE,
2435 MultiExprArg Args, SourceLocation RParenLoc,
2436 OverloadCandidateSet *CandidateSet,
2437 ExprResult *Result);
2439 ExprResult CreateOverloadedUnaryOp(SourceLocation OpLoc,
2441 const UnresolvedSetImpl &Fns,
2444 ExprResult CreateOverloadedBinOp(SourceLocation OpLoc,
2446 const UnresolvedSetImpl &Fns,
2447 Expr *LHS, Expr *RHS);
2449 ExprResult CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
2450 SourceLocation RLoc,
2451 Expr *Base,Expr *Idx);
2454 BuildCallToMemberFunction(Scope *S, Expr *MemExpr,
2455 SourceLocation LParenLoc,
2457 SourceLocation RParenLoc);
2459 BuildCallToObjectOfClassType(Scope *S, Expr *Object, SourceLocation LParenLoc,
2461 SourceLocation RParenLoc);
2463 ExprResult BuildOverloadedArrowExpr(Scope *S, Expr *Base,
2464 SourceLocation OpLoc,
2465 bool *NoArrowOperatorFound = nullptr);
2467 /// CheckCallReturnType - Checks that a call expression's return type is
2468 /// complete. Returns true on failure. The location passed in is the location
2469 /// that best represents the call.
2470 bool CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
2471 CallExpr *CE, FunctionDecl *FD);
2473 /// Helpers for dealing with blocks and functions.
2474 bool CheckParmsForFunctionDef(ParmVarDecl *const *Param,
2475 ParmVarDecl *const *ParamEnd,
2476 bool CheckParameterNames);
2477 void CheckCXXDefaultArguments(FunctionDecl *FD);
2478 void CheckExtraCXXDefaultArguments(Declarator &D);
2479 Scope *getNonFieldDeclScope(Scope *S);
2481 /// \name Name lookup
2483 /// These routines provide name lookup that is used during semantic
2484 /// analysis to resolve the various kinds of names (identifiers,
2485 /// overloaded operator names, constructor names, etc.) into zero or
2486 /// more declarations within a particular scope. The major entry
2487 /// points are LookupName, which performs unqualified name lookup,
2488 /// and LookupQualifiedName, which performs qualified name lookup.
2490 /// All name lookup is performed based on some specific criteria,
2491 /// which specify what names will be visible to name lookup and how
2492 /// far name lookup should work. These criteria are important both
2493 /// for capturing language semantics (certain lookups will ignore
2494 /// certain names, for example) and for performance, since name
2495 /// lookup is often a bottleneck in the compilation of C++. Name
2496 /// lookup criteria is specified via the LookupCriteria enumeration.
2498 /// The results of name lookup can vary based on the kind of name
2499 /// lookup performed, the current language, and the translation
2500 /// unit. In C, for example, name lookup will either return nothing
2501 /// (no entity found) or a single declaration. In C++, name lookup
2502 /// can additionally refer to a set of overloaded functions or
2503 /// result in an ambiguity. All of the possible results of name
2504 /// lookup are captured by the LookupResult class, which provides
2505 /// the ability to distinguish among them.
2508 /// @brief Describes the kind of name lookup to perform.
2509 enum LookupNameKind {
2510 /// Ordinary name lookup, which finds ordinary names (functions,
2511 /// variables, typedefs, etc.) in C and most kinds of names
2512 /// (functions, variables, members, types, etc.) in C++.
2513 LookupOrdinaryName = 0,
2514 /// Tag name lookup, which finds the names of enums, classes,
2515 /// structs, and unions.
2517 /// Label name lookup.
2519 /// Member name lookup, which finds the names of
2520 /// class/struct/union members.
2522 /// Look up of an operator name (e.g., operator+) for use with
2523 /// operator overloading. This lookup is similar to ordinary name
2524 /// lookup, but will ignore any declarations that are class members.
2526 /// Look up of a name that precedes the '::' scope resolution
2527 /// operator in C++. This lookup completely ignores operator, object,
2528 /// function, and enumerator names (C++ [basic.lookup.qual]p1).
2529 LookupNestedNameSpecifierName,
2530 /// Look up a namespace name within a C++ using directive or
2531 /// namespace alias definition, ignoring non-namespace names (C++
2532 /// [basic.lookup.udir]p1).
2533 LookupNamespaceName,
2534 /// Look up all declarations in a scope with the given name,
2535 /// including resolved using declarations. This is appropriate
2536 /// for checking redeclarations for a using declaration.
2537 LookupUsingDeclName,
2538 /// Look up an ordinary name that is going to be redeclared as a
2539 /// name with linkage. This lookup ignores any declarations that
2540 /// are outside of the current scope unless they have linkage. See
2541 /// C99 6.2.2p4-5 and C++ [basic.link]p6.
2542 LookupRedeclarationWithLinkage,
2543 /// Look up a friend of a local class. This lookup does not look
2544 /// outside the innermost non-class scope. See C++11 [class.friend]p11.
2545 LookupLocalFriendName,
2546 /// Look up the name of an Objective-C protocol.
2547 LookupObjCProtocolName,
2548 /// Look up implicit 'self' parameter of an objective-c method.
2549 LookupObjCImplicitSelfParam,
2550 /// \brief Look up any declaration with any name.
2554 /// \brief Specifies whether (or how) name lookup is being performed for a
2555 /// redeclaration (vs. a reference).
2556 enum RedeclarationKind {
2557 /// \brief The lookup is a reference to this name that is not for the
2558 /// purpose of redeclaring the name.
2559 NotForRedeclaration = 0,
2560 /// \brief The lookup results will be used for redeclaration of a name,
2561 /// if an entity by that name already exists.
2565 /// \brief The possible outcomes of name lookup for a literal operator.
2566 enum LiteralOperatorLookupResult {
2567 /// \brief The lookup resulted in an error.
2569 /// \brief The lookup found a single 'cooked' literal operator, which
2570 /// expects a normal literal to be built and passed to it.
2572 /// \brief The lookup found a single 'raw' literal operator, which expects
2573 /// a string literal containing the spelling of the literal token.
2575 /// \brief The lookup found an overload set of literal operator templates,
2576 /// which expect the characters of the spelling of the literal token to be
2577 /// passed as a non-type template argument pack.
2579 /// \brief The lookup found an overload set of literal operator templates,
2580 /// which expect the character type and characters of the spelling of the
2581 /// string literal token to be passed as template arguments.
2585 SpecialMemberOverloadResult *LookupSpecialMember(CXXRecordDecl *D,
2586 CXXSpecialMember SM,
2593 typedef std::function<void(const TypoCorrection &)> TypoDiagnosticGenerator;
2594 typedef std::function<ExprResult(Sema &, TypoExpr *, TypoCorrection)>
2595 TypoRecoveryCallback;
2598 bool CppLookupName(LookupResult &R, Scope *S);
2600 struct TypoExprState {
2601 std::unique_ptr<TypoCorrectionConsumer> Consumer;
2602 TypoDiagnosticGenerator DiagHandler;
2603 TypoRecoveryCallback RecoveryHandler;
2605 TypoExprState(TypoExprState&& other) LLVM_NOEXCEPT;
2606 TypoExprState& operator=(TypoExprState&& other) LLVM_NOEXCEPT;
2609 /// \brief The set of unhandled TypoExprs and their associated state.
2610 llvm::MapVector<TypoExpr *, TypoExprState> DelayedTypos;
2612 /// \brief Creates a new TypoExpr AST node.
2613 TypoExpr *createDelayedTypo(std::unique_ptr<TypoCorrectionConsumer> TCC,
2614 TypoDiagnosticGenerator TDG,
2615 TypoRecoveryCallback TRC);
2617 // \brief The set of known/encountered (unique, canonicalized) NamespaceDecls.
2619 // The boolean value will be true to indicate that the namespace was loaded
2620 // from an AST/PCH file, or false otherwise.
2621 llvm::MapVector<NamespaceDecl*, bool> KnownNamespaces;
2623 /// \brief Whether we have already loaded known namespaces from an extenal
2625 bool LoadedExternalKnownNamespaces;
2627 /// \brief Helper for CorrectTypo and CorrectTypoDelayed used to create and
2628 /// populate a new TypoCorrectionConsumer. Returns nullptr if typo correction
2629 /// should be skipped entirely.
2630 std::unique_ptr<TypoCorrectionConsumer>
2631 makeTypoCorrectionConsumer(const DeclarationNameInfo &Typo,
2632 Sema::LookupNameKind LookupKind, Scope *S,
2634 std::unique_ptr<CorrectionCandidateCallback> CCC,
2635 DeclContext *MemberContext, bool EnteringContext,
2636 const ObjCObjectPointerType *OPT,
2637 bool ErrorRecovery);
2640 const TypoExprState &getTypoExprState(TypoExpr *TE) const;
2642 /// \brief Clears the state of the given TypoExpr.
2643 void clearDelayedTypo(TypoExpr *TE);
2645 /// \brief Look up a name, looking for a single declaration. Return
2646 /// null if the results were absent, ambiguous, or overloaded.
2648 /// It is preferable to use the elaborated form and explicitly handle
2649 /// ambiguity and overloaded.
2650 NamedDecl *LookupSingleName(Scope *S, DeclarationName Name,
2652 LookupNameKind NameKind,
2653 RedeclarationKind Redecl
2654 = NotForRedeclaration);
2655 bool LookupName(LookupResult &R, Scope *S,
2656 bool AllowBuiltinCreation = false);
2657 bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
2658 bool InUnqualifiedLookup = false);
2659 bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
2661 bool LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS,
2662 bool AllowBuiltinCreation = false,
2663 bool EnteringContext = false);
2664 ObjCProtocolDecl *LookupProtocol(IdentifierInfo *II, SourceLocation IdLoc,
2665 RedeclarationKind Redecl
2666 = NotForRedeclaration);
2667 bool LookupInSuper(LookupResult &R, CXXRecordDecl *Class);
2669 void LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S,
2670 QualType T1, QualType T2,
2671 UnresolvedSetImpl &Functions);
2672 void addOverloadedOperatorToUnresolvedSet(UnresolvedSetImpl &Functions,
2673 DeclAccessPair Operator,
2674 QualType T1, QualType T2);
2676 LabelDecl *LookupOrCreateLabel(IdentifierInfo *II, SourceLocation IdentLoc,
2677 SourceLocation GnuLabelLoc = SourceLocation());
2679 DeclContextLookupResult LookupConstructors(CXXRecordDecl *Class);
2680 CXXConstructorDecl *LookupDefaultConstructor(CXXRecordDecl *Class);
2681 CXXConstructorDecl *LookupCopyingConstructor(CXXRecordDecl *Class,
2683 CXXMethodDecl *LookupCopyingAssignment(CXXRecordDecl *Class, unsigned Quals,
2684 bool RValueThis, unsigned ThisQuals);
2685 CXXConstructorDecl *LookupMovingConstructor(CXXRecordDecl *Class,
2687 CXXMethodDecl *LookupMovingAssignment(CXXRecordDecl *Class, unsigned Quals,
2688 bool RValueThis, unsigned ThisQuals);
2689 CXXDestructorDecl *LookupDestructor(CXXRecordDecl *Class);
2691 bool checkLiteralOperatorId(const CXXScopeSpec &SS, const UnqualifiedId &Id);
2692 LiteralOperatorLookupResult LookupLiteralOperator(Scope *S, LookupResult &R,
2693 ArrayRef<QualType> ArgTys,
2696 bool AllowStringTemplate);
2697 bool isKnownName(StringRef name);
2699 void ArgumentDependentLookup(DeclarationName Name, SourceLocation Loc,
2700 ArrayRef<Expr *> Args, ADLResult &Functions);
2702 void LookupVisibleDecls(Scope *S, LookupNameKind Kind,
2703 VisibleDeclConsumer &Consumer,
2704 bool IncludeGlobalScope = true);
2705 void LookupVisibleDecls(DeclContext *Ctx, LookupNameKind Kind,
2706 VisibleDeclConsumer &Consumer,
2707 bool IncludeGlobalScope = true);
2709 enum CorrectTypoKind {
2710 CTK_NonError, // CorrectTypo used in a non error recovery situation.
2711 CTK_ErrorRecovery // CorrectTypo used in normal error recovery.
2714 TypoCorrection CorrectTypo(const DeclarationNameInfo &Typo,
2715 Sema::LookupNameKind LookupKind,
2716 Scope *S, CXXScopeSpec *SS,
2717 std::unique_ptr<CorrectionCandidateCallback> CCC,
2718 CorrectTypoKind Mode,
2719 DeclContext *MemberContext = nullptr,
2720 bool EnteringContext = false,
2721 const ObjCObjectPointerType *OPT = nullptr,
2722 bool RecordFailure = true);
2724 TypoExpr *CorrectTypoDelayed(const DeclarationNameInfo &Typo,
2725 Sema::LookupNameKind LookupKind, Scope *S,
2727 std::unique_ptr<CorrectionCandidateCallback> CCC,
2728 TypoDiagnosticGenerator TDG,
2729 TypoRecoveryCallback TRC, CorrectTypoKind Mode,
2730 DeclContext *MemberContext = nullptr,
2731 bool EnteringContext = false,
2732 const ObjCObjectPointerType *OPT = nullptr);
2735 CorrectDelayedTyposInExpr(Expr *E,
2736 llvm::function_ref<ExprResult(Expr *)> Filter =
2737 [](Expr *E) -> ExprResult { return E; });
2740 CorrectDelayedTyposInExpr(ExprResult ER,
2741 llvm::function_ref<ExprResult(Expr *)> Filter =
2742 [](Expr *E) -> ExprResult { return E; }) {
2743 return ER.isInvalid() ? ER : CorrectDelayedTyposInExpr(ER.get(), Filter);
2746 void diagnoseTypo(const TypoCorrection &Correction,
2747 const PartialDiagnostic &TypoDiag,
2748 bool ErrorRecovery = true);
2750 void diagnoseTypo(const TypoCorrection &Correction,
2751 const PartialDiagnostic &TypoDiag,
2752 const PartialDiagnostic &PrevNote,
2753 bool ErrorRecovery = true);
2755 void FindAssociatedClassesAndNamespaces(SourceLocation InstantiationLoc,
2756 ArrayRef<Expr *> Args,
2757 AssociatedNamespaceSet &AssociatedNamespaces,
2758 AssociatedClassSet &AssociatedClasses);
2760 void FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S,
2761 bool ConsiderLinkage, bool AllowInlineNamespace);
2763 void DiagnoseAmbiguousLookup(LookupResult &Result);
2766 ObjCInterfaceDecl *getObjCInterfaceDecl(IdentifierInfo *&Id,
2767 SourceLocation IdLoc,
2768 bool TypoCorrection = false);
2769 NamedDecl *LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID,
2770 Scope *S, bool ForRedeclaration,
2771 SourceLocation Loc);
2772 NamedDecl *ImplicitlyDefineFunction(SourceLocation Loc, IdentifierInfo &II,
2774 void AddKnownFunctionAttributes(FunctionDecl *FD);
2776 // More parsing and symbol table subroutines.
2778 void ProcessPragmaWeak(Scope *S, Decl *D);
2779 // Decl attributes - this routine is the top level dispatcher.
2780 void ProcessDeclAttributes(Scope *S, Decl *D, const Declarator &PD);
2781 void ProcessDeclAttributeList(Scope *S, Decl *D, const AttributeList *AL,
2782 bool IncludeCXX11Attributes = true);
2783 bool ProcessAccessDeclAttributeList(AccessSpecDecl *ASDecl,
2784 const AttributeList *AttrList);
2786 void checkUnusedDeclAttributes(Declarator &D);
2788 /// Determine if type T is a valid subject for a nonnull and similar
2789 /// attributes. By default, we look through references (the behavior used by
2790 /// nonnull), but if the second parameter is true, then we treat a reference
2792 bool isValidPointerAttrType(QualType T, bool RefOkay = false);
2794 bool CheckRegparmAttr(const AttributeList &attr, unsigned &value);
2795 bool CheckCallingConvAttr(const AttributeList &attr, CallingConv &CC,
2796 const FunctionDecl *FD = nullptr);
2797 bool CheckNoReturnAttr(const AttributeList &attr);
2798 bool checkStringLiteralArgumentAttr(const AttributeList &Attr,
2799 unsigned ArgNum, StringRef &Str,
2800 SourceLocation *ArgLocation = nullptr);
2801 bool checkMSInheritanceAttrOnDefinition(
2802 CXXRecordDecl *RD, SourceRange Range, bool BestCase,
2803 MSInheritanceAttr::Spelling SemanticSpelling);
2805 void CheckAlignasUnderalignment(Decl *D);
2807 /// Adjust the calling convention of a method to be the ABI default if it
2808 /// wasn't specified explicitly. This handles method types formed from
2809 /// function type typedefs and typename template arguments.
2810 void adjustMemberFunctionCC(QualType &T, bool IsStatic);
2812 // Check if there is an explicit attribute, but only look through parens.
2813 // The intent is to look for an attribute on the current declarator, but not
2814 // one that came from a typedef.
2815 bool hasExplicitCallingConv(QualType &T);
2817 /// Get the outermost AttributedType node that sets a calling convention.
2818 /// Valid types should not have multiple attributes with different CCs.
2819 const AttributedType *getCallingConvAttributedType(QualType T) const;
2821 /// \brief Stmt attributes - this routine is the top level dispatcher.
2822 StmtResult ProcessStmtAttributes(Stmt *Stmt, AttributeList *Attrs,
2825 void WarnConflictingTypedMethods(ObjCMethodDecl *Method,
2826 ObjCMethodDecl *MethodDecl,
2827 bool IsProtocolMethodDecl);
2829 void CheckConflictingOverridingMethod(ObjCMethodDecl *Method,
2830 ObjCMethodDecl *Overridden,
2831 bool IsProtocolMethodDecl);
2833 /// WarnExactTypedMethods - This routine issues a warning if method
2834 /// implementation declaration matches exactly that of its declaration.
2835 void WarnExactTypedMethods(ObjCMethodDecl *Method,
2836 ObjCMethodDecl *MethodDecl,
2837 bool IsProtocolMethodDecl);
2839 typedef llvm::SmallPtrSet<Selector, 8> SelectorSet;
2840 typedef llvm::DenseMap<Selector, ObjCMethodDecl*> ProtocolsMethodsMap;
2842 /// CheckImplementationIvars - This routine checks if the instance variables
2843 /// listed in the implelementation match those listed in the interface.
2844 void CheckImplementationIvars(ObjCImplementationDecl *ImpDecl,
2845 ObjCIvarDecl **Fields, unsigned nIvars,
2846 SourceLocation Loc);
2848 /// ImplMethodsVsClassMethods - This is main routine to warn if any method
2849 /// remains unimplemented in the class or category \@implementation.
2850 void ImplMethodsVsClassMethods(Scope *S, ObjCImplDecl* IMPDecl,
2851 ObjCContainerDecl* IDecl,
2852 bool IncompleteImpl = false);
2854 /// DiagnoseUnimplementedProperties - This routine warns on those properties
2855 /// which must be implemented by this implementation.
2856 void DiagnoseUnimplementedProperties(Scope *S, ObjCImplDecl* IMPDecl,
2857 ObjCContainerDecl *CDecl,
2858 bool SynthesizeProperties);
2860 /// DefaultSynthesizeProperties - This routine default synthesizes all
2861 /// properties which must be synthesized in the class's \@implementation.
2862 void DefaultSynthesizeProperties (Scope *S, ObjCImplDecl* IMPDecl,
2863 ObjCInterfaceDecl *IDecl);
2864 void DefaultSynthesizeProperties(Scope *S, Decl *D);
2866 /// IvarBacksCurrentMethodAccessor - This routine returns 'true' if 'IV' is
2867 /// an ivar synthesized for 'Method' and 'Method' is a property accessor
2868 /// declared in class 'IFace'.
2869 bool IvarBacksCurrentMethodAccessor(ObjCInterfaceDecl *IFace,
2870 ObjCMethodDecl *Method, ObjCIvarDecl *IV);
2872 /// DiagnoseUnusedBackingIvarInAccessor - Issue an 'unused' warning if ivar which
2873 /// backs the property is not used in the property's accessor.
2874 void DiagnoseUnusedBackingIvarInAccessor(Scope *S,
2875 const ObjCImplementationDecl *ImplD);
2877 /// GetIvarBackingPropertyAccessor - If method is a property setter/getter and
2878 /// it property has a backing ivar, returns this ivar; otherwise, returns NULL.
2879 /// It also returns ivar's property on success.
2880 ObjCIvarDecl *GetIvarBackingPropertyAccessor(const ObjCMethodDecl *Method,
2881 const ObjCPropertyDecl *&PDecl) const;
2883 /// Called by ActOnProperty to handle \@property declarations in
2884 /// class extensions.
2885 ObjCPropertyDecl *HandlePropertyInClassExtension(Scope *S,
2886 SourceLocation AtLoc,
2887 SourceLocation LParenLoc,
2888 FieldDeclarator &FD,
2891 const bool isAssign,
2892 const bool isReadWrite,
2893 const unsigned Attributes,
2894 const unsigned AttributesAsWritten,
2895 bool *isOverridingProperty,
2897 tok::ObjCKeywordKind MethodImplKind);
2899 /// Called by ActOnProperty and HandlePropertyInClassExtension to
2900 /// handle creating the ObjcPropertyDecl for a category or \@interface.
2901 ObjCPropertyDecl *CreatePropertyDecl(Scope *S,
2902 ObjCContainerDecl *CDecl,
2903 SourceLocation AtLoc,
2904 SourceLocation LParenLoc,
2905 FieldDeclarator &FD,
2908 const bool isAssign,
2909 const bool isReadWrite,
2910 const unsigned Attributes,
2911 const unsigned AttributesAsWritten,
2913 tok::ObjCKeywordKind MethodImplKind,
2914 DeclContext *lexicalDC = nullptr);
2916 /// AtomicPropertySetterGetterRules - This routine enforces the rule (via
2917 /// warning) when atomic property has one but not the other user-declared
2918 /// setter or getter.
2919 void AtomicPropertySetterGetterRules(ObjCImplDecl* IMPDecl,
2920 ObjCContainerDecl* IDecl);
2922 void DiagnoseOwningPropertyGetterSynthesis(const ObjCImplementationDecl *D);
2924 void DiagnoseMissingDesignatedInitOverrides(
2925 const ObjCImplementationDecl *ImplD,
2926 const ObjCInterfaceDecl *IFD);
2928 void DiagnoseDuplicateIvars(ObjCInterfaceDecl *ID, ObjCInterfaceDecl *SID);
2930 enum MethodMatchStrategy {
2935 /// MatchTwoMethodDeclarations - Checks if two methods' type match and returns
2936 /// true, or false, accordingly.
2937 bool MatchTwoMethodDeclarations(const ObjCMethodDecl *Method,
2938 const ObjCMethodDecl *PrevMethod,
2939 MethodMatchStrategy strategy = MMS_strict);
2941 /// MatchAllMethodDeclarations - Check methods declaraed in interface or
2942 /// or protocol against those declared in their implementations.
2943 void MatchAllMethodDeclarations(const SelectorSet &InsMap,
2944 const SelectorSet &ClsMap,
2945 SelectorSet &InsMapSeen,
2946 SelectorSet &ClsMapSeen,
2947 ObjCImplDecl* IMPDecl,
2948 ObjCContainerDecl* IDecl,
2949 bool &IncompleteImpl,
2950 bool ImmediateClass,
2951 bool WarnCategoryMethodImpl=false);
2953 /// CheckCategoryVsClassMethodMatches - Checks that methods implemented in
2954 /// category matches with those implemented in its primary class and
2955 /// warns each time an exact match is found.
2956 void CheckCategoryVsClassMethodMatches(ObjCCategoryImplDecl *CatIMP);
2958 /// \brief Add the given method to the list of globally-known methods.
2959 void addMethodToGlobalList(ObjCMethodList *List, ObjCMethodDecl *Method);
2962 /// AddMethodToGlobalPool - Add an instance or factory method to the global
2963 /// pool. See descriptoin of AddInstanceMethodToGlobalPool.
2964 void AddMethodToGlobalPool(ObjCMethodDecl *Method, bool impl, bool instance);
2966 /// LookupMethodInGlobalPool - Returns the instance or factory method and
2967 /// optionally warns if there are multiple signatures.
2968 ObjCMethodDecl *LookupMethodInGlobalPool(Selector Sel, SourceRange R,
2969 bool receiverIdOrClass,
2970 bool warn, bool instance);
2973 /// \brief - Returns instance or factory methods in global method pool for
2974 /// given selector. If no such method or only one method found, function returns
2975 /// false; otherwise, it returns true
2976 bool CollectMultipleMethodsInGlobalPool(Selector Sel,
2977 SmallVectorImpl<ObjCMethodDecl*>& Methods,
2980 bool AreMultipleMethodsInGlobalPool(Selector Sel,
2984 /// \brief - Returns a selector which best matches given argument list or
2985 /// nullptr if none could be found
2986 ObjCMethodDecl *SelectBestMethod(Selector Sel, MultiExprArg Args,
2990 /// \brief Record the typo correction failure and return an empty correction.
2991 TypoCorrection FailedCorrection(IdentifierInfo *Typo, SourceLocation TypoLoc,
2992 bool RecordFailure = true) {
2994 TypoCorrectionFailures[Typo].insert(TypoLoc);
2995 return TypoCorrection();
2999 /// AddInstanceMethodToGlobalPool - All instance methods in a translation
3000 /// unit are added to a global pool. This allows us to efficiently associate
3001 /// a selector with a method declaraation for purposes of typechecking
3002 /// messages sent to "id" (where the class of the object is unknown).
3003 void AddInstanceMethodToGlobalPool(ObjCMethodDecl *Method, bool impl=false) {
3004 AddMethodToGlobalPool(Method, impl, /*instance*/true);
3007 /// AddFactoryMethodToGlobalPool - Same as above, but for factory methods.
3008 void AddFactoryMethodToGlobalPool(ObjCMethodDecl *Method, bool impl=false) {
3009 AddMethodToGlobalPool(Method, impl, /*instance*/false);
3012 /// AddAnyMethodToGlobalPool - Add any method, instance or factory to global
3014 void AddAnyMethodToGlobalPool(Decl *D);
3016 /// LookupInstanceMethodInGlobalPool - Returns the method and warns if
3017 /// there are multiple signatures.
3018 ObjCMethodDecl *LookupInstanceMethodInGlobalPool(Selector Sel, SourceRange R,
3019 bool receiverIdOrClass=false,
3021 return LookupMethodInGlobalPool(Sel, R, receiverIdOrClass,
3022 warn, /*instance*/true);
3025 /// LookupFactoryMethodInGlobalPool - Returns the method and warns if
3026 /// there are multiple signatures.
3027 ObjCMethodDecl *LookupFactoryMethodInGlobalPool(Selector Sel, SourceRange R,
3028 bool receiverIdOrClass=false,
3030 return LookupMethodInGlobalPool(Sel, R, receiverIdOrClass,
3031 warn, /*instance*/false);
3034 const ObjCMethodDecl *SelectorsForTypoCorrection(Selector Sel,
3035 QualType ObjectType=QualType());
3036 /// LookupImplementedMethodInGlobalPool - Returns the method which has an
3038 ObjCMethodDecl *LookupImplementedMethodInGlobalPool(Selector Sel);
3040 /// CollectIvarsToConstructOrDestruct - Collect those ivars which require
3042 void CollectIvarsToConstructOrDestruct(ObjCInterfaceDecl *OI,
3043 SmallVectorImpl<ObjCIvarDecl*> &Ivars);
3045 //===--------------------------------------------------------------------===//
3046 // Statement Parsing Callbacks: SemaStmt.cpp.
3050 FullExprArg(Sema &actions) : E(nullptr) { }
3052 ExprResult release() {
3056 Expr *get() const { return E; }
3058 Expr *operator->() {
3063 // FIXME: No need to make the entire Sema class a friend when it's just
3064 // Sema::MakeFullExpr that needs access to the constructor below.
3067 explicit FullExprArg(Expr *expr) : E(expr) {}
3072 FullExprArg MakeFullExpr(Expr *Arg) {
3073 return MakeFullExpr(Arg, Arg ? Arg->getExprLoc() : SourceLocation());
3075 FullExprArg MakeFullExpr(Expr *Arg, SourceLocation CC) {
3076 return FullExprArg(ActOnFinishFullExpr(Arg, CC).get());
3078 FullExprArg MakeFullDiscardedValueExpr(Expr *Arg) {
3080 ActOnFinishFullExpr(Arg, Arg ? Arg->getExprLoc() : SourceLocation(),
3081 /*DiscardedValue*/ true);
3082 return FullExprArg(FE.get());
3085 StmtResult ActOnExprStmt(ExprResult Arg);
3086 StmtResult ActOnExprStmtError();
3088 StmtResult ActOnNullStmt(SourceLocation SemiLoc,
3089 bool HasLeadingEmptyMacro = false);
3091 void ActOnStartOfCompoundStmt();
3092 void ActOnFinishOfCompoundStmt();
3093 StmtResult ActOnCompoundStmt(SourceLocation L, SourceLocation R,
3094 ArrayRef<Stmt *> Elts, bool isStmtExpr);
3096 /// \brief A RAII object to enter scope of a compound statement.
3097 class CompoundScopeRAII {
3099 CompoundScopeRAII(Sema &S): S(S) {
3100 S.ActOnStartOfCompoundStmt();
3103 ~CompoundScopeRAII() {
3104 S.ActOnFinishOfCompoundStmt();
3111 /// An RAII helper that pops function a function scope on exit.
3112 struct FunctionScopeRAII {
3115 FunctionScopeRAII(Sema &S) : S(S), Active(true) {}
3116 ~FunctionScopeRAII() {
3118 S.PopFunctionScopeInfo();
3120 void disable() { Active = false; }
3123 StmtResult ActOnDeclStmt(DeclGroupPtrTy Decl,
3124 SourceLocation StartLoc,
3125 SourceLocation EndLoc);
3126 void ActOnForEachDeclStmt(DeclGroupPtrTy Decl);
3127 StmtResult ActOnForEachLValueExpr(Expr *E);
3128 StmtResult ActOnCaseStmt(SourceLocation CaseLoc, Expr *LHSVal,
3129 SourceLocation DotDotDotLoc, Expr *RHSVal,
3130 SourceLocation ColonLoc);
3131 void ActOnCaseStmtBody(Stmt *CaseStmt, Stmt *SubStmt);
3133 StmtResult ActOnDefaultStmt(SourceLocation DefaultLoc,
3134 SourceLocation ColonLoc,
3135 Stmt *SubStmt, Scope *CurScope);
3136 StmtResult ActOnLabelStmt(SourceLocation IdentLoc, LabelDecl *TheDecl,
3137 SourceLocation ColonLoc, Stmt *SubStmt);
3139 StmtResult ActOnAttributedStmt(SourceLocation AttrLoc,
3140 ArrayRef<const Attr*> Attrs,
3143 StmtResult ActOnIfStmt(SourceLocation IfLoc,
3144 FullExprArg CondVal, Decl *CondVar,
3146 SourceLocation ElseLoc, Stmt *ElseVal);
3147 StmtResult ActOnStartOfSwitchStmt(SourceLocation SwitchLoc,
3150 StmtResult ActOnFinishSwitchStmt(SourceLocation SwitchLoc,
3151 Stmt *Switch, Stmt *Body);
3152 StmtResult ActOnWhileStmt(SourceLocation WhileLoc,
3154 Decl *CondVar, Stmt *Body);
3155 StmtResult ActOnDoStmt(SourceLocation DoLoc, Stmt *Body,
3156 SourceLocation WhileLoc,
3157 SourceLocation CondLParen, Expr *Cond,
3158 SourceLocation CondRParen);
3160 StmtResult ActOnForStmt(SourceLocation ForLoc,
3161 SourceLocation LParenLoc,
3162 Stmt *First, FullExprArg Second,
3165 SourceLocation RParenLoc,
3167 ExprResult CheckObjCForCollectionOperand(SourceLocation forLoc,
3169 StmtResult ActOnObjCForCollectionStmt(SourceLocation ForColLoc,
3170 Stmt *First, Expr *collection,
3171 SourceLocation RParenLoc);
3172 StmtResult FinishObjCForCollectionStmt(Stmt *ForCollection, Stmt *Body);
3174 enum BuildForRangeKind {
3175 /// Initial building of a for-range statement.
3177 /// Instantiation or recovery rebuild of a for-range statement. Don't
3178 /// attempt any typo-correction.
3180 /// Determining whether a for-range statement could be built. Avoid any
3181 /// unnecessary or irreversible actions.
3185 StmtResult ActOnCXXForRangeStmt(SourceLocation ForLoc, Stmt *LoopVar,
3186 SourceLocation ColonLoc, Expr *Collection,
3187 SourceLocation RParenLoc,
3188 BuildForRangeKind Kind);
3189 StmtResult BuildCXXForRangeStmt(SourceLocation ForLoc,
3190 SourceLocation ColonLoc,
3191 Stmt *RangeDecl, Stmt *BeginEndDecl,
3192 Expr *Cond, Expr *Inc,
3194 SourceLocation RParenLoc,
3195 BuildForRangeKind Kind);
3196 StmtResult FinishCXXForRangeStmt(Stmt *ForRange, Stmt *Body);
3198 StmtResult ActOnGotoStmt(SourceLocation GotoLoc,
3199 SourceLocation LabelLoc,
3200 LabelDecl *TheDecl);
3201 StmtResult ActOnIndirectGotoStmt(SourceLocation GotoLoc,
3202 SourceLocation StarLoc,
3204 StmtResult ActOnContinueStmt(SourceLocation ContinueLoc, Scope *CurScope);
3205 StmtResult ActOnBreakStmt(SourceLocation BreakLoc, Scope *CurScope);
3207 void ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope,
3208 CapturedRegionKind Kind, unsigned NumParams);
3209 typedef std::pair<StringRef, QualType> CapturedParamNameType;
3210 void ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope,
3211 CapturedRegionKind Kind,
3212 ArrayRef<CapturedParamNameType> Params);
3213 StmtResult ActOnCapturedRegionEnd(Stmt *S);
3214 void ActOnCapturedRegionError();
3215 RecordDecl *CreateCapturedStmtRecordDecl(CapturedDecl *&CD,
3217 unsigned NumParams);
3218 VarDecl *getCopyElisionCandidate(QualType ReturnType, Expr *E,
3219 bool AllowFunctionParameters);
3220 bool isCopyElisionCandidate(QualType ReturnType, const VarDecl *VD,
3221 bool AllowFunctionParameters);
3223 StmtResult ActOnReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp,
3225 StmtResult BuildReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp);
3226 StmtResult ActOnCapScopeReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp);
3228 StmtResult ActOnGCCAsmStmt(SourceLocation AsmLoc, bool IsSimple,
3229 bool IsVolatile, unsigned NumOutputs,
3230 unsigned NumInputs, IdentifierInfo **Names,
3231 MultiExprArg Constraints, MultiExprArg Exprs,
3232 Expr *AsmString, MultiExprArg Clobbers,
3233 SourceLocation RParenLoc);
3235 ExprResult LookupInlineAsmIdentifier(CXXScopeSpec &SS,
3236 SourceLocation TemplateKWLoc,
3238 llvm::InlineAsmIdentifierInfo &Info,
3239 bool IsUnevaluatedContext);
3240 bool LookupInlineAsmField(StringRef Base, StringRef Member,
3241 unsigned &Offset, SourceLocation AsmLoc);
3242 StmtResult ActOnMSAsmStmt(SourceLocation AsmLoc, SourceLocation LBraceLoc,
3243 ArrayRef<Token> AsmToks,
3244 StringRef AsmString,
3245 unsigned NumOutputs, unsigned NumInputs,
3246 ArrayRef<StringRef> Constraints,
3247 ArrayRef<StringRef> Clobbers,
3248 ArrayRef<Expr*> Exprs,
3249 SourceLocation EndLoc);
3250 LabelDecl *GetOrCreateMSAsmLabel(StringRef ExternalLabelName,
3251 SourceLocation Location,
3254 VarDecl *BuildObjCExceptionDecl(TypeSourceInfo *TInfo, QualType ExceptionType,
3255 SourceLocation StartLoc,
3256 SourceLocation IdLoc, IdentifierInfo *Id,
3257 bool Invalid = false);
3259 Decl *ActOnObjCExceptionDecl(Scope *S, Declarator &D);
3261 StmtResult ActOnObjCAtCatchStmt(SourceLocation AtLoc, SourceLocation RParen,
3262 Decl *Parm, Stmt *Body);
3264 StmtResult ActOnObjCAtFinallyStmt(SourceLocation AtLoc, Stmt *Body);
3266 StmtResult ActOnObjCAtTryStmt(SourceLocation AtLoc, Stmt *Try,
3267 MultiStmtArg Catch, Stmt *Finally);
3269 StmtResult BuildObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw);
3270 StmtResult ActOnObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw,
3272 ExprResult ActOnObjCAtSynchronizedOperand(SourceLocation atLoc,
3274 StmtResult ActOnObjCAtSynchronizedStmt(SourceLocation AtLoc,
3278 StmtResult ActOnObjCAutoreleasePoolStmt(SourceLocation AtLoc, Stmt *Body);
3280 VarDecl *BuildExceptionDeclaration(Scope *S, TypeSourceInfo *TInfo,
3281 SourceLocation StartLoc,
3282 SourceLocation IdLoc,
3283 IdentifierInfo *Id);
3285 Decl *ActOnExceptionDeclarator(Scope *S, Declarator &D);
3287 StmtResult ActOnCXXCatchBlock(SourceLocation CatchLoc,
3288 Decl *ExDecl, Stmt *HandlerBlock);
3289 StmtResult ActOnCXXTryBlock(SourceLocation TryLoc, Stmt *TryBlock,
3290 ArrayRef<Stmt *> Handlers);
3292 StmtResult ActOnSEHTryBlock(bool IsCXXTry, // try (true) or __try (false) ?
3293 SourceLocation TryLoc, Stmt *TryBlock,
3295 StmtResult ActOnSEHExceptBlock(SourceLocation Loc,
3298 StmtResult ActOnSEHFinallyBlock(SourceLocation Loc, Stmt *Block);
3299 StmtResult ActOnSEHLeaveStmt(SourceLocation Loc, Scope *CurScope);
3301 void DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock);
3303 bool ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const;
3305 /// \brief If it's a file scoped decl that must warn if not used, keep track
3307 void MarkUnusedFileScopedDecl(const DeclaratorDecl *D);
3309 /// DiagnoseUnusedExprResult - If the statement passed in is an expression
3310 /// whose result is unused, warn.
3311 void DiagnoseUnusedExprResult(const Stmt *S);
3312 void DiagnoseUnusedNestedTypedefs(const RecordDecl *D);
3313 void DiagnoseUnusedDecl(const NamedDecl *ND);
3315 /// Emit \p DiagID if statement located on \p StmtLoc has a suspicious null
3316 /// statement as a \p Body, and it is located on the same line.
3318 /// This helps prevent bugs due to typos, such as:
3321 void DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
3325 /// Warn if a for/while loop statement \p S, which is followed by
3326 /// \p PossibleBody, has a suspicious null statement as a body.
3327 void DiagnoseEmptyLoopBody(const Stmt *S,
3328 const Stmt *PossibleBody);
3330 /// Warn if a value is moved to itself.
3331 void DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
3332 SourceLocation OpLoc);
3334 ParsingDeclState PushParsingDeclaration(sema::DelayedDiagnosticPool &pool) {
3335 return DelayedDiagnostics.push(pool);
3337 void PopParsingDeclaration(ParsingDeclState state, Decl *decl);
3339 typedef ProcessingContextState ParsingClassState;
3340 ParsingClassState PushParsingClass() {
3341 return DelayedDiagnostics.pushUndelayed();
3343 void PopParsingClass(ParsingClassState state) {
3344 DelayedDiagnostics.popUndelayed(state);
3347 void redelayDiagnostics(sema::DelayedDiagnosticPool &pool);
3349 enum AvailabilityDiagnostic { AD_Deprecation, AD_Unavailable };
3351 void EmitAvailabilityWarning(AvailabilityDiagnostic AD,
3352 NamedDecl *D, StringRef Message,
3354 const ObjCInterfaceDecl *UnknownObjCClass,
3355 const ObjCPropertyDecl *ObjCProperty,
3356 bool ObjCPropertyAccess);
3358 bool makeUnavailableInSystemHeader(SourceLocation loc,
3361 //===--------------------------------------------------------------------===//
3362 // Expression Parsing Callbacks: SemaExpr.cpp.
3364 bool CanUseDecl(NamedDecl *D);
3365 bool DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc,
3366 const ObjCInterfaceDecl *UnknownObjCClass=nullptr,
3367 bool ObjCPropertyAccess=false);
3368 void NoteDeletedFunction(FunctionDecl *FD);
3369 std::string getDeletedOrUnavailableSuffix(const FunctionDecl *FD);
3370 bool DiagnosePropertyAccessorMismatch(ObjCPropertyDecl *PD,
3371 ObjCMethodDecl *Getter,
3372 SourceLocation Loc);
3373 void DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
3374 ArrayRef<Expr *> Args);
3376 void PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
3377 Decl *LambdaContextDecl = nullptr,
3378 bool IsDecltype = false);
3379 enum ReuseLambdaContextDecl_t { ReuseLambdaContextDecl };
3380 void PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
3381 ReuseLambdaContextDecl_t,
3382 bool IsDecltype = false);
3383 void PopExpressionEvaluationContext();
3385 void DiscardCleanupsInEvaluationContext();
3387 ExprResult TransformToPotentiallyEvaluated(Expr *E);
3388 ExprResult HandleExprEvaluationContextForTypeof(Expr *E);
3390 ExprResult ActOnConstantExpression(ExprResult Res);
3392 // Functions for marking a declaration referenced. These functions also
3393 // contain the relevant logic for marking if a reference to a function or
3394 // variable is an odr-use (in the C++11 sense). There are separate variants
3395 // for expressions referring to a decl; these exist because odr-use marking
3396 // needs to be delayed for some constant variables when we build one of the
3397 // named expressions.
3398 void MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, bool OdrUse);
3399 void MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func,
3400 bool OdrUse = true);
3401 void MarkVariableReferenced(SourceLocation Loc, VarDecl *Var);
3402 void MarkDeclRefReferenced(DeclRefExpr *E);
3403 void MarkMemberReferenced(MemberExpr *E);
3405 void UpdateMarkingForLValueToRValue(Expr *E);
3406 void CleanupVarDeclMarking();
3408 enum TryCaptureKind {
3409 TryCapture_Implicit, TryCapture_ExplicitByVal, TryCapture_ExplicitByRef
3412 /// \brief Try to capture the given variable.
3414 /// \param Var The variable to capture.
3416 /// \param Loc The location at which the capture occurs.
3418 /// \param Kind The kind of capture, which may be implicit (for either a
3419 /// block or a lambda), or explicit by-value or by-reference (for a lambda).
3421 /// \param EllipsisLoc The location of the ellipsis, if one is provided in
3422 /// an explicit lambda capture.
3424 /// \param BuildAndDiagnose Whether we are actually supposed to add the
3425 /// captures or diagnose errors. If false, this routine merely check whether
3426 /// the capture can occur without performing the capture itself or complaining
3427 /// if the variable cannot be captured.
3429 /// \param CaptureType Will be set to the type of the field used to capture
3430 /// this variable in the innermost block or lambda. Only valid when the
3431 /// variable can be captured.
3433 /// \param DeclRefType Will be set to the type of a reference to the capture
3434 /// from within the current scope. Only valid when the variable can be
3437 /// \param FunctionScopeIndexToStopAt If non-null, it points to the index
3438 /// of the FunctionScopeInfo stack beyond which we do not attempt to capture.
3439 /// This is useful when enclosing lambdas must speculatively capture
3440 /// variables that may or may not be used in certain specializations of
3441 /// a nested generic lambda.
3443 /// \returns true if an error occurred (i.e., the variable cannot be
3444 /// captured) and false if the capture succeeded.
3445 bool tryCaptureVariable(VarDecl *Var, SourceLocation Loc, TryCaptureKind Kind,
3446 SourceLocation EllipsisLoc, bool BuildAndDiagnose,
3447 QualType &CaptureType,
3448 QualType &DeclRefType,
3449 const unsigned *const FunctionScopeIndexToStopAt);
3451 /// \brief Try to capture the given variable.
3452 bool tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
3453 TryCaptureKind Kind = TryCapture_Implicit,
3454 SourceLocation EllipsisLoc = SourceLocation());
3456 /// \brief Checks if the variable must be captured.
3457 bool NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc);
3459 /// \brief Given a variable, determine the type that a reference to that
3460 /// variable will have in the given scope.
3461 QualType getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc);
3463 void MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T);
3464 void MarkDeclarationsReferencedInExpr(Expr *E,
3465 bool SkipLocalVariables = false);
3467 /// \brief Try to recover by turning the given expression into a
3468 /// call. Returns true if recovery was attempted or an error was
3469 /// emitted; this may also leave the ExprResult invalid.
3470 bool tryToRecoverWithCall(ExprResult &E, const PartialDiagnostic &PD,
3471 bool ForceComplain = false,
3472 bool (*IsPlausibleResult)(QualType) = nullptr);
3474 /// \brief Figure out if an expression could be turned into a call.
3475 bool tryExprAsCall(Expr &E, QualType &ZeroArgCallReturnTy,
3476 UnresolvedSetImpl &NonTemplateOverloads);
3478 /// \brief Conditionally issue a diagnostic based on the current
3479 /// evaluation context.
3481 /// \param Statement If Statement is non-null, delay reporting the
3482 /// diagnostic until the function body is parsed, and then do a basic
3483 /// reachability analysis to determine if the statement is reachable.
3484 /// If it is unreachable, the diagnostic will not be emitted.
3485 bool DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
3486 const PartialDiagnostic &PD);
3488 // Primary Expressions.
3489 SourceRange getExprRange(Expr *E) const;
3491 ExprResult ActOnIdExpression(
3492 Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
3493 UnqualifiedId &Id, bool HasTrailingLParen, bool IsAddressOfOperand,
3494 std::unique_ptr<CorrectionCandidateCallback> CCC = nullptr,
3495 bool IsInlineAsmIdentifier = false, Token *KeywordReplacement = nullptr);
3497 void DecomposeUnqualifiedId(const UnqualifiedId &Id,
3498 TemplateArgumentListInfo &Buffer,
3499 DeclarationNameInfo &NameInfo,
3500 const TemplateArgumentListInfo *&TemplateArgs);
3503 DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
3504 std::unique_ptr<CorrectionCandidateCallback> CCC,
3505 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr,
3506 ArrayRef<Expr *> Args = None, TypoExpr **Out = nullptr);
3508 ExprResult LookupInObjCMethod(LookupResult &LookUp, Scope *S,
3510 bool AllowBuiltinCreation=false);
3512 ExprResult ActOnDependentIdExpression(const CXXScopeSpec &SS,
3513 SourceLocation TemplateKWLoc,
3514 const DeclarationNameInfo &NameInfo,
3515 bool isAddressOfOperand,
3516 const TemplateArgumentListInfo *TemplateArgs);
3518 ExprResult BuildDeclRefExpr(ValueDecl *D, QualType Ty,
3521 const CXXScopeSpec *SS = nullptr);
3523 BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
3524 const DeclarationNameInfo &NameInfo,
3525 const CXXScopeSpec *SS = nullptr,
3526 NamedDecl *FoundD = nullptr,
3527 const TemplateArgumentListInfo *TemplateArgs = nullptr);
3529 BuildAnonymousStructUnionMemberReference(
3530 const CXXScopeSpec &SS,
3531 SourceLocation nameLoc,
3532 IndirectFieldDecl *indirectField,
3533 DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_none),
3534 Expr *baseObjectExpr = nullptr,
3535 SourceLocation opLoc = SourceLocation());
3537 ExprResult BuildPossibleImplicitMemberExpr(const CXXScopeSpec &SS,
3538 SourceLocation TemplateKWLoc,
3540 const TemplateArgumentListInfo *TemplateArgs);
3541 ExprResult BuildImplicitMemberExpr(const CXXScopeSpec &SS,
3542 SourceLocation TemplateKWLoc,
3544 const TemplateArgumentListInfo *TemplateArgs,
3545 bool IsDefiniteInstance);
3546 bool UseArgumentDependentLookup(const CXXScopeSpec &SS,
3547 const LookupResult &R,
3548 bool HasTrailingLParen);
3550 ExprResult BuildQualifiedDeclarationNameExpr(
3551 CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo,
3552 bool IsAddressOfOperand, TypeSourceInfo **RecoveryTSI = nullptr);
3554 ExprResult BuildDependentDeclRefExpr(const CXXScopeSpec &SS,
3555 SourceLocation TemplateKWLoc,
3556 const DeclarationNameInfo &NameInfo,
3557 const TemplateArgumentListInfo *TemplateArgs);
3559 ExprResult BuildDeclarationNameExpr(const CXXScopeSpec &SS,
3562 bool AcceptInvalidDecl = false);
3563 ExprResult BuildDeclarationNameExpr(
3564 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
3565 NamedDecl *FoundD = nullptr,
3566 const TemplateArgumentListInfo *TemplateArgs = nullptr,
3567 bool AcceptInvalidDecl = false);
3569 ExprResult BuildLiteralOperatorCall(LookupResult &R,
3570 DeclarationNameInfo &SuffixInfo,
3571 ArrayRef<Expr *> Args,
3572 SourceLocation LitEndLoc,
3573 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr);
3575 ExprResult BuildPredefinedExpr(SourceLocation Loc,
3576 PredefinedExpr::IdentType IT);
3577 ExprResult ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind);
3578 ExprResult ActOnIntegerConstant(SourceLocation Loc, uint64_t Val);
3580 bool CheckLoopHintExpr(Expr *E, SourceLocation Loc);
3582 ExprResult ActOnNumericConstant(const Token &Tok, Scope *UDLScope = nullptr);
3583 ExprResult ActOnCharacterConstant(const Token &Tok,
3584 Scope *UDLScope = nullptr);
3585 ExprResult ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E);
3586 ExprResult ActOnParenListExpr(SourceLocation L,
3590 /// ActOnStringLiteral - The specified tokens were lexed as pasted string
3591 /// fragments (e.g. "foo" "bar" L"baz").
3592 ExprResult ActOnStringLiteral(ArrayRef<Token> StringToks,
3593 Scope *UDLScope = nullptr);
3595 ExprResult ActOnGenericSelectionExpr(SourceLocation KeyLoc,
3596 SourceLocation DefaultLoc,
3597 SourceLocation RParenLoc,
3598 Expr *ControllingExpr,
3599 ArrayRef<ParsedType> ArgTypes,
3600 ArrayRef<Expr *> ArgExprs);
3601 ExprResult CreateGenericSelectionExpr(SourceLocation KeyLoc,
3602 SourceLocation DefaultLoc,
3603 SourceLocation RParenLoc,
3604 Expr *ControllingExpr,
3605 ArrayRef<TypeSourceInfo *> Types,
3606 ArrayRef<Expr *> Exprs);
3608 // Binary/Unary Operators. 'Tok' is the token for the operator.
3609 ExprResult CreateBuiltinUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc,
3611 ExprResult BuildUnaryOp(Scope *S, SourceLocation OpLoc,
3612 UnaryOperatorKind Opc, Expr *Input);
3613 ExprResult ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
3614 tok::TokenKind Op, Expr *Input);
3616 QualType CheckAddressOfOperand(ExprResult &Operand, SourceLocation OpLoc);
3618 ExprResult CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
3619 SourceLocation OpLoc,
3620 UnaryExprOrTypeTrait ExprKind,
3622 ExprResult CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
3623 UnaryExprOrTypeTrait ExprKind);
3625 ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
3626 UnaryExprOrTypeTrait ExprKind,
3627 bool IsType, void *TyOrEx,
3628 const SourceRange &ArgRange);
3630 ExprResult CheckPlaceholderExpr(Expr *E);
3631 bool CheckVecStepExpr(Expr *E);
3633 bool CheckUnaryExprOrTypeTraitOperand(Expr *E, UnaryExprOrTypeTrait ExprKind);
3634 bool CheckUnaryExprOrTypeTraitOperand(QualType ExprType, SourceLocation OpLoc,
3635 SourceRange ExprRange,
3636 UnaryExprOrTypeTrait ExprKind);
3637 ExprResult ActOnSizeofParameterPackExpr(Scope *S,
3638 SourceLocation OpLoc,
3639 IdentifierInfo &Name,
3640 SourceLocation NameLoc,
3641 SourceLocation RParenLoc);
3642 ExprResult ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
3643 tok::TokenKind Kind, Expr *Input);
3645 ExprResult ActOnArraySubscriptExpr(Scope *S, Expr *Base, SourceLocation LLoc,
3646 Expr *Idx, SourceLocation RLoc);
3647 ExprResult CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
3648 Expr *Idx, SourceLocation RLoc);
3650 // This struct is for use by ActOnMemberAccess to allow
3651 // BuildMemberReferenceExpr to be able to reinvoke ActOnMemberAccess after
3652 // changing the access operator from a '.' to a '->' (to see if that is the
3653 // change needed to fix an error about an unknown member, e.g. when the class
3654 // defines a custom operator->).
3655 struct ActOnMemberAccessExtraArgs {
3659 bool HasTrailingLParen;
3662 ExprResult BuildMemberReferenceExpr(
3663 Expr *Base, QualType BaseType, SourceLocation OpLoc, bool IsArrow,
3664 CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
3665 NamedDecl *FirstQualifierInScope, const DeclarationNameInfo &NameInfo,
3666 const TemplateArgumentListInfo *TemplateArgs,
3667 ActOnMemberAccessExtraArgs *ExtraArgs = nullptr);
3670 BuildMemberReferenceExpr(Expr *Base, QualType BaseType, SourceLocation OpLoc,
3671 bool IsArrow, const CXXScopeSpec &SS,
3672 SourceLocation TemplateKWLoc,
3673 NamedDecl *FirstQualifierInScope, LookupResult &R,
3674 const TemplateArgumentListInfo *TemplateArgs,
3675 bool SuppressQualifierCheck = false,
3676 ActOnMemberAccessExtraArgs *ExtraArgs = nullptr);
3678 ExprResult PerformMemberExprBaseConversion(Expr *Base, bool IsArrow);
3680 bool CheckQualifiedMemberReference(Expr *BaseExpr, QualType BaseType,
3681 const CXXScopeSpec &SS,
3682 const LookupResult &R);
3684 ExprResult ActOnDependentMemberExpr(Expr *Base, QualType BaseType,
3685 bool IsArrow, SourceLocation OpLoc,
3686 const CXXScopeSpec &SS,
3687 SourceLocation TemplateKWLoc,
3688 NamedDecl *FirstQualifierInScope,
3689 const DeclarationNameInfo &NameInfo,
3690 const TemplateArgumentListInfo *TemplateArgs);
3692 ExprResult ActOnMemberAccessExpr(Scope *S, Expr *Base,
3693 SourceLocation OpLoc,
3694 tok::TokenKind OpKind,
3696 SourceLocation TemplateKWLoc,
3697 UnqualifiedId &Member,
3699 bool HasTrailingLParen);
3701 void ActOnDefaultCtorInitializers(Decl *CDtorDecl);
3702 bool ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
3703 FunctionDecl *FDecl,
3704 const FunctionProtoType *Proto,
3705 ArrayRef<Expr *> Args,
3706 SourceLocation RParenLoc,
3707 bool ExecConfig = false);
3708 void CheckStaticArrayArgument(SourceLocation CallLoc,
3710 const Expr *ArgExpr);
3712 /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
3713 /// This provides the location of the left/right parens and a list of comma
3715 ExprResult ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
3716 MultiExprArg ArgExprs, SourceLocation RParenLoc,
3717 Expr *ExecConfig = nullptr,
3718 bool IsExecConfig = false);
3719 ExprResult BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
3720 SourceLocation LParenLoc,
3721 ArrayRef<Expr *> Arg,
3722 SourceLocation RParenLoc,
3723 Expr *Config = nullptr,
3724 bool IsExecConfig = false);
3726 ExprResult ActOnCUDAExecConfigExpr(Scope *S, SourceLocation LLLLoc,
3727 MultiExprArg ExecConfig,
3728 SourceLocation GGGLoc);
3730 ExprResult ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
3731 Declarator &D, ParsedType &Ty,
3732 SourceLocation RParenLoc, Expr *CastExpr);
3733 ExprResult BuildCStyleCastExpr(SourceLocation LParenLoc,
3735 SourceLocation RParenLoc,
3737 CastKind PrepareScalarCast(ExprResult &src, QualType destType);
3739 /// \brief Build an altivec or OpenCL literal.
3740 ExprResult BuildVectorLiteral(SourceLocation LParenLoc,
3741 SourceLocation RParenLoc, Expr *E,
3742 TypeSourceInfo *TInfo);
3744 ExprResult MaybeConvertParenListExprToParenExpr(Scope *S, Expr *ME);
3746 ExprResult ActOnCompoundLiteral(SourceLocation LParenLoc,
3748 SourceLocation RParenLoc,
3751 ExprResult BuildCompoundLiteralExpr(SourceLocation LParenLoc,
3752 TypeSourceInfo *TInfo,
3753 SourceLocation RParenLoc,
3756 ExprResult ActOnInitList(SourceLocation LBraceLoc,
3757 MultiExprArg InitArgList,
3758 SourceLocation RBraceLoc);
3760 ExprResult ActOnDesignatedInitializer(Designation &Desig,
3766 static BinaryOperatorKind ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind);
3769 ExprResult ActOnBinOp(Scope *S, SourceLocation TokLoc,
3770 tok::TokenKind Kind, Expr *LHSExpr, Expr *RHSExpr);
3771 ExprResult BuildBinOp(Scope *S, SourceLocation OpLoc,
3772 BinaryOperatorKind Opc, Expr *LHSExpr, Expr *RHSExpr);
3773 ExprResult CreateBuiltinBinOp(SourceLocation OpLoc, BinaryOperatorKind Opc,
3774 Expr *LHSExpr, Expr *RHSExpr);
3776 /// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
3777 /// in the case of a the GNU conditional expr extension.
3778 ExprResult ActOnConditionalOp(SourceLocation QuestionLoc,
3779 SourceLocation ColonLoc,
3780 Expr *CondExpr, Expr *LHSExpr, Expr *RHSExpr);
3782 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
3783 ExprResult ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
3784 LabelDecl *TheDecl);
3786 void ActOnStartStmtExpr();
3787 ExprResult ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
3788 SourceLocation RPLoc); // "({..})"
3789 void ActOnStmtExprError();
3791 // __builtin_offsetof(type, identifier(.identifier|[expr])*)
3792 struct OffsetOfComponent {
3793 SourceLocation LocStart, LocEnd;
3794 bool isBrackets; // true if [expr], false if .ident
3796 IdentifierInfo *IdentInfo;
3801 /// __builtin_offsetof(type, a.b[123][456].c)
3802 ExprResult BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
3803 TypeSourceInfo *TInfo,
3804 OffsetOfComponent *CompPtr,
3805 unsigned NumComponents,
3806 SourceLocation RParenLoc);
3807 ExprResult ActOnBuiltinOffsetOf(Scope *S,
3808 SourceLocation BuiltinLoc,
3809 SourceLocation TypeLoc,
3810 ParsedType ParsedArgTy,
3811 OffsetOfComponent *CompPtr,
3812 unsigned NumComponents,
3813 SourceLocation RParenLoc);
3815 // __builtin_choose_expr(constExpr, expr1, expr2)
3816 ExprResult ActOnChooseExpr(SourceLocation BuiltinLoc,
3817 Expr *CondExpr, Expr *LHSExpr,
3818 Expr *RHSExpr, SourceLocation RPLoc);
3820 // __builtin_va_arg(expr, type)
3821 ExprResult ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty,
3822 SourceLocation RPLoc);
3823 ExprResult BuildVAArgExpr(SourceLocation BuiltinLoc, Expr *E,
3824 TypeSourceInfo *TInfo, SourceLocation RPLoc);
3827 ExprResult ActOnGNUNullExpr(SourceLocation TokenLoc);
3829 bool CheckCaseExpression(Expr *E);
3831 /// \brief Describes the result of an "if-exists" condition check.
3832 enum IfExistsResult {
3833 /// \brief The symbol exists.
3836 /// \brief The symbol does not exist.
3839 /// \brief The name is a dependent name, so the results will differ
3840 /// from one instantiation to the next.
3843 /// \brief An error occurred.
3848 CheckMicrosoftIfExistsSymbol(Scope *S, CXXScopeSpec &SS,
3849 const DeclarationNameInfo &TargetNameInfo);
3852 CheckMicrosoftIfExistsSymbol(Scope *S, SourceLocation KeywordLoc,
3853 bool IsIfExists, CXXScopeSpec &SS,
3854 UnqualifiedId &Name);
3856 StmtResult BuildMSDependentExistsStmt(SourceLocation KeywordLoc,
3858 NestedNameSpecifierLoc QualifierLoc,
3859 DeclarationNameInfo NameInfo,
3861 StmtResult ActOnMSDependentExistsStmt(SourceLocation KeywordLoc,
3863 CXXScopeSpec &SS, UnqualifiedId &Name,
3866 //===------------------------- "Block" Extension ------------------------===//
3868 /// ActOnBlockStart - This callback is invoked when a block literal is
3870 void ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope);
3872 /// ActOnBlockArguments - This callback allows processing of block arguments.
3873 /// If there are no arguments, this is still invoked.
3874 void ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
3877 /// ActOnBlockError - If there is an error parsing a block, this callback
3878 /// is invoked to pop the information about the block from the action impl.
3879 void ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope);
3881 /// ActOnBlockStmtExpr - This is called when the body of a block statement
3882 /// literal was successfully completed. ^(int x){...}
3883 ExprResult ActOnBlockStmtExpr(SourceLocation CaretLoc, Stmt *Body,
3886 //===---------------------------- Clang Extensions ----------------------===//
3888 /// __builtin_convertvector(...)
3889 ExprResult ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy,
3890 SourceLocation BuiltinLoc,
3891 SourceLocation RParenLoc);
3893 //===---------------------------- OpenCL Features -----------------------===//
3895 /// __builtin_astype(...)
3896 ExprResult ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
3897 SourceLocation BuiltinLoc,
3898 SourceLocation RParenLoc);
3900 //===---------------------------- C++ Features --------------------------===//
3902 // Act on C++ namespaces
3903 Decl *ActOnStartNamespaceDef(Scope *S, SourceLocation InlineLoc,
3904 SourceLocation NamespaceLoc,
3905 SourceLocation IdentLoc,
3906 IdentifierInfo *Ident,
3907 SourceLocation LBrace,
3908 AttributeList *AttrList);
3909 void ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace);
3911 NamespaceDecl *getStdNamespace() const;
3912 NamespaceDecl *getOrCreateStdNamespace();
3914 CXXRecordDecl *getStdBadAlloc() const;
3916 /// \brief Tests whether Ty is an instance of std::initializer_list and, if
3917 /// it is and Element is not NULL, assigns the element type to Element.
3918 bool isStdInitializerList(QualType Ty, QualType *Element);
3920 /// \brief Looks for the std::initializer_list template and instantiates it
3921 /// with Element, or emits an error if it's not found.
3923 /// \returns The instantiated template, or null on error.
3924 QualType BuildStdInitializerList(QualType Element, SourceLocation Loc);
3926 /// \brief Determine whether Ctor is an initializer-list constructor, as
3927 /// defined in [dcl.init.list]p2.
3928 bool isInitListConstructor(const CXXConstructorDecl *Ctor);
3930 Decl *ActOnUsingDirective(Scope *CurScope,
3931 SourceLocation UsingLoc,
3932 SourceLocation NamespcLoc,
3934 SourceLocation IdentLoc,
3935 IdentifierInfo *NamespcName,
3936 AttributeList *AttrList);
3938 void PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir);
3940 Decl *ActOnNamespaceAliasDef(Scope *CurScope,
3941 SourceLocation NamespaceLoc,
3942 SourceLocation AliasLoc,
3943 IdentifierInfo *Alias,
3945 SourceLocation IdentLoc,
3946 IdentifierInfo *Ident);
3948 void HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow);
3949 bool CheckUsingShadowDecl(UsingDecl *UD, NamedDecl *Target,
3950 const LookupResult &PreviousDecls,
3951 UsingShadowDecl *&PrevShadow);
3952 UsingShadowDecl *BuildUsingShadowDecl(Scope *S, UsingDecl *UD,
3954 UsingShadowDecl *PrevDecl);
3956 bool CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
3957 bool HasTypenameKeyword,
3958 const CXXScopeSpec &SS,
3959 SourceLocation NameLoc,
3960 const LookupResult &Previous);
3961 bool CheckUsingDeclQualifier(SourceLocation UsingLoc,
3962 const CXXScopeSpec &SS,
3963 const DeclarationNameInfo &NameInfo,
3964 SourceLocation NameLoc);
3966 NamedDecl *BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
3967 SourceLocation UsingLoc,
3969 DeclarationNameInfo NameInfo,
3970 AttributeList *AttrList,
3971 bool IsInstantiation,
3972 bool HasTypenameKeyword,
3973 SourceLocation TypenameLoc);
3975 bool CheckInheritingConstructorUsingDecl(UsingDecl *UD);
3977 Decl *ActOnUsingDeclaration(Scope *CurScope,
3979 bool HasUsingKeyword,
3980 SourceLocation UsingLoc,
3982 UnqualifiedId &Name,
3983 AttributeList *AttrList,
3984 bool HasTypenameKeyword,
3985 SourceLocation TypenameLoc);
3986 Decl *ActOnAliasDeclaration(Scope *CurScope,
3988 MultiTemplateParamsArg TemplateParams,
3989 SourceLocation UsingLoc,
3990 UnqualifiedId &Name,
3991 AttributeList *AttrList,
3994 /// BuildCXXConstructExpr - Creates a complete call to a constructor,
3995 /// including handling of its default argument expressions.
3997 /// \param ConstructKind - a CXXConstructExpr::ConstructionKind
3999 BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
4000 CXXConstructorDecl *Constructor, MultiExprArg Exprs,
4001 bool HadMultipleCandidates, bool IsListInitialization,
4002 bool IsStdInitListInitialization,
4003 bool RequiresZeroInit, unsigned ConstructKind,
4004 SourceRange ParenRange);
4006 // FIXME: Can we remove this and have the above BuildCXXConstructExpr check if
4007 // the constructor can be elidable?
4009 BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
4010 CXXConstructorDecl *Constructor, bool Elidable,
4011 MultiExprArg Exprs, bool HadMultipleCandidates,
4012 bool IsListInitialization,
4013 bool IsStdInitListInitialization, bool RequiresZeroInit,
4014 unsigned ConstructKind, SourceRange ParenRange);
4016 ExprResult BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field);
4018 /// BuildCXXDefaultArgExpr - Creates a CXXDefaultArgExpr, instantiating
4019 /// the default expr if needed.
4020 ExprResult BuildCXXDefaultArgExpr(SourceLocation CallLoc,
4022 ParmVarDecl *Param);
4024 /// FinalizeVarWithDestructor - Prepare for calling destructor on the
4025 /// constructed variable.
4026 void FinalizeVarWithDestructor(VarDecl *VD, const RecordType *DeclInitType);
4028 /// \brief Helper class that collects exception specifications for
4029 /// implicitly-declared special member functions.
4030 class ImplicitExceptionSpecification {
4031 // Pointer to allow copying
4033 // We order exception specifications thus:
4034 // noexcept is the most restrictive, but is only used in C++11.
4035 // throw() comes next.
4036 // Then a throw(collected exceptions)
4037 // Finally no specification, which is expressed as noexcept(false).
4038 // throw(...) is used instead if any called function uses it.
4039 ExceptionSpecificationType ComputedEST;
4040 llvm::SmallPtrSet<CanQualType, 4> ExceptionsSeen;
4041 SmallVector<QualType, 4> Exceptions;
4043 void ClearExceptions() {
4044 ExceptionsSeen.clear();
4049 explicit ImplicitExceptionSpecification(Sema &Self)
4050 : Self(&Self), ComputedEST(EST_BasicNoexcept) {
4051 if (!Self.getLangOpts().CPlusPlus11)
4052 ComputedEST = EST_DynamicNone;
4055 /// \brief Get the computed exception specification type.
4056 ExceptionSpecificationType getExceptionSpecType() const {
4057 assert(ComputedEST != EST_ComputedNoexcept &&
4058 "noexcept(expr) should not be a possible result");
4062 /// \brief The number of exceptions in the exception specification.
4063 unsigned size() const { return Exceptions.size(); }
4065 /// \brief The set of exceptions in the exception specification.
4066 const QualType *data() const { return Exceptions.data(); }
4068 /// \brief Integrate another called method into the collected data.
4069 void CalledDecl(SourceLocation CallLoc, const CXXMethodDecl *Method);
4071 /// \brief Integrate an invoked expression into the collected data.
4072 void CalledExpr(Expr *E);
4074 /// \brief Overwrite an EPI's exception specification with this
4075 /// computed exception specification.
4076 FunctionProtoType::ExceptionSpecInfo getExceptionSpec() const {
4077 FunctionProtoType::ExceptionSpecInfo ESI;
4078 ESI.Type = getExceptionSpecType();
4079 if (ESI.Type == EST_Dynamic) {
4080 ESI.Exceptions = Exceptions;
4081 } else if (ESI.Type == EST_None) {
4082 /// C++11 [except.spec]p14:
4083 /// The exception-specification is noexcept(false) if the set of
4084 /// potential exceptions of the special member function contains "any"
4085 ESI.Type = EST_ComputedNoexcept;
4086 ESI.NoexceptExpr = Self->ActOnCXXBoolLiteral(SourceLocation(),
4087 tok::kw_false).get();
4093 /// \brief Determine what sort of exception specification a defaulted
4094 /// copy constructor of a class will have.
4095 ImplicitExceptionSpecification
4096 ComputeDefaultedDefaultCtorExceptionSpec(SourceLocation Loc,
4099 /// \brief Determine what sort of exception specification a defaulted
4100 /// default constructor of a class will have, and whether the parameter
4102 ImplicitExceptionSpecification
4103 ComputeDefaultedCopyCtorExceptionSpec(CXXMethodDecl *MD);
4105 /// \brief Determine what sort of exception specification a defautled
4106 /// copy assignment operator of a class will have, and whether the
4107 /// parameter will be const.
4108 ImplicitExceptionSpecification
4109 ComputeDefaultedCopyAssignmentExceptionSpec(CXXMethodDecl *MD);
4111 /// \brief Determine what sort of exception specification a defaulted move
4112 /// constructor of a class will have.
4113 ImplicitExceptionSpecification
4114 ComputeDefaultedMoveCtorExceptionSpec(CXXMethodDecl *MD);
4116 /// \brief Determine what sort of exception specification a defaulted move
4117 /// assignment operator of a class will have.
4118 ImplicitExceptionSpecification
4119 ComputeDefaultedMoveAssignmentExceptionSpec(CXXMethodDecl *MD);
4121 /// \brief Determine what sort of exception specification a defaulted
4122 /// destructor of a class will have.
4123 ImplicitExceptionSpecification
4124 ComputeDefaultedDtorExceptionSpec(CXXMethodDecl *MD);
4126 /// \brief Determine what sort of exception specification an inheriting
4127 /// constructor of a class will have.
4128 ImplicitExceptionSpecification
4129 ComputeInheritingCtorExceptionSpec(CXXConstructorDecl *CD);
4131 /// \brief Evaluate the implicit exception specification for a defaulted
4132 /// special member function.
4133 void EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD);
4135 /// \brief Check the given exception-specification and update the
4136 /// exception specification information with the results.
4137 void checkExceptionSpecification(bool IsTopLevel,
4138 ExceptionSpecificationType EST,
4139 ArrayRef<ParsedType> DynamicExceptions,
4140 ArrayRef<SourceRange> DynamicExceptionRanges,
4142 SmallVectorImpl<QualType> &Exceptions,
4143 FunctionProtoType::ExceptionSpecInfo &ESI);
4145 /// \brief Determine if we're in a case where we need to (incorrectly) eagerly
4146 /// parse an exception specification to work around a libstdc++ bug.
4147 bool isLibstdcxxEagerExceptionSpecHack(const Declarator &D);
4149 /// \brief Add an exception-specification to the given member function
4150 /// (or member function template). The exception-specification was parsed
4151 /// after the method itself was declared.
4152 void actOnDelayedExceptionSpecification(Decl *Method,
4153 ExceptionSpecificationType EST,
4154 SourceRange SpecificationRange,
4155 ArrayRef<ParsedType> DynamicExceptions,
4156 ArrayRef<SourceRange> DynamicExceptionRanges,
4157 Expr *NoexceptExpr);
4159 /// \brief Determine if a special member function should have a deleted
4160 /// definition when it is defaulted.
4161 bool ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
4162 bool Diagnose = false);
4164 /// \brief Declare the implicit default constructor for the given class.
4166 /// \param ClassDecl The class declaration into which the implicit
4167 /// default constructor will be added.
4169 /// \returns The implicitly-declared default constructor.
4170 CXXConstructorDecl *DeclareImplicitDefaultConstructor(
4171 CXXRecordDecl *ClassDecl);
4173 /// DefineImplicitDefaultConstructor - Checks for feasibility of
4174 /// defining this constructor as the default constructor.
4175 void DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
4176 CXXConstructorDecl *Constructor);
4178 /// \brief Declare the implicit destructor for the given class.
4180 /// \param ClassDecl The class declaration into which the implicit
4181 /// destructor will be added.
4183 /// \returns The implicitly-declared destructor.
4184 CXXDestructorDecl *DeclareImplicitDestructor(CXXRecordDecl *ClassDecl);
4186 /// DefineImplicitDestructor - Checks for feasibility of
4187 /// defining this destructor as the default destructor.
4188 void DefineImplicitDestructor(SourceLocation CurrentLocation,
4189 CXXDestructorDecl *Destructor);
4191 /// \brief Build an exception spec for destructors that don't have one.
4193 /// C++11 says that user-defined destructors with no exception spec get one
4194 /// that looks as if the destructor was implicitly declared.
4195 void AdjustDestructorExceptionSpec(CXXRecordDecl *ClassDecl,
4196 CXXDestructorDecl *Destructor);
4198 /// \brief Declare all inheriting constructors for the given class.
4200 /// \param ClassDecl The class declaration into which the inheriting
4201 /// constructors will be added.
4202 void DeclareInheritingConstructors(CXXRecordDecl *ClassDecl);
4204 /// \brief Define the specified inheriting constructor.
4205 void DefineInheritingConstructor(SourceLocation UseLoc,
4206 CXXConstructorDecl *Constructor);
4208 /// \brief Declare the implicit copy constructor for the given class.
4210 /// \param ClassDecl The class declaration into which the implicit
4211 /// copy constructor will be added.
4213 /// \returns The implicitly-declared copy constructor.
4214 CXXConstructorDecl *DeclareImplicitCopyConstructor(CXXRecordDecl *ClassDecl);
4216 /// DefineImplicitCopyConstructor - Checks for feasibility of
4217 /// defining this constructor as the copy constructor.
4218 void DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
4219 CXXConstructorDecl *Constructor);
4221 /// \brief Declare the implicit move constructor for the given class.
4223 /// \param ClassDecl The Class declaration into which the implicit
4224 /// move constructor will be added.
4226 /// \returns The implicitly-declared move constructor, or NULL if it wasn't
4228 CXXConstructorDecl *DeclareImplicitMoveConstructor(CXXRecordDecl *ClassDecl);
4230 /// DefineImplicitMoveConstructor - Checks for feasibility of
4231 /// defining this constructor as the move constructor.
4232 void DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
4233 CXXConstructorDecl *Constructor);
4235 /// \brief Declare the implicit copy assignment operator for the given class.
4237 /// \param ClassDecl The class declaration into which the implicit
4238 /// copy assignment operator will be added.
4240 /// \returns The implicitly-declared copy assignment operator.
4241 CXXMethodDecl *DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl);
4243 /// \brief Defines an implicitly-declared copy assignment operator.
4244 void DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
4245 CXXMethodDecl *MethodDecl);
4247 /// \brief Declare the implicit move assignment operator for the given class.
4249 /// \param ClassDecl The Class declaration into which the implicit
4250 /// move assignment operator will be added.
4252 /// \returns The implicitly-declared move assignment operator, or NULL if it
4253 /// wasn't declared.
4254 CXXMethodDecl *DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl);
4256 /// \brief Defines an implicitly-declared move assignment operator.
4257 void DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
4258 CXXMethodDecl *MethodDecl);
4260 /// \brief Force the declaration of any implicitly-declared members of this
4262 void ForceDeclarationOfImplicitMembers(CXXRecordDecl *Class);
4264 /// \brief Determine whether the given function is an implicitly-deleted
4265 /// special member function.
4266 bool isImplicitlyDeleted(FunctionDecl *FD);
4268 /// \brief Check whether 'this' shows up in the type of a static member
4269 /// function after the (naturally empty) cv-qualifier-seq would be.
4271 /// \returns true if an error occurred.
4272 bool checkThisInStaticMemberFunctionType(CXXMethodDecl *Method);
4274 /// \brief Whether this' shows up in the exception specification of a static
4275 /// member function.
4276 bool checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method);
4278 /// \brief Check whether 'this' shows up in the attributes of the given
4279 /// static member function.
4281 /// \returns true if an error occurred.
4282 bool checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method);
4284 /// MaybeBindToTemporary - If the passed in expression has a record type with
4285 /// a non-trivial destructor, this will return CXXBindTemporaryExpr. Otherwise
4286 /// it simply returns the passed in expression.
4287 ExprResult MaybeBindToTemporary(Expr *E);
4289 bool CompleteConstructorCall(CXXConstructorDecl *Constructor,
4290 MultiExprArg ArgsPtr,
4292 SmallVectorImpl<Expr*> &ConvertedArgs,
4293 bool AllowExplicit = false,
4294 bool IsListInitialization = false);
4296 ParsedType getInheritingConstructorName(CXXScopeSpec &SS,
4297 SourceLocation NameLoc,
4298 IdentifierInfo &Name);
4300 ParsedType getDestructorName(SourceLocation TildeLoc,
4301 IdentifierInfo &II, SourceLocation NameLoc,
4302 Scope *S, CXXScopeSpec &SS,
4303 ParsedType ObjectType,
4304 bool EnteringContext);
4306 ParsedType getDestructorType(const DeclSpec& DS, ParsedType ObjectType);
4308 // Checks that reinterpret casts don't have undefined behavior.
4309 void CheckCompatibleReinterpretCast(QualType SrcType, QualType DestType,
4310 bool IsDereference, SourceRange Range);
4312 /// ActOnCXXNamedCast - Parse {dynamic,static,reinterpret,const}_cast's.
4313 ExprResult ActOnCXXNamedCast(SourceLocation OpLoc,
4314 tok::TokenKind Kind,
4315 SourceLocation LAngleBracketLoc,
4317 SourceLocation RAngleBracketLoc,
4318 SourceLocation LParenLoc,
4320 SourceLocation RParenLoc);
4322 ExprResult BuildCXXNamedCast(SourceLocation OpLoc,
4323 tok::TokenKind Kind,
4326 SourceRange AngleBrackets,
4327 SourceRange Parens);
4329 ExprResult BuildCXXTypeId(QualType TypeInfoType,
4330 SourceLocation TypeidLoc,
4331 TypeSourceInfo *Operand,
4332 SourceLocation RParenLoc);
4333 ExprResult BuildCXXTypeId(QualType TypeInfoType,
4334 SourceLocation TypeidLoc,
4336 SourceLocation RParenLoc);
4338 /// ActOnCXXTypeid - Parse typeid( something ).
4339 ExprResult ActOnCXXTypeid(SourceLocation OpLoc,
4340 SourceLocation LParenLoc, bool isType,
4342 SourceLocation RParenLoc);
4344 ExprResult BuildCXXUuidof(QualType TypeInfoType,
4345 SourceLocation TypeidLoc,
4346 TypeSourceInfo *Operand,
4347 SourceLocation RParenLoc);
4348 ExprResult BuildCXXUuidof(QualType TypeInfoType,
4349 SourceLocation TypeidLoc,
4351 SourceLocation RParenLoc);
4353 /// ActOnCXXUuidof - Parse __uuidof( something ).
4354 ExprResult ActOnCXXUuidof(SourceLocation OpLoc,
4355 SourceLocation LParenLoc, bool isType,
4357 SourceLocation RParenLoc);
4359 /// \brief Handle a C++1z fold-expression: ( expr op ... op expr ).
4360 ExprResult ActOnCXXFoldExpr(SourceLocation LParenLoc, Expr *LHS,
4361 tok::TokenKind Operator,
4362 SourceLocation EllipsisLoc, Expr *RHS,
4363 SourceLocation RParenLoc);
4364 ExprResult BuildCXXFoldExpr(SourceLocation LParenLoc, Expr *LHS,
4365 BinaryOperatorKind Operator,
4366 SourceLocation EllipsisLoc, Expr *RHS,
4367 SourceLocation RParenLoc);
4368 ExprResult BuildEmptyCXXFoldExpr(SourceLocation EllipsisLoc,
4369 BinaryOperatorKind Operator);
4371 //// ActOnCXXThis - Parse 'this' pointer.
4372 ExprResult ActOnCXXThis(SourceLocation loc);
4374 /// \brief Try to retrieve the type of the 'this' pointer.
4376 /// \returns The type of 'this', if possible. Otherwise, returns a NULL type.
4377 QualType getCurrentThisType();
4379 /// \brief When non-NULL, the C++ 'this' expression is allowed despite the
4380 /// current context not being a non-static member function. In such cases,
4381 /// this provides the type used for 'this'.
4382 QualType CXXThisTypeOverride;
4384 /// \brief RAII object used to temporarily allow the C++ 'this' expression
4385 /// to be used, with the given qualifiers on the current class type.
4386 class CXXThisScopeRAII {
4388 QualType OldCXXThisTypeOverride;
4392 /// \brief Introduce a new scope where 'this' may be allowed (when enabled),
4393 /// using the given declaration (which is either a class template or a
4394 /// class) along with the given qualifiers.
4395 /// along with the qualifiers placed on '*this'.
4396 CXXThisScopeRAII(Sema &S, Decl *ContextDecl, unsigned CXXThisTypeQuals,
4397 bool Enabled = true);
4399 ~CXXThisScopeRAII();
4402 /// \brief Make sure the value of 'this' is actually available in the current
4403 /// context, if it is a potentially evaluated context.
4405 /// \param Loc The location at which the capture of 'this' occurs.
4407 /// \param Explicit Whether 'this' is explicitly captured in a lambda
4410 /// \param FunctionScopeIndexToStopAt If non-null, it points to the index
4411 /// of the FunctionScopeInfo stack beyond which we do not attempt to capture.
4412 /// This is useful when enclosing lambdas must speculatively capture
4413 /// 'this' that may or may not be used in certain specializations of
4414 /// a nested generic lambda (depending on whether the name resolves to
4415 /// a non-static member function or a static function).
4416 /// \return returns 'true' if failed, 'false' if success.
4417 bool CheckCXXThisCapture(SourceLocation Loc, bool Explicit = false,
4418 bool BuildAndDiagnose = true,
4419 const unsigned *const FunctionScopeIndexToStopAt = nullptr);
4421 /// \brief Determine whether the given type is the type of *this that is used
4422 /// outside of the body of a member function for a type that is currently
4424 bool isThisOutsideMemberFunctionBody(QualType BaseType);
4426 /// ActOnCXXBoolLiteral - Parse {true,false} literals.
4427 ExprResult ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind);
4430 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
4431 ExprResult ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind);
4433 /// ActOnCXXNullPtrLiteral - Parse 'nullptr'.
4434 ExprResult ActOnCXXNullPtrLiteral(SourceLocation Loc);
4436 //// ActOnCXXThrow - Parse throw expressions.
4437 ExprResult ActOnCXXThrow(Scope *S, SourceLocation OpLoc, Expr *expr);
4438 ExprResult BuildCXXThrow(SourceLocation OpLoc, Expr *Ex,
4439 bool IsThrownVarInScope);
4440 ExprResult CheckCXXThrowOperand(SourceLocation ThrowLoc, Expr *E,
4441 bool IsThrownVarInScope);
4443 /// ActOnCXXTypeConstructExpr - Parse construction of a specified type.
4444 /// Can be interpreted either as function-style casting ("int(x)")
4445 /// or class type construction ("ClassType(x,y,z)")
4446 /// or creation of a value-initialized type ("int()").
4447 ExprResult ActOnCXXTypeConstructExpr(ParsedType TypeRep,
4448 SourceLocation LParenLoc,
4450 SourceLocation RParenLoc);
4452 ExprResult BuildCXXTypeConstructExpr(TypeSourceInfo *Type,
4453 SourceLocation LParenLoc,
4455 SourceLocation RParenLoc);
4457 /// ActOnCXXNew - Parsed a C++ 'new' expression.
4458 ExprResult ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
4459 SourceLocation PlacementLParen,
4460 MultiExprArg PlacementArgs,
4461 SourceLocation PlacementRParen,
4462 SourceRange TypeIdParens, Declarator &D,
4464 ExprResult BuildCXXNew(SourceRange Range, bool UseGlobal,
4465 SourceLocation PlacementLParen,
4466 MultiExprArg PlacementArgs,
4467 SourceLocation PlacementRParen,
4468 SourceRange TypeIdParens,
4470 TypeSourceInfo *AllocTypeInfo,
4472 SourceRange DirectInitRange,
4474 bool TypeMayContainAuto = true);
4476 bool CheckAllocatedType(QualType AllocType, SourceLocation Loc,
4478 bool FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,
4479 bool UseGlobal, QualType AllocType, bool IsArray,
4480 MultiExprArg PlaceArgs,
4481 FunctionDecl *&OperatorNew,
4482 FunctionDecl *&OperatorDelete);
4483 bool FindAllocationOverload(SourceLocation StartLoc, SourceRange Range,
4484 DeclarationName Name, MultiExprArg Args,
4486 bool AllowMissing, FunctionDecl *&Operator,
4487 bool Diagnose = true);
4488 void DeclareGlobalNewDelete();
4489 void DeclareGlobalAllocationFunction(DeclarationName Name, QualType Return,
4491 QualType Param2 = QualType(),
4492 bool addMallocAttr = false);
4494 bool FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD,
4495 DeclarationName Name, FunctionDecl* &Operator,
4496 bool Diagnose = true);
4497 FunctionDecl *FindUsualDeallocationFunction(SourceLocation StartLoc,
4498 bool CanProvideSize,
4499 DeclarationName Name);
4501 /// ActOnCXXDelete - Parsed a C++ 'delete' expression
4502 ExprResult ActOnCXXDelete(SourceLocation StartLoc,
4503 bool UseGlobal, bool ArrayForm,
4506 DeclResult ActOnCXXConditionDeclaration(Scope *S, Declarator &D);
4507 ExprResult CheckConditionVariable(VarDecl *ConditionVar,
4508 SourceLocation StmtLoc,
4509 bool ConvertToBoolean);
4511 ExprResult ActOnNoexceptExpr(SourceLocation KeyLoc, SourceLocation LParen,
4512 Expr *Operand, SourceLocation RParen);
4513 ExprResult BuildCXXNoexceptExpr(SourceLocation KeyLoc, Expr *Operand,
4514 SourceLocation RParen);
4516 /// \brief Parsed one of the type trait support pseudo-functions.
4517 ExprResult ActOnTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
4518 ArrayRef<ParsedType> Args,
4519 SourceLocation RParenLoc);
4520 ExprResult BuildTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
4521 ArrayRef<TypeSourceInfo *> Args,
4522 SourceLocation RParenLoc);
4524 /// ActOnArrayTypeTrait - Parsed one of the bianry type trait support
4525 /// pseudo-functions.
4526 ExprResult ActOnArrayTypeTrait(ArrayTypeTrait ATT,
4527 SourceLocation KWLoc,
4530 SourceLocation RParen);
4532 ExprResult BuildArrayTypeTrait(ArrayTypeTrait ATT,
4533 SourceLocation KWLoc,
4534 TypeSourceInfo *TSInfo,
4536 SourceLocation RParen);
4538 /// ActOnExpressionTrait - Parsed one of the unary type trait support
4539 /// pseudo-functions.
4540 ExprResult ActOnExpressionTrait(ExpressionTrait OET,
4541 SourceLocation KWLoc,
4543 SourceLocation RParen);
4545 ExprResult BuildExpressionTrait(ExpressionTrait OET,
4546 SourceLocation KWLoc,
4548 SourceLocation RParen);
4550 ExprResult ActOnStartCXXMemberReference(Scope *S,
4552 SourceLocation OpLoc,
4553 tok::TokenKind OpKind,
4554 ParsedType &ObjectType,
4555 bool &MayBePseudoDestructor);
4557 ExprResult DiagnoseDtorReference(SourceLocation NameLoc, Expr *MemExpr);
4559 ExprResult BuildPseudoDestructorExpr(Expr *Base,
4560 SourceLocation OpLoc,
4561 tok::TokenKind OpKind,
4562 const CXXScopeSpec &SS,
4563 TypeSourceInfo *ScopeType,
4564 SourceLocation CCLoc,
4565 SourceLocation TildeLoc,
4566 PseudoDestructorTypeStorage DestroyedType,
4567 bool HasTrailingLParen);
4569 ExprResult ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
4570 SourceLocation OpLoc,
4571 tok::TokenKind OpKind,
4573 UnqualifiedId &FirstTypeName,
4574 SourceLocation CCLoc,
4575 SourceLocation TildeLoc,
4576 UnqualifiedId &SecondTypeName,
4577 bool HasTrailingLParen);
4579 ExprResult ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
4580 SourceLocation OpLoc,
4581 tok::TokenKind OpKind,
4582 SourceLocation TildeLoc,
4584 bool HasTrailingLParen);
4586 /// MaybeCreateExprWithCleanups - If the current full-expression
4587 /// requires any cleanups, surround it with a ExprWithCleanups node.
4588 /// Otherwise, just returns the passed-in expression.
4589 Expr *MaybeCreateExprWithCleanups(Expr *SubExpr);
4590 Stmt *MaybeCreateStmtWithCleanups(Stmt *SubStmt);
4591 ExprResult MaybeCreateExprWithCleanups(ExprResult SubExpr);
4593 ExprResult ActOnFinishFullExpr(Expr *Expr) {
4594 return ActOnFinishFullExpr(Expr, Expr ? Expr->getExprLoc()
4595 : SourceLocation());
4597 ExprResult ActOnFinishFullExpr(Expr *Expr, SourceLocation CC,
4598 bool DiscardedValue = false,
4599 bool IsConstexpr = false,
4600 bool IsLambdaInitCaptureInitializer = false);
4601 StmtResult ActOnFinishFullStmt(Stmt *Stmt);
4603 // Marks SS invalid if it represents an incomplete type.
4604 bool RequireCompleteDeclContext(CXXScopeSpec &SS, DeclContext *DC);
4606 DeclContext *computeDeclContext(QualType T);
4607 DeclContext *computeDeclContext(const CXXScopeSpec &SS,
4608 bool EnteringContext = false);
4609 bool isDependentScopeSpecifier(const CXXScopeSpec &SS);
4610 CXXRecordDecl *getCurrentInstantiationOf(NestedNameSpecifier *NNS);
4612 /// \brief The parser has parsed a global nested-name-specifier '::'.
4614 /// \param CCLoc The location of the '::'.
4616 /// \param SS The nested-name-specifier, which will be updated in-place
4617 /// to reflect the parsed nested-name-specifier.
4619 /// \returns true if an error occurred, false otherwise.
4620 bool ActOnCXXGlobalScopeSpecifier(SourceLocation CCLoc, CXXScopeSpec &SS);
4622 /// \brief The parser has parsed a '__super' nested-name-specifier.
4624 /// \param SuperLoc The location of the '__super' keyword.
4626 /// \param ColonColonLoc The location of the '::'.
4628 /// \param SS The nested-name-specifier, which will be updated in-place
4629 /// to reflect the parsed nested-name-specifier.
4631 /// \returns true if an error occurred, false otherwise.
4632 bool ActOnSuperScopeSpecifier(SourceLocation SuperLoc,
4633 SourceLocation ColonColonLoc, CXXScopeSpec &SS);
4635 bool isAcceptableNestedNameSpecifier(const NamedDecl *SD);
4636 NamedDecl *FindFirstQualifierInScope(Scope *S, NestedNameSpecifier *NNS);
4638 bool isNonTypeNestedNameSpecifier(Scope *S, CXXScopeSpec &SS,
4639 SourceLocation IdLoc,
4641 ParsedType ObjectType);
4643 bool BuildCXXNestedNameSpecifier(Scope *S,
4644 IdentifierInfo &Identifier,
4645 SourceLocation IdentifierLoc,
4646 SourceLocation CCLoc,
4647 QualType ObjectType,
4648 bool EnteringContext,
4650 NamedDecl *ScopeLookupResult,
4651 bool ErrorRecoveryLookup,
4652 bool *IsCorrectedToColon = nullptr);
4654 /// \brief The parser has parsed a nested-name-specifier 'identifier::'.
4656 /// \param S The scope in which this nested-name-specifier occurs.
4658 /// \param Identifier The identifier preceding the '::'.
4660 /// \param IdentifierLoc The location of the identifier.
4662 /// \param CCLoc The location of the '::'.
4664 /// \param ObjectType The type of the object, if we're parsing
4665 /// nested-name-specifier in a member access expression.
4667 /// \param EnteringContext Whether we're entering the context nominated by
4668 /// this nested-name-specifier.
4670 /// \param SS The nested-name-specifier, which is both an input
4671 /// parameter (the nested-name-specifier before this type) and an
4672 /// output parameter (containing the full nested-name-specifier,
4673 /// including this new type).
4675 /// \param ErrorRecoveryLookup If true, then this method is called to improve
4676 /// error recovery. In this case do not emit error message.
4678 /// \param IsCorrectedToColon If not null, suggestions to replace '::' -> ':'
4679 /// are allowed. The bool value pointed by this parameter is set to 'true'
4680 /// if the identifier is treated as if it was followed by ':', not '::'.
4682 /// \returns true if an error occurred, false otherwise.
4683 bool ActOnCXXNestedNameSpecifier(Scope *S,
4684 IdentifierInfo &Identifier,
4685 SourceLocation IdentifierLoc,
4686 SourceLocation CCLoc,
4687 ParsedType ObjectType,
4688 bool EnteringContext,
4690 bool ErrorRecoveryLookup = false,
4691 bool *IsCorrectedToColon = nullptr);
4693 ExprResult ActOnDecltypeExpression(Expr *E);
4695 bool ActOnCXXNestedNameSpecifierDecltype(CXXScopeSpec &SS,
4697 SourceLocation ColonColonLoc);
4699 bool IsInvalidUnlessNestedName(Scope *S, CXXScopeSpec &SS,
4700 IdentifierInfo &Identifier,
4701 SourceLocation IdentifierLoc,
4702 SourceLocation ColonLoc,
4703 ParsedType ObjectType,
4704 bool EnteringContext);
4706 /// \brief The parser has parsed a nested-name-specifier
4707 /// 'template[opt] template-name < template-args >::'.
4709 /// \param S The scope in which this nested-name-specifier occurs.
4711 /// \param SS The nested-name-specifier, which is both an input
4712 /// parameter (the nested-name-specifier before this type) and an
4713 /// output parameter (containing the full nested-name-specifier,
4714 /// including this new type).
4716 /// \param TemplateKWLoc the location of the 'template' keyword, if any.
4717 /// \param TemplateName the template name.
4718 /// \param TemplateNameLoc The location of the template name.
4719 /// \param LAngleLoc The location of the opening angle bracket ('<').
4720 /// \param TemplateArgs The template arguments.
4721 /// \param RAngleLoc The location of the closing angle bracket ('>').
4722 /// \param CCLoc The location of the '::'.
4724 /// \param EnteringContext Whether we're entering the context of the
4725 /// nested-name-specifier.
4728 /// \returns true if an error occurred, false otherwise.
4729 bool ActOnCXXNestedNameSpecifier(Scope *S,
4731 SourceLocation TemplateKWLoc,
4732 TemplateTy TemplateName,
4733 SourceLocation TemplateNameLoc,
4734 SourceLocation LAngleLoc,
4735 ASTTemplateArgsPtr TemplateArgs,
4736 SourceLocation RAngleLoc,
4737 SourceLocation CCLoc,
4738 bool EnteringContext);
4740 /// \brief Given a C++ nested-name-specifier, produce an annotation value
4741 /// that the parser can use later to reconstruct the given
4742 /// nested-name-specifier.
4744 /// \param SS A nested-name-specifier.
4746 /// \returns A pointer containing all of the information in the
4747 /// nested-name-specifier \p SS.
4748 void *SaveNestedNameSpecifierAnnotation(CXXScopeSpec &SS);
4750 /// \brief Given an annotation pointer for a nested-name-specifier, restore
4751 /// the nested-name-specifier structure.
4753 /// \param Annotation The annotation pointer, produced by
4754 /// \c SaveNestedNameSpecifierAnnotation().
4756 /// \param AnnotationRange The source range corresponding to the annotation.
4758 /// \param SS The nested-name-specifier that will be updated with the contents
4759 /// of the annotation pointer.
4760 void RestoreNestedNameSpecifierAnnotation(void *Annotation,
4761 SourceRange AnnotationRange,
4764 bool ShouldEnterDeclaratorScope(Scope *S, const CXXScopeSpec &SS);
4766 /// ActOnCXXEnterDeclaratorScope - Called when a C++ scope specifier (global
4767 /// scope or nested-name-specifier) is parsed, part of a declarator-id.
4768 /// After this method is called, according to [C++ 3.4.3p3], names should be
4769 /// looked up in the declarator-id's scope, until the declarator is parsed and
4770 /// ActOnCXXExitDeclaratorScope is called.
4771 /// The 'SS' should be a non-empty valid CXXScopeSpec.
4772 bool ActOnCXXEnterDeclaratorScope(Scope *S, CXXScopeSpec &SS);
4774 /// ActOnCXXExitDeclaratorScope - Called when a declarator that previously
4775 /// invoked ActOnCXXEnterDeclaratorScope(), is finished. 'SS' is the same
4776 /// CXXScopeSpec that was passed to ActOnCXXEnterDeclaratorScope as well.
4777 /// Used to indicate that names should revert to being looked up in the
4779 void ActOnCXXExitDeclaratorScope(Scope *S, const CXXScopeSpec &SS);
4781 /// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse an
4782 /// initializer for the declaration 'Dcl'.
4783 /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
4784 /// static data member of class X, names should be looked up in the scope of
4786 void ActOnCXXEnterDeclInitializer(Scope *S, Decl *Dcl);
4788 /// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
4789 /// initializer for the declaration 'Dcl'.
4790 void ActOnCXXExitDeclInitializer(Scope *S, Decl *Dcl);
4792 /// \brief Create a new lambda closure type.
4793 CXXRecordDecl *createLambdaClosureType(SourceRange IntroducerRange,
4794 TypeSourceInfo *Info,
4795 bool KnownDependent,
4796 LambdaCaptureDefault CaptureDefault);
4798 /// \brief Start the definition of a lambda expression.
4799 CXXMethodDecl *startLambdaDefinition(CXXRecordDecl *Class,
4800 SourceRange IntroducerRange,
4801 TypeSourceInfo *MethodType,
4802 SourceLocation EndLoc,
4803 ArrayRef<ParmVarDecl *> Params);
4805 /// \brief Endow the lambda scope info with the relevant properties.
4806 void buildLambdaScope(sema::LambdaScopeInfo *LSI,
4807 CXXMethodDecl *CallOperator,
4808 SourceRange IntroducerRange,
4809 LambdaCaptureDefault CaptureDefault,
4810 SourceLocation CaptureDefaultLoc,
4811 bool ExplicitParams,
4812 bool ExplicitResultType,
4815 /// \brief Perform initialization analysis of the init-capture and perform
4816 /// any implicit conversions such as an lvalue-to-rvalue conversion if
4817 /// not being used to initialize a reference.
4818 QualType performLambdaInitCaptureInitialization(SourceLocation Loc,
4819 bool ByRef, IdentifierInfo *Id, Expr *&Init);
4820 /// \brief Create a dummy variable within the declcontext of the lambda's
4821 /// call operator, for name lookup purposes for a lambda init capture.
4823 /// CodeGen handles emission of lambda captures, ignoring these dummy
4824 /// variables appropriately.
4825 VarDecl *createLambdaInitCaptureVarDecl(SourceLocation Loc,
4826 QualType InitCaptureType, IdentifierInfo *Id, Expr *Init);
4828 /// \brief Build the implicit field for an init-capture.
4829 FieldDecl *buildInitCaptureField(sema::LambdaScopeInfo *LSI, VarDecl *Var);
4831 /// \brief Note that we have finished the explicit captures for the
4833 void finishLambdaExplicitCaptures(sema::LambdaScopeInfo *LSI);
4835 /// \brief Introduce the lambda parameters into scope.
4836 void addLambdaParameters(CXXMethodDecl *CallOperator, Scope *CurScope);
4838 /// \brief Deduce a block or lambda's return type based on the return
4839 /// statements present in the body.
4840 void deduceClosureReturnType(sema::CapturingScopeInfo &CSI);
4842 /// ActOnStartOfLambdaDefinition - This is called just before we start
4843 /// parsing the body of a lambda; it analyzes the explicit captures and
4844 /// arguments, and sets up various data-structures for the body of the
4846 void ActOnStartOfLambdaDefinition(LambdaIntroducer &Intro,
4847 Declarator &ParamInfo, Scope *CurScope);
4849 /// ActOnLambdaError - If there is an error parsing a lambda, this callback
4850 /// is invoked to pop the information about the lambda.
4851 void ActOnLambdaError(SourceLocation StartLoc, Scope *CurScope,
4852 bool IsInstantiation = false);
4854 /// ActOnLambdaExpr - This is called when the body of a lambda expression
4855 /// was successfully completed.
4856 ExprResult ActOnLambdaExpr(SourceLocation StartLoc, Stmt *Body,
4858 bool IsInstantiation = false);
4860 /// \brief Define the "body" of the conversion from a lambda object to a
4861 /// function pointer.
4863 /// This routine doesn't actually define a sensible body; rather, it fills
4864 /// in the initialization expression needed to copy the lambda object into
4865 /// the block, and IR generation actually generates the real body of the
4866 /// block pointer conversion.
4867 void DefineImplicitLambdaToFunctionPointerConversion(
4868 SourceLocation CurrentLoc, CXXConversionDecl *Conv);
4870 /// \brief Define the "body" of the conversion from a lambda object to a
4873 /// This routine doesn't actually define a sensible body; rather, it fills
4874 /// in the initialization expression needed to copy the lambda object into
4875 /// the block, and IR generation actually generates the real body of the
4876 /// block pointer conversion.
4877 void DefineImplicitLambdaToBlockPointerConversion(SourceLocation CurrentLoc,
4878 CXXConversionDecl *Conv);
4880 ExprResult BuildBlockForLambdaConversion(SourceLocation CurrentLocation,
4881 SourceLocation ConvLocation,
4882 CXXConversionDecl *Conv,
4885 // ParseObjCStringLiteral - Parse Objective-C string literals.
4886 ExprResult ParseObjCStringLiteral(SourceLocation *AtLocs,
4888 unsigned NumStrings);
4890 ExprResult BuildObjCStringLiteral(SourceLocation AtLoc, StringLiteral *S);
4892 /// BuildObjCNumericLiteral - builds an ObjCBoxedExpr AST node for the
4893 /// numeric literal expression. Type of the expression will be "NSNumber *"
4894 /// or "id" if NSNumber is unavailable.
4895 ExprResult BuildObjCNumericLiteral(SourceLocation AtLoc, Expr *Number);
4896 ExprResult ActOnObjCBoolLiteral(SourceLocation AtLoc, SourceLocation ValueLoc,
4898 ExprResult BuildObjCArrayLiteral(SourceRange SR, MultiExprArg Elements);
4900 /// BuildObjCBoxedExpr - builds an ObjCBoxedExpr AST node for the
4901 /// '@' prefixed parenthesized expression. The type of the expression will
4902 /// either be "NSNumber *" or "NSString *" depending on the type of
4903 /// ValueType, which is allowed to be a built-in numeric type or
4904 /// "char *" or "const char *".
4905 ExprResult BuildObjCBoxedExpr(SourceRange SR, Expr *ValueExpr);
4907 ExprResult BuildObjCSubscriptExpression(SourceLocation RB, Expr *BaseExpr,
4909 ObjCMethodDecl *getterMethod,
4910 ObjCMethodDecl *setterMethod);
4912 ExprResult BuildObjCDictionaryLiteral(SourceRange SR,
4913 ObjCDictionaryElement *Elements,
4914 unsigned NumElements);
4916 ExprResult BuildObjCEncodeExpression(SourceLocation AtLoc,
4917 TypeSourceInfo *EncodedTypeInfo,
4918 SourceLocation RParenLoc);
4919 ExprResult BuildCXXMemberCallExpr(Expr *Exp, NamedDecl *FoundDecl,
4920 CXXConversionDecl *Method,
4921 bool HadMultipleCandidates);
4923 ExprResult ParseObjCEncodeExpression(SourceLocation AtLoc,
4924 SourceLocation EncodeLoc,
4925 SourceLocation LParenLoc,
4927 SourceLocation RParenLoc);
4929 /// ParseObjCSelectorExpression - Build selector expression for \@selector
4930 ExprResult ParseObjCSelectorExpression(Selector Sel,
4931 SourceLocation AtLoc,
4932 SourceLocation SelLoc,
4933 SourceLocation LParenLoc,
4934 SourceLocation RParenLoc,
4935 bool WarnMultipleSelectors);
4937 /// ParseObjCProtocolExpression - Build protocol expression for \@protocol
4938 ExprResult ParseObjCProtocolExpression(IdentifierInfo * ProtocolName,
4939 SourceLocation AtLoc,
4940 SourceLocation ProtoLoc,
4941 SourceLocation LParenLoc,
4942 SourceLocation ProtoIdLoc,
4943 SourceLocation RParenLoc);
4945 //===--------------------------------------------------------------------===//
4948 Decl *ActOnStartLinkageSpecification(Scope *S,
4949 SourceLocation ExternLoc,
4951 SourceLocation LBraceLoc);
4952 Decl *ActOnFinishLinkageSpecification(Scope *S,
4954 SourceLocation RBraceLoc);
4957 //===--------------------------------------------------------------------===//
4960 bool isCurrentClassName(const IdentifierInfo &II, Scope *S,
4961 const CXXScopeSpec *SS = nullptr);
4962 bool isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS);
4964 bool ActOnAccessSpecifier(AccessSpecifier Access,
4965 SourceLocation ASLoc,
4966 SourceLocation ColonLoc,
4967 AttributeList *Attrs = nullptr);
4969 NamedDecl *ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS,
4971 MultiTemplateParamsArg TemplateParameterLists,
4972 Expr *BitfieldWidth, const VirtSpecifiers &VS,
4973 InClassInitStyle InitStyle);
4975 void ActOnStartCXXInClassMemberInitializer();
4976 void ActOnFinishCXXInClassMemberInitializer(Decl *VarDecl,
4977 SourceLocation EqualLoc,
4980 MemInitResult ActOnMemInitializer(Decl *ConstructorD,
4983 IdentifierInfo *MemberOrBase,
4984 ParsedType TemplateTypeTy,
4986 SourceLocation IdLoc,
4987 SourceLocation LParenLoc,
4988 ArrayRef<Expr *> Args,
4989 SourceLocation RParenLoc,
4990 SourceLocation EllipsisLoc);
4992 MemInitResult ActOnMemInitializer(Decl *ConstructorD,
4995 IdentifierInfo *MemberOrBase,
4996 ParsedType TemplateTypeTy,
4998 SourceLocation IdLoc,
5000 SourceLocation EllipsisLoc);
5002 MemInitResult BuildMemInitializer(Decl *ConstructorD,
5005 IdentifierInfo *MemberOrBase,
5006 ParsedType TemplateTypeTy,
5008 SourceLocation IdLoc,
5010 SourceLocation EllipsisLoc);
5012 MemInitResult BuildMemberInitializer(ValueDecl *Member,
5014 SourceLocation IdLoc);
5016 MemInitResult BuildBaseInitializer(QualType BaseType,
5017 TypeSourceInfo *BaseTInfo,
5019 CXXRecordDecl *ClassDecl,
5020 SourceLocation EllipsisLoc);
5022 MemInitResult BuildDelegatingInitializer(TypeSourceInfo *TInfo,
5024 CXXRecordDecl *ClassDecl);
5026 bool SetDelegatingInitializer(CXXConstructorDecl *Constructor,
5027 CXXCtorInitializer *Initializer);
5029 bool SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
5030 ArrayRef<CXXCtorInitializer *> Initializers = None);
5032 void SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation);
5035 /// MarkBaseAndMemberDestructorsReferenced - Given a record decl,
5036 /// mark all the non-trivial destructors of its members and bases as
5038 void MarkBaseAndMemberDestructorsReferenced(SourceLocation Loc,
5039 CXXRecordDecl *Record);
5041 /// \brief The list of classes whose vtables have been used within
5042 /// this translation unit, and the source locations at which the
5043 /// first use occurred.
5044 typedef std::pair<CXXRecordDecl*, SourceLocation> VTableUse;
5046 /// \brief The list of vtables that are required but have not yet been
5048 SmallVector<VTableUse, 16> VTableUses;
5050 /// \brief The set of classes whose vtables have been used within
5051 /// this translation unit, and a bit that will be true if the vtable is
5052 /// required to be emitted (otherwise, it should be emitted only if needed
5053 /// by code generation).
5054 llvm::DenseMap<CXXRecordDecl *, bool> VTablesUsed;
5056 /// \brief Load any externally-stored vtable uses.
5057 void LoadExternalVTableUses();
5059 typedef LazyVector<CXXRecordDecl *, ExternalSemaSource,
5060 &ExternalSemaSource::ReadDynamicClasses, 2, 2>
5063 /// \brief A list of all of the dynamic classes in this translation
5065 DynamicClassesType DynamicClasses;
5067 /// \brief Note that the vtable for the given class was used at the
5069 void MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
5070 bool DefinitionRequired = false);
5072 /// \brief Mark the exception specifications of all virtual member functions
5073 /// in the given class as needed.
5074 void MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
5075 const CXXRecordDecl *RD);
5077 /// MarkVirtualMembersReferenced - Will mark all members of the given
5078 /// CXXRecordDecl referenced.
5079 void MarkVirtualMembersReferenced(SourceLocation Loc,
5080 const CXXRecordDecl *RD);
5082 /// \brief Define all of the vtables that have been used in this
5083 /// translation unit and reference any virtual members used by those
5086 /// \returns true if any work was done, false otherwise.
5087 bool DefineUsedVTables();
5089 void AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl);
5091 void ActOnMemInitializers(Decl *ConstructorDecl,
5092 SourceLocation ColonLoc,
5093 ArrayRef<CXXCtorInitializer*> MemInits,
5096 void CheckCompletedCXXClass(CXXRecordDecl *Record);
5097 void ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
5099 SourceLocation LBrac,
5100 SourceLocation RBrac,
5101 AttributeList *AttrList);
5102 void ActOnFinishCXXMemberDecls();
5104 void ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param);
5105 unsigned ActOnReenterTemplateScope(Scope *S, Decl *Template);
5106 void ActOnStartDelayedMemberDeclarations(Scope *S, Decl *Record);
5107 void ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *Method);
5108 void ActOnDelayedCXXMethodParameter(Scope *S, Decl *Param);
5109 void ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *Record);
5110 void ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *Method);
5111 void ActOnFinishDelayedMemberInitializers(Decl *Record);
5112 void MarkAsLateParsedTemplate(FunctionDecl *FD, Decl *FnD,
5113 CachedTokens &Toks);
5114 void UnmarkAsLateParsedTemplate(FunctionDecl *FD);
5115 bool IsInsideALocalClassWithinATemplateFunction();
5117 Decl *ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
5119 Expr *AssertMessageExpr,
5120 SourceLocation RParenLoc);
5121 Decl *BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
5123 StringLiteral *AssertMessageExpr,
5124 SourceLocation RParenLoc,
5127 FriendDecl *CheckFriendTypeDecl(SourceLocation LocStart,
5128 SourceLocation FriendLoc,
5129 TypeSourceInfo *TSInfo);
5130 Decl *ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
5131 MultiTemplateParamsArg TemplateParams);
5132 NamedDecl *ActOnFriendFunctionDecl(Scope *S, Declarator &D,
5133 MultiTemplateParamsArg TemplateParams);
5135 QualType CheckConstructorDeclarator(Declarator &D, QualType R,
5137 void CheckConstructor(CXXConstructorDecl *Constructor);
5138 QualType CheckDestructorDeclarator(Declarator &D, QualType R,
5140 bool CheckDestructor(CXXDestructorDecl *Destructor);
5141 void CheckConversionDeclarator(Declarator &D, QualType &R,
5143 Decl *ActOnConversionDeclarator(CXXConversionDecl *Conversion);
5145 void CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD);
5146 void CheckExplicitlyDefaultedMemberExceptionSpec(CXXMethodDecl *MD,
5147 const FunctionProtoType *T);
5148 void CheckDelayedMemberExceptionSpecs();
5150 //===--------------------------------------------------------------------===//
5151 // C++ Derived Classes
5154 /// ActOnBaseSpecifier - Parsed a base specifier
5155 CXXBaseSpecifier *CheckBaseSpecifier(CXXRecordDecl *Class,
5156 SourceRange SpecifierRange,
5157 bool Virtual, AccessSpecifier Access,
5158 TypeSourceInfo *TInfo,
5159 SourceLocation EllipsisLoc);
5161 BaseResult ActOnBaseSpecifier(Decl *classdecl,
5162 SourceRange SpecifierRange,
5163 ParsedAttributes &Attrs,
5164 bool Virtual, AccessSpecifier Access,
5165 ParsedType basetype,
5166 SourceLocation BaseLoc,
5167 SourceLocation EllipsisLoc);
5169 bool AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
5171 void ActOnBaseSpecifiers(Decl *ClassDecl, CXXBaseSpecifier **Bases,
5174 bool IsDerivedFrom(QualType Derived, QualType Base);
5175 bool IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths);
5177 // FIXME: I don't like this name.
5178 void BuildBasePathArray(const CXXBasePaths &Paths, CXXCastPath &BasePath);
5180 bool BasePathInvolvesVirtualBase(const CXXCastPath &BasePath);
5182 bool CheckDerivedToBaseConversion(QualType Derived, QualType Base,
5183 SourceLocation Loc, SourceRange Range,
5184 CXXCastPath *BasePath = nullptr,
5185 bool IgnoreAccess = false);
5186 bool CheckDerivedToBaseConversion(QualType Derived, QualType Base,
5187 unsigned InaccessibleBaseID,
5188 unsigned AmbigiousBaseConvID,
5189 SourceLocation Loc, SourceRange Range,
5190 DeclarationName Name,
5191 CXXCastPath *BasePath);
5193 std::string getAmbiguousPathsDisplayString(CXXBasePaths &Paths);
5195 bool CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
5196 const CXXMethodDecl *Old);
5198 /// CheckOverridingFunctionReturnType - Checks whether the return types are
5199 /// covariant, according to C++ [class.virtual]p5.
5200 bool CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
5201 const CXXMethodDecl *Old);
5203 /// CheckOverridingFunctionExceptionSpec - Checks whether the exception
5204 /// spec is a subset of base spec.
5205 bool CheckOverridingFunctionExceptionSpec(const CXXMethodDecl *New,
5206 const CXXMethodDecl *Old);
5208 bool CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange);
5210 /// CheckOverrideControl - Check C++11 override control semantics.
5211 void CheckOverrideControl(NamedDecl *D);
5213 /// DiagnoseAbsenceOfOverrideControl - Diagnose if 'override' keyword was
5214 /// not used in the declaration of an overriding method.
5215 void DiagnoseAbsenceOfOverrideControl(NamedDecl *D);
5217 /// CheckForFunctionMarkedFinal - Checks whether a virtual member function
5218 /// overrides a virtual member function marked 'final', according to
5219 /// C++11 [class.virtual]p4.
5220 bool CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
5221 const CXXMethodDecl *Old);
5224 //===--------------------------------------------------------------------===//
5225 // C++ Access Control
5235 bool SetMemberAccessSpecifier(NamedDecl *MemberDecl,
5236 NamedDecl *PrevMemberDecl,
5237 AccessSpecifier LexicalAS);
5239 AccessResult CheckUnresolvedMemberAccess(UnresolvedMemberExpr *E,
5240 DeclAccessPair FoundDecl);
5241 AccessResult CheckUnresolvedLookupAccess(UnresolvedLookupExpr *E,
5242 DeclAccessPair FoundDecl);
5243 AccessResult CheckAllocationAccess(SourceLocation OperatorLoc,
5244 SourceRange PlacementRange,
5245 CXXRecordDecl *NamingClass,
5246 DeclAccessPair FoundDecl,
5247 bool Diagnose = true);
5248 AccessResult CheckConstructorAccess(SourceLocation Loc,
5249 CXXConstructorDecl *D,
5250 const InitializedEntity &Entity,
5251 AccessSpecifier Access,
5252 bool IsCopyBindingRefToTemp = false);
5253 AccessResult CheckConstructorAccess(SourceLocation Loc,
5254 CXXConstructorDecl *D,
5255 const InitializedEntity &Entity,
5256 AccessSpecifier Access,
5257 const PartialDiagnostic &PDiag);
5258 AccessResult CheckDestructorAccess(SourceLocation Loc,
5259 CXXDestructorDecl *Dtor,
5260 const PartialDiagnostic &PDiag,
5261 QualType objectType = QualType());
5262 AccessResult CheckFriendAccess(NamedDecl *D);
5263 AccessResult CheckMemberAccess(SourceLocation UseLoc,
5264 CXXRecordDecl *NamingClass,
5265 DeclAccessPair Found);
5266 AccessResult CheckMemberOperatorAccess(SourceLocation Loc,
5269 DeclAccessPair FoundDecl);
5270 AccessResult CheckAddressOfMemberAccess(Expr *OvlExpr,
5271 DeclAccessPair FoundDecl);
5272 AccessResult CheckBaseClassAccess(SourceLocation AccessLoc,
5273 QualType Base, QualType Derived,
5274 const CXXBasePath &Path,
5276 bool ForceCheck = false,
5277 bool ForceUnprivileged = false);
5278 void CheckLookupAccess(const LookupResult &R);
5279 bool IsSimplyAccessible(NamedDecl *decl, DeclContext *Ctx);
5280 bool isSpecialMemberAccessibleForDeletion(CXXMethodDecl *decl,
5281 AccessSpecifier access,
5282 QualType objectType);
5284 void HandleDependentAccessCheck(const DependentDiagnostic &DD,
5285 const MultiLevelTemplateArgumentList &TemplateArgs);
5286 void PerformDependentDiagnostics(const DeclContext *Pattern,
5287 const MultiLevelTemplateArgumentList &TemplateArgs);
5289 void HandleDelayedAccessCheck(sema::DelayedDiagnostic &DD, Decl *Ctx);
5291 /// \brief When true, access checking violations are treated as SFINAE
5292 /// failures rather than hard errors.
5293 bool AccessCheckingSFINAE;
5295 enum AbstractDiagSelID {
5299 AbstractVariableType,
5302 AbstractSynthesizedIvarType,
5306 bool RequireNonAbstractType(SourceLocation Loc, QualType T,
5307 TypeDiagnoser &Diagnoser);
5308 template<typename T1>
5309 bool RequireNonAbstractType(SourceLocation Loc, QualType T,
5312 BoundTypeDiagnoser1<T1> Diagnoser(DiagID, Arg1);
5313 return RequireNonAbstractType(Loc, T, Diagnoser);
5316 template<typename T1, typename T2>
5317 bool RequireNonAbstractType(SourceLocation Loc, QualType T,
5319 const T1 &Arg1, const T2 &Arg2) {
5320 BoundTypeDiagnoser2<T1, T2> Diagnoser(DiagID, Arg1, Arg2);
5321 return RequireNonAbstractType(Loc, T, Diagnoser);
5324 template<typename T1, typename T2, typename T3>
5325 bool RequireNonAbstractType(SourceLocation Loc, QualType T,
5327 const T1 &Arg1, const T2 &Arg2, const T3 &Arg3) {
5328 BoundTypeDiagnoser3<T1, T2, T3> Diagnoser(DiagID, Arg1, Arg2, Arg3);
5329 return RequireNonAbstractType(Loc, T, Diagnoser);
5332 void DiagnoseAbstractType(const CXXRecordDecl *RD);
5334 bool RequireNonAbstractType(SourceLocation Loc, QualType T, unsigned DiagID,
5335 AbstractDiagSelID SelID = AbstractNone);
5337 //===--------------------------------------------------------------------===//
5338 // C++ Overloaded Operators [C++ 13.5]
5341 bool CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl);
5343 bool CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl);
5345 //===--------------------------------------------------------------------===//
5346 // C++ Templates [C++ 14]
5348 void FilterAcceptableTemplateNames(LookupResult &R,
5349 bool AllowFunctionTemplates = true);
5350 bool hasAnyAcceptableTemplateNames(LookupResult &R,
5351 bool AllowFunctionTemplates = true);
5353 void LookupTemplateName(LookupResult &R, Scope *S, CXXScopeSpec &SS,
5354 QualType ObjectType, bool EnteringContext,
5355 bool &MemberOfUnknownSpecialization);
5357 TemplateNameKind isTemplateName(Scope *S,
5359 bool hasTemplateKeyword,
5360 UnqualifiedId &Name,
5361 ParsedType ObjectType,
5362 bool EnteringContext,
5363 TemplateTy &Template,
5364 bool &MemberOfUnknownSpecialization);
5366 bool DiagnoseUnknownTemplateName(const IdentifierInfo &II,
5367 SourceLocation IILoc,
5369 const CXXScopeSpec *SS,
5370 TemplateTy &SuggestedTemplate,
5371 TemplateNameKind &SuggestedKind);
5373 void DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl);
5374 TemplateDecl *AdjustDeclIfTemplate(Decl *&Decl);
5376 Decl *ActOnTypeParameter(Scope *S, bool Typename,
5377 SourceLocation EllipsisLoc,
5378 SourceLocation KeyLoc,
5379 IdentifierInfo *ParamName,
5380 SourceLocation ParamNameLoc,
5381 unsigned Depth, unsigned Position,
5382 SourceLocation EqualLoc,
5383 ParsedType DefaultArg);
5385 QualType CheckNonTypeTemplateParameterType(QualType T, SourceLocation Loc);
5386 Decl *ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
5389 SourceLocation EqualLoc,
5391 Decl *ActOnTemplateTemplateParameter(Scope *S,
5392 SourceLocation TmpLoc,
5393 TemplateParameterList *Params,
5394 SourceLocation EllipsisLoc,
5395 IdentifierInfo *ParamName,
5396 SourceLocation ParamNameLoc,
5399 SourceLocation EqualLoc,
5400 ParsedTemplateArgument DefaultArg);
5402 TemplateParameterList *
5403 ActOnTemplateParameterList(unsigned Depth,
5404 SourceLocation ExportLoc,
5405 SourceLocation TemplateLoc,
5406 SourceLocation LAngleLoc,
5407 Decl **Params, unsigned NumParams,
5408 SourceLocation RAngleLoc);
5410 /// \brief The context in which we are checking a template parameter list.
5411 enum TemplateParamListContext {
5414 TPC_FunctionTemplate,
5415 TPC_ClassTemplateMember,
5416 TPC_FriendClassTemplate,
5417 TPC_FriendFunctionTemplate,
5418 TPC_FriendFunctionTemplateDefinition,
5419 TPC_TypeAliasTemplate
5422 bool CheckTemplateParameterList(TemplateParameterList *NewParams,
5423 TemplateParameterList *OldParams,
5424 TemplateParamListContext TPC);
5425 TemplateParameterList *MatchTemplateParametersToScopeSpecifier(
5426 SourceLocation DeclStartLoc, SourceLocation DeclLoc,
5427 const CXXScopeSpec &SS, TemplateIdAnnotation *TemplateId,
5428 ArrayRef<TemplateParameterList *> ParamLists,
5429 bool IsFriend, bool &IsExplicitSpecialization, bool &Invalid);
5431 DeclResult CheckClassTemplate(Scope *S, unsigned TagSpec, TagUseKind TUK,
5432 SourceLocation KWLoc, CXXScopeSpec &SS,
5433 IdentifierInfo *Name, SourceLocation NameLoc,
5434 AttributeList *Attr,
5435 TemplateParameterList *TemplateParams,
5437 SourceLocation ModulePrivateLoc,
5438 SourceLocation FriendLoc,
5439 unsigned NumOuterTemplateParamLists,
5440 TemplateParameterList **OuterTemplateParamLists);
5442 void translateTemplateArguments(const ASTTemplateArgsPtr &In,
5443 TemplateArgumentListInfo &Out);
5445 void NoteAllFoundTemplates(TemplateName Name);
5447 QualType CheckTemplateIdType(TemplateName Template,
5448 SourceLocation TemplateLoc,
5449 TemplateArgumentListInfo &TemplateArgs);
5452 ActOnTemplateIdType(CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
5453 TemplateTy Template, SourceLocation TemplateLoc,
5454 SourceLocation LAngleLoc,
5455 ASTTemplateArgsPtr TemplateArgs,
5456 SourceLocation RAngleLoc,
5457 bool IsCtorOrDtorName = false);
5459 /// \brief Parsed an elaborated-type-specifier that refers to a template-id,
5460 /// such as \c class T::template apply<U>.
5461 TypeResult ActOnTagTemplateIdType(TagUseKind TUK,
5462 TypeSpecifierType TagSpec,
5463 SourceLocation TagLoc,
5465 SourceLocation TemplateKWLoc,
5466 TemplateTy TemplateD,
5467 SourceLocation TemplateLoc,
5468 SourceLocation LAngleLoc,
5469 ASTTemplateArgsPtr TemplateArgsIn,
5470 SourceLocation RAngleLoc);
5472 DeclResult ActOnVarTemplateSpecialization(
5473 Scope *S, Declarator &D, TypeSourceInfo *DI,
5474 SourceLocation TemplateKWLoc, TemplateParameterList *TemplateParams,
5475 StorageClass SC, bool IsPartialSpecialization);
5477 DeclResult CheckVarTemplateId(VarTemplateDecl *Template,
5478 SourceLocation TemplateLoc,
5479 SourceLocation TemplateNameLoc,
5480 const TemplateArgumentListInfo &TemplateArgs);
5482 ExprResult CheckVarTemplateId(const CXXScopeSpec &SS,
5483 const DeclarationNameInfo &NameInfo,
5484 VarTemplateDecl *Template,
5485 SourceLocation TemplateLoc,
5486 const TemplateArgumentListInfo *TemplateArgs);
5488 ExprResult BuildTemplateIdExpr(const CXXScopeSpec &SS,
5489 SourceLocation TemplateKWLoc,
5492 const TemplateArgumentListInfo *TemplateArgs);
5494 ExprResult BuildQualifiedTemplateIdExpr(CXXScopeSpec &SS,
5495 SourceLocation TemplateKWLoc,
5496 const DeclarationNameInfo &NameInfo,
5497 const TemplateArgumentListInfo *TemplateArgs);
5499 TemplateNameKind ActOnDependentTemplateName(Scope *S,
5501 SourceLocation TemplateKWLoc,
5502 UnqualifiedId &Name,
5503 ParsedType ObjectType,
5504 bool EnteringContext,
5505 TemplateTy &Template);
5508 ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec, TagUseKind TUK,
5509 SourceLocation KWLoc,
5510 SourceLocation ModulePrivateLoc,
5511 TemplateIdAnnotation &TemplateId,
5512 AttributeList *Attr,
5513 MultiTemplateParamsArg TemplateParameterLists);
5515 Decl *ActOnTemplateDeclarator(Scope *S,
5516 MultiTemplateParamsArg TemplateParameterLists,
5519 Decl *ActOnStartOfFunctionTemplateDef(Scope *FnBodyScope,
5520 MultiTemplateParamsArg TemplateParameterLists,
5524 CheckSpecializationInstantiationRedecl(SourceLocation NewLoc,
5525 TemplateSpecializationKind NewTSK,
5526 NamedDecl *PrevDecl,
5527 TemplateSpecializationKind PrevTSK,
5528 SourceLocation PrevPtOfInstantiation,
5531 bool CheckDependentFunctionTemplateSpecialization(FunctionDecl *FD,
5532 const TemplateArgumentListInfo &ExplicitTemplateArgs,
5533 LookupResult &Previous);
5535 bool CheckFunctionTemplateSpecialization(FunctionDecl *FD,
5536 TemplateArgumentListInfo *ExplicitTemplateArgs,
5537 LookupResult &Previous);
5538 bool CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous);
5541 ActOnExplicitInstantiation(Scope *S,
5542 SourceLocation ExternLoc,
5543 SourceLocation TemplateLoc,
5545 SourceLocation KWLoc,
5546 const CXXScopeSpec &SS,
5547 TemplateTy Template,
5548 SourceLocation TemplateNameLoc,
5549 SourceLocation LAngleLoc,
5550 ASTTemplateArgsPtr TemplateArgs,
5551 SourceLocation RAngleLoc,
5552 AttributeList *Attr);
5555 ActOnExplicitInstantiation(Scope *S,
5556 SourceLocation ExternLoc,
5557 SourceLocation TemplateLoc,
5559 SourceLocation KWLoc,
5561 IdentifierInfo *Name,
5562 SourceLocation NameLoc,
5563 AttributeList *Attr);
5565 DeclResult ActOnExplicitInstantiation(Scope *S,
5566 SourceLocation ExternLoc,
5567 SourceLocation TemplateLoc,
5571 SubstDefaultTemplateArgumentIfAvailable(TemplateDecl *Template,
5572 SourceLocation TemplateLoc,
5573 SourceLocation RAngleLoc,
5575 SmallVectorImpl<TemplateArgument>
5577 bool &HasDefaultArg);
5579 /// \brief Specifies the context in which a particular template
5580 /// argument is being checked.
5581 enum CheckTemplateArgumentKind {
5582 /// \brief The template argument was specified in the code or was
5583 /// instantiated with some deduced template arguments.
5586 /// \brief The template argument was deduced via template argument
5590 /// \brief The template argument was deduced from an array bound
5591 /// via template argument deduction.
5592 CTAK_DeducedFromArrayBound
5595 bool CheckTemplateArgument(NamedDecl *Param,
5596 TemplateArgumentLoc &Arg,
5597 NamedDecl *Template,
5598 SourceLocation TemplateLoc,
5599 SourceLocation RAngleLoc,
5600 unsigned ArgumentPackIndex,
5601 SmallVectorImpl<TemplateArgument> &Converted,
5602 CheckTemplateArgumentKind CTAK = CTAK_Specified);
5604 /// \brief Check that the given template arguments can be be provided to
5605 /// the given template, converting the arguments along the way.
5607 /// \param Template The template to which the template arguments are being
5610 /// \param TemplateLoc The location of the template name in the source.
5612 /// \param TemplateArgs The list of template arguments. If the template is
5613 /// a template template parameter, this function may extend the set of
5614 /// template arguments to also include substituted, defaulted template
5617 /// \param PartialTemplateArgs True if the list of template arguments is
5618 /// intentionally partial, e.g., because we're checking just the initial
5619 /// set of template arguments.
5621 /// \param Converted Will receive the converted, canonicalized template
5624 /// \returns true if an error occurred, false otherwise.
5625 bool CheckTemplateArgumentList(TemplateDecl *Template,
5626 SourceLocation TemplateLoc,
5627 TemplateArgumentListInfo &TemplateArgs,
5628 bool PartialTemplateArgs,
5629 SmallVectorImpl<TemplateArgument> &Converted);
5631 bool CheckTemplateTypeArgument(TemplateTypeParmDecl *Param,
5632 TemplateArgumentLoc &Arg,
5633 SmallVectorImpl<TemplateArgument> &Converted);
5635 bool CheckTemplateArgument(TemplateTypeParmDecl *Param,
5636 TypeSourceInfo *Arg);
5637 ExprResult CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
5638 QualType InstantiatedParamType, Expr *Arg,
5639 TemplateArgument &Converted,
5640 CheckTemplateArgumentKind CTAK = CTAK_Specified);
5641 bool CheckTemplateArgument(TemplateTemplateParmDecl *Param,
5642 TemplateArgumentLoc &Arg,
5643 unsigned ArgumentPackIndex);
5646 BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg,
5648 SourceLocation Loc);
5650 BuildExpressionFromIntegralTemplateArgument(const TemplateArgument &Arg,
5651 SourceLocation Loc);
5653 /// \brief Enumeration describing how template parameter lists are compared
5655 enum TemplateParameterListEqualKind {
5656 /// \brief We are matching the template parameter lists of two templates
5657 /// that might be redeclarations.
5660 /// template<typename T> struct X;
5661 /// template<typename T> struct X;
5665 /// \brief We are matching the template parameter lists of two template
5666 /// template parameters as part of matching the template parameter lists
5667 /// of two templates that might be redeclarations.
5670 /// template<template<int I> class TT> struct X;
5671 /// template<template<int Value> class Other> struct X;
5673 TPL_TemplateTemplateParmMatch,
5675 /// \brief We are matching the template parameter lists of a template
5676 /// template argument against the template parameter lists of a template
5677 /// template parameter.
5680 /// template<template<int Value> class Metafun> struct X;
5681 /// template<int Value> struct integer_c;
5682 /// X<integer_c> xic;
5684 TPL_TemplateTemplateArgumentMatch
5687 bool TemplateParameterListsAreEqual(TemplateParameterList *New,
5688 TemplateParameterList *Old,
5690 TemplateParameterListEqualKind Kind,
5691 SourceLocation TemplateArgLoc
5692 = SourceLocation());
5694 bool CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams);
5696 /// \brief Called when the parser has parsed a C++ typename
5697 /// specifier, e.g., "typename T::type".
5699 /// \param S The scope in which this typename type occurs.
5700 /// \param TypenameLoc the location of the 'typename' keyword
5701 /// \param SS the nested-name-specifier following the typename (e.g., 'T::').
5702 /// \param II the identifier we're retrieving (e.g., 'type' in the example).
5703 /// \param IdLoc the location of the identifier.
5705 ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
5706 const CXXScopeSpec &SS, const IdentifierInfo &II,
5707 SourceLocation IdLoc);
5709 /// \brief Called when the parser has parsed a C++ typename
5710 /// specifier that ends in a template-id, e.g.,
5711 /// "typename MetaFun::template apply<T1, T2>".
5713 /// \param S The scope in which this typename type occurs.
5714 /// \param TypenameLoc the location of the 'typename' keyword
5715 /// \param SS the nested-name-specifier following the typename (e.g., 'T::').
5716 /// \param TemplateLoc the location of the 'template' keyword, if any.
5717 /// \param TemplateName The template name.
5718 /// \param TemplateNameLoc The location of the template name.
5719 /// \param LAngleLoc The location of the opening angle bracket ('<').
5720 /// \param TemplateArgs The template arguments.
5721 /// \param RAngleLoc The location of the closing angle bracket ('>').
5723 ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
5724 const CXXScopeSpec &SS,
5725 SourceLocation TemplateLoc,
5726 TemplateTy TemplateName,
5727 SourceLocation TemplateNameLoc,
5728 SourceLocation LAngleLoc,
5729 ASTTemplateArgsPtr TemplateArgs,
5730 SourceLocation RAngleLoc);
5732 QualType CheckTypenameType(ElaboratedTypeKeyword Keyword,
5733 SourceLocation KeywordLoc,
5734 NestedNameSpecifierLoc QualifierLoc,
5735 const IdentifierInfo &II,
5736 SourceLocation IILoc);
5738 TypeSourceInfo *RebuildTypeInCurrentInstantiation(TypeSourceInfo *T,
5740 DeclarationName Name);
5741 bool RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS);
5743 ExprResult RebuildExprInCurrentInstantiation(Expr *E);
5744 bool RebuildTemplateParamsInCurrentInstantiation(
5745 TemplateParameterList *Params);
5748 getTemplateArgumentBindingsText(const TemplateParameterList *Params,
5749 const TemplateArgumentList &Args);
5752 getTemplateArgumentBindingsText(const TemplateParameterList *Params,
5753 const TemplateArgument *Args,
5756 //===--------------------------------------------------------------------===//
5757 // C++ Variadic Templates (C++0x [temp.variadic])
5758 //===--------------------------------------------------------------------===//
5760 /// Determine whether an unexpanded parameter pack might be permitted in this
5761 /// location. Useful for error recovery.
5762 bool isUnexpandedParameterPackPermitted();
5764 /// \brief The context in which an unexpanded parameter pack is
5765 /// being diagnosed.
5767 /// Note that the values of this enumeration line up with the first
5768 /// argument to the \c err_unexpanded_parameter_pack diagnostic.
5769 enum UnexpandedParameterPackContext {
5770 /// \brief An arbitrary expression.
5771 UPPC_Expression = 0,
5773 /// \brief The base type of a class type.
5776 /// \brief The type of an arbitrary declaration.
5777 UPPC_DeclarationType,
5779 /// \brief The type of a data member.
5780 UPPC_DataMemberType,
5782 /// \brief The size of a bit-field.
5785 /// \brief The expression in a static assertion.
5786 UPPC_StaticAssertExpression,
5788 /// \brief The fixed underlying type of an enumeration.
5789 UPPC_FixedUnderlyingType,
5791 /// \brief The enumerator value.
5792 UPPC_EnumeratorValue,
5794 /// \brief A using declaration.
5795 UPPC_UsingDeclaration,
5797 /// \brief A friend declaration.
5798 UPPC_FriendDeclaration,
5800 /// \brief A declaration qualifier.
5801 UPPC_DeclarationQualifier,
5803 /// \brief An initializer.
5806 /// \brief A default argument.
5807 UPPC_DefaultArgument,
5809 /// \brief The type of a non-type template parameter.
5810 UPPC_NonTypeTemplateParameterType,
5812 /// \brief The type of an exception.
5815 /// \brief Partial specialization.
5816 UPPC_PartialSpecialization,
5818 /// \brief Microsoft __if_exists.
5821 /// \brief Microsoft __if_not_exists.
5824 /// \brief Lambda expression.
5827 /// \brief Block expression,
5831 /// \brief Diagnose unexpanded parameter packs.
5833 /// \param Loc The location at which we should emit the diagnostic.
5835 /// \param UPPC The context in which we are diagnosing unexpanded
5836 /// parameter packs.
5838 /// \param Unexpanded the set of unexpanded parameter packs.
5840 /// \returns true if an error occurred, false otherwise.
5841 bool DiagnoseUnexpandedParameterPacks(SourceLocation Loc,
5842 UnexpandedParameterPackContext UPPC,
5843 ArrayRef<UnexpandedParameterPack> Unexpanded);
5845 /// \brief If the given type contains an unexpanded parameter pack,
5846 /// diagnose the error.
5848 /// \param Loc The source location where a diagnostc should be emitted.
5850 /// \param T The type that is being checked for unexpanded parameter
5853 /// \returns true if an error occurred, false otherwise.
5854 bool DiagnoseUnexpandedParameterPack(SourceLocation Loc, TypeSourceInfo *T,
5855 UnexpandedParameterPackContext UPPC);
5857 /// \brief If the given expression contains an unexpanded parameter
5858 /// pack, diagnose the error.
5860 /// \param E The expression that is being checked for unexpanded
5861 /// parameter packs.
5863 /// \returns true if an error occurred, false otherwise.
5864 bool DiagnoseUnexpandedParameterPack(Expr *E,
5865 UnexpandedParameterPackContext UPPC = UPPC_Expression);
5867 /// \brief If the given nested-name-specifier contains an unexpanded
5868 /// parameter pack, diagnose the error.
5870 /// \param SS The nested-name-specifier that is being checked for
5871 /// unexpanded parameter packs.
5873 /// \returns true if an error occurred, false otherwise.
5874 bool DiagnoseUnexpandedParameterPack(const CXXScopeSpec &SS,
5875 UnexpandedParameterPackContext UPPC);
5877 /// \brief If the given name contains an unexpanded parameter pack,
5878 /// diagnose the error.
5880 /// \param NameInfo The name (with source location information) that
5881 /// is being checked for unexpanded parameter packs.
5883 /// \returns true if an error occurred, false otherwise.
5884 bool DiagnoseUnexpandedParameterPack(const DeclarationNameInfo &NameInfo,
5885 UnexpandedParameterPackContext UPPC);
5887 /// \brief If the given template name contains an unexpanded parameter pack,
5888 /// diagnose the error.
5890 /// \param Loc The location of the template name.
5892 /// \param Template The template name that is being checked for unexpanded
5893 /// parameter packs.
5895 /// \returns true if an error occurred, false otherwise.
5896 bool DiagnoseUnexpandedParameterPack(SourceLocation Loc,
5897 TemplateName Template,
5898 UnexpandedParameterPackContext UPPC);
5900 /// \brief If the given template argument contains an unexpanded parameter
5901 /// pack, diagnose the error.
5903 /// \param Arg The template argument that is being checked for unexpanded
5904 /// parameter packs.
5906 /// \returns true if an error occurred, false otherwise.
5907 bool DiagnoseUnexpandedParameterPack(TemplateArgumentLoc Arg,
5908 UnexpandedParameterPackContext UPPC);
5910 /// \brief Collect the set of unexpanded parameter packs within the given
5911 /// template argument.
5913 /// \param Arg The template argument that will be traversed to find
5914 /// unexpanded parameter packs.
5915 void collectUnexpandedParameterPacks(TemplateArgument Arg,
5916 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
5918 /// \brief Collect the set of unexpanded parameter packs within the given
5919 /// template argument.
5921 /// \param Arg The template argument that will be traversed to find
5922 /// unexpanded parameter packs.
5923 void collectUnexpandedParameterPacks(TemplateArgumentLoc Arg,
5924 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
5926 /// \brief Collect the set of unexpanded parameter packs within the given
5929 /// \param T The type that will be traversed to find
5930 /// unexpanded parameter packs.
5931 void collectUnexpandedParameterPacks(QualType T,
5932 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
5934 /// \brief Collect the set of unexpanded parameter packs within the given
5937 /// \param TL The type that will be traversed to find
5938 /// unexpanded parameter packs.
5939 void collectUnexpandedParameterPacks(TypeLoc TL,
5940 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
5942 /// \brief Collect the set of unexpanded parameter packs within the given
5943 /// nested-name-specifier.
5945 /// \param SS The nested-name-specifier that will be traversed to find
5946 /// unexpanded parameter packs.
5947 void collectUnexpandedParameterPacks(CXXScopeSpec &SS,
5948 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
5950 /// \brief Collect the set of unexpanded parameter packs within the given
5953 /// \param NameInfo The name that will be traversed to find
5954 /// unexpanded parameter packs.
5955 void collectUnexpandedParameterPacks(const DeclarationNameInfo &NameInfo,
5956 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
5958 /// \brief Invoked when parsing a template argument followed by an
5959 /// ellipsis, which creates a pack expansion.
5961 /// \param Arg The template argument preceding the ellipsis, which
5962 /// may already be invalid.
5964 /// \param EllipsisLoc The location of the ellipsis.
5965 ParsedTemplateArgument ActOnPackExpansion(const ParsedTemplateArgument &Arg,
5966 SourceLocation EllipsisLoc);
5968 /// \brief Invoked when parsing a type followed by an ellipsis, which
5969 /// creates a pack expansion.
5971 /// \param Type The type preceding the ellipsis, which will become
5972 /// the pattern of the pack expansion.
5974 /// \param EllipsisLoc The location of the ellipsis.
5975 TypeResult ActOnPackExpansion(ParsedType Type, SourceLocation EllipsisLoc);
5977 /// \brief Construct a pack expansion type from the pattern of the pack
5979 TypeSourceInfo *CheckPackExpansion(TypeSourceInfo *Pattern,
5980 SourceLocation EllipsisLoc,
5981 Optional<unsigned> NumExpansions);
5983 /// \brief Construct a pack expansion type from the pattern of the pack
5985 QualType CheckPackExpansion(QualType Pattern,
5986 SourceRange PatternRange,
5987 SourceLocation EllipsisLoc,
5988 Optional<unsigned> NumExpansions);
5990 /// \brief Invoked when parsing an expression followed by an ellipsis, which
5991 /// creates a pack expansion.
5993 /// \param Pattern The expression preceding the ellipsis, which will become
5994 /// the pattern of the pack expansion.
5996 /// \param EllipsisLoc The location of the ellipsis.
5997 ExprResult ActOnPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc);
5999 /// \brief Invoked when parsing an expression followed by an ellipsis, which
6000 /// creates a pack expansion.
6002 /// \param Pattern The expression preceding the ellipsis, which will become
6003 /// the pattern of the pack expansion.
6005 /// \param EllipsisLoc The location of the ellipsis.
6006 ExprResult CheckPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc,
6007 Optional<unsigned> NumExpansions);
6009 /// \brief Determine whether we could expand a pack expansion with the
6010 /// given set of parameter packs into separate arguments by repeatedly
6011 /// transforming the pattern.
6013 /// \param EllipsisLoc The location of the ellipsis that identifies the
6016 /// \param PatternRange The source range that covers the entire pattern of
6017 /// the pack expansion.
6019 /// \param Unexpanded The set of unexpanded parameter packs within the
6022 /// \param ShouldExpand Will be set to \c true if the transformer should
6023 /// expand the corresponding pack expansions into separate arguments. When
6024 /// set, \c NumExpansions must also be set.
6026 /// \param RetainExpansion Whether the caller should add an unexpanded
6027 /// pack expansion after all of the expanded arguments. This is used
6028 /// when extending explicitly-specified template argument packs per
6029 /// C++0x [temp.arg.explicit]p9.
6031 /// \param NumExpansions The number of separate arguments that will be in
6032 /// the expanded form of the corresponding pack expansion. This is both an
6033 /// input and an output parameter, which can be set by the caller if the
6034 /// number of expansions is known a priori (e.g., due to a prior substitution)
6035 /// and will be set by the callee when the number of expansions is known.
6036 /// The callee must set this value when \c ShouldExpand is \c true; it may
6037 /// set this value in other cases.
6039 /// \returns true if an error occurred (e.g., because the parameter packs
6040 /// are to be instantiated with arguments of different lengths), false
6041 /// otherwise. If false, \c ShouldExpand (and possibly \c NumExpansions)
6043 bool CheckParameterPacksForExpansion(SourceLocation EllipsisLoc,
6044 SourceRange PatternRange,
6045 ArrayRef<UnexpandedParameterPack> Unexpanded,
6046 const MultiLevelTemplateArgumentList &TemplateArgs,
6048 bool &RetainExpansion,
6049 Optional<unsigned> &NumExpansions);
6051 /// \brief Determine the number of arguments in the given pack expansion
6054 /// This routine assumes that the number of arguments in the expansion is
6055 /// consistent across all of the unexpanded parameter packs in its pattern.
6057 /// Returns an empty Optional if the type can't be expanded.
6058 Optional<unsigned> getNumArgumentsInExpansion(QualType T,
6059 const MultiLevelTemplateArgumentList &TemplateArgs);
6061 /// \brief Determine whether the given declarator contains any unexpanded
6062 /// parameter packs.
6064 /// This routine is used by the parser to disambiguate function declarators
6065 /// with an ellipsis prior to the ')', e.g.,
6071 /// To determine whether we have an (unnamed) function parameter pack or
6072 /// a variadic function.
6074 /// \returns true if the declarator contains any unexpanded parameter packs,
6075 /// false otherwise.
6076 bool containsUnexpandedParameterPacks(Declarator &D);
6078 /// \brief Returns the pattern of the pack expansion for a template argument.
6080 /// \param OrigLoc The template argument to expand.
6082 /// \param Ellipsis Will be set to the location of the ellipsis.
6084 /// \param NumExpansions Will be set to the number of expansions that will
6085 /// be generated from this pack expansion, if known a priori.
6086 TemplateArgumentLoc getTemplateArgumentPackExpansionPattern(
6087 TemplateArgumentLoc OrigLoc,
6088 SourceLocation &Ellipsis,
6089 Optional<unsigned> &NumExpansions) const;
6091 //===--------------------------------------------------------------------===//
6092 // C++ Template Argument Deduction (C++ [temp.deduct])
6093 //===--------------------------------------------------------------------===//
6095 QualType adjustCCAndNoReturn(QualType ArgFunctionType, QualType FunctionType);
6097 /// \brief Describes the result of template argument deduction.
6099 /// The TemplateDeductionResult enumeration describes the result of
6100 /// template argument deduction, as returned from
6101 /// DeduceTemplateArguments(). The separate TemplateDeductionInfo
6102 /// structure provides additional information about the results of
6103 /// template argument deduction, e.g., the deduced template argument
6104 /// list (if successful) or the specific template parameters or
6105 /// deduced arguments that were involved in the failure.
6106 enum TemplateDeductionResult {
6107 /// \brief Template argument deduction was successful.
6109 /// \brief The declaration was invalid; do nothing.
6111 /// \brief Template argument deduction exceeded the maximum template
6112 /// instantiation depth (which has already been diagnosed).
6113 TDK_InstantiationDepth,
6114 /// \brief Template argument deduction did not deduce a value
6115 /// for every template parameter.
6117 /// \brief Template argument deduction produced inconsistent
6118 /// deduced values for the given template parameter.
6120 /// \brief Template argument deduction failed due to inconsistent
6121 /// cv-qualifiers on a template parameter type that would
6122 /// otherwise be deduced, e.g., we tried to deduce T in "const T"
6123 /// but were given a non-const "X".
6125 /// \brief Substitution of the deduced template argument values
6126 /// resulted in an error.
6127 TDK_SubstitutionFailure,
6128 /// \brief A non-depnedent component of the parameter did not match the
6129 /// corresponding component of the argument.
6130 TDK_NonDeducedMismatch,
6131 /// \brief When performing template argument deduction for a function
6132 /// template, there were too many call arguments.
6133 TDK_TooManyArguments,
6134 /// \brief When performing template argument deduction for a function
6135 /// template, there were too few call arguments.
6136 TDK_TooFewArguments,
6137 /// \brief The explicitly-specified template arguments were not valid
6138 /// template arguments for the given template.
6139 TDK_InvalidExplicitArguments,
6140 /// \brief The arguments included an overloaded function name that could
6141 /// not be resolved to a suitable function.
6142 TDK_FailedOverloadResolution,
6143 /// \brief Deduction failed; that's all we know.
6144 TDK_MiscellaneousDeductionFailure
6147 TemplateDeductionResult
6148 DeduceTemplateArguments(ClassTemplatePartialSpecializationDecl *Partial,
6149 const TemplateArgumentList &TemplateArgs,
6150 sema::TemplateDeductionInfo &Info);
6152 TemplateDeductionResult
6153 DeduceTemplateArguments(VarTemplatePartialSpecializationDecl *Partial,
6154 const TemplateArgumentList &TemplateArgs,
6155 sema::TemplateDeductionInfo &Info);
6157 TemplateDeductionResult SubstituteExplicitTemplateArguments(
6158 FunctionTemplateDecl *FunctionTemplate,
6159 TemplateArgumentListInfo &ExplicitTemplateArgs,
6160 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
6161 SmallVectorImpl<QualType> &ParamTypes, QualType *FunctionType,
6162 sema::TemplateDeductionInfo &Info);
6164 /// brief A function argument from which we performed template argument
6165 // deduction for a call.
6166 struct OriginalCallArg {
6167 OriginalCallArg(QualType OriginalParamType,
6169 QualType OriginalArgType)
6170 : OriginalParamType(OriginalParamType), ArgIdx(ArgIdx),
6171 OriginalArgType(OriginalArgType) { }
6173 QualType OriginalParamType;
6175 QualType OriginalArgType;
6178 TemplateDeductionResult
6179 FinishTemplateArgumentDeduction(FunctionTemplateDecl *FunctionTemplate,
6180 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
6181 unsigned NumExplicitlySpecified,
6182 FunctionDecl *&Specialization,
6183 sema::TemplateDeductionInfo &Info,
6184 SmallVectorImpl<OriginalCallArg> const *OriginalCallArgs = nullptr);
6186 TemplateDeductionResult
6187 DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
6188 TemplateArgumentListInfo *ExplicitTemplateArgs,
6189 ArrayRef<Expr *> Args,
6190 FunctionDecl *&Specialization,
6191 sema::TemplateDeductionInfo &Info);
6193 TemplateDeductionResult
6194 DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
6195 TemplateArgumentListInfo *ExplicitTemplateArgs,
6196 QualType ArgFunctionType,
6197 FunctionDecl *&Specialization,
6198 sema::TemplateDeductionInfo &Info,
6199 bool InOverloadResolution = false);
6201 TemplateDeductionResult
6202 DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
6204 CXXConversionDecl *&Specialization,
6205 sema::TemplateDeductionInfo &Info);
6207 TemplateDeductionResult
6208 DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
6209 TemplateArgumentListInfo *ExplicitTemplateArgs,
6210 FunctionDecl *&Specialization,
6211 sema::TemplateDeductionInfo &Info,
6212 bool InOverloadResolution = false);
6214 /// \brief Substitute Replacement for \p auto in \p TypeWithAuto
6215 QualType SubstAutoType(QualType TypeWithAuto, QualType Replacement);
6216 /// \brief Substitute Replacement for auto in TypeWithAuto
6217 TypeSourceInfo* SubstAutoTypeSourceInfo(TypeSourceInfo *TypeWithAuto,
6218 QualType Replacement);
6220 /// \brief Result type of DeduceAutoType.
6221 enum DeduceAutoResult {
6224 DAR_FailedAlreadyDiagnosed
6227 DeduceAutoResult DeduceAutoType(TypeSourceInfo *AutoType, Expr *&Initializer,
6229 DeduceAutoResult DeduceAutoType(TypeLoc AutoTypeLoc, Expr *&Initializer,
6231 void DiagnoseAutoDeductionFailure(VarDecl *VDecl, Expr *Init);
6232 bool DeduceReturnType(FunctionDecl *FD, SourceLocation Loc,
6233 bool Diagnose = true);
6235 TypeLoc getReturnTypeLoc(FunctionDecl *FD) const;
6237 bool DeduceFunctionTypeFromReturnExpr(FunctionDecl *FD,
6238 SourceLocation ReturnLoc,
6239 Expr *&RetExpr, AutoType *AT);
6241 FunctionTemplateDecl *getMoreSpecializedTemplate(FunctionTemplateDecl *FT1,
6242 FunctionTemplateDecl *FT2,
6244 TemplatePartialOrderingContext TPOC,
6245 unsigned NumCallArguments1,
6246 unsigned NumCallArguments2);
6247 UnresolvedSetIterator
6248 getMostSpecialized(UnresolvedSetIterator SBegin, UnresolvedSetIterator SEnd,
6249 TemplateSpecCandidateSet &FailedCandidates,
6251 const PartialDiagnostic &NoneDiag,
6252 const PartialDiagnostic &AmbigDiag,
6253 const PartialDiagnostic &CandidateDiag,
6254 bool Complain = true, QualType TargetType = QualType());
6256 ClassTemplatePartialSpecializationDecl *
6257 getMoreSpecializedPartialSpecialization(
6258 ClassTemplatePartialSpecializationDecl *PS1,
6259 ClassTemplatePartialSpecializationDecl *PS2,
6260 SourceLocation Loc);
6262 VarTemplatePartialSpecializationDecl *getMoreSpecializedPartialSpecialization(
6263 VarTemplatePartialSpecializationDecl *PS1,
6264 VarTemplatePartialSpecializationDecl *PS2, SourceLocation Loc);
6266 void MarkUsedTemplateParameters(const TemplateArgumentList &TemplateArgs,
6269 llvm::SmallBitVector &Used);
6270 void MarkDeducedTemplateParameters(
6271 const FunctionTemplateDecl *FunctionTemplate,
6272 llvm::SmallBitVector &Deduced) {
6273 return MarkDeducedTemplateParameters(Context, FunctionTemplate, Deduced);
6275 static void MarkDeducedTemplateParameters(ASTContext &Ctx,
6276 const FunctionTemplateDecl *FunctionTemplate,
6277 llvm::SmallBitVector &Deduced);
6279 //===--------------------------------------------------------------------===//
6280 // C++ Template Instantiation
6283 MultiLevelTemplateArgumentList
6284 getTemplateInstantiationArgs(NamedDecl *D,
6285 const TemplateArgumentList *Innermost = nullptr,
6286 bool RelativeToPrimary = false,
6287 const FunctionDecl *Pattern = nullptr);
6289 /// \brief A template instantiation that is currently in progress.
6290 struct ActiveTemplateInstantiation {
6291 /// \brief The kind of template instantiation we are performing
6292 enum InstantiationKind {
6293 /// We are instantiating a template declaration. The entity is
6294 /// the declaration we're instantiating (e.g., a CXXRecordDecl).
6295 TemplateInstantiation,
6297 /// We are instantiating a default argument for a template
6298 /// parameter. The Entity is the template, and
6299 /// TemplateArgs/NumTemplateArguments provides the template
6300 /// arguments as specified.
6301 /// FIXME: Use a TemplateArgumentList
6302 DefaultTemplateArgumentInstantiation,
6304 /// We are instantiating a default argument for a function.
6305 /// The Entity is the ParmVarDecl, and TemplateArgs/NumTemplateArgs
6306 /// provides the template arguments as specified.
6307 DefaultFunctionArgumentInstantiation,
6309 /// We are substituting explicit template arguments provided for
6310 /// a function template. The entity is a FunctionTemplateDecl.
6311 ExplicitTemplateArgumentSubstitution,
6313 /// We are substituting template argument determined as part of
6314 /// template argument deduction for either a class template
6315 /// partial specialization or a function template. The
6316 /// Entity is either a ClassTemplatePartialSpecializationDecl or
6317 /// a FunctionTemplateDecl.
6318 DeducedTemplateArgumentSubstitution,
6320 /// We are substituting prior template arguments into a new
6321 /// template parameter. The template parameter itself is either a
6322 /// NonTypeTemplateParmDecl or a TemplateTemplateParmDecl.
6323 PriorTemplateArgumentSubstitution,
6325 /// We are checking the validity of a default template argument that
6326 /// has been used when naming a template-id.
6327 DefaultTemplateArgumentChecking,
6329 /// We are instantiating the exception specification for a function
6330 /// template which was deferred until it was needed.
6331 ExceptionSpecInstantiation
6334 /// \brief The point of instantiation within the source code.
6335 SourceLocation PointOfInstantiation;
6337 /// \brief The template (or partial specialization) in which we are
6338 /// performing the instantiation, for substitutions of prior template
6340 NamedDecl *Template;
6342 /// \brief The entity that is being instantiated.
6345 /// \brief The list of template arguments we are substituting, if they
6346 /// are not part of the entity.
6347 const TemplateArgument *TemplateArgs;
6349 /// \brief The number of template arguments in TemplateArgs.
6350 unsigned NumTemplateArgs;
6352 /// \brief The template deduction info object associated with the
6353 /// substitution or checking of explicit or deduced template arguments.
6354 sema::TemplateDeductionInfo *DeductionInfo;
6356 /// \brief The source range that covers the construct that cause
6357 /// the instantiation, e.g., the template-id that causes a class
6358 /// template instantiation.
6359 SourceRange InstantiationRange;
6361 ActiveTemplateInstantiation()
6362 : Kind(TemplateInstantiation), Template(nullptr), Entity(nullptr),
6363 TemplateArgs(nullptr), NumTemplateArgs(0), DeductionInfo(nullptr) {}
6365 /// \brief Determines whether this template is an actual instantiation
6366 /// that should be counted toward the maximum instantiation depth.
6367 bool isInstantiationRecord() const;
6369 friend bool operator==(const ActiveTemplateInstantiation &X,
6370 const ActiveTemplateInstantiation &Y) {
6371 if (X.Kind != Y.Kind)
6374 if (X.Entity != Y.Entity)
6378 case TemplateInstantiation:
6379 case ExceptionSpecInstantiation:
6382 case PriorTemplateArgumentSubstitution:
6383 case DefaultTemplateArgumentChecking:
6384 return X.Template == Y.Template && X.TemplateArgs == Y.TemplateArgs;
6386 case DefaultTemplateArgumentInstantiation:
6387 case ExplicitTemplateArgumentSubstitution:
6388 case DeducedTemplateArgumentSubstitution:
6389 case DefaultFunctionArgumentInstantiation:
6390 return X.TemplateArgs == Y.TemplateArgs;
6394 llvm_unreachable("Invalid InstantiationKind!");
6397 friend bool operator!=(const ActiveTemplateInstantiation &X,
6398 const ActiveTemplateInstantiation &Y) {
6403 /// \brief List of active template instantiations.
6405 /// This vector is treated as a stack. As one template instantiation
6406 /// requires another template instantiation, additional
6407 /// instantiations are pushed onto the stack up to a
6408 /// user-configurable limit LangOptions::InstantiationDepth.
6409 SmallVector<ActiveTemplateInstantiation, 16>
6410 ActiveTemplateInstantiations;
6412 /// \brief Extra modules inspected when performing a lookup during a template
6413 /// instantiation. Computed lazily.
6414 SmallVector<Module*, 16> ActiveTemplateInstantiationLookupModules;
6416 /// \brief Cache of additional modules that should be used for name lookup
6417 /// within the current template instantiation. Computed lazily; use
6418 /// getLookupModules() to get a complete set.
6419 llvm::DenseSet<Module*> LookupModulesCache;
6421 /// \brief Get the set of additional modules that should be checked during
6422 /// name lookup. A module and its imports become visible when instanting a
6423 /// template defined within it.
6424 llvm::DenseSet<Module*> &getLookupModules();
6426 /// \brief Whether we are in a SFINAE context that is not associated with
6427 /// template instantiation.
6429 /// This is used when setting up a SFINAE trap (\c see SFINAETrap) outside
6430 /// of a template instantiation or template argument deduction.
6431 bool InNonInstantiationSFINAEContext;
6433 /// \brief The number of ActiveTemplateInstantiation entries in
6434 /// \c ActiveTemplateInstantiations that are not actual instantiations and,
6435 /// therefore, should not be counted as part of the instantiation depth.
6436 unsigned NonInstantiationEntries;
6438 /// \brief The last template from which a template instantiation
6439 /// error or warning was produced.
6441 /// This value is used to suppress printing of redundant template
6442 /// instantiation backtraces when there are multiple errors in the
6443 /// same instantiation. FIXME: Does this belong in Sema? It's tough
6444 /// to implement it anywhere else.
6445 ActiveTemplateInstantiation LastTemplateInstantiationErrorContext;
6447 /// \brief The current index into pack expansion arguments that will be
6448 /// used for substitution of parameter packs.
6450 /// The pack expansion index will be -1 to indicate that parameter packs
6451 /// should be instantiated as themselves. Otherwise, the index specifies
6452 /// which argument within the parameter pack will be used for substitution.
6453 int ArgumentPackSubstitutionIndex;
6455 /// \brief RAII object used to change the argument pack substitution index
6456 /// within a \c Sema object.
6458 /// See \c ArgumentPackSubstitutionIndex for more information.
6459 class ArgumentPackSubstitutionIndexRAII {
6461 int OldSubstitutionIndex;
6464 ArgumentPackSubstitutionIndexRAII(Sema &Self, int NewSubstitutionIndex)
6465 : Self(Self), OldSubstitutionIndex(Self.ArgumentPackSubstitutionIndex) {
6466 Self.ArgumentPackSubstitutionIndex = NewSubstitutionIndex;
6469 ~ArgumentPackSubstitutionIndexRAII() {
6470 Self.ArgumentPackSubstitutionIndex = OldSubstitutionIndex;
6474 friend class ArgumentPackSubstitutionRAII;
6476 /// \brief The stack of calls expression undergoing template instantiation.
6478 /// The top of this stack is used by a fixit instantiating unresolved
6479 /// function calls to fix the AST to match the textual change it prints.
6480 SmallVector<CallExpr *, 8> CallsUndergoingInstantiation;
6482 /// \brief For each declaration that involved template argument deduction, the
6483 /// set of diagnostics that were suppressed during that template argument
6486 /// FIXME: Serialize this structure to the AST file.
6487 typedef llvm::DenseMap<Decl *, SmallVector<PartialDiagnosticAt, 1> >
6488 SuppressedDiagnosticsMap;
6489 SuppressedDiagnosticsMap SuppressedDiagnostics;
6491 /// \brief A stack object to be created when performing template
6494 /// Construction of an object of type \c InstantiatingTemplate
6495 /// pushes the current instantiation onto the stack of active
6496 /// instantiations. If the size of this stack exceeds the maximum
6497 /// number of recursive template instantiations, construction
6498 /// produces an error and evaluates true.
6500 /// Destruction of this object will pop the named instantiation off
6502 struct InstantiatingTemplate {
6503 /// \brief Note that we are instantiating a class template,
6504 /// function template, or a member thereof.
6505 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
6507 SourceRange InstantiationRange = SourceRange());
6509 struct ExceptionSpecification {};
6510 /// \brief Note that we are instantiating an exception specification
6511 /// of a function template.
6512 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
6513 FunctionDecl *Entity, ExceptionSpecification,
6514 SourceRange InstantiationRange = SourceRange());
6516 /// \brief Note that we are instantiating a default argument in a
6518 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
6519 TemplateDecl *Template,
6520 ArrayRef<TemplateArgument> TemplateArgs,
6521 SourceRange InstantiationRange = SourceRange());
6523 /// \brief Note that we are instantiating a default argument in a
6525 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
6526 FunctionTemplateDecl *FunctionTemplate,
6527 ArrayRef<TemplateArgument> TemplateArgs,
6528 ActiveTemplateInstantiation::InstantiationKind Kind,
6529 sema::TemplateDeductionInfo &DeductionInfo,
6530 SourceRange InstantiationRange = SourceRange());
6532 /// \brief Note that we are instantiating as part of template
6533 /// argument deduction for a class template partial
6535 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
6536 ClassTemplatePartialSpecializationDecl *PartialSpec,
6537 ArrayRef<TemplateArgument> TemplateArgs,
6538 sema::TemplateDeductionInfo &DeductionInfo,
6539 SourceRange InstantiationRange = SourceRange());
6541 /// \brief Note that we are instantiating as part of template
6542 /// argument deduction for a variable template partial
6544 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
6545 VarTemplatePartialSpecializationDecl *PartialSpec,
6546 ArrayRef<TemplateArgument> TemplateArgs,
6547 sema::TemplateDeductionInfo &DeductionInfo,
6548 SourceRange InstantiationRange = SourceRange());
6550 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
6552 ArrayRef<TemplateArgument> TemplateArgs,
6553 SourceRange InstantiationRange = SourceRange());
6555 /// \brief Note that we are substituting prior template arguments into a
6556 /// non-type parameter.
6557 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
6558 NamedDecl *Template,
6559 NonTypeTemplateParmDecl *Param,
6560 ArrayRef<TemplateArgument> TemplateArgs,
6561 SourceRange InstantiationRange);
6563 /// \brief Note that we are substituting prior template arguments into a
6564 /// template template parameter.
6565 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
6566 NamedDecl *Template,
6567 TemplateTemplateParmDecl *Param,
6568 ArrayRef<TemplateArgument> TemplateArgs,
6569 SourceRange InstantiationRange);
6571 /// \brief Note that we are checking the default template argument
6572 /// against the template parameter for a given template-id.
6573 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
6574 TemplateDecl *Template,
6576 ArrayRef<TemplateArgument> TemplateArgs,
6577 SourceRange InstantiationRange);
6580 /// \brief Note that we have finished instantiating this template.
6583 ~InstantiatingTemplate() { Clear(); }
6585 /// \brief Determines whether we have exceeded the maximum
6586 /// recursive template instantiations.
6587 bool isInvalid() const { return Invalid; }
6592 bool SavedInNonInstantiationSFINAEContext;
6593 bool CheckInstantiationDepth(SourceLocation PointOfInstantiation,
6594 SourceRange InstantiationRange);
6596 // FIXME: Replace this with a constructor once we can use delegating
6597 // constructors in llvm.
6599 ActiveTemplateInstantiation::InstantiationKind Kind,
6600 SourceLocation PointOfInstantiation, SourceRange InstantiationRange,
6601 Decl *Entity, NamedDecl *Template = nullptr,
6602 ArrayRef<TemplateArgument> TemplateArgs = ArrayRef<TemplateArgument>(),
6603 sema::TemplateDeductionInfo *DeductionInfo = nullptr);
6605 InstantiatingTemplate(const InstantiatingTemplate&) LLVM_DELETED_FUNCTION;
6607 InstantiatingTemplate&
6608 operator=(const InstantiatingTemplate&) LLVM_DELETED_FUNCTION;
6611 void PrintInstantiationStack();
6613 /// \brief Determines whether we are currently in a context where
6614 /// template argument substitution failures are not considered
6617 /// \returns An empty \c Optional if we're not in a SFINAE context.
6618 /// Otherwise, contains a pointer that, if non-NULL, contains the nearest
6619 /// template-deduction context object, which can be used to capture
6620 /// diagnostics that will be suppressed.
6621 Optional<sema::TemplateDeductionInfo *> isSFINAEContext() const;
6623 /// \brief Determines whether we are currently in a context that
6624 /// is not evaluated as per C++ [expr] p5.
6625 bool isUnevaluatedContext() const {
6626 assert(!ExprEvalContexts.empty() &&
6627 "Must be in an expression evaluation context");
6628 return ExprEvalContexts.back().isUnevaluated();
6631 /// \brief RAII class used to determine whether SFINAE has
6632 /// trapped any errors that occur during template argument
6636 unsigned PrevSFINAEErrors;
6637 bool PrevInNonInstantiationSFINAEContext;
6638 bool PrevAccessCheckingSFINAE;
6641 explicit SFINAETrap(Sema &SemaRef, bool AccessCheckingSFINAE = false)
6642 : SemaRef(SemaRef), PrevSFINAEErrors(SemaRef.NumSFINAEErrors),
6643 PrevInNonInstantiationSFINAEContext(
6644 SemaRef.InNonInstantiationSFINAEContext),
6645 PrevAccessCheckingSFINAE(SemaRef.AccessCheckingSFINAE)
6647 if (!SemaRef.isSFINAEContext())
6648 SemaRef.InNonInstantiationSFINAEContext = true;
6649 SemaRef.AccessCheckingSFINAE = AccessCheckingSFINAE;
6653 SemaRef.NumSFINAEErrors = PrevSFINAEErrors;
6654 SemaRef.InNonInstantiationSFINAEContext
6655 = PrevInNonInstantiationSFINAEContext;
6656 SemaRef.AccessCheckingSFINAE = PrevAccessCheckingSFINAE;
6659 /// \brief Determine whether any SFINAE errors have been trapped.
6660 bool hasErrorOccurred() const {
6661 return SemaRef.NumSFINAEErrors > PrevSFINAEErrors;
6665 /// \brief RAII class used to indicate that we are performing provisional
6666 /// semantic analysis to determine the validity of a construct, so
6667 /// typo-correction and diagnostics in the immediate context (not within
6668 /// implicitly-instantiated templates) should be suppressed.
6669 class TentativeAnalysisScope {
6671 // FIXME: Using a SFINAETrap for this is a hack.
6673 bool PrevDisableTypoCorrection;
6675 explicit TentativeAnalysisScope(Sema &SemaRef)
6676 : SemaRef(SemaRef), Trap(SemaRef, true),
6677 PrevDisableTypoCorrection(SemaRef.DisableTypoCorrection) {
6678 SemaRef.DisableTypoCorrection = true;
6680 ~TentativeAnalysisScope() {
6681 SemaRef.DisableTypoCorrection = PrevDisableTypoCorrection;
6685 /// \brief The current instantiation scope used to store local
6687 LocalInstantiationScope *CurrentInstantiationScope;
6689 /// \brief Tracks whether we are in a context where typo correction is
6691 bool DisableTypoCorrection;
6693 /// \brief The number of typos corrected by CorrectTypo.
6694 unsigned TyposCorrected;
6696 typedef llvm::SmallSet<SourceLocation, 2> SrcLocSet;
6697 typedef llvm::DenseMap<IdentifierInfo *, SrcLocSet> IdentifierSourceLocations;
6699 /// \brief A cache containing identifiers for which typo correction failed and
6700 /// their locations, so that repeated attempts to correct an identifier in a
6701 /// given location are ignored if typo correction already failed for it.
6702 IdentifierSourceLocations TypoCorrectionFailures;
6704 /// \brief Worker object for performing CFG-based warnings.
6705 sema::AnalysisBasedWarnings AnalysisWarnings;
6707 /// \brief An entity for which implicit template instantiation is required.
6709 /// The source location associated with the declaration is the first place in
6710 /// the source code where the declaration was "used". It is not necessarily
6711 /// the point of instantiation (which will be either before or after the
6712 /// namespace-scope declaration that triggered this implicit instantiation),
6713 /// However, it is the location that diagnostics should generally refer to,
6714 /// because users will need to know what code triggered the instantiation.
6715 typedef std::pair<ValueDecl *, SourceLocation> PendingImplicitInstantiation;
6717 /// \brief The queue of implicit template instantiations that are required
6718 /// but have not yet been performed.
6719 std::deque<PendingImplicitInstantiation> PendingInstantiations;
6721 class SavePendingInstantiationsAndVTableUsesRAII {
6723 SavePendingInstantiationsAndVTableUsesRAII(Sema &S): S(S) {
6724 SavedPendingInstantiations.swap(S.PendingInstantiations);
6725 SavedVTableUses.swap(S.VTableUses);
6728 ~SavePendingInstantiationsAndVTableUsesRAII() {
6729 // Restore the set of pending vtables.
6730 assert(S.VTableUses.empty() &&
6731 "VTableUses should be empty before it is discarded.");
6732 S.VTableUses.swap(SavedVTableUses);
6734 // Restore the set of pending implicit instantiations.
6735 assert(S.PendingInstantiations.empty() &&
6736 "PendingInstantiations should be empty before it is discarded.");
6737 S.PendingInstantiations.swap(SavedPendingInstantiations);
6742 SmallVector<VTableUse, 16> SavedVTableUses;
6743 std::deque<PendingImplicitInstantiation> SavedPendingInstantiations;
6746 /// \brief The queue of implicit template instantiations that are required
6747 /// and must be performed within the current local scope.
6749 /// This queue is only used for member functions of local classes in
6750 /// templates, which must be instantiated in the same scope as their
6751 /// enclosing function, so that they can reference function-local
6752 /// types, static variables, enumerators, etc.
6753 std::deque<PendingImplicitInstantiation> PendingLocalImplicitInstantiations;
6755 class SavePendingLocalImplicitInstantiationsRAII {
6757 SavePendingLocalImplicitInstantiationsRAII(Sema &S): S(S) {
6758 SavedPendingLocalImplicitInstantiations.swap(
6759 S.PendingLocalImplicitInstantiations);
6762 ~SavePendingLocalImplicitInstantiationsRAII() {
6763 assert(S.PendingLocalImplicitInstantiations.empty() &&
6764 "there shouldn't be any pending local implicit instantiations");
6765 SavedPendingLocalImplicitInstantiations.swap(
6766 S.PendingLocalImplicitInstantiations);
6771 std::deque<PendingImplicitInstantiation>
6772 SavedPendingLocalImplicitInstantiations;
6775 void PerformPendingInstantiations(bool LocalOnly = false);
6777 TypeSourceInfo *SubstType(TypeSourceInfo *T,
6778 const MultiLevelTemplateArgumentList &TemplateArgs,
6779 SourceLocation Loc, DeclarationName Entity);
6781 QualType SubstType(QualType T,
6782 const MultiLevelTemplateArgumentList &TemplateArgs,
6783 SourceLocation Loc, DeclarationName Entity);
6785 TypeSourceInfo *SubstType(TypeLoc TL,
6786 const MultiLevelTemplateArgumentList &TemplateArgs,
6787 SourceLocation Loc, DeclarationName Entity);
6789 TypeSourceInfo *SubstFunctionDeclType(TypeSourceInfo *T,
6790 const MultiLevelTemplateArgumentList &TemplateArgs,
6792 DeclarationName Entity,
6793 CXXRecordDecl *ThisContext,
6794 unsigned ThisTypeQuals);
6795 void SubstExceptionSpec(FunctionDecl *New, const FunctionProtoType *Proto,
6796 const MultiLevelTemplateArgumentList &Args);
6797 ParmVarDecl *SubstParmVarDecl(ParmVarDecl *D,
6798 const MultiLevelTemplateArgumentList &TemplateArgs,
6799 int indexAdjustment,
6800 Optional<unsigned> NumExpansions,
6801 bool ExpectParameterPack);
6802 bool SubstParmTypes(SourceLocation Loc,
6803 ParmVarDecl **Params, unsigned NumParams,
6804 const MultiLevelTemplateArgumentList &TemplateArgs,
6805 SmallVectorImpl<QualType> &ParamTypes,
6806 SmallVectorImpl<ParmVarDecl *> *OutParams = nullptr);
6807 ExprResult SubstExpr(Expr *E,
6808 const MultiLevelTemplateArgumentList &TemplateArgs);
6810 /// \brief Substitute the given template arguments into a list of
6811 /// expressions, expanding pack expansions if required.
6813 /// \param Exprs The list of expressions to substitute into.
6815 /// \param NumExprs The number of expressions in \p Exprs.
6817 /// \param IsCall Whether this is some form of call, in which case
6818 /// default arguments will be dropped.
6820 /// \param TemplateArgs The set of template arguments to substitute.
6822 /// \param Outputs Will receive all of the substituted arguments.
6824 /// \returns true if an error occurred, false otherwise.
6825 bool SubstExprs(Expr **Exprs, unsigned NumExprs, bool IsCall,
6826 const MultiLevelTemplateArgumentList &TemplateArgs,
6827 SmallVectorImpl<Expr *> &Outputs);
6829 StmtResult SubstStmt(Stmt *S,
6830 const MultiLevelTemplateArgumentList &TemplateArgs);
6832 Decl *SubstDecl(Decl *D, DeclContext *Owner,
6833 const MultiLevelTemplateArgumentList &TemplateArgs);
6835 ExprResult SubstInitializer(Expr *E,
6836 const MultiLevelTemplateArgumentList &TemplateArgs,
6837 bool CXXDirectInit);
6840 SubstBaseSpecifiers(CXXRecordDecl *Instantiation,
6841 CXXRecordDecl *Pattern,
6842 const MultiLevelTemplateArgumentList &TemplateArgs);
6845 InstantiateClass(SourceLocation PointOfInstantiation,
6846 CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern,
6847 const MultiLevelTemplateArgumentList &TemplateArgs,
6848 TemplateSpecializationKind TSK,
6849 bool Complain = true);
6851 bool InstantiateEnum(SourceLocation PointOfInstantiation,
6852 EnumDecl *Instantiation, EnumDecl *Pattern,
6853 const MultiLevelTemplateArgumentList &TemplateArgs,
6854 TemplateSpecializationKind TSK);
6856 bool InstantiateInClassInitializer(
6857 SourceLocation PointOfInstantiation, FieldDecl *Instantiation,
6858 FieldDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs);
6860 struct LateInstantiatedAttribute {
6861 const Attr *TmplAttr;
6862 LocalInstantiationScope *Scope;
6865 LateInstantiatedAttribute(const Attr *A, LocalInstantiationScope *S,
6867 : TmplAttr(A), Scope(S), NewDecl(D)
6870 typedef SmallVector<LateInstantiatedAttribute, 16> LateInstantiatedAttrVec;
6872 void InstantiateAttrs(const MultiLevelTemplateArgumentList &TemplateArgs,
6873 const Decl *Pattern, Decl *Inst,
6874 LateInstantiatedAttrVec *LateAttrs = nullptr,
6875 LocalInstantiationScope *OuterMostScope = nullptr);
6878 InstantiateClassTemplateSpecialization(SourceLocation PointOfInstantiation,
6879 ClassTemplateSpecializationDecl *ClassTemplateSpec,
6880 TemplateSpecializationKind TSK,
6881 bool Complain = true);
6883 void InstantiateClassMembers(SourceLocation PointOfInstantiation,
6884 CXXRecordDecl *Instantiation,
6885 const MultiLevelTemplateArgumentList &TemplateArgs,
6886 TemplateSpecializationKind TSK);
6888 void InstantiateClassTemplateSpecializationMembers(
6889 SourceLocation PointOfInstantiation,
6890 ClassTemplateSpecializationDecl *ClassTemplateSpec,
6891 TemplateSpecializationKind TSK);
6893 NestedNameSpecifierLoc
6894 SubstNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS,
6895 const MultiLevelTemplateArgumentList &TemplateArgs);
6898 SubstDeclarationNameInfo(const DeclarationNameInfo &NameInfo,
6899 const MultiLevelTemplateArgumentList &TemplateArgs);
6901 SubstTemplateName(NestedNameSpecifierLoc QualifierLoc, TemplateName Name,
6903 const MultiLevelTemplateArgumentList &TemplateArgs);
6904 bool Subst(const TemplateArgumentLoc *Args, unsigned NumArgs,
6905 TemplateArgumentListInfo &Result,
6906 const MultiLevelTemplateArgumentList &TemplateArgs);
6908 void InstantiateExceptionSpec(SourceLocation PointOfInstantiation,
6909 FunctionDecl *Function);
6910 void InstantiateFunctionDefinition(SourceLocation PointOfInstantiation,
6911 FunctionDecl *Function,
6912 bool Recursive = false,
6913 bool DefinitionRequired = false);
6914 VarTemplateSpecializationDecl *BuildVarTemplateInstantiation(
6915 VarTemplateDecl *VarTemplate, VarDecl *FromVar,
6916 const TemplateArgumentList &TemplateArgList,
6917 const TemplateArgumentListInfo &TemplateArgsInfo,
6918 SmallVectorImpl<TemplateArgument> &Converted,
6919 SourceLocation PointOfInstantiation, void *InsertPos,
6920 LateInstantiatedAttrVec *LateAttrs = nullptr,
6921 LocalInstantiationScope *StartingScope = nullptr);
6922 VarTemplateSpecializationDecl *CompleteVarTemplateSpecializationDecl(
6923 VarTemplateSpecializationDecl *VarSpec, VarDecl *PatternDecl,
6924 const MultiLevelTemplateArgumentList &TemplateArgs);
6926 BuildVariableInstantiation(VarDecl *NewVar, VarDecl *OldVar,
6927 const MultiLevelTemplateArgumentList &TemplateArgs,
6928 LateInstantiatedAttrVec *LateAttrs,
6930 LocalInstantiationScope *StartingScope,
6931 bool InstantiatingVarTemplate = false);
6932 void InstantiateVariableInitializer(
6933 VarDecl *Var, VarDecl *OldVar,
6934 const MultiLevelTemplateArgumentList &TemplateArgs);
6935 void InstantiateVariableDefinition(SourceLocation PointOfInstantiation,
6936 VarDecl *Var, bool Recursive = false,
6937 bool DefinitionRequired = false);
6938 void InstantiateStaticDataMemberDefinition(
6939 SourceLocation PointOfInstantiation,
6941 bool Recursive = false,
6942 bool DefinitionRequired = false);
6944 void InstantiateMemInitializers(CXXConstructorDecl *New,
6945 const CXXConstructorDecl *Tmpl,
6946 const MultiLevelTemplateArgumentList &TemplateArgs);
6948 NamedDecl *FindInstantiatedDecl(SourceLocation Loc, NamedDecl *D,
6949 const MultiLevelTemplateArgumentList &TemplateArgs);
6950 DeclContext *FindInstantiatedContext(SourceLocation Loc, DeclContext *DC,
6951 const MultiLevelTemplateArgumentList &TemplateArgs);
6953 // Objective-C declarations.
6954 enum ObjCContainerKind {
6961 OCK_CategoryImplementation
6963 ObjCContainerKind getObjCContainerKind() const;
6965 Decl *ActOnStartClassInterface(SourceLocation AtInterfaceLoc,
6966 IdentifierInfo *ClassName,
6967 SourceLocation ClassLoc,
6968 IdentifierInfo *SuperName,
6969 SourceLocation SuperLoc,
6970 Decl * const *ProtoRefs,
6971 unsigned NumProtoRefs,
6972 const SourceLocation *ProtoLocs,
6973 SourceLocation EndProtoLoc,
6974 AttributeList *AttrList);
6976 void ActOnTypedefedProtocols(SmallVectorImpl<Decl *> &ProtocolRefs,
6977 IdentifierInfo *SuperName,
6978 SourceLocation SuperLoc);
6980 Decl *ActOnCompatibilityAlias(
6981 SourceLocation AtCompatibilityAliasLoc,
6982 IdentifierInfo *AliasName, SourceLocation AliasLocation,
6983 IdentifierInfo *ClassName, SourceLocation ClassLocation);
6985 bool CheckForwardProtocolDeclarationForCircularDependency(
6986 IdentifierInfo *PName,
6987 SourceLocation &PLoc, SourceLocation PrevLoc,
6988 const ObjCList<ObjCProtocolDecl> &PList);
6990 Decl *ActOnStartProtocolInterface(
6991 SourceLocation AtProtoInterfaceLoc,
6992 IdentifierInfo *ProtocolName, SourceLocation ProtocolLoc,
6993 Decl * const *ProtoRefNames, unsigned NumProtoRefs,
6994 const SourceLocation *ProtoLocs,
6995 SourceLocation EndProtoLoc,
6996 AttributeList *AttrList);
6998 Decl *ActOnStartCategoryInterface(SourceLocation AtInterfaceLoc,
6999 IdentifierInfo *ClassName,
7000 SourceLocation ClassLoc,
7001 IdentifierInfo *CategoryName,
7002 SourceLocation CategoryLoc,
7003 Decl * const *ProtoRefs,
7004 unsigned NumProtoRefs,
7005 const SourceLocation *ProtoLocs,
7006 SourceLocation EndProtoLoc);
7008 Decl *ActOnStartClassImplementation(
7009 SourceLocation AtClassImplLoc,
7010 IdentifierInfo *ClassName, SourceLocation ClassLoc,
7011 IdentifierInfo *SuperClassname,
7012 SourceLocation SuperClassLoc);
7014 Decl *ActOnStartCategoryImplementation(SourceLocation AtCatImplLoc,
7015 IdentifierInfo *ClassName,
7016 SourceLocation ClassLoc,
7017 IdentifierInfo *CatName,
7018 SourceLocation CatLoc);
7020 DeclGroupPtrTy ActOnFinishObjCImplementation(Decl *ObjCImpDecl,
7021 ArrayRef<Decl *> Decls);
7023 DeclGroupPtrTy ActOnForwardClassDeclaration(SourceLocation Loc,
7024 IdentifierInfo **IdentList,
7025 SourceLocation *IdentLocs,
7028 DeclGroupPtrTy ActOnForwardProtocolDeclaration(SourceLocation AtProtoclLoc,
7029 const IdentifierLocPair *IdentList,
7031 AttributeList *attrList);
7033 void FindProtocolDeclaration(bool WarnOnDeclarations,
7034 const IdentifierLocPair *ProtocolId,
7035 unsigned NumProtocols,
7036 SmallVectorImpl<Decl *> &Protocols);
7038 /// Ensure attributes are consistent with type.
7039 /// \param [in, out] Attributes The attributes to check; they will
7040 /// be modified to be consistent with \p PropertyTy.
7041 void CheckObjCPropertyAttributes(Decl *PropertyPtrTy,
7043 unsigned &Attributes,
7044 bool propertyInPrimaryClass);
7046 /// Process the specified property declaration and create decls for the
7047 /// setters and getters as needed.
7048 /// \param property The property declaration being processed
7049 /// \param CD The semantic container for the property
7050 /// \param redeclaredProperty Declaration for property if redeclared
7051 /// in class extension.
7052 /// \param lexicalDC Container for redeclaredProperty.
7053 void ProcessPropertyDecl(ObjCPropertyDecl *property,
7054 ObjCContainerDecl *CD,
7055 ObjCPropertyDecl *redeclaredProperty = nullptr,
7056 ObjCContainerDecl *lexicalDC = nullptr);
7059 void DiagnosePropertyMismatch(ObjCPropertyDecl *Property,
7060 ObjCPropertyDecl *SuperProperty,
7061 const IdentifierInfo *Name,
7062 bool OverridingProtocolProperty);
7064 void DiagnoseClassExtensionDupMethods(ObjCCategoryDecl *CAT,
7065 ObjCInterfaceDecl *ID);
7067 Decl *ActOnAtEnd(Scope *S, SourceRange AtEnd,
7068 ArrayRef<Decl *> allMethods = None,
7069 ArrayRef<DeclGroupPtrTy> allTUVars = None);
7071 Decl *ActOnProperty(Scope *S, SourceLocation AtLoc,
7072 SourceLocation LParenLoc,
7073 FieldDeclarator &FD, ObjCDeclSpec &ODS,
7074 Selector GetterSel, Selector SetterSel,
7075 bool *OverridingProperty,
7076 tok::ObjCKeywordKind MethodImplKind,
7077 DeclContext *lexicalDC = nullptr);
7079 Decl *ActOnPropertyImplDecl(Scope *S,
7080 SourceLocation AtLoc,
7081 SourceLocation PropertyLoc,
7083 IdentifierInfo *PropertyId,
7084 IdentifierInfo *PropertyIvar,
7085 SourceLocation PropertyIvarLoc);
7087 enum ObjCSpecialMethodKind {
7093 OSMK_NonRetainingInit
7096 struct ObjCArgInfo {
7097 IdentifierInfo *Name;
7098 SourceLocation NameLoc;
7099 // The Type is null if no type was specified, and the DeclSpec is invalid
7102 ObjCDeclSpec DeclSpec;
7104 /// ArgAttrs - Attribute list for this argument.
7105 AttributeList *ArgAttrs;
7108 Decl *ActOnMethodDeclaration(
7110 SourceLocation BeginLoc, // location of the + or -.
7111 SourceLocation EndLoc, // location of the ; or {.
7112 tok::TokenKind MethodType,
7113 ObjCDeclSpec &ReturnQT, ParsedType ReturnType,
7114 ArrayRef<SourceLocation> SelectorLocs, Selector Sel,
7115 // optional arguments. The number of types/arguments is obtained
7116 // from the Sel.getNumArgs().
7117 ObjCArgInfo *ArgInfo,
7118 DeclaratorChunk::ParamInfo *CParamInfo, unsigned CNumArgs, // c-style args
7119 AttributeList *AttrList, tok::ObjCKeywordKind MethodImplKind,
7120 bool isVariadic, bool MethodDefinition);
7122 ObjCMethodDecl *LookupMethodInQualifiedType(Selector Sel,
7123 const ObjCObjectPointerType *OPT,
7125 ObjCMethodDecl *LookupMethodInObjectType(Selector Sel, QualType Ty,
7128 bool CheckARCMethodDecl(ObjCMethodDecl *method);
7129 bool inferObjCARCLifetime(ValueDecl *decl);
7132 HandleExprPropertyRefExpr(const ObjCObjectPointerType *OPT,
7134 SourceLocation OpLoc,
7135 DeclarationName MemberName,
7136 SourceLocation MemberLoc,
7137 SourceLocation SuperLoc, QualType SuperType,
7141 ActOnClassPropertyRefExpr(IdentifierInfo &receiverName,
7142 IdentifierInfo &propertyName,
7143 SourceLocation receiverNameLoc,
7144 SourceLocation propertyNameLoc);
7146 ObjCMethodDecl *tryCaptureObjCSelf(SourceLocation Loc);
7148 /// \brief Describes the kind of message expression indicated by a message
7149 /// send that starts with an identifier.
7150 enum ObjCMessageKind {
7151 /// \brief The message is sent to 'super'.
7153 /// \brief The message is an instance message.
7154 ObjCInstanceMessage,
7155 /// \brief The message is a class message, and the identifier is a type
7160 ObjCMessageKind getObjCMessageKind(Scope *S,
7161 IdentifierInfo *Name,
7162 SourceLocation NameLoc,
7164 bool HasTrailingDot,
7165 ParsedType &ReceiverType);
7167 ExprResult ActOnSuperMessage(Scope *S, SourceLocation SuperLoc,
7169 SourceLocation LBracLoc,
7170 ArrayRef<SourceLocation> SelectorLocs,
7171 SourceLocation RBracLoc,
7174 ExprResult BuildClassMessage(TypeSourceInfo *ReceiverTypeInfo,
7175 QualType ReceiverType,
7176 SourceLocation SuperLoc,
7178 ObjCMethodDecl *Method,
7179 SourceLocation LBracLoc,
7180 ArrayRef<SourceLocation> SelectorLocs,
7181 SourceLocation RBracLoc,
7183 bool isImplicit = false);
7185 ExprResult BuildClassMessageImplicit(QualType ReceiverType,
7186 bool isSuperReceiver,
7189 ObjCMethodDecl *Method,
7192 ExprResult ActOnClassMessage(Scope *S,
7193 ParsedType Receiver,
7195 SourceLocation LBracLoc,
7196 ArrayRef<SourceLocation> SelectorLocs,
7197 SourceLocation RBracLoc,
7200 ExprResult BuildInstanceMessage(Expr *Receiver,
7201 QualType ReceiverType,
7202 SourceLocation SuperLoc,
7204 ObjCMethodDecl *Method,
7205 SourceLocation LBracLoc,
7206 ArrayRef<SourceLocation> SelectorLocs,
7207 SourceLocation RBracLoc,
7209 bool isImplicit = false);
7211 ExprResult BuildInstanceMessageImplicit(Expr *Receiver,
7212 QualType ReceiverType,
7215 ObjCMethodDecl *Method,
7218 ExprResult ActOnInstanceMessage(Scope *S,
7221 SourceLocation LBracLoc,
7222 ArrayRef<SourceLocation> SelectorLocs,
7223 SourceLocation RBracLoc,
7226 ExprResult BuildObjCBridgedCast(SourceLocation LParenLoc,
7227 ObjCBridgeCastKind Kind,
7228 SourceLocation BridgeKeywordLoc,
7229 TypeSourceInfo *TSInfo,
7232 ExprResult ActOnObjCBridgedCast(Scope *S,
7233 SourceLocation LParenLoc,
7234 ObjCBridgeCastKind Kind,
7235 SourceLocation BridgeKeywordLoc,
7237 SourceLocation RParenLoc,
7240 void CheckTollFreeBridgeCast(QualType castType, Expr *castExpr);
7242 void CheckObjCBridgeRelatedCast(QualType castType, Expr *castExpr);
7244 bool CheckTollFreeBridgeStaticCast(QualType castType, Expr *castExpr,
7247 bool checkObjCBridgeRelatedComponents(SourceLocation Loc,
7248 QualType DestType, QualType SrcType,
7249 ObjCInterfaceDecl *&RelatedClass,
7250 ObjCMethodDecl *&ClassMethod,
7251 ObjCMethodDecl *&InstanceMethod,
7252 TypedefNameDecl *&TDNDecl,
7255 bool CheckObjCBridgeRelatedConversions(SourceLocation Loc,
7256 QualType DestType, QualType SrcType,
7259 bool ConversionToObjCStringLiteralCheck(QualType DstType, Expr *&SrcExpr);
7261 bool checkInitMethod(ObjCMethodDecl *method, QualType receiverTypeIfCall);
7263 /// \brief Check whether the given new method is a valid override of the
7264 /// given overridden method, and set any properties that should be inherited.
7265 void CheckObjCMethodOverride(ObjCMethodDecl *NewMethod,
7266 const ObjCMethodDecl *Overridden);
7268 /// \brief Describes the compatibility of a result type with its method.
7269 enum ResultTypeCompatibilityKind {
7275 void CheckObjCMethodOverrides(ObjCMethodDecl *ObjCMethod,
7276 ObjCInterfaceDecl *CurrentClass,
7277 ResultTypeCompatibilityKind RTC);
7279 enum PragmaOptionsAlignKind {
7280 POAK_Native, // #pragma options align=native
7281 POAK_Natural, // #pragma options align=natural
7282 POAK_Packed, // #pragma options align=packed
7283 POAK_Power, // #pragma options align=power
7284 POAK_Mac68k, // #pragma options align=mac68k
7285 POAK_Reset // #pragma options align=reset
7288 /// ActOnPragmaOptionsAlign - Called on well formed \#pragma options align.
7289 void ActOnPragmaOptionsAlign(PragmaOptionsAlignKind Kind,
7290 SourceLocation PragmaLoc);
7292 enum PragmaPackKind {
7293 PPK_Default, // #pragma pack([n])
7294 PPK_Show, // #pragma pack(show), only supported by MSVC.
7295 PPK_Push, // #pragma pack(push, [identifier], [n])
7296 PPK_Pop // #pragma pack(pop, [identifier], [n])
7299 enum PragmaMSStructKind {
7300 PMSST_OFF, // #pragms ms_struct off
7301 PMSST_ON // #pragms ms_struct on
7304 enum PragmaMSCommentKind {
7306 PCK_Linker, // #pragma comment(linker, ...)
7307 PCK_Lib, // #pragma comment(lib, ...)
7308 PCK_Compiler, // #pragma comment(compiler, ...)
7309 PCK_ExeStr, // #pragma comment(exestr, ...)
7310 PCK_User // #pragma comment(user, ...)
7313 /// ActOnPragmaPack - Called on well formed \#pragma pack(...).
7314 void ActOnPragmaPack(PragmaPackKind Kind,
7315 IdentifierInfo *Name,
7317 SourceLocation PragmaLoc,
7318 SourceLocation LParenLoc,
7319 SourceLocation RParenLoc);
7321 /// ActOnPragmaMSStruct - Called on well formed \#pragma ms_struct [on|off].
7322 void ActOnPragmaMSStruct(PragmaMSStructKind Kind);
7324 /// ActOnPragmaMSComment - Called on well formed
7325 /// \#pragma comment(kind, "arg").
7326 void ActOnPragmaMSComment(PragmaMSCommentKind Kind, StringRef Arg);
7328 /// ActOnPragmaMSPointersToMembers - called on well formed \#pragma
7329 /// pointers_to_members(representation method[, general purpose
7330 /// representation]).
7331 void ActOnPragmaMSPointersToMembers(
7332 LangOptions::PragmaMSPointersToMembersKind Kind,
7333 SourceLocation PragmaLoc);
7335 /// \brief Called on well formed \#pragma vtordisp().
7336 void ActOnPragmaMSVtorDisp(PragmaVtorDispKind Kind, SourceLocation PragmaLoc,
7337 MSVtorDispAttr::Mode Value);
7339 enum PragmaSectionKind {
7346 bool UnifySection(StringRef SectionName,
7348 DeclaratorDecl *TheDecl);
7349 bool UnifySection(StringRef SectionName,
7351 SourceLocation PragmaSectionLocation);
7353 /// \brief Called on well formed \#pragma bss_seg/data_seg/const_seg/code_seg.
7354 void ActOnPragmaMSSeg(SourceLocation PragmaLocation,
7355 PragmaMsStackAction Action,
7356 llvm::StringRef StackSlotLabel,
7357 StringLiteral *SegmentName,
7358 llvm::StringRef PragmaName);
7360 /// \brief Called on well formed \#pragma section().
7361 void ActOnPragmaMSSection(SourceLocation PragmaLocation,
7362 int SectionFlags, StringLiteral *SegmentName);
7364 /// \brief Called on well-formed \#pragma init_seg().
7365 void ActOnPragmaMSInitSeg(SourceLocation PragmaLocation,
7366 StringLiteral *SegmentName);
7368 /// ActOnPragmaDetectMismatch - Call on well-formed \#pragma detect_mismatch
7369 void ActOnPragmaDetectMismatch(StringRef Name, StringRef Value);
7371 /// ActOnPragmaUnused - Called on well-formed '\#pragma unused'.
7372 void ActOnPragmaUnused(const Token &Identifier,
7374 SourceLocation PragmaLoc);
7376 /// ActOnPragmaVisibility - Called on well formed \#pragma GCC visibility... .
7377 void ActOnPragmaVisibility(const IdentifierInfo* VisType,
7378 SourceLocation PragmaLoc);
7380 NamedDecl *DeclClonePragmaWeak(NamedDecl *ND, IdentifierInfo *II,
7381 SourceLocation Loc);
7382 void DeclApplyPragmaWeak(Scope *S, NamedDecl *ND, WeakInfo &W);
7384 /// ActOnPragmaWeakID - Called on well formed \#pragma weak ident.
7385 void ActOnPragmaWeakID(IdentifierInfo* WeakName,
7386 SourceLocation PragmaLoc,
7387 SourceLocation WeakNameLoc);
7389 /// ActOnPragmaRedefineExtname - Called on well formed
7390 /// \#pragma redefine_extname oldname newname.
7391 void ActOnPragmaRedefineExtname(IdentifierInfo* WeakName,
7392 IdentifierInfo* AliasName,
7393 SourceLocation PragmaLoc,
7394 SourceLocation WeakNameLoc,
7395 SourceLocation AliasNameLoc);
7397 /// ActOnPragmaWeakAlias - Called on well formed \#pragma weak ident = ident.
7398 void ActOnPragmaWeakAlias(IdentifierInfo* WeakName,
7399 IdentifierInfo* AliasName,
7400 SourceLocation PragmaLoc,
7401 SourceLocation WeakNameLoc,
7402 SourceLocation AliasNameLoc);
7404 /// ActOnPragmaFPContract - Called on well formed
7405 /// \#pragma {STDC,OPENCL} FP_CONTRACT
7406 void ActOnPragmaFPContract(tok::OnOffSwitch OOS);
7408 /// AddAlignmentAttributesForRecord - Adds any needed alignment attributes to
7409 /// a the record decl, to handle '\#pragma pack' and '\#pragma options align'.
7410 void AddAlignmentAttributesForRecord(RecordDecl *RD);
7412 /// AddMsStructLayoutForRecord - Adds ms_struct layout attribute to record.
7413 void AddMsStructLayoutForRecord(RecordDecl *RD);
7415 /// FreePackedContext - Deallocate and null out PackContext.
7416 void FreePackedContext();
7418 /// PushNamespaceVisibilityAttr - Note that we've entered a
7419 /// namespace with a visibility attribute.
7420 void PushNamespaceVisibilityAttr(const VisibilityAttr *Attr,
7421 SourceLocation Loc);
7423 /// AddPushedVisibilityAttribute - If '\#pragma GCC visibility' was used,
7424 /// add an appropriate visibility attribute.
7425 void AddPushedVisibilityAttribute(Decl *RD);
7427 /// PopPragmaVisibility - Pop the top element of the visibility stack; used
7428 /// for '\#pragma GCC visibility' and visibility attributes on namespaces.
7429 void PopPragmaVisibility(bool IsNamespaceEnd, SourceLocation EndLoc);
7431 /// FreeVisContext - Deallocate and null out VisContext.
7432 void FreeVisContext();
7434 /// AddCFAuditedAttribute - Check whether we're currently within
7435 /// '\#pragma clang arc_cf_code_audited' and, if so, consider adding
7436 /// the appropriate attribute.
7437 void AddCFAuditedAttribute(Decl *D);
7439 /// \brief Called on well formed \#pragma clang optimize.
7440 void ActOnPragmaOptimize(bool On, SourceLocation PragmaLoc);
7442 /// \brief Get the location for the currently active "\#pragma clang optimize
7443 /// off". If this location is invalid, then the state of the pragma is "on".
7444 SourceLocation getOptimizeOffPragmaLocation() const {
7445 return OptimizeOffPragmaLocation;
7448 /// \brief Only called on function definitions; if there is a pragma in scope
7449 /// with the effect of a range-based optnone, consider marking the function
7450 /// with attribute optnone.
7451 void AddRangeBasedOptnone(FunctionDecl *FD);
7453 /// \brief Adds the 'optnone' attribute to the function declaration if there
7454 /// are no conflicts; Loc represents the location causing the 'optnone'
7455 /// attribute to be added (usually because of a pragma).
7456 void AddOptnoneAttributeIfNoConflicts(FunctionDecl *FD, SourceLocation Loc);
7458 /// AddAlignedAttr - Adds an aligned attribute to a particular declaration.
7459 void AddAlignedAttr(SourceRange AttrRange, Decl *D, Expr *E,
7460 unsigned SpellingListIndex, bool IsPackExpansion);
7461 void AddAlignedAttr(SourceRange AttrRange, Decl *D, TypeSourceInfo *T,
7462 unsigned SpellingListIndex, bool IsPackExpansion);
7464 /// AddAssumeAlignedAttr - Adds an assume_aligned attribute to a particular
7466 void AddAssumeAlignedAttr(SourceRange AttrRange, Decl *D, Expr *E, Expr *OE,
7467 unsigned SpellingListIndex);
7469 /// AddAlignValueAttr - Adds an align_value attribute to a particular
7471 void AddAlignValueAttr(SourceRange AttrRange, Decl *D, Expr *E,
7472 unsigned SpellingListIndex);
7474 // OpenMP directives and clauses.
7476 void *VarDataSharingAttributesStack;
7477 /// \brief Initialization of data-sharing attributes stack.
7478 void InitDataSharingAttributesStack();
7479 void DestroyDataSharingAttributesStack();
7480 ExprResult VerifyPositiveIntegerConstantInClause(Expr *Op,
7481 OpenMPClauseKind CKind);
7482 /// \brief Checks if the specified variable is used in one of the private
7483 /// clauses in OpenMP constructs.
7484 bool IsOpenMPCapturedVar(VarDecl *VD);
7487 ExprResult PerformOpenMPImplicitIntegerConversion(SourceLocation OpLoc,
7489 /// \brief Called on start of new data sharing attribute block.
7490 void StartOpenMPDSABlock(OpenMPDirectiveKind K,
7491 const DeclarationNameInfo &DirName, Scope *CurScope,
7492 SourceLocation Loc);
7493 /// \brief Called on end of data sharing attribute block.
7494 void EndOpenMPDSABlock(Stmt *CurDirective);
7496 // OpenMP directives and clauses.
7497 /// \brief Called on correct id-expression from the '#pragma omp
7499 ExprResult ActOnOpenMPIdExpression(Scope *CurScope,
7500 CXXScopeSpec &ScopeSpec,
7501 const DeclarationNameInfo &Id);
7502 /// \brief Called on well-formed '#pragma omp threadprivate'.
7503 DeclGroupPtrTy ActOnOpenMPThreadprivateDirective(
7505 ArrayRef<Expr *> VarList);
7506 /// \brief Builds a new OpenMPThreadPrivateDecl and checks its correctness.
7507 OMPThreadPrivateDecl *CheckOMPThreadPrivateDecl(
7509 ArrayRef<Expr *> VarList);
7511 /// \brief Initialization of captured region for OpenMP region.
7512 void ActOnOpenMPRegionStart(OpenMPDirectiveKind DKind, Scope *CurScope);
7513 StmtResult ActOnOpenMPExecutableDirective(OpenMPDirectiveKind Kind,
7514 const DeclarationNameInfo &DirName,
7515 ArrayRef<OMPClause *> Clauses,
7517 SourceLocation StartLoc,
7518 SourceLocation EndLoc);
7519 /// \brief Called on well-formed '\#pragma omp parallel' after parsing
7520 /// of the associated statement.
7521 StmtResult ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses,
7523 SourceLocation StartLoc,
7524 SourceLocation EndLoc);
7525 /// \brief Called on well-formed '\#pragma omp simd' after parsing
7526 /// of the associated statement.
7527 StmtResult ActOnOpenMPSimdDirective(
7528 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7529 SourceLocation EndLoc,
7530 llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA);
7531 /// \brief Called on well-formed '\#pragma omp for' after parsing
7532 /// of the associated statement.
7533 StmtResult ActOnOpenMPForDirective(
7534 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7535 SourceLocation EndLoc,
7536 llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA);
7537 /// \brief Called on well-formed '\#pragma omp for simd' after parsing
7538 /// of the associated statement.
7539 StmtResult ActOnOpenMPForSimdDirective(
7540 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7541 SourceLocation EndLoc,
7542 llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA);
7543 /// \brief Called on well-formed '\#pragma omp sections' after parsing
7544 /// of the associated statement.
7545 StmtResult ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses,
7546 Stmt *AStmt, SourceLocation StartLoc,
7547 SourceLocation EndLoc);
7548 /// \brief Called on well-formed '\#pragma omp section' after parsing of the
7549 /// associated statement.
7550 StmtResult ActOnOpenMPSectionDirective(Stmt *AStmt, SourceLocation StartLoc,
7551 SourceLocation EndLoc);
7552 /// \brief Called on well-formed '\#pragma omp single' after parsing of the
7553 /// associated statement.
7554 StmtResult ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses,
7555 Stmt *AStmt, SourceLocation StartLoc,
7556 SourceLocation EndLoc);
7557 /// \brief Called on well-formed '\#pragma omp master' after parsing of the
7558 /// associated statement.
7559 StmtResult ActOnOpenMPMasterDirective(Stmt *AStmt, SourceLocation StartLoc,
7560 SourceLocation EndLoc);
7561 /// \brief Called on well-formed '\#pragma omp critical' after parsing of the
7562 /// associated statement.
7563 StmtResult ActOnOpenMPCriticalDirective(const DeclarationNameInfo &DirName,
7564 Stmt *AStmt, SourceLocation StartLoc,
7565 SourceLocation EndLoc);
7566 /// \brief Called on well-formed '\#pragma omp parallel for' after parsing
7567 /// of the associated statement.
7568 StmtResult ActOnOpenMPParallelForDirective(
7569 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7570 SourceLocation EndLoc,
7571 llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA);
7572 /// \brief Called on well-formed '\#pragma omp parallel for simd' after
7573 /// parsing of the associated statement.
7574 StmtResult ActOnOpenMPParallelForSimdDirective(
7575 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7576 SourceLocation EndLoc,
7577 llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA);
7578 /// \brief Called on well-formed '\#pragma omp parallel sections' after
7579 /// parsing of the associated statement.
7580 StmtResult ActOnOpenMPParallelSectionsDirective(ArrayRef<OMPClause *> Clauses,
7582 SourceLocation StartLoc,
7583 SourceLocation EndLoc);
7584 /// \brief Called on well-formed '\#pragma omp task' after parsing of the
7585 /// associated statement.
7586 StmtResult ActOnOpenMPTaskDirective(ArrayRef<OMPClause *> Clauses,
7587 Stmt *AStmt, SourceLocation StartLoc,
7588 SourceLocation EndLoc);
7589 /// \brief Called on well-formed '\#pragma omp taskyield'.
7590 StmtResult ActOnOpenMPTaskyieldDirective(SourceLocation StartLoc,
7591 SourceLocation EndLoc);
7592 /// \brief Called on well-formed '\#pragma omp barrier'.
7593 StmtResult ActOnOpenMPBarrierDirective(SourceLocation StartLoc,
7594 SourceLocation EndLoc);
7595 /// \brief Called on well-formed '\#pragma omp taskwait'.
7596 StmtResult ActOnOpenMPTaskwaitDirective(SourceLocation StartLoc,
7597 SourceLocation EndLoc);
7598 /// \brief Called on well-formed '\#pragma omp flush'.
7599 StmtResult ActOnOpenMPFlushDirective(ArrayRef<OMPClause *> Clauses,
7600 SourceLocation StartLoc,
7601 SourceLocation EndLoc);
7602 /// \brief Called on well-formed '\#pragma omp ordered' after parsing of the
7603 /// associated statement.
7604 StmtResult ActOnOpenMPOrderedDirective(Stmt *AStmt, SourceLocation StartLoc,
7605 SourceLocation EndLoc);
7606 /// \brief Called on well-formed '\#pragma omp atomic' after parsing of the
7607 /// associated statement.
7608 StmtResult ActOnOpenMPAtomicDirective(ArrayRef<OMPClause *> Clauses,
7609 Stmt *AStmt, SourceLocation StartLoc,
7610 SourceLocation EndLoc);
7611 /// \brief Called on well-formed '\#pragma omp target' after parsing of the
7612 /// associated statement.
7613 StmtResult ActOnOpenMPTargetDirective(ArrayRef<OMPClause *> Clauses,
7614 Stmt *AStmt, SourceLocation StartLoc,
7615 SourceLocation EndLoc);
7616 /// \brief Called on well-formed '\#pragma omp teams' after parsing of the
7617 /// associated statement.
7618 StmtResult ActOnOpenMPTeamsDirective(ArrayRef<OMPClause *> Clauses,
7619 Stmt *AStmt, SourceLocation StartLoc,
7620 SourceLocation EndLoc);
7622 OMPClause *ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind,
7624 SourceLocation StartLoc,
7625 SourceLocation LParenLoc,
7626 SourceLocation EndLoc);
7627 /// \brief Called on well-formed 'if' clause.
7628 OMPClause *ActOnOpenMPIfClause(Expr *Condition, SourceLocation StartLoc,
7629 SourceLocation LParenLoc,
7630 SourceLocation EndLoc);
7631 /// \brief Called on well-formed 'final' clause.
7632 OMPClause *ActOnOpenMPFinalClause(Expr *Condition, SourceLocation StartLoc,
7633 SourceLocation LParenLoc,
7634 SourceLocation EndLoc);
7635 /// \brief Called on well-formed 'num_threads' clause.
7636 OMPClause *ActOnOpenMPNumThreadsClause(Expr *NumThreads,
7637 SourceLocation StartLoc,
7638 SourceLocation LParenLoc,
7639 SourceLocation EndLoc);
7640 /// \brief Called on well-formed 'safelen' clause.
7641 OMPClause *ActOnOpenMPSafelenClause(Expr *Length,
7642 SourceLocation StartLoc,
7643 SourceLocation LParenLoc,
7644 SourceLocation EndLoc);
7645 /// \brief Called on well-formed 'collapse' clause.
7646 OMPClause *ActOnOpenMPCollapseClause(Expr *NumForLoops,
7647 SourceLocation StartLoc,
7648 SourceLocation LParenLoc,
7649 SourceLocation EndLoc);
7651 OMPClause *ActOnOpenMPSimpleClause(OpenMPClauseKind Kind,
7653 SourceLocation ArgumentLoc,
7654 SourceLocation StartLoc,
7655 SourceLocation LParenLoc,
7656 SourceLocation EndLoc);
7657 /// \brief Called on well-formed 'default' clause.
7658 OMPClause *ActOnOpenMPDefaultClause(OpenMPDefaultClauseKind Kind,
7659 SourceLocation KindLoc,
7660 SourceLocation StartLoc,
7661 SourceLocation LParenLoc,
7662 SourceLocation EndLoc);
7663 /// \brief Called on well-formed 'proc_bind' clause.
7664 OMPClause *ActOnOpenMPProcBindClause(OpenMPProcBindClauseKind Kind,
7665 SourceLocation KindLoc,
7666 SourceLocation StartLoc,
7667 SourceLocation LParenLoc,
7668 SourceLocation EndLoc);
7670 OMPClause *ActOnOpenMPSingleExprWithArgClause(OpenMPClauseKind Kind,
7671 unsigned Argument, Expr *Expr,
7672 SourceLocation StartLoc,
7673 SourceLocation LParenLoc,
7674 SourceLocation ArgumentLoc,
7675 SourceLocation CommaLoc,
7676 SourceLocation EndLoc);
7677 /// \brief Called on well-formed 'schedule' clause.
7678 OMPClause *ActOnOpenMPScheduleClause(OpenMPScheduleClauseKind Kind,
7679 Expr *ChunkSize, SourceLocation StartLoc,
7680 SourceLocation LParenLoc,
7681 SourceLocation KindLoc,
7682 SourceLocation CommaLoc,
7683 SourceLocation EndLoc);
7685 OMPClause *ActOnOpenMPClause(OpenMPClauseKind Kind, SourceLocation StartLoc,
7686 SourceLocation EndLoc);
7687 /// \brief Called on well-formed 'ordered' clause.
7688 OMPClause *ActOnOpenMPOrderedClause(SourceLocation StartLoc,
7689 SourceLocation EndLoc);
7690 /// \brief Called on well-formed 'nowait' clause.
7691 OMPClause *ActOnOpenMPNowaitClause(SourceLocation StartLoc,
7692 SourceLocation EndLoc);
7693 /// \brief Called on well-formed 'untied' clause.
7694 OMPClause *ActOnOpenMPUntiedClause(SourceLocation StartLoc,
7695 SourceLocation EndLoc);
7696 /// \brief Called on well-formed 'mergeable' clause.
7697 OMPClause *ActOnOpenMPMergeableClause(SourceLocation StartLoc,
7698 SourceLocation EndLoc);
7699 /// \brief Called on well-formed 'read' clause.
7700 OMPClause *ActOnOpenMPReadClause(SourceLocation StartLoc,
7701 SourceLocation EndLoc);
7702 /// \brief Called on well-formed 'write' clause.
7703 OMPClause *ActOnOpenMPWriteClause(SourceLocation StartLoc,
7704 SourceLocation EndLoc);
7705 /// \brief Called on well-formed 'update' clause.
7706 OMPClause *ActOnOpenMPUpdateClause(SourceLocation StartLoc,
7707 SourceLocation EndLoc);
7708 /// \brief Called on well-formed 'capture' clause.
7709 OMPClause *ActOnOpenMPCaptureClause(SourceLocation StartLoc,
7710 SourceLocation EndLoc);
7711 /// \brief Called on well-formed 'seq_cst' clause.
7712 OMPClause *ActOnOpenMPSeqCstClause(SourceLocation StartLoc,
7713 SourceLocation EndLoc);
7716 ActOnOpenMPVarListClause(OpenMPClauseKind Kind, ArrayRef<Expr *> Vars,
7717 Expr *TailExpr, SourceLocation StartLoc,
7718 SourceLocation LParenLoc, SourceLocation ColonLoc,
7719 SourceLocation EndLoc,
7720 CXXScopeSpec &ReductionIdScopeSpec,
7721 const DeclarationNameInfo &ReductionId);
7722 /// \brief Called on well-formed 'private' clause.
7723 OMPClause *ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList,
7724 SourceLocation StartLoc,
7725 SourceLocation LParenLoc,
7726 SourceLocation EndLoc);
7727 /// \brief Called on well-formed 'firstprivate' clause.
7728 OMPClause *ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList,
7729 SourceLocation StartLoc,
7730 SourceLocation LParenLoc,
7731 SourceLocation EndLoc);
7732 /// \brief Called on well-formed 'lastprivate' clause.
7733 OMPClause *ActOnOpenMPLastprivateClause(ArrayRef<Expr *> VarList,
7734 SourceLocation StartLoc,
7735 SourceLocation LParenLoc,
7736 SourceLocation EndLoc);
7737 /// \brief Called on well-formed 'shared' clause.
7738 OMPClause *ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList,
7739 SourceLocation StartLoc,
7740 SourceLocation LParenLoc,
7741 SourceLocation EndLoc);
7742 /// \brief Called on well-formed 'reduction' clause.
7744 ActOnOpenMPReductionClause(ArrayRef<Expr *> VarList, SourceLocation StartLoc,
7745 SourceLocation LParenLoc, SourceLocation ColonLoc,
7746 SourceLocation EndLoc,
7747 CXXScopeSpec &ReductionIdScopeSpec,
7748 const DeclarationNameInfo &ReductionId);
7749 /// \brief Called on well-formed 'linear' clause.
7750 OMPClause *ActOnOpenMPLinearClause(ArrayRef<Expr *> VarList,
7752 SourceLocation StartLoc,
7753 SourceLocation LParenLoc,
7754 SourceLocation ColonLoc,
7755 SourceLocation EndLoc);
7756 /// \brief Called on well-formed 'aligned' clause.
7757 OMPClause *ActOnOpenMPAlignedClause(ArrayRef<Expr *> VarList,
7759 SourceLocation StartLoc,
7760 SourceLocation LParenLoc,
7761 SourceLocation ColonLoc,
7762 SourceLocation EndLoc);
7763 /// \brief Called on well-formed 'copyin' clause.
7764 OMPClause *ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList,
7765 SourceLocation StartLoc,
7766 SourceLocation LParenLoc,
7767 SourceLocation EndLoc);
7768 /// \brief Called on well-formed 'copyprivate' clause.
7769 OMPClause *ActOnOpenMPCopyprivateClause(ArrayRef<Expr *> VarList,
7770 SourceLocation StartLoc,
7771 SourceLocation LParenLoc,
7772 SourceLocation EndLoc);
7773 /// \brief Called on well-formed 'flush' pseudo clause.
7774 OMPClause *ActOnOpenMPFlushClause(ArrayRef<Expr *> VarList,
7775 SourceLocation StartLoc,
7776 SourceLocation LParenLoc,
7777 SourceLocation EndLoc);
7779 /// \brief The kind of conversion being performed.
7780 enum CheckedConversionKind {
7781 /// \brief An implicit conversion.
7782 CCK_ImplicitConversion,
7783 /// \brief A C-style cast.
7785 /// \brief A functional-style cast.
7787 /// \brief A cast other than a C-style cast.
7791 /// ImpCastExprToType - If Expr is not of type 'Type', insert an implicit
7792 /// cast. If there is already an implicit cast, merge into the existing one.
7793 /// If isLvalue, the result of the cast is an lvalue.
7794 ExprResult ImpCastExprToType(Expr *E, QualType Type, CastKind CK,
7795 ExprValueKind VK = VK_RValue,
7796 const CXXCastPath *BasePath = nullptr,
7797 CheckedConversionKind CCK
7798 = CCK_ImplicitConversion);
7800 /// ScalarTypeToBooleanCastKind - Returns the cast kind corresponding
7801 /// to the conversion from scalar type ScalarTy to the Boolean type.
7802 static CastKind ScalarTypeToBooleanCastKind(QualType ScalarTy);
7804 /// IgnoredValueConversions - Given that an expression's result is
7805 /// syntactically ignored, perform any conversions that are
7807 ExprResult IgnoredValueConversions(Expr *E);
7809 // UsualUnaryConversions - promotes integers (C99 6.3.1.1p2) and converts
7810 // functions and arrays to their respective pointers (C99 6.3.2.1).
7811 ExprResult UsualUnaryConversions(Expr *E);
7813 /// CallExprUnaryConversions - a special case of an unary conversion
7814 /// performed on a function designator of a call expression.
7815 ExprResult CallExprUnaryConversions(Expr *E);
7817 // DefaultFunctionArrayConversion - converts functions and arrays
7818 // to their respective pointers (C99 6.3.2.1).
7819 ExprResult DefaultFunctionArrayConversion(Expr *E);
7821 // DefaultFunctionArrayLvalueConversion - converts functions and
7822 // arrays to their respective pointers and performs the
7823 // lvalue-to-rvalue conversion.
7824 ExprResult DefaultFunctionArrayLvalueConversion(Expr *E);
7826 // DefaultLvalueConversion - performs lvalue-to-rvalue conversion on
7827 // the operand. This is DefaultFunctionArrayLvalueConversion,
7828 // except that it assumes the operand isn't of function or array
7830 ExprResult DefaultLvalueConversion(Expr *E);
7832 // DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
7833 // do not have a prototype. Integer promotions are performed on each
7834 // argument, and arguments that have type float are promoted to double.
7835 ExprResult DefaultArgumentPromotion(Expr *E);
7837 // Used for emitting the right warning by DefaultVariadicArgumentPromotion
7838 enum VariadicCallType {
7842 VariadicConstructor,
7843 VariadicDoesNotApply
7846 VariadicCallType getVariadicCallType(FunctionDecl *FDecl,
7847 const FunctionProtoType *Proto,
7850 // Used for determining in which context a type is allowed to be passed to a
7860 // Determines which VarArgKind fits an expression.
7861 VarArgKind isValidVarArgType(const QualType &Ty);
7863 /// Check to see if the given expression is a valid argument to a variadic
7864 /// function, issuing a diagnostic if not.
7865 void checkVariadicArgument(const Expr *E, VariadicCallType CT);
7867 /// Check to see if a given expression could have '.c_str()' called on it.
7868 bool hasCStrMethod(const Expr *E);
7870 /// GatherArgumentsForCall - Collector argument expressions for various
7871 /// form of call prototypes.
7872 bool GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl,
7873 const FunctionProtoType *Proto,
7874 unsigned FirstParam, ArrayRef<Expr *> Args,
7875 SmallVectorImpl<Expr *> &AllArgs,
7876 VariadicCallType CallType = VariadicDoesNotApply,
7877 bool AllowExplicit = false,
7878 bool IsListInitialization = false);
7880 // DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
7881 // will create a runtime trap if the resulting type is not a POD type.
7882 ExprResult DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
7883 FunctionDecl *FDecl);
7885 // UsualArithmeticConversions - performs the UsualUnaryConversions on it's
7886 // operands and then handles various conversions that are common to binary
7887 // operators (C99 6.3.1.8). If both operands aren't arithmetic, this
7888 // routine returns the first non-arithmetic type found. The client is
7889 // responsible for emitting appropriate error diagnostics.
7890 QualType UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
7891 bool IsCompAssign = false);
7893 /// AssignConvertType - All of the 'assignment' semantic checks return this
7894 /// enum to indicate whether the assignment was allowed. These checks are
7895 /// done for simple assignments, as well as initialization, return from
7896 /// function, argument passing, etc. The query is phrased in terms of a
7897 /// source and destination type.
7898 enum AssignConvertType {
7899 /// Compatible - the types are compatible according to the standard.
7902 /// PointerToInt - The assignment converts a pointer to an int, which we
7903 /// accept as an extension.
7906 /// IntToPointer - The assignment converts an int to a pointer, which we
7907 /// accept as an extension.
7910 /// FunctionVoidPointer - The assignment is between a function pointer and
7911 /// void*, which the standard doesn't allow, but we accept as an extension.
7912 FunctionVoidPointer,
7914 /// IncompatiblePointer - The assignment is between two pointers types that
7915 /// are not compatible, but we accept them as an extension.
7916 IncompatiblePointer,
7918 /// IncompatiblePointer - The assignment is between two pointers types which
7919 /// point to integers which have a different sign, but are otherwise
7920 /// identical. This is a subset of the above, but broken out because it's by
7921 /// far the most common case of incompatible pointers.
7922 IncompatiblePointerSign,
7924 /// CompatiblePointerDiscardsQualifiers - The assignment discards
7925 /// c/v/r qualifiers, which we accept as an extension.
7926 CompatiblePointerDiscardsQualifiers,
7928 /// IncompatiblePointerDiscardsQualifiers - The assignment
7929 /// discards qualifiers that we don't permit to be discarded,
7930 /// like address spaces.
7931 IncompatiblePointerDiscardsQualifiers,
7933 /// IncompatibleNestedPointerQualifiers - The assignment is between two
7934 /// nested pointer types, and the qualifiers other than the first two
7935 /// levels differ e.g. char ** -> const char **, but we accept them as an
7937 IncompatibleNestedPointerQualifiers,
7939 /// IncompatibleVectors - The assignment is between two vector types that
7940 /// have the same size, which we accept as an extension.
7941 IncompatibleVectors,
7943 /// IntToBlockPointer - The assignment converts an int to a block
7944 /// pointer. We disallow this.
7947 /// IncompatibleBlockPointer - The assignment is between two block
7948 /// pointers types that are not compatible.
7949 IncompatibleBlockPointer,
7951 /// IncompatibleObjCQualifiedId - The assignment is between a qualified
7952 /// id type and something else (that is incompatible with it). For example,
7953 /// "id <XXX>" = "Foo *", where "Foo *" doesn't implement the XXX protocol.
7954 IncompatibleObjCQualifiedId,
7956 /// IncompatibleObjCWeakRef - Assigning a weak-unavailable object to an
7957 /// object with __weak qualifier.
7958 IncompatibleObjCWeakRef,
7960 /// Incompatible - We reject this conversion outright, it is invalid to
7961 /// represent it in the AST.
7965 /// DiagnoseAssignmentResult - Emit a diagnostic, if required, for the
7966 /// assignment conversion type specified by ConvTy. This returns true if the
7967 /// conversion was invalid or false if the conversion was accepted.
7968 bool DiagnoseAssignmentResult(AssignConvertType ConvTy,
7970 QualType DstType, QualType SrcType,
7971 Expr *SrcExpr, AssignmentAction Action,
7972 bool *Complained = nullptr);
7974 /// DiagnoseAssignmentEnum - Warn if assignment to enum is a constant
7975 /// integer not in the range of enum values.
7976 void DiagnoseAssignmentEnum(QualType DstType, QualType SrcType,
7979 /// CheckAssignmentConstraints - Perform type checking for assignment,
7980 /// argument passing, variable initialization, and function return values.
7982 AssignConvertType CheckAssignmentConstraints(SourceLocation Loc,
7986 /// Check assignment constraints and prepare for a conversion of the
7987 /// RHS to the LHS type.
7988 AssignConvertType CheckAssignmentConstraints(QualType LHSType,
7992 // CheckSingleAssignmentConstraints - Currently used by
7993 // CheckAssignmentOperands, and ActOnReturnStmt. Prior to type checking,
7994 // this routine performs the default function/array converions.
7995 AssignConvertType CheckSingleAssignmentConstraints(QualType LHSType,
7997 bool Diagnose = true,
7998 bool DiagnoseCFAudited = false);
8000 // \brief If the lhs type is a transparent union, check whether we
8001 // can initialize the transparent union with the given expression.
8002 AssignConvertType CheckTransparentUnionArgumentConstraints(QualType ArgType,
8005 bool IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType);
8007 bool CheckExceptionSpecCompatibility(Expr *From, QualType ToType);
8009 ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
8010 AssignmentAction Action,
8011 bool AllowExplicit = false);
8012 ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
8013 AssignmentAction Action,
8015 ImplicitConversionSequence& ICS);
8016 ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
8017 const ImplicitConversionSequence& ICS,
8018 AssignmentAction Action,
8019 CheckedConversionKind CCK
8020 = CCK_ImplicitConversion);
8021 ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
8022 const StandardConversionSequence& SCS,
8023 AssignmentAction Action,
8024 CheckedConversionKind CCK);
8026 /// the following "Check" methods will return a valid/converted QualType
8027 /// or a null QualType (indicating an error diagnostic was issued).
8029 /// type checking binary operators (subroutines of CreateBuiltinBinOp).
8030 QualType InvalidOperands(SourceLocation Loc, ExprResult &LHS,
8032 QualType CheckPointerToMemberOperands( // C++ 5.5
8033 ExprResult &LHS, ExprResult &RHS, ExprValueKind &VK,
8034 SourceLocation OpLoc, bool isIndirect);
8035 QualType CheckMultiplyDivideOperands( // C99 6.5.5
8036 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign,
8038 QualType CheckRemainderOperands( // C99 6.5.5
8039 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
8040 bool IsCompAssign = false);
8041 QualType CheckAdditionOperands( // C99 6.5.6
8042 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc,
8043 QualType* CompLHSTy = nullptr);
8044 QualType CheckSubtractionOperands( // C99 6.5.6
8045 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
8046 QualType* CompLHSTy = nullptr);
8047 QualType CheckShiftOperands( // C99 6.5.7
8048 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc,
8049 bool IsCompAssign = false);
8050 QualType CheckCompareOperands( // C99 6.5.8/9
8051 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned OpaqueOpc,
8053 QualType CheckBitwiseOperands( // C99 6.5.[10...12]
8054 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
8055 bool IsCompAssign = false);
8056 QualType CheckLogicalOperands( // C99 6.5.[13,14]
8057 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc);
8058 // CheckAssignmentOperands is used for both simple and compound assignment.
8059 // For simple assignment, pass both expressions and a null converted type.
8060 // For compound assignment, pass both expressions and the converted type.
8061 QualType CheckAssignmentOperands( // C99 6.5.16.[1,2]
8062 Expr *LHSExpr, ExprResult &RHS, SourceLocation Loc, QualType CompoundType);
8064 ExprResult checkPseudoObjectIncDec(Scope *S, SourceLocation OpLoc,
8065 UnaryOperatorKind Opcode, Expr *Op);
8066 ExprResult checkPseudoObjectAssignment(Scope *S, SourceLocation OpLoc,
8067 BinaryOperatorKind Opcode,
8068 Expr *LHS, Expr *RHS);
8069 ExprResult checkPseudoObjectRValue(Expr *E);
8070 Expr *recreateSyntacticForm(PseudoObjectExpr *E);
8072 QualType CheckConditionalOperands( // C99 6.5.15
8073 ExprResult &Cond, ExprResult &LHS, ExprResult &RHS,
8074 ExprValueKind &VK, ExprObjectKind &OK, SourceLocation QuestionLoc);
8075 QualType CXXCheckConditionalOperands( // C++ 5.16
8076 ExprResult &cond, ExprResult &lhs, ExprResult &rhs,
8077 ExprValueKind &VK, ExprObjectKind &OK, SourceLocation questionLoc);
8078 QualType FindCompositePointerType(SourceLocation Loc, Expr *&E1, Expr *&E2,
8079 bool *NonStandardCompositeType = nullptr);
8080 QualType FindCompositePointerType(SourceLocation Loc,
8081 ExprResult &E1, ExprResult &E2,
8082 bool *NonStandardCompositeType = nullptr) {
8083 Expr *E1Tmp = E1.get(), *E2Tmp = E2.get();
8084 QualType Composite = FindCompositePointerType(Loc, E1Tmp, E2Tmp,
8085 NonStandardCompositeType);
8091 QualType FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
8092 SourceLocation QuestionLoc);
8094 bool DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
8095 SourceLocation QuestionLoc);
8097 void DiagnoseAlwaysNonNullPointer(Expr *E,
8098 Expr::NullPointerConstantKind NullType,
8099 bool IsEqual, SourceRange Range);
8101 /// type checking for vector binary operators.
8102 QualType CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
8103 SourceLocation Loc, bool IsCompAssign);
8104 QualType GetSignedVectorType(QualType V);
8105 QualType CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
8106 SourceLocation Loc, bool isRelational);
8107 QualType CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
8108 SourceLocation Loc);
8110 bool isLaxVectorConversion(QualType srcType, QualType destType);
8112 /// type checking declaration initializers (C99 6.7.8)
8113 bool CheckForConstantInitializer(Expr *e, QualType t);
8115 // type checking C++ declaration initializers (C++ [dcl.init]).
8117 /// ReferenceCompareResult - Expresses the result of comparing two
8118 /// types (cv1 T1 and cv2 T2) to determine their compatibility for the
8119 /// purposes of initialization by reference (C++ [dcl.init.ref]p4).
8120 enum ReferenceCompareResult {
8121 /// Ref_Incompatible - The two types are incompatible, so direct
8122 /// reference binding is not possible.
8123 Ref_Incompatible = 0,
8124 /// Ref_Related - The two types are reference-related, which means
8125 /// that their unqualified forms (T1 and T2) are either the same
8126 /// or T1 is a base class of T2.
8128 /// Ref_Compatible_With_Added_Qualification - The two types are
8129 /// reference-compatible with added qualification, meaning that
8130 /// they are reference-compatible and the qualifiers on T1 (cv1)
8131 /// are greater than the qualifiers on T2 (cv2).
8132 Ref_Compatible_With_Added_Qualification,
8133 /// Ref_Compatible - The two types are reference-compatible and
8134 /// have equivalent qualifiers (cv1 == cv2).
8138 ReferenceCompareResult CompareReferenceRelationship(SourceLocation Loc,
8139 QualType T1, QualType T2,
8140 bool &DerivedToBase,
8141 bool &ObjCConversion,
8142 bool &ObjCLifetimeConversion);
8144 ExprResult checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
8145 Expr *CastExpr, CastKind &CastKind,
8146 ExprValueKind &VK, CXXCastPath &Path);
8148 /// \brief Force an expression with unknown-type to an expression of the
8150 ExprResult forceUnknownAnyToType(Expr *E, QualType ToType);
8152 /// \brief Type-check an expression that's being passed to an
8153 /// __unknown_anytype parameter.
8154 ExprResult checkUnknownAnyArg(SourceLocation callLoc,
8155 Expr *result, QualType ¶mType);
8157 // CheckVectorCast - check type constraints for vectors.
8158 // Since vectors are an extension, there are no C standard reference for this.
8159 // We allow casting between vectors and integer datatypes of the same size.
8160 // returns true if the cast is invalid
8161 bool CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
8164 // CheckExtVectorCast - check type constraints for extended vectors.
8165 // Since vectors are an extension, there are no C standard reference for this.
8166 // We allow casting between vectors and integer datatypes of the same size,
8167 // or vectors and the element type of that vector.
8168 // returns the cast expr
8169 ExprResult CheckExtVectorCast(SourceRange R, QualType DestTy, Expr *CastExpr,
8172 ExprResult BuildCXXFunctionalCastExpr(TypeSourceInfo *TInfo,
8173 SourceLocation LParenLoc,
8175 SourceLocation RParenLoc);
8177 enum ARCConversionResult { ACR_okay, ACR_unbridged };
8179 /// \brief Checks for invalid conversions and casts between
8180 /// retainable pointers and other pointer kinds.
8181 ARCConversionResult CheckObjCARCConversion(SourceRange castRange,
8182 QualType castType, Expr *&op,
8183 CheckedConversionKind CCK,
8184 bool DiagnoseCFAudited = false,
8185 BinaryOperatorKind Opc = BO_PtrMemD
8188 Expr *stripARCUnbridgedCast(Expr *e);
8189 void diagnoseARCUnbridgedCast(Expr *e);
8191 bool CheckObjCARCUnavailableWeakConversion(QualType castType,
8194 /// checkRetainCycles - Check whether an Objective-C message send
8195 /// might create an obvious retain cycle.
8196 void checkRetainCycles(ObjCMessageExpr *msg);
8197 void checkRetainCycles(Expr *receiver, Expr *argument);
8198 void checkRetainCycles(VarDecl *Var, Expr *Init);
8200 /// checkUnsafeAssigns - Check whether +1 expr is being assigned
8201 /// to weak/__unsafe_unretained type.
8202 bool checkUnsafeAssigns(SourceLocation Loc, QualType LHS, Expr *RHS);
8204 /// checkUnsafeExprAssigns - Check whether +1 expr is being assigned
8205 /// to weak/__unsafe_unretained expression.
8206 void checkUnsafeExprAssigns(SourceLocation Loc, Expr *LHS, Expr *RHS);
8208 /// CheckMessageArgumentTypes - Check types in an Obj-C message send.
8209 /// \param Method - May be null.
8210 /// \param [out] ReturnType - The return type of the send.
8211 /// \return true iff there were any incompatible types.
8212 bool CheckMessageArgumentTypes(QualType ReceiverType,
8213 MultiExprArg Args, Selector Sel,
8214 ArrayRef<SourceLocation> SelectorLocs,
8215 ObjCMethodDecl *Method, bool isClassMessage,
8216 bool isSuperMessage,
8217 SourceLocation lbrac, SourceLocation rbrac,
8218 SourceRange RecRange,
8219 QualType &ReturnType, ExprValueKind &VK);
8221 /// \brief Determine the result of a message send expression based on
8222 /// the type of the receiver, the method expected to receive the message,
8223 /// and the form of the message send.
8224 QualType getMessageSendResultType(QualType ReceiverType,
8225 ObjCMethodDecl *Method,
8226 bool isClassMessage, bool isSuperMessage);
8228 /// \brief If the given expression involves a message send to a method
8229 /// with a related result type, emit a note describing what happened.
8230 void EmitRelatedResultTypeNote(const Expr *E);
8232 /// \brief Given that we had incompatible pointer types in a return
8233 /// statement, check whether we're in a method with a related result
8234 /// type, and if so, emit a note describing what happened.
8235 void EmitRelatedResultTypeNoteForReturn(QualType destType);
8237 /// CheckBooleanCondition - Diagnose problems involving the use of
8238 /// the given expression as a boolean condition (e.g. in an if
8239 /// statement). Also performs the standard function and array
8240 /// decays, possibly changing the input variable.
8242 /// \param Loc - A location associated with the condition, e.g. the
8244 /// \return true iff there were any errors
8245 ExprResult CheckBooleanCondition(Expr *E, SourceLocation Loc);
8247 ExprResult ActOnBooleanCondition(Scope *S, SourceLocation Loc,
8250 /// DiagnoseAssignmentAsCondition - Given that an expression is
8251 /// being used as a boolean condition, warn if it's an assignment.
8252 void DiagnoseAssignmentAsCondition(Expr *E);
8254 /// \brief Redundant parentheses over an equality comparison can indicate
8255 /// that the user intended an assignment used as condition.
8256 void DiagnoseEqualityWithExtraParens(ParenExpr *ParenE);
8258 /// CheckCXXBooleanCondition - Returns true if conversion to bool is invalid.
8259 ExprResult CheckCXXBooleanCondition(Expr *CondExpr);
8261 /// ConvertIntegerToTypeWarnOnOverflow - Convert the specified APInt to have
8262 /// the specified width and sign. If an overflow occurs, detect it and emit
8263 /// the specified diagnostic.
8264 void ConvertIntegerToTypeWarnOnOverflow(llvm::APSInt &OldVal,
8265 unsigned NewWidth, bool NewSign,
8266 SourceLocation Loc, unsigned DiagID);
8268 /// Checks that the Objective-C declaration is declared in the global scope.
8269 /// Emits an error and marks the declaration as invalid if it's not declared
8270 /// in the global scope.
8271 bool CheckObjCDeclScope(Decl *D);
8273 /// \brief Abstract base class used for diagnosing integer constant
8274 /// expression violations.
8275 class VerifyICEDiagnoser {
8279 VerifyICEDiagnoser(bool Suppress = false) : Suppress(Suppress) { }
8281 virtual void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) =0;
8282 virtual void diagnoseFold(Sema &S, SourceLocation Loc, SourceRange SR);
8283 virtual ~VerifyICEDiagnoser() { }
8286 /// VerifyIntegerConstantExpression - Verifies that an expression is an ICE,
8287 /// and reports the appropriate diagnostics. Returns false on success.
8288 /// Can optionally return the value of the expression.
8289 ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
8290 VerifyICEDiagnoser &Diagnoser,
8291 bool AllowFold = true);
8292 ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
8294 bool AllowFold = true);
8295 ExprResult VerifyIntegerConstantExpression(Expr *E,
8296 llvm::APSInt *Result = nullptr);
8298 /// VerifyBitField - verifies that a bit field expression is an ICE and has
8299 /// the correct width, and that the field type is valid.
8300 /// Returns false on success.
8301 /// Can optionally return whether the bit-field is of width 0
8302 ExprResult VerifyBitField(SourceLocation FieldLoc, IdentifierInfo *FieldName,
8303 QualType FieldTy, bool IsMsStruct,
8304 Expr *BitWidth, bool *ZeroWidth = nullptr);
8306 enum CUDAFunctionTarget {
8314 CUDAFunctionTarget IdentifyCUDATarget(const FunctionDecl *D);
8316 bool CheckCUDATarget(const FunctionDecl *Caller, const FunctionDecl *Callee);
8318 /// Given a implicit special member, infer its CUDA target from the
8319 /// calls it needs to make to underlying base/field special members.
8320 /// \param ClassDecl the class for which the member is being created.
8321 /// \param CSM the kind of special member.
8322 /// \param MemberDecl the special member itself.
8323 /// \param ConstRHS true if this is a copy operation with a const object on
8325 /// \param Diagnose true if this call should emit diagnostics.
8326 /// \return true if there was an error inferring.
8327 /// The result of this call is implicit CUDA target attribute(s) attached to
8328 /// the member declaration.
8329 bool inferCUDATargetForImplicitSpecialMember(CXXRecordDecl *ClassDecl,
8330 CXXSpecialMember CSM,
8331 CXXMethodDecl *MemberDecl,
8335 /// \name Code completion
8337 /// \brief Describes the context in which code completion occurs.
8338 enum ParserCompletionContext {
8339 /// \brief Code completion occurs at top-level or namespace context.
8341 /// \brief Code completion occurs within a class, struct, or union.
8343 /// \brief Code completion occurs within an Objective-C interface, protocol,
8346 /// \brief Code completion occurs within an Objective-C implementation or
8347 /// category implementation
8348 PCC_ObjCImplementation,
8349 /// \brief Code completion occurs within the list of instance variables
8350 /// in an Objective-C interface, protocol, category, or implementation.
8351 PCC_ObjCInstanceVariableList,
8352 /// \brief Code completion occurs following one or more template
8355 /// \brief Code completion occurs following one or more template
8356 /// headers within a class.
8358 /// \brief Code completion occurs within an expression.
8360 /// \brief Code completion occurs within a statement, which may
8361 /// also be an expression or a declaration.
8363 /// \brief Code completion occurs at the beginning of the
8364 /// initialization statement (or expression) in a for loop.
8366 /// \brief Code completion occurs within the condition of an if,
8367 /// while, switch, or for statement.
8369 /// \brief Code completion occurs within the body of a function on a
8370 /// recovery path, where we do not have a specific handle on our position
8372 PCC_RecoveryInFunction,
8373 /// \brief Code completion occurs where only a type is permitted.
8375 /// \brief Code completion occurs in a parenthesized expression, which
8376 /// might also be a type cast.
8377 PCC_ParenthesizedExpression,
8378 /// \brief Code completion occurs within a sequence of declaration
8379 /// specifiers within a function, method, or block.
8380 PCC_LocalDeclarationSpecifiers
8383 void CodeCompleteModuleImport(SourceLocation ImportLoc, ModuleIdPath Path);
8384 void CodeCompleteOrdinaryName(Scope *S,
8385 ParserCompletionContext CompletionContext);
8386 void CodeCompleteDeclSpec(Scope *S, DeclSpec &DS,
8387 bool AllowNonIdentifiers,
8388 bool AllowNestedNameSpecifiers);
8390 struct CodeCompleteExpressionData;
8391 void CodeCompleteExpression(Scope *S,
8392 const CodeCompleteExpressionData &Data);
8393 void CodeCompleteMemberReferenceExpr(Scope *S, Expr *Base,
8394 SourceLocation OpLoc,
8396 void CodeCompletePostfixExpression(Scope *S, ExprResult LHS);
8397 void CodeCompleteTag(Scope *S, unsigned TagSpec);
8398 void CodeCompleteTypeQualifiers(DeclSpec &DS);
8399 void CodeCompleteCase(Scope *S);
8400 void CodeCompleteCall(Scope *S, Expr *Fn, ArrayRef<Expr *> Args);
8401 void CodeCompleteInitializer(Scope *S, Decl *D);
8402 void CodeCompleteReturn(Scope *S);
8403 void CodeCompleteAfterIf(Scope *S);
8404 void CodeCompleteAssignmentRHS(Scope *S, Expr *LHS);
8406 void CodeCompleteQualifiedId(Scope *S, CXXScopeSpec &SS,
8407 bool EnteringContext);
8408 void CodeCompleteUsing(Scope *S);
8409 void CodeCompleteUsingDirective(Scope *S);
8410 void CodeCompleteNamespaceDecl(Scope *S);
8411 void CodeCompleteNamespaceAliasDecl(Scope *S);
8412 void CodeCompleteOperatorName(Scope *S);
8413 void CodeCompleteConstructorInitializer(
8415 ArrayRef<CXXCtorInitializer *> Initializers);
8417 void CodeCompleteLambdaIntroducer(Scope *S, LambdaIntroducer &Intro,
8418 bool AfterAmpersand);
8420 void CodeCompleteObjCAtDirective(Scope *S);
8421 void CodeCompleteObjCAtVisibility(Scope *S);
8422 void CodeCompleteObjCAtStatement(Scope *S);
8423 void CodeCompleteObjCAtExpression(Scope *S);
8424 void CodeCompleteObjCPropertyFlags(Scope *S, ObjCDeclSpec &ODS);
8425 void CodeCompleteObjCPropertyGetter(Scope *S);
8426 void CodeCompleteObjCPropertySetter(Scope *S);
8427 void CodeCompleteObjCPassingType(Scope *S, ObjCDeclSpec &DS,
8429 void CodeCompleteObjCMessageReceiver(Scope *S);
8430 void CodeCompleteObjCSuperMessage(Scope *S, SourceLocation SuperLoc,
8431 ArrayRef<IdentifierInfo *> SelIdents,
8432 bool AtArgumentExpression);
8433 void CodeCompleteObjCClassMessage(Scope *S, ParsedType Receiver,
8434 ArrayRef<IdentifierInfo *> SelIdents,
8435 bool AtArgumentExpression,
8436 bool IsSuper = false);
8437 void CodeCompleteObjCInstanceMessage(Scope *S, Expr *Receiver,
8438 ArrayRef<IdentifierInfo *> SelIdents,
8439 bool AtArgumentExpression,
8440 ObjCInterfaceDecl *Super = nullptr);
8441 void CodeCompleteObjCForCollection(Scope *S,
8442 DeclGroupPtrTy IterationVar);
8443 void CodeCompleteObjCSelector(Scope *S,
8444 ArrayRef<IdentifierInfo *> SelIdents);
8445 void CodeCompleteObjCProtocolReferences(IdentifierLocPair *Protocols,
8446 unsigned NumProtocols);
8447 void CodeCompleteObjCProtocolDecl(Scope *S);
8448 void CodeCompleteObjCInterfaceDecl(Scope *S);
8449 void CodeCompleteObjCSuperclass(Scope *S,
8450 IdentifierInfo *ClassName,
8451 SourceLocation ClassNameLoc);
8452 void CodeCompleteObjCImplementationDecl(Scope *S);
8453 void CodeCompleteObjCInterfaceCategory(Scope *S,
8454 IdentifierInfo *ClassName,
8455 SourceLocation ClassNameLoc);
8456 void CodeCompleteObjCImplementationCategory(Scope *S,
8457 IdentifierInfo *ClassName,
8458 SourceLocation ClassNameLoc);
8459 void CodeCompleteObjCPropertyDefinition(Scope *S);
8460 void CodeCompleteObjCPropertySynthesizeIvar(Scope *S,
8461 IdentifierInfo *PropertyName);
8462 void CodeCompleteObjCMethodDecl(Scope *S,
8463 bool IsInstanceMethod,
8464 ParsedType ReturnType);
8465 void CodeCompleteObjCMethodDeclSelector(Scope *S,
8466 bool IsInstanceMethod,
8467 bool AtParameterName,
8468 ParsedType ReturnType,
8469 ArrayRef<IdentifierInfo *> SelIdents);
8470 void CodeCompletePreprocessorDirective(bool InConditional);
8471 void CodeCompleteInPreprocessorConditionalExclusion(Scope *S);
8472 void CodeCompletePreprocessorMacroName(bool IsDefinition);
8473 void CodeCompletePreprocessorExpression();
8474 void CodeCompletePreprocessorMacroArgument(Scope *S,
8475 IdentifierInfo *Macro,
8476 MacroInfo *MacroInfo,
8478 void CodeCompleteNaturalLanguage();
8479 void GatherGlobalCodeCompletions(CodeCompletionAllocator &Allocator,
8480 CodeCompletionTUInfo &CCTUInfo,
8481 SmallVectorImpl<CodeCompletionResult> &Results);
8484 //===--------------------------------------------------------------------===//
8485 // Extra semantic analysis beyond the C type system
8488 SourceLocation getLocationOfStringLiteralByte(const StringLiteral *SL,
8489 unsigned ByteNo) const;
8492 void CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
8493 const ArraySubscriptExpr *ASE=nullptr,
8494 bool AllowOnePastEnd=true, bool IndexNegated=false);
8495 void CheckArrayAccess(const Expr *E);
8496 // Used to grab the relevant information from a FormatAttr and a
8497 // FunctionDeclaration.
8498 struct FormatStringInfo {
8500 unsigned FirstDataArg;
8504 bool getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
8505 FormatStringInfo *FSI);
8506 bool CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
8507 const FunctionProtoType *Proto);
8508 bool CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation loc,
8509 ArrayRef<const Expr *> Args);
8510 bool CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
8511 const FunctionProtoType *Proto);
8512 bool CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto);
8513 void CheckConstructorCall(FunctionDecl *FDecl,
8514 ArrayRef<const Expr *> Args,
8515 const FunctionProtoType *Proto,
8516 SourceLocation Loc);
8518 void checkCall(NamedDecl *FDecl, ArrayRef<const Expr *> Args,
8519 unsigned NumParams, bool IsMemberFunction, SourceLocation Loc,
8520 SourceRange Range, VariadicCallType CallType);
8522 bool CheckObjCString(Expr *Arg);
8524 ExprResult CheckBuiltinFunctionCall(FunctionDecl *FDecl,
8525 unsigned BuiltinID, CallExpr *TheCall);
8527 bool CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
8529 bool CheckNeonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
8530 bool CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
8532 bool CheckAArch64BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
8533 bool CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
8534 bool CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
8536 bool SemaBuiltinVAStart(CallExpr *TheCall);
8537 bool SemaBuiltinVAStartARM(CallExpr *Call);
8538 bool SemaBuiltinUnorderedCompare(CallExpr *TheCall);
8539 bool SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs);
8542 // Used by C++ template instantiation.
8543 ExprResult SemaBuiltinShuffleVector(CallExpr *TheCall);
8544 ExprResult SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
8545 SourceLocation BuiltinLoc,
8546 SourceLocation RParenLoc);
8549 bool SemaBuiltinPrefetch(CallExpr *TheCall);
8550 bool SemaBuiltinAssume(CallExpr *TheCall);
8551 bool SemaBuiltinAssumeAligned(CallExpr *TheCall);
8552 bool SemaBuiltinLongjmp(CallExpr *TheCall);
8553 bool SemaBuiltinSetjmp(CallExpr *TheCall);
8554 ExprResult SemaBuiltinAtomicOverloaded(ExprResult TheCallResult);
8555 ExprResult SemaAtomicOpsOverloaded(ExprResult TheCallResult,
8556 AtomicExpr::AtomicOp Op);
8557 bool SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
8558 llvm::APSInt &Result);
8559 bool SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
8563 enum FormatStringType {
8573 static FormatStringType GetFormatStringType(const FormatAttr *Format);
8575 void CheckFormatString(const StringLiteral *FExpr, const Expr *OrigFormatExpr,
8576 ArrayRef<const Expr *> Args, bool HasVAListArg,
8577 unsigned format_idx, unsigned firstDataArg,
8578 FormatStringType Type, bool inFunctionCall,
8579 VariadicCallType CallType,
8580 llvm::SmallBitVector &CheckedVarArgs);
8582 bool FormatStringHasSArg(const StringLiteral *FExpr);
8584 bool GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx);
8587 bool CheckFormatArguments(const FormatAttr *Format,
8588 ArrayRef<const Expr *> Args,
8590 VariadicCallType CallType,
8591 SourceLocation Loc, SourceRange Range,
8592 llvm::SmallBitVector &CheckedVarArgs);
8593 bool CheckFormatArguments(ArrayRef<const Expr *> Args,
8594 bool HasVAListArg, unsigned format_idx,
8595 unsigned firstDataArg, FormatStringType Type,
8596 VariadicCallType CallType,
8597 SourceLocation Loc, SourceRange range,
8598 llvm::SmallBitVector &CheckedVarArgs);
8600 void CheckAbsoluteValueFunction(const CallExpr *Call,
8601 const FunctionDecl *FDecl,
8602 IdentifierInfo *FnInfo);
8604 void CheckMemaccessArguments(const CallExpr *Call,
8606 IdentifierInfo *FnName);
8608 void CheckStrlcpycatArguments(const CallExpr *Call,
8609 IdentifierInfo *FnName);
8611 void CheckStrncatArguments(const CallExpr *Call,
8612 IdentifierInfo *FnName);
8614 void CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
8615 SourceLocation ReturnLoc,
8616 bool isObjCMethod = false,
8617 const AttrVec *Attrs = nullptr,
8618 const FunctionDecl *FD = nullptr);
8620 void CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr* RHS);
8621 void CheckImplicitConversions(Expr *E, SourceLocation CC = SourceLocation());
8622 void CheckBoolLikeConversion(Expr *E, SourceLocation CC);
8623 void CheckForIntOverflow(Expr *E);
8624 void CheckUnsequencedOperations(Expr *E);
8626 /// \brief Perform semantic checks on a completed expression. This will either
8627 /// be a full-expression or a default argument expression.
8628 void CheckCompletedExpr(Expr *E, SourceLocation CheckLoc = SourceLocation(),
8629 bool IsConstexpr = false);
8631 void CheckBitFieldInitialization(SourceLocation InitLoc, FieldDecl *Field,
8634 /// \brief Check if the given expression contains 'break' or 'continue'
8635 /// statement that produces control flow different from GCC.
8636 void CheckBreakContinueBinding(Expr *E);
8639 /// \brief Register a magic integral constant to be used as a type tag.
8640 void RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
8641 uint64_t MagicValue, QualType Type,
8642 bool LayoutCompatible, bool MustBeNull);
8644 struct TypeTagData {
8647 TypeTagData(QualType Type, bool LayoutCompatible, bool MustBeNull) :
8648 Type(Type), LayoutCompatible(LayoutCompatible),
8649 MustBeNull(MustBeNull)
8654 /// If true, \c Type should be compared with other expression's types for
8655 /// layout-compatibility.
8656 unsigned LayoutCompatible : 1;
8657 unsigned MustBeNull : 1;
8660 /// A pair of ArgumentKind identifier and magic value. This uniquely
8661 /// identifies the magic value.
8662 typedef std::pair<const IdentifierInfo *, uint64_t> TypeTagMagicValue;
8665 /// \brief A map from magic value to type information.
8666 std::unique_ptr<llvm::DenseMap<TypeTagMagicValue, TypeTagData>>
8667 TypeTagForDatatypeMagicValues;
8669 /// \brief Peform checks on a call of a function with argument_with_type_tag
8670 /// or pointer_with_type_tag attributes.
8671 void CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
8672 const Expr * const *ExprArgs);
8674 /// \brief The parser's current scope.
8676 /// The parser maintains this state here.
8679 mutable IdentifierInfo *Ident_super;
8680 mutable IdentifierInfo *Ident___float128;
8683 friend class Parser;
8684 friend class InitializationSequence;
8685 friend class ASTReader;
8686 friend class ASTWriter;
8689 /// \brief Retrieve the parser's current scope.
8691 /// This routine must only be used when it is certain that semantic analysis
8692 /// and the parser are in precisely the same context, which is not the case
8693 /// when, e.g., we are performing any kind of template instantiation.
8694 /// Therefore, the only safe places to use this scope are in the parser
8695 /// itself and in routines directly invoked from the parser and *never* from
8696 /// template substitution or instantiation.
8697 Scope *getCurScope() const { return CurScope; }
8699 void incrementMSLocalManglingNumber() const {
8700 return CurScope->incrementMSLocalManglingNumber();
8703 IdentifierInfo *getSuperIdentifier() const;
8704 IdentifierInfo *getFloat128Identifier() const;
8706 Decl *getObjCDeclContext() const;
8708 DeclContext *getCurLexicalContext() const {
8709 return OriginalLexicalContext ? OriginalLexicalContext : CurContext;
8712 AvailabilityResult getCurContextAvailability() const;
8714 const DeclContext *getCurObjCLexicalContext() const {
8715 const DeclContext *DC = getCurLexicalContext();
8716 // A category implicitly has the attribute of the interface.
8717 if (const ObjCCategoryDecl *CatD = dyn_cast<ObjCCategoryDecl>(DC))
8718 DC = CatD->getClassInterface();
8723 /// \brief RAII object that enters a new expression evaluation context.
8724 class EnterExpressionEvaluationContext {
8728 EnterExpressionEvaluationContext(Sema &Actions,
8729 Sema::ExpressionEvaluationContext NewContext,
8730 Decl *LambdaContextDecl = nullptr,
8731 bool IsDecltype = false)
8732 : Actions(Actions) {
8733 Actions.PushExpressionEvaluationContext(NewContext, LambdaContextDecl,
8736 EnterExpressionEvaluationContext(Sema &Actions,
8737 Sema::ExpressionEvaluationContext NewContext,
8738 Sema::ReuseLambdaContextDecl_t,
8739 bool IsDecltype = false)
8740 : Actions(Actions) {
8741 Actions.PushExpressionEvaluationContext(NewContext,
8742 Sema::ReuseLambdaContextDecl,
8746 ~EnterExpressionEvaluationContext() {
8747 Actions.PopExpressionEvaluationContext();
8751 DeductionFailureInfo
8752 MakeDeductionFailureInfo(ASTContext &Context, Sema::TemplateDeductionResult TDK,
8753 sema::TemplateDeductionInfo &Info);
8755 /// \brief Contains a late templated function.
8756 /// Will be parsed at the end of the translation unit, used by Sema & Parser.
8757 struct LateParsedTemplate {
8759 /// \brief The template function declaration to be late parsed.
8763 } // end namespace clang