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/OpenMPKinds.h"
30 #include "clang/Basic/Specifiers.h"
31 #include "clang/Basic/TemplateKinds.h"
32 #include "clang/Basic/TypeTraits.h"
33 #include "clang/Lex/ModuleLoader.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/ScopeInfo.h"
42 #include "clang/Sema/TypoCorrection.h"
43 #include "clang/Sema/Weak.h"
44 #include "llvm/ADT/ArrayRef.h"
45 #include "llvm/ADT/Optional.h"
46 #include "llvm/ADT/OwningPtr.h"
47 #include "llvm/ADT/SetVector.h"
48 #include "llvm/ADT/SmallPtrSet.h"
49 #include "llvm/ADT/SmallVector.h"
50 #include "llvm/MC/MCParser/MCAsmParser.h"
57 template <typename ValueT> struct DenseMapInfo;
58 template <typename ValueT, typename ValueInfoT> class DenseSet;
66 class ASTMutationListener;
75 class CXXBindTemporaryExpr;
76 typedef SmallVector<CXXBaseSpecifier*, 4> CXXCastPath;
77 class CXXConstructorDecl;
78 class CXXConversionDecl;
79 class CXXDestructorDecl;
80 class CXXFieldCollector;
81 class CXXMemberCallExpr;
87 class ClassTemplateDecl;
88 class ClassTemplatePartialSpecializationDecl;
89 class ClassTemplateSpecializationDecl;
90 class VarTemplatePartialSpecializationDecl;
91 class CodeCompleteConsumer;
92 class CodeCompletionAllocator;
93 class CodeCompletionTUInfo;
94 class CodeCompletionResult;
100 class DeducedTemplateArgument;
101 class DependentDiagnostic;
102 class DesignatedInitExpr;
104 class EnumConstantDecl;
107 class ExternalSemaSource;
111 class FunctionProtoType;
112 class FunctionTemplateDecl;
113 class ImplicitConversionSequence;
115 class InitializationKind;
116 class InitializationSequence;
117 class InitializedEntity;
118 class IntegerLiteral;
122 class LocalInstantiationScope;
125 class MultiLevelTemplateArgumentList;
128 class ObjCCategoryDecl;
129 class ObjCCategoryImplDecl;
130 class ObjCCompatibleAliasDecl;
131 class ObjCContainerDecl;
133 class ObjCImplementationDecl;
134 class ObjCInterfaceDecl;
136 template <class T> class ObjCList;
137 class ObjCMessageExpr;
138 class ObjCMethodDecl;
139 class ObjCPropertyDecl;
140 class ObjCProtocolDecl;
141 class OMPThreadPrivateDecl;
143 class OverloadCandidateSet;
148 class PseudoDestructorTypeStorage;
149 class PseudoObjectExpr;
151 class StandardConversionSequence;
155 class TargetAttributesSema;
156 class TemplateArgument;
157 class TemplateArgumentList;
158 class TemplateArgumentLoc;
160 class TemplateParameterList;
161 class TemplatePartialOrderingContext;
162 class TemplateTemplateParmDecl;
166 class TypedefNameDecl;
169 class UnresolvedLookupExpr;
170 class UnresolvedMemberExpr;
171 class UnresolvedSetImpl;
172 class UnresolvedSetIterator;
174 class UsingShadowDecl;
177 class VarTemplateSpecializationDecl;
178 class VisibilityAttr;
179 class VisibleDeclConsumer;
180 class IndirectFieldDecl;
181 struct DeductionFailureInfo;
182 class TemplateSpecCandidateSet;
185 class AccessedEntity;
186 class BlockScopeInfo;
187 class CapturedRegionScopeInfo;
188 class CapturingScopeInfo;
189 class CompoundScopeInfo;
190 class DelayedDiagnostic;
191 class DelayedDiagnosticPool;
192 class FunctionScopeInfo;
193 class LambdaScopeInfo;
194 class PossiblyUnreachableDiag;
195 class TemplateDeductionInfo;
198 // FIXME: No way to easily map from TemplateTypeParmTypes to
199 // TemplateTypeParmDecls, so we have this horrible PointerUnion.
200 typedef std::pair<llvm::PointerUnion<const TemplateTypeParmType*, NamedDecl*>,
201 SourceLocation> UnexpandedParameterPack;
203 /// Sema - This implements semantic analysis and AST building for C.
205 Sema(const Sema &) LLVM_DELETED_FUNCTION;
206 void operator=(const Sema &) LLVM_DELETED_FUNCTION;
207 mutable const TargetAttributesSema* TheTargetAttributesSema;
209 ///\brief Source of additional semantic information.
210 ExternalSemaSource *ExternalSource;
212 ///\brief Whether Sema has generated a multiplexer and has to delete it.
213 bool isMultiplexExternalSource;
215 static bool mightHaveNonExternalLinkage(const DeclaratorDecl *FD);
218 shouldLinkPossiblyHiddenDecl(const NamedDecl *Old, const NamedDecl *New) {
219 // We are about to link these. It is now safe to compute the linkage of
220 // the new decl. If the new decl has external linkage, we will
221 // link it with the hidden decl (which also has external linkage) and
222 // it will keep having external linkage. If it has internal linkage, we
223 // will not link it. Since it has no previous decls, it will remain
224 // with internal linkage.
225 return !Old->isHidden() || New->isExternallyVisible();
229 typedef OpaquePtr<DeclGroupRef> DeclGroupPtrTy;
230 typedef OpaquePtr<TemplateName> TemplateTy;
231 typedef OpaquePtr<QualType> TypeTy;
233 OpenCLOptions OpenCLFeatures;
234 FPOptions FPFeatures;
236 const LangOptions &LangOpts;
239 ASTConsumer &Consumer;
240 DiagnosticsEngine &Diags;
241 SourceManager &SourceMgr;
243 /// \brief Flag indicating whether or not to collect detailed statistics.
246 /// \brief Code-completion consumer.
247 CodeCompleteConsumer *CodeCompleter;
249 /// CurContext - This is the current declaration context of parsing.
250 DeclContext *CurContext;
252 /// \brief Generally null except when we temporarily switch decl contexts,
253 /// like in \see ActOnObjCTemporaryExitContainerContext.
254 DeclContext *OriginalLexicalContext;
256 /// VAListTagName - The declaration name corresponding to __va_list_tag.
257 /// This is used as part of a hack to omit that class from ADL results.
258 DeclarationName VAListTagName;
260 /// PackContext - Manages the stack for \#pragma pack. An alignment
261 /// of 0 indicates default alignment.
262 void *PackContext; // Really a "PragmaPackStack*"
264 bool MSStructPragmaOn; // True when \#pragma ms_struct on
266 /// VisContext - Manages the stack for \#pragma GCC visibility.
267 void *VisContext; // Really a "PragmaVisStack*"
269 /// \brief Flag indicating if Sema is building a recovery call expression.
271 /// This flag is used to avoid building recovery call expressions
272 /// if Sema is already doing so, which would cause infinite recursions.
273 bool IsBuildingRecoveryCallExpr;
275 /// ExprNeedsCleanups - True if the current evaluation context
276 /// requires cleanups to be run at its conclusion.
277 bool ExprNeedsCleanups;
279 /// ExprCleanupObjects - This is the stack of objects requiring
280 /// cleanup that are created by the current full expression. The
281 /// element type here is ExprWithCleanups::Object.
282 SmallVector<BlockDecl*, 8> ExprCleanupObjects;
284 /// \brief Store a list of either DeclRefExprs or MemberExprs
285 /// that contain a reference to a variable (constant) that may or may not
286 /// be odr-used in this Expr, and we won't know until all lvalue-to-rvalue
287 /// and discarded value conversions have been applied to all subexpressions
288 /// of the enclosing full expression. This is cleared at the end of each
290 llvm::SmallPtrSet<Expr*, 2> MaybeODRUseExprs;
292 /// \brief Stack containing information about each of the nested
293 /// function, block, and method scopes that are currently active.
295 /// This array is never empty. Clients should ignore the first
296 /// element, which is used to cache a single FunctionScopeInfo
297 /// that's used to parse every top-level function.
298 SmallVector<sema::FunctionScopeInfo *, 4> FunctionScopes;
300 typedef LazyVector<TypedefNameDecl *, ExternalSemaSource,
301 &ExternalSemaSource::ReadExtVectorDecls, 2, 2>
304 /// ExtVectorDecls - This is a list all the extended vector types. This allows
305 /// us to associate a raw vector type with one of the ext_vector type names.
306 /// This is only necessary for issuing pretty diagnostics.
307 ExtVectorDeclsType ExtVectorDecls;
309 /// FieldCollector - Collects CXXFieldDecls during parsing of C++ classes.
310 OwningPtr<CXXFieldCollector> FieldCollector;
312 typedef llvm::SmallSetVector<const NamedDecl*, 16> NamedDeclSetType;
314 /// \brief Set containing all declared private fields that are not used.
315 NamedDeclSetType UnusedPrivateFields;
317 typedef llvm::SmallPtrSet<const CXXRecordDecl*, 8> RecordDeclSetTy;
319 /// PureVirtualClassDiagSet - a set of class declarations which we have
320 /// emitted a list of pure virtual functions. Used to prevent emitting the
321 /// same list more than once.
322 OwningPtr<RecordDeclSetTy> PureVirtualClassDiagSet;
324 /// ParsingInitForAutoVars - a set of declarations with auto types for which
325 /// we are currently parsing the initializer.
326 llvm::SmallPtrSet<const Decl*, 4> ParsingInitForAutoVars;
328 /// \brief A mapping from external names to the most recent
329 /// locally-scoped extern "C" declaration with that name.
331 /// This map contains external declarations introduced in local
335 /// extern "C" void f() {
336 /// void foo(int, int);
340 /// Here, the name "foo" will be associated with the declaration of
341 /// "foo" within f. This name is not visible outside of
342 /// "f". However, we still find it in two cases:
344 /// - If we are declaring another global or extern "C" entity with
345 /// the name "foo", we can find "foo" as a previous declaration,
346 /// so that the types of this external declaration can be checked
347 /// for compatibility.
349 /// - If we would implicitly declare "foo" (e.g., due to a call to
350 /// "foo" in C when no prototype or definition is visible), then
351 /// we find this declaration of "foo" and complain that it is
353 llvm::DenseMap<DeclarationName, NamedDecl *> LocallyScopedExternCDecls;
355 /// \brief Look for a locally scoped extern "C" declaration by the given name.
356 NamedDecl *findLocallyScopedExternCDecl(DeclarationName Name);
358 typedef LazyVector<VarDecl *, ExternalSemaSource,
359 &ExternalSemaSource::ReadTentativeDefinitions, 2, 2>
360 TentativeDefinitionsType;
362 /// \brief All the tentative definitions encountered in the TU.
363 TentativeDefinitionsType TentativeDefinitions;
365 typedef LazyVector<const DeclaratorDecl *, ExternalSemaSource,
366 &ExternalSemaSource::ReadUnusedFileScopedDecls, 2, 2>
367 UnusedFileScopedDeclsType;
369 /// \brief The set of file scoped decls seen so far that have not been used
370 /// and must warn if not used. Only contains the first declaration.
371 UnusedFileScopedDeclsType UnusedFileScopedDecls;
373 typedef LazyVector<CXXConstructorDecl *, ExternalSemaSource,
374 &ExternalSemaSource::ReadDelegatingConstructors, 2, 2>
375 DelegatingCtorDeclsType;
377 /// \brief All the delegating constructors seen so far in the file, used for
378 /// cycle detection at the end of the TU.
379 DelegatingCtorDeclsType DelegatingCtorDecls;
381 /// \brief All the overriding destructors seen during a class definition
382 /// (there could be multiple due to nested classes) that had their exception
383 /// spec checks delayed, plus the overridden destructor.
384 SmallVector<std::pair<const CXXDestructorDecl*,
385 const CXXDestructorDecl*>, 2>
386 DelayedDestructorExceptionSpecChecks;
388 /// \brief All the members seen during a class definition which were both
389 /// explicitly defaulted and had explicitly-specified exception
390 /// specifications, along with the function type containing their
391 /// user-specified exception specification. Those exception specifications
392 /// were overridden with the default specifications, but we still need to
393 /// check whether they are compatible with the default specification, and
394 /// we can't do that until the nesting set of class definitions is complete.
395 SmallVector<std::pair<CXXMethodDecl*, const FunctionProtoType*>, 2>
396 DelayedDefaultedMemberExceptionSpecs;
398 typedef llvm::DenseMap<const FunctionDecl *, LateParsedTemplate *>
399 LateParsedTemplateMapT;
400 LateParsedTemplateMapT LateParsedTemplateMap;
402 /// \brief Callback to the parser to parse templated functions when needed.
403 typedef void LateTemplateParserCB(void *P, LateParsedTemplate &LPT);
404 LateTemplateParserCB *LateTemplateParser;
407 void SetLateTemplateParser(LateTemplateParserCB *LTP, void *P) {
408 LateTemplateParser = LTP;
412 class DelayedDiagnostics;
414 class DelayedDiagnosticsState {
415 sema::DelayedDiagnosticPool *SavedPool;
416 friend class Sema::DelayedDiagnostics;
418 typedef DelayedDiagnosticsState ParsingDeclState;
419 typedef DelayedDiagnosticsState ProcessingContextState;
421 /// A class which encapsulates the logic for delaying diagnostics
422 /// during parsing and other processing.
423 class DelayedDiagnostics {
424 /// \brief The current pool of diagnostics into which delayed
425 /// diagnostics should go.
426 sema::DelayedDiagnosticPool *CurPool;
429 DelayedDiagnostics() : CurPool(0) {}
431 /// Adds a delayed diagnostic.
432 void add(const sema::DelayedDiagnostic &diag); // in DelayedDiagnostic.h
434 /// Determines whether diagnostics should be delayed.
435 bool shouldDelayDiagnostics() { return CurPool != 0; }
437 /// Returns the current delayed-diagnostics pool.
438 sema::DelayedDiagnosticPool *getCurrentPool() const {
442 /// Enter a new scope. Access and deprecation diagnostics will be
443 /// collected in this pool.
444 DelayedDiagnosticsState push(sema::DelayedDiagnosticPool &pool) {
445 DelayedDiagnosticsState state;
446 state.SavedPool = CurPool;
451 /// Leave a delayed-diagnostic state that was previously pushed.
452 /// Do not emit any of the diagnostics. This is performed as part
453 /// of the bookkeeping of popping a pool "properly".
454 void popWithoutEmitting(DelayedDiagnosticsState state) {
455 CurPool = state.SavedPool;
458 /// Enter a new scope where access and deprecation diagnostics are
460 DelayedDiagnosticsState pushUndelayed() {
461 DelayedDiagnosticsState state;
462 state.SavedPool = CurPool;
467 /// Undo a previous pushUndelayed().
468 void popUndelayed(DelayedDiagnosticsState state) {
469 assert(CurPool == NULL);
470 CurPool = state.SavedPool;
472 } DelayedDiagnostics;
474 /// A RAII object to temporarily push a declaration context.
478 DeclContext *SavedContext;
479 ProcessingContextState SavedContextState;
480 QualType SavedCXXThisTypeOverride;
483 ContextRAII(Sema &S, DeclContext *ContextToPush)
484 : S(S), SavedContext(S.CurContext),
485 SavedContextState(S.DelayedDiagnostics.pushUndelayed()),
486 SavedCXXThisTypeOverride(S.CXXThisTypeOverride)
488 assert(ContextToPush && "pushing null context");
489 S.CurContext = ContextToPush;
493 if (!SavedContext) return;
494 S.CurContext = SavedContext;
495 S.DelayedDiagnostics.popUndelayed(SavedContextState);
496 S.CXXThisTypeOverride = SavedCXXThisTypeOverride;
505 /// \brief RAII object to handle the state changes required to synthesize
507 class SynthesizedFunctionScope {
509 Sema::ContextRAII SavedContext;
512 SynthesizedFunctionScope(Sema &S, DeclContext *DC)
513 : S(S), SavedContext(S, DC)
515 S.PushFunctionScope();
516 S.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated);
519 ~SynthesizedFunctionScope() {
520 S.PopExpressionEvaluationContext();
521 S.PopFunctionScopeInfo();
525 /// WeakUndeclaredIdentifiers - Identifiers contained in
526 /// \#pragma weak before declared. rare. may alias another
527 /// identifier, declared or undeclared
528 llvm::DenseMap<IdentifierInfo*,WeakInfo> WeakUndeclaredIdentifiers;
530 /// ExtnameUndeclaredIdentifiers - Identifiers contained in
531 /// \#pragma redefine_extname before declared. Used in Solaris system headers
532 /// to define functions that occur in multiple standards to call the version
533 /// in the currently selected standard.
534 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*> ExtnameUndeclaredIdentifiers;
537 /// \brief Load weak undeclared identifiers from the external source.
538 void LoadExternalWeakUndeclaredIdentifiers();
540 /// WeakTopLevelDecl - Translation-unit scoped declarations generated by
541 /// \#pragma weak during processing of other Decls.
542 /// I couldn't figure out a clean way to generate these in-line, so
543 /// we store them here and handle separately -- which is a hack.
544 /// It would be best to refactor this.
545 SmallVector<Decl*,2> WeakTopLevelDecl;
547 IdentifierResolver IdResolver;
549 /// Translation Unit Scope - useful to Objective-C actions that need
550 /// to lookup file scope declarations in the "ordinary" C decl namespace.
551 /// For example, user-defined classes, built-in "id" type, etc.
554 /// \brief The C++ "std" namespace, where the standard library resides.
555 LazyDeclPtr StdNamespace;
557 /// \brief The C++ "std::bad_alloc" class, which is defined by the C++
558 /// standard library.
559 LazyDeclPtr StdBadAlloc;
561 /// \brief The C++ "std::initializer_list" template, which is defined in
562 /// \<initializer_list>.
563 ClassTemplateDecl *StdInitializerList;
565 /// \brief The C++ "type_info" declaration, which is defined in \<typeinfo>.
566 RecordDecl *CXXTypeInfoDecl;
568 /// \brief The MSVC "_GUID" struct, which is defined in MSVC header files.
569 RecordDecl *MSVCGuidDecl;
571 /// \brief Caches identifiers/selectors for NSFoundation APIs.
572 OwningPtr<NSAPI> NSAPIObj;
574 /// \brief The declaration of the Objective-C NSNumber class.
575 ObjCInterfaceDecl *NSNumberDecl;
577 /// \brief Pointer to NSNumber type (NSNumber *).
578 QualType NSNumberPointer;
580 /// \brief The Objective-C NSNumber methods used to create NSNumber literals.
581 ObjCMethodDecl *NSNumberLiteralMethods[NSAPI::NumNSNumberLiteralMethods];
583 /// \brief The declaration of the Objective-C NSString class.
584 ObjCInterfaceDecl *NSStringDecl;
586 /// \brief Pointer to NSString type (NSString *).
587 QualType NSStringPointer;
589 /// \brief The declaration of the stringWithUTF8String: method.
590 ObjCMethodDecl *StringWithUTF8StringMethod;
592 /// \brief The declaration of the Objective-C NSArray class.
593 ObjCInterfaceDecl *NSArrayDecl;
595 /// \brief The declaration of the arrayWithObjects:count: method.
596 ObjCMethodDecl *ArrayWithObjectsMethod;
598 /// \brief The declaration of the Objective-C NSDictionary class.
599 ObjCInterfaceDecl *NSDictionaryDecl;
601 /// \brief The declaration of the dictionaryWithObjects:forKeys:count: method.
602 ObjCMethodDecl *DictionaryWithObjectsMethod;
604 /// \brief id<NSCopying> type.
605 QualType QIDNSCopying;
607 /// \brief will hold 'respondsToSelector:'
608 Selector RespondsToSelectorSel;
610 /// A flag to remember whether the implicit forms of operator new and delete
611 /// have been declared.
612 bool GlobalNewDeleteDeclared;
614 /// A flag to indicate that we're in a context that permits abstract
615 /// references to fields. This is really a
616 bool AllowAbstractFieldReference;
618 /// \brief Describes how the expressions currently being parsed are
619 /// evaluated at run-time, if at all.
620 enum ExpressionEvaluationContext {
621 /// \brief The current expression and its subexpressions occur within an
622 /// unevaluated operand (C++11 [expr]p7), such as the subexpression of
623 /// \c sizeof, where the type of the expression may be significant but
624 /// no code will be generated to evaluate the value of the expression at
628 /// \brief The current expression occurs within an unevaluated
629 /// operand that unconditionally permits abstract references to
630 /// fields, such as a SIZE operator in MS-style inline assembly.
633 /// \brief The current context is "potentially evaluated" in C++11 terms,
634 /// but the expression is evaluated at compile-time (like the values of
635 /// cases in a switch statement).
638 /// \brief The current expression is potentially evaluated at run time,
639 /// which means that code may be generated to evaluate the value of the
640 /// expression at run time.
641 PotentiallyEvaluated,
643 /// \brief The current expression is potentially evaluated, but any
644 /// declarations referenced inside that expression are only used if
645 /// in fact the current expression is used.
647 /// This value is used when parsing default function arguments, for which
648 /// we would like to provide diagnostics (e.g., passing non-POD arguments
649 /// through varargs) but do not want to mark declarations as "referenced"
650 /// until the default argument is used.
651 PotentiallyEvaluatedIfUsed
654 /// \brief Data structure used to record current or nested
655 /// expression evaluation contexts.
656 struct ExpressionEvaluationContextRecord {
657 /// \brief The expression evaluation context.
658 ExpressionEvaluationContext Context;
660 /// \brief Whether the enclosing context needed a cleanup.
661 bool ParentNeedsCleanups;
663 /// \brief Whether we are in a decltype expression.
666 /// \brief The number of active cleanup objects when we entered
667 /// this expression evaluation context.
668 unsigned NumCleanupObjects;
670 llvm::SmallPtrSet<Expr*, 2> SavedMaybeODRUseExprs;
672 /// \brief The lambdas that are present within this context, if it
673 /// is indeed an unevaluated context.
674 SmallVector<LambdaExpr *, 2> Lambdas;
676 /// \brief The declaration that provides context for lambda expressions
677 /// and block literals if the normal declaration context does not
678 /// suffice, e.g., in a default function argument.
679 Decl *ManglingContextDecl;
681 /// \brief The context information used to mangle lambda expressions
682 /// and block literals within this context.
684 /// This mangling information is allocated lazily, since most contexts
685 /// do not have lambda expressions or block literals.
686 IntrusiveRefCntPtr<MangleNumberingContext> MangleNumbering;
688 /// \brief If we are processing a decltype type, a set of call expressions
689 /// for which we have deferred checking the completeness of the return type.
690 SmallVector<CallExpr *, 8> DelayedDecltypeCalls;
692 /// \brief If we are processing a decltype type, a set of temporary binding
693 /// expressions for which we have deferred checking the destructor.
694 SmallVector<CXXBindTemporaryExpr *, 8> DelayedDecltypeBinds;
696 ExpressionEvaluationContextRecord(ExpressionEvaluationContext Context,
697 unsigned NumCleanupObjects,
698 bool ParentNeedsCleanups,
699 Decl *ManglingContextDecl,
701 : Context(Context), ParentNeedsCleanups(ParentNeedsCleanups),
702 IsDecltype(IsDecltype), NumCleanupObjects(NumCleanupObjects),
703 ManglingContextDecl(ManglingContextDecl), MangleNumbering() { }
705 /// \brief Retrieve the mangling numbering context, used to consistently
706 /// number constructs like lambdas for mangling.
707 MangleNumberingContext &getMangleNumberingContext(ASTContext &Ctx);
709 bool isUnevaluated() const {
710 return Context == Unevaluated || Context == UnevaluatedAbstract;
714 /// A stack of expression evaluation contexts.
715 SmallVector<ExpressionEvaluationContextRecord, 8> ExprEvalContexts;
717 /// \brief Compute the mangling number context for a lambda expression or
720 /// \param DC - The DeclContext containing the lambda expression or
722 /// \param[out] ManglingContextDecl - Returns the ManglingContextDecl
723 /// associated with the context, if relevant.
724 MangleNumberingContext *getCurrentMangleNumberContext(
725 const DeclContext *DC,
726 Decl *&ManglingContextDecl);
729 /// SpecialMemberOverloadResult - The overloading result for a special member
732 /// This is basically a wrapper around PointerIntPair. The lowest bits of the
733 /// integer are used to determine whether overload resolution succeeded.
734 class SpecialMemberOverloadResult : public llvm::FastFoldingSetNode {
743 llvm::PointerIntPair<CXXMethodDecl*, 2> Pair;
746 SpecialMemberOverloadResult(const llvm::FoldingSetNodeID &ID)
747 : FastFoldingSetNode(ID)
750 CXXMethodDecl *getMethod() const { return Pair.getPointer(); }
751 void setMethod(CXXMethodDecl *MD) { Pair.setPointer(MD); }
753 Kind getKind() const { return static_cast<Kind>(Pair.getInt()); }
754 void setKind(Kind K) { Pair.setInt(K); }
757 /// \brief A cache of special member function overload resolution results
759 llvm::FoldingSet<SpecialMemberOverloadResult> SpecialMemberCache;
761 /// \brief The kind of translation unit we are processing.
763 /// When we're processing a complete translation unit, Sema will perform
764 /// end-of-translation-unit semantic tasks (such as creating
765 /// initializers for tentative definitions in C) once parsing has
766 /// completed. Modules and precompiled headers perform different kinds of
768 TranslationUnitKind TUKind;
770 llvm::BumpPtrAllocator BumpAlloc;
772 /// \brief The number of SFINAE diagnostics that have been trapped.
773 unsigned NumSFINAEErrors;
775 typedef llvm::DenseMap<ParmVarDecl *, SmallVector<ParmVarDecl *, 1> >
776 UnparsedDefaultArgInstantiationsMap;
778 /// \brief A mapping from parameters with unparsed default arguments to the
779 /// set of instantiations of each parameter.
781 /// This mapping is a temporary data structure used when parsing
782 /// nested class templates or nested classes of class templates,
783 /// where we might end up instantiating an inner class before the
784 /// default arguments of its methods have been parsed.
785 UnparsedDefaultArgInstantiationsMap UnparsedDefaultArgInstantiations;
787 // Contains the locations of the beginning of unparsed default
788 // argument locations.
789 llvm::DenseMap<ParmVarDecl *, SourceLocation> UnparsedDefaultArgLocs;
791 /// UndefinedInternals - all the used, undefined objects which require a
792 /// definition in this translation unit.
793 llvm::DenseMap<NamedDecl *, SourceLocation> UndefinedButUsed;
795 /// Obtain a sorted list of functions that are undefined but ODR-used.
796 void getUndefinedButUsed(
797 SmallVectorImpl<std::pair<NamedDecl *, SourceLocation> > &Undefined);
799 typedef std::pair<ObjCMethodList, ObjCMethodList> GlobalMethods;
800 typedef llvm::DenseMap<Selector, GlobalMethods> GlobalMethodPool;
802 /// Method Pool - allows efficient lookup when typechecking messages to "id".
803 /// We need to maintain a list, since selectors can have differing signatures
804 /// across classes. In Cocoa, this happens to be extremely uncommon (only 1%
805 /// of selectors are "overloaded").
806 /// At the head of the list it is recorded whether there were 0, 1, or >= 2
807 /// methods inside categories with a particular selector.
808 GlobalMethodPool MethodPool;
810 /// Method selectors used in a \@selector expression. Used for implementation
812 llvm::DenseMap<Selector, SourceLocation> ReferencedSelectors;
814 /// Kinds of C++ special members.
815 enum CXXSpecialMember {
816 CXXDefaultConstructor,
825 typedef std::pair<CXXRecordDecl*, CXXSpecialMember> SpecialMemberDecl;
827 /// The C++ special members which we are currently in the process of
828 /// declaring. If this process recursively triggers the declaration of the
829 /// same special member, we should act as if it is not yet declared.
830 llvm::SmallSet<SpecialMemberDecl, 4> SpecialMembersBeingDeclared;
832 void ReadMethodPool(Selector Sel);
834 /// Private Helper predicate to check for 'self'.
835 bool isSelfExpr(Expr *RExpr);
837 /// \brief Cause the active diagnostic on the DiagosticsEngine to be
838 /// emitted. This is closely coupled to the SemaDiagnosticBuilder class and
839 /// should not be used elsewhere.
840 void EmitCurrentDiagnostic(unsigned DiagID);
842 /// Records and restores the FP_CONTRACT state on entry/exit of compound
844 class FPContractStateRAII {
846 FPContractStateRAII(Sema& S)
847 : S(S), OldFPContractState(S.FPFeatures.fp_contract) {}
848 ~FPContractStateRAII() {
849 S.FPFeatures.fp_contract = OldFPContractState;
853 bool OldFPContractState : 1;
856 typedef llvm::MCAsmParserSemaCallback::InlineAsmIdentifierInfo
857 InlineAsmIdentifierInfo;
860 Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer,
861 TranslationUnitKind TUKind = TU_Complete,
862 CodeCompleteConsumer *CompletionConsumer = 0);
865 /// \brief Perform initialization that occurs after the parser has been
866 /// initialized but before it parses anything.
869 const LangOptions &getLangOpts() const { return LangOpts; }
870 OpenCLOptions &getOpenCLOptions() { return OpenCLFeatures; }
871 FPOptions &getFPOptions() { return FPFeatures; }
873 DiagnosticsEngine &getDiagnostics() const { return Diags; }
874 SourceManager &getSourceManager() const { return SourceMgr; }
875 const TargetAttributesSema &getTargetAttributesSema() const;
876 Preprocessor &getPreprocessor() const { return PP; }
877 ASTContext &getASTContext() const { return Context; }
878 ASTConsumer &getASTConsumer() const { return Consumer; }
879 ASTMutationListener *getASTMutationListener() const;
880 ExternalSemaSource* getExternalSource() const { return ExternalSource; }
882 ///\brief Registers an external source. If an external source already exists,
883 /// creates a multiplex external source and appends to it.
885 ///\param[in] E - A non-null external sema source.
887 void addExternalSource(ExternalSemaSource *E);
889 void PrintStats() const;
891 /// \brief Helper class that creates diagnostics with optional
892 /// template instantiation stacks.
894 /// This class provides a wrapper around the basic DiagnosticBuilder
895 /// class that emits diagnostics. SemaDiagnosticBuilder is
896 /// responsible for emitting the diagnostic (as DiagnosticBuilder
897 /// does) and, if the diagnostic comes from inside a template
898 /// instantiation, printing the template instantiation stack as
900 class SemaDiagnosticBuilder : public DiagnosticBuilder {
905 SemaDiagnosticBuilder(DiagnosticBuilder &DB, Sema &SemaRef, unsigned DiagID)
906 : DiagnosticBuilder(DB), SemaRef(SemaRef), DiagID(DiagID) { }
908 ~SemaDiagnosticBuilder() {
909 // If we aren't active, there is nothing to do.
910 if (!isActive()) return;
912 // Otherwise, we need to emit the diagnostic. First flush the underlying
913 // DiagnosticBuilder data, and clear the diagnostic builder itself so it
914 // won't emit the diagnostic in its own destructor.
916 // This seems wasteful, in that as written the DiagnosticBuilder dtor will
917 // do its own needless checks to see if the diagnostic needs to be
918 // emitted. However, because we take care to ensure that the builder
919 // objects never escape, a sufficiently smart compiler will be able to
920 // eliminate that code.
924 // Dispatch to Sema to emit the diagnostic.
925 SemaRef.EmitCurrentDiagnostic(DiagID);
928 /// Teach operator<< to produce an object of the correct type.
930 friend const SemaDiagnosticBuilder &operator<<(
931 const SemaDiagnosticBuilder &Diag, const T &Value) {
932 const DiagnosticBuilder &BaseDiag = Diag;
938 /// \brief Emit a diagnostic.
939 SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID) {
940 DiagnosticBuilder DB = Diags.Report(Loc, DiagID);
941 return SemaDiagnosticBuilder(DB, *this, DiagID);
944 /// \brief Emit a partial diagnostic.
945 SemaDiagnosticBuilder Diag(SourceLocation Loc, const PartialDiagnostic& PD);
947 /// \brief Build a partial diagnostic.
948 PartialDiagnostic PDiag(unsigned DiagID = 0); // in SemaInternal.h
950 bool findMacroSpelling(SourceLocation &loc, StringRef name);
952 /// \brief Get a string to suggest for zero-initialization of a type.
954 getFixItZeroInitializerForType(QualType T, SourceLocation Loc) const;
955 std::string getFixItZeroLiteralForType(QualType T, SourceLocation Loc) const;
957 ExprResult Owned(Expr* E) { return E; }
958 ExprResult Owned(ExprResult R) { return R; }
959 StmtResult Owned(Stmt* S) { return S; }
961 void ActOnEndOfTranslationUnit();
963 void CheckDelegatingCtorCycles();
965 Scope *getScopeForContext(DeclContext *Ctx);
967 void PushFunctionScope();
968 void PushBlockScope(Scope *BlockScope, BlockDecl *Block);
969 sema::LambdaScopeInfo *PushLambdaScope();
971 /// \brief This is used to inform Sema what the current TemplateParameterDepth
972 /// is during Parsing. Currently it is used to pass on the depth
973 /// when parsing generic lambda 'auto' parameters.
974 void RecordParsingTemplateParameterDepth(unsigned Depth);
976 void PushCapturedRegionScope(Scope *RegionScope, CapturedDecl *CD,
978 CapturedRegionKind K);
979 void PopFunctionScopeInfo(const sema::AnalysisBasedWarnings::Policy *WP =0,
980 const Decl *D = 0, const BlockExpr *blkExpr = 0);
982 sema::FunctionScopeInfo *getCurFunction() const {
983 return FunctionScopes.back();
986 template <typename ExprT>
987 void recordUseOfEvaluatedWeak(const ExprT *E, bool IsRead=true) {
988 if (!isUnevaluatedContext())
989 getCurFunction()->recordUseOfWeak(E, IsRead);
992 void PushCompoundScope();
993 void PopCompoundScope();
995 sema::CompoundScopeInfo &getCurCompoundScope() const;
997 bool hasAnyUnrecoverableErrorsInThisFunction() const;
999 /// \brief Retrieve the current block, if any.
1000 sema::BlockScopeInfo *getCurBlock();
1002 /// \brief Retrieve the current lambda scope info, if any.
1003 sema::LambdaScopeInfo *getCurLambda();
1005 /// \brief Retrieve the current generic lambda info, if any.
1006 sema::LambdaScopeInfo *getCurGenericLambda();
1008 /// \brief Retrieve the current captured region, if any.
1009 sema::CapturedRegionScopeInfo *getCurCapturedRegion();
1011 /// WeakTopLevelDeclDecls - access to \#pragma weak-generated Decls
1012 SmallVectorImpl<Decl *> &WeakTopLevelDecls() { return WeakTopLevelDecl; }
1014 void ActOnComment(SourceRange Comment);
1016 //===--------------------------------------------------------------------===//
1017 // Type Analysis / Processing: SemaType.cpp.
1020 QualType BuildQualifiedType(QualType T, SourceLocation Loc, Qualifiers Qs,
1021 const DeclSpec *DS = 0);
1022 QualType BuildQualifiedType(QualType T, SourceLocation Loc, unsigned CVRA,
1023 const DeclSpec *DS = 0);
1024 QualType BuildPointerType(QualType T,
1025 SourceLocation Loc, DeclarationName Entity);
1026 QualType BuildReferenceType(QualType T, bool LValueRef,
1027 SourceLocation Loc, DeclarationName Entity);
1028 QualType BuildArrayType(QualType T, ArrayType::ArraySizeModifier ASM,
1029 Expr *ArraySize, unsigned Quals,
1030 SourceRange Brackets, DeclarationName Entity);
1031 QualType BuildExtVectorType(QualType T, Expr *ArraySize,
1032 SourceLocation AttrLoc);
1034 bool CheckFunctionReturnType(QualType T, SourceLocation Loc);
1036 /// \brief Build a function type.
1038 /// This routine checks the function type according to C++ rules and
1039 /// under the assumption that the result type and parameter types have
1040 /// just been instantiated from a template. It therefore duplicates
1041 /// some of the behavior of GetTypeForDeclarator, but in a much
1042 /// simpler form that is only suitable for this narrow use case.
1044 /// \param T The return type of the function.
1046 /// \param ParamTypes The parameter types of the function. This array
1047 /// will be modified to account for adjustments to the types of the
1048 /// function parameters.
1050 /// \param Loc The location of the entity whose type involves this
1051 /// function type or, if there is no such entity, the location of the
1052 /// type that will have function type.
1054 /// \param Entity The name of the entity that involves the function
1057 /// \param EPI Extra information about the function type. Usually this will
1058 /// be taken from an existing function with the same prototype.
1060 /// \returns A suitable function type, if there are no errors. The
1061 /// unqualified type will always be a FunctionProtoType.
1062 /// Otherwise, returns a NULL type.
1063 QualType BuildFunctionType(QualType T,
1064 llvm::MutableArrayRef<QualType> ParamTypes,
1065 SourceLocation Loc, DeclarationName Entity,
1066 const FunctionProtoType::ExtProtoInfo &EPI);
1068 QualType BuildMemberPointerType(QualType T, QualType Class,
1070 DeclarationName Entity);
1071 QualType BuildBlockPointerType(QualType T,
1072 SourceLocation Loc, DeclarationName Entity);
1073 QualType BuildParenType(QualType T);
1074 QualType BuildAtomicType(QualType T, SourceLocation Loc);
1076 TypeSourceInfo *GetTypeForDeclarator(Declarator &D, Scope *S);
1077 TypeSourceInfo *GetTypeForDeclaratorCast(Declarator &D, QualType FromTy);
1078 TypeSourceInfo *GetTypeSourceInfoForDeclarator(Declarator &D, QualType T,
1079 TypeSourceInfo *ReturnTypeInfo);
1081 /// \brief Package the given type and TSI into a ParsedType.
1082 ParsedType CreateParsedType(QualType T, TypeSourceInfo *TInfo);
1083 DeclarationNameInfo GetNameForDeclarator(Declarator &D);
1084 DeclarationNameInfo GetNameFromUnqualifiedId(const UnqualifiedId &Name);
1085 static QualType GetTypeFromParser(ParsedType Ty, TypeSourceInfo **TInfo = 0);
1086 CanThrowResult canThrow(const Expr *E);
1087 const FunctionProtoType *ResolveExceptionSpec(SourceLocation Loc,
1088 const FunctionProtoType *FPT);
1089 bool CheckSpecifiedExceptionType(QualType &T, const SourceRange &Range);
1090 bool CheckDistantExceptionSpec(QualType T);
1091 bool CheckEquivalentExceptionSpec(FunctionDecl *Old, FunctionDecl *New);
1092 bool CheckEquivalentExceptionSpec(
1093 const FunctionProtoType *Old, SourceLocation OldLoc,
1094 const FunctionProtoType *New, SourceLocation NewLoc);
1095 bool CheckEquivalentExceptionSpec(
1096 const PartialDiagnostic &DiagID, const PartialDiagnostic & NoteID,
1097 const FunctionProtoType *Old, SourceLocation OldLoc,
1098 const FunctionProtoType *New, SourceLocation NewLoc,
1099 bool *MissingExceptionSpecification = 0,
1100 bool *MissingEmptyExceptionSpecification = 0,
1101 bool AllowNoexceptAllMatchWithNoSpec = false,
1102 bool IsOperatorNew = false);
1103 bool CheckExceptionSpecSubset(
1104 const PartialDiagnostic &DiagID, const PartialDiagnostic & NoteID,
1105 const FunctionProtoType *Superset, SourceLocation SuperLoc,
1106 const FunctionProtoType *Subset, SourceLocation SubLoc);
1107 bool CheckParamExceptionSpec(const PartialDiagnostic & NoteID,
1108 const FunctionProtoType *Target, SourceLocation TargetLoc,
1109 const FunctionProtoType *Source, SourceLocation SourceLoc);
1111 TypeResult ActOnTypeName(Scope *S, Declarator &D);
1113 /// \brief The parser has parsed the context-sensitive type 'instancetype'
1114 /// in an Objective-C message declaration. Return the appropriate type.
1115 ParsedType ActOnObjCInstanceType(SourceLocation Loc);
1117 /// \brief Abstract class used to diagnose incomplete types.
1118 struct TypeDiagnoser {
1121 TypeDiagnoser(bool Suppressed = false) : Suppressed(Suppressed) { }
1123 virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) = 0;
1124 virtual ~TypeDiagnoser() {}
1127 static int getPrintable(int I) { return I; }
1128 static unsigned getPrintable(unsigned I) { return I; }
1129 static bool getPrintable(bool B) { return B; }
1130 static const char * getPrintable(const char *S) { return S; }
1131 static StringRef getPrintable(StringRef S) { return S; }
1132 static const std::string &getPrintable(const std::string &S) { return S; }
1133 static const IdentifierInfo *getPrintable(const IdentifierInfo *II) {
1136 static DeclarationName getPrintable(DeclarationName N) { return N; }
1137 static QualType getPrintable(QualType T) { return T; }
1138 static SourceRange getPrintable(SourceRange R) { return R; }
1139 static SourceRange getPrintable(SourceLocation L) { return L; }
1140 static SourceRange getPrintable(Expr *E) { return E->getSourceRange(); }
1141 static SourceRange getPrintable(TypeLoc TL) { return TL.getSourceRange();}
1143 template<typename T1>
1144 class BoundTypeDiagnoser1 : public TypeDiagnoser {
1149 BoundTypeDiagnoser1(unsigned DiagID, const T1 &Arg1)
1150 : TypeDiagnoser(DiagID == 0), DiagID(DiagID), Arg1(Arg1) { }
1151 virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) {
1152 if (Suppressed) return;
1153 S.Diag(Loc, DiagID) << getPrintable(Arg1) << T;
1156 virtual ~BoundTypeDiagnoser1() { }
1159 template<typename T1, typename T2>
1160 class BoundTypeDiagnoser2 : public TypeDiagnoser {
1166 BoundTypeDiagnoser2(unsigned DiagID, const T1 &Arg1,
1168 : TypeDiagnoser(DiagID == 0), DiagID(DiagID), Arg1(Arg1),
1171 virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) {
1172 if (Suppressed) return;
1173 S.Diag(Loc, DiagID) << getPrintable(Arg1) << getPrintable(Arg2) << T;
1176 virtual ~BoundTypeDiagnoser2() { }
1179 template<typename T1, typename T2, typename T3>
1180 class BoundTypeDiagnoser3 : public TypeDiagnoser {
1187 BoundTypeDiagnoser3(unsigned DiagID, const T1 &Arg1,
1188 const T2 &Arg2, const T3 &Arg3)
1189 : TypeDiagnoser(DiagID == 0), DiagID(DiagID), Arg1(Arg1),
1190 Arg2(Arg2), Arg3(Arg3) { }
1192 virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) {
1193 if (Suppressed) return;
1195 << getPrintable(Arg1) << getPrintable(Arg2) << getPrintable(Arg3) << T;
1198 virtual ~BoundTypeDiagnoser3() { }
1202 bool RequireCompleteTypeImpl(SourceLocation Loc, QualType T,
1203 TypeDiagnoser &Diagnoser);
1205 bool RequireCompleteType(SourceLocation Loc, QualType T,
1206 TypeDiagnoser &Diagnoser);
1207 bool RequireCompleteType(SourceLocation Loc, QualType T,
1210 template<typename T1>
1211 bool RequireCompleteType(SourceLocation Loc, QualType T,
1212 unsigned DiagID, const T1 &Arg1) {
1213 BoundTypeDiagnoser1<T1> Diagnoser(DiagID, Arg1);
1214 return RequireCompleteType(Loc, T, Diagnoser);
1217 template<typename T1, typename T2>
1218 bool RequireCompleteType(SourceLocation Loc, QualType T,
1219 unsigned DiagID, const T1 &Arg1, const T2 &Arg2) {
1220 BoundTypeDiagnoser2<T1, T2> Diagnoser(DiagID, Arg1, Arg2);
1221 return RequireCompleteType(Loc, T, Diagnoser);
1224 template<typename T1, typename T2, typename T3>
1225 bool RequireCompleteType(SourceLocation Loc, QualType T,
1226 unsigned DiagID, const T1 &Arg1, const T2 &Arg2,
1228 BoundTypeDiagnoser3<T1, T2, T3> Diagnoser(DiagID, Arg1, Arg2,
1230 return RequireCompleteType(Loc, T, Diagnoser);
1233 bool RequireCompleteExprType(Expr *E, TypeDiagnoser &Diagnoser);
1234 bool RequireCompleteExprType(Expr *E, unsigned DiagID);
1236 template<typename T1>
1237 bool RequireCompleteExprType(Expr *E, unsigned DiagID, const T1 &Arg1) {
1238 BoundTypeDiagnoser1<T1> Diagnoser(DiagID, Arg1);
1239 return RequireCompleteExprType(E, Diagnoser);
1242 template<typename T1, typename T2>
1243 bool RequireCompleteExprType(Expr *E, unsigned DiagID, const T1 &Arg1,
1245 BoundTypeDiagnoser2<T1, T2> Diagnoser(DiagID, Arg1, Arg2);
1246 return RequireCompleteExprType(E, Diagnoser);
1249 template<typename T1, typename T2, typename T3>
1250 bool RequireCompleteExprType(Expr *E, unsigned DiagID, const T1 &Arg1,
1251 const T2 &Arg2, const T3 &Arg3) {
1252 BoundTypeDiagnoser3<T1, T2, T3> Diagnoser(DiagID, Arg1, Arg2,
1254 return RequireCompleteExprType(E, Diagnoser);
1257 bool RequireLiteralType(SourceLocation Loc, QualType T,
1258 TypeDiagnoser &Diagnoser);
1259 bool RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID);
1261 template<typename T1>
1262 bool RequireLiteralType(SourceLocation Loc, QualType T,
1263 unsigned DiagID, const T1 &Arg1) {
1264 BoundTypeDiagnoser1<T1> Diagnoser(DiagID, Arg1);
1265 return RequireLiteralType(Loc, T, Diagnoser);
1268 template<typename T1, typename T2>
1269 bool RequireLiteralType(SourceLocation Loc, QualType T,
1270 unsigned DiagID, const T1 &Arg1, const T2 &Arg2) {
1271 BoundTypeDiagnoser2<T1, T2> Diagnoser(DiagID, Arg1, Arg2);
1272 return RequireLiteralType(Loc, T, Diagnoser);
1275 template<typename T1, typename T2, typename T3>
1276 bool RequireLiteralType(SourceLocation Loc, QualType T,
1277 unsigned DiagID, const T1 &Arg1, const T2 &Arg2,
1279 BoundTypeDiagnoser3<T1, T2, T3> Diagnoser(DiagID, Arg1, Arg2,
1281 return RequireLiteralType(Loc, T, Diagnoser);
1284 QualType getElaboratedType(ElaboratedTypeKeyword Keyword,
1285 const CXXScopeSpec &SS, QualType T);
1287 QualType BuildTypeofExprType(Expr *E, SourceLocation Loc);
1288 QualType BuildDecltypeType(Expr *E, SourceLocation Loc);
1289 QualType BuildUnaryTransformType(QualType BaseType,
1290 UnaryTransformType::UTTKind UKind,
1291 SourceLocation Loc);
1293 //===--------------------------------------------------------------------===//
1294 // Symbol table / Decl tracking callbacks: SemaDecl.cpp.
1297 /// List of decls defined in a function prototype. This contains EnumConstants
1298 /// that incorrectly end up in translation unit scope because there is no
1299 /// function to pin them on. ActOnFunctionDeclarator reads this list and patches
1300 /// them into the FunctionDecl.
1301 std::vector<NamedDecl*> DeclsInPrototypeScope;
1302 /// Nonzero if we are currently parsing a function declarator. This is a counter
1303 /// as opposed to a boolean so we can deal with nested function declarators
1305 /// void f(void (*g)(), ...)
1306 unsigned InFunctionDeclarator;
1308 DeclGroupPtrTy ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType = 0);
1310 void DiagnoseUseOfUnimplementedSelectors();
1312 bool isSimpleTypeSpecifier(tok::TokenKind Kind) const;
1314 ParsedType getTypeName(const IdentifierInfo &II, SourceLocation NameLoc,
1315 Scope *S, CXXScopeSpec *SS = 0,
1316 bool isClassName = false,
1317 bool HasTrailingDot = false,
1318 ParsedType ObjectType = ParsedType(),
1319 bool IsCtorOrDtorName = false,
1320 bool WantNontrivialTypeSourceInfo = false,
1321 IdentifierInfo **CorrectedII = 0);
1322 TypeSpecifierType isTagName(IdentifierInfo &II, Scope *S);
1323 bool isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S);
1324 bool DiagnoseUnknownTypeName(IdentifierInfo *&II,
1325 SourceLocation IILoc,
1328 ParsedType &SuggestedType);
1330 /// \brief Describes the result of the name lookup and resolution performed
1331 /// by \c ClassifyName().
1332 enum NameClassificationKind {
1338 NC_NestedNameSpecifier,
1344 class NameClassification {
1345 NameClassificationKind Kind;
1347 TemplateName Template;
1349 const IdentifierInfo *Keyword;
1351 explicit NameClassification(NameClassificationKind Kind) : Kind(Kind) {}
1354 NameClassification(ExprResult Expr) : Kind(NC_Expression), Expr(Expr) {}
1356 NameClassification(ParsedType Type) : Kind(NC_Type), Type(Type) {}
1358 NameClassification(const IdentifierInfo *Keyword)
1359 : Kind(NC_Keyword), Keyword(Keyword) { }
1361 static NameClassification Error() {
1362 return NameClassification(NC_Error);
1365 static NameClassification Unknown() {
1366 return NameClassification(NC_Unknown);
1369 static NameClassification NestedNameSpecifier() {
1370 return NameClassification(NC_NestedNameSpecifier);
1373 static NameClassification TypeTemplate(TemplateName Name) {
1374 NameClassification Result(NC_TypeTemplate);
1375 Result.Template = Name;
1379 static NameClassification VarTemplate(TemplateName Name) {
1380 NameClassification Result(NC_VarTemplate);
1381 Result.Template = Name;
1385 static NameClassification FunctionTemplate(TemplateName Name) {
1386 NameClassification Result(NC_FunctionTemplate);
1387 Result.Template = Name;
1391 NameClassificationKind getKind() const { return Kind; }
1393 ParsedType getType() const {
1394 assert(Kind == NC_Type);
1398 ExprResult getExpression() const {
1399 assert(Kind == NC_Expression);
1403 TemplateName getTemplateName() const {
1404 assert(Kind == NC_TypeTemplate || Kind == NC_FunctionTemplate ||
1405 Kind == NC_VarTemplate);
1409 TemplateNameKind getTemplateNameKind() const {
1411 case NC_TypeTemplate:
1412 return TNK_Type_template;
1413 case NC_FunctionTemplate:
1414 return TNK_Function_template;
1415 case NC_VarTemplate:
1416 return TNK_Var_template;
1418 llvm_unreachable("unsupported name classification.");
1423 /// \brief Perform name lookup on the given name, classifying it based on
1424 /// the results of name lookup and the following token.
1426 /// This routine is used by the parser to resolve identifiers and help direct
1427 /// parsing. When the identifier cannot be found, this routine will attempt
1428 /// to correct the typo and classify based on the resulting name.
1430 /// \param S The scope in which we're performing name lookup.
1432 /// \param SS The nested-name-specifier that precedes the name.
1434 /// \param Name The identifier. If typo correction finds an alternative name,
1435 /// this pointer parameter will be updated accordingly.
1437 /// \param NameLoc The location of the identifier.
1439 /// \param NextToken The token following the identifier. Used to help
1440 /// disambiguate the name.
1442 /// \param IsAddressOfOperand True if this name is the operand of a unary
1443 /// address of ('&') expression, assuming it is classified as an
1446 /// \param CCC The correction callback, if typo correction is desired.
1447 NameClassification ClassifyName(Scope *S,
1449 IdentifierInfo *&Name,
1450 SourceLocation NameLoc,
1451 const Token &NextToken,
1452 bool IsAddressOfOperand,
1453 CorrectionCandidateCallback *CCC = 0);
1455 Decl *ActOnDeclarator(Scope *S, Declarator &D);
1457 NamedDecl *HandleDeclarator(Scope *S, Declarator &D,
1458 MultiTemplateParamsArg TemplateParameterLists);
1459 void RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S);
1460 bool DiagnoseClassNameShadow(DeclContext *DC, DeclarationNameInfo Info);
1461 bool diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
1462 DeclarationName Name,
1463 SourceLocation Loc);
1464 static bool adjustContextForLocalExternDecl(DeclContext *&DC);
1465 void DiagnoseFunctionSpecifiers(const DeclSpec &DS);
1466 void CheckShadow(Scope *S, VarDecl *D, const LookupResult& R);
1467 void CheckShadow(Scope *S, VarDecl *D);
1468 void CheckCastAlign(Expr *Op, QualType T, SourceRange TRange);
1469 void CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *D);
1470 NamedDecl* ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
1471 TypeSourceInfo *TInfo,
1472 LookupResult &Previous);
1473 NamedDecl* ActOnTypedefNameDecl(Scope* S, DeclContext* DC, TypedefNameDecl *D,
1474 LookupResult &Previous, bool &Redeclaration);
1475 NamedDecl *ActOnVariableDeclarator(Scope *S, Declarator &D, DeclContext *DC,
1476 TypeSourceInfo *TInfo,
1477 LookupResult &Previous,
1478 MultiTemplateParamsArg TemplateParamLists,
1480 // Returns true if the variable declaration is a redeclaration
1481 bool CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous);
1482 void CheckVariableDeclarationType(VarDecl *NewVD);
1483 void CheckCompleteVariableDeclaration(VarDecl *var);
1484 void MaybeSuggestAddingStaticToDecl(const FunctionDecl *D);
1485 void ActOnStartFunctionDeclarator();
1486 void ActOnEndFunctionDeclarator();
1488 NamedDecl* ActOnFunctionDeclarator(Scope* S, Declarator& D, DeclContext* DC,
1489 TypeSourceInfo *TInfo,
1490 LookupResult &Previous,
1491 MultiTemplateParamsArg TemplateParamLists,
1493 bool AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD);
1494 void checkVoidParamDecl(ParmVarDecl *Param);
1496 bool CheckConstexprFunctionDecl(const FunctionDecl *FD);
1497 bool CheckConstexprFunctionBody(const FunctionDecl *FD, Stmt *Body);
1499 void DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD);
1500 void FindHiddenVirtualMethods(CXXMethodDecl *MD,
1501 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods);
1502 void NoteHiddenVirtualMethods(CXXMethodDecl *MD,
1503 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods);
1504 // Returns true if the function declaration is a redeclaration
1505 bool CheckFunctionDeclaration(Scope *S,
1506 FunctionDecl *NewFD, LookupResult &Previous,
1507 bool IsExplicitSpecialization);
1508 void CheckMain(FunctionDecl *FD, const DeclSpec &D);
1509 void CheckMSVCRTEntryPoint(FunctionDecl *FD);
1510 Decl *ActOnParamDeclarator(Scope *S, Declarator &D);
1511 ParmVarDecl *BuildParmVarDeclForTypedef(DeclContext *DC,
1514 ParmVarDecl *CheckParameter(DeclContext *DC, SourceLocation StartLoc,
1515 SourceLocation NameLoc, IdentifierInfo *Name,
1516 QualType T, TypeSourceInfo *TSInfo,
1518 void ActOnParamDefaultArgument(Decl *param,
1519 SourceLocation EqualLoc,
1521 void ActOnParamUnparsedDefaultArgument(Decl *param,
1522 SourceLocation EqualLoc,
1523 SourceLocation ArgLoc);
1524 void ActOnParamDefaultArgumentError(Decl *param);
1525 bool SetParamDefaultArgument(ParmVarDecl *Param, Expr *DefaultArg,
1526 SourceLocation EqualLoc);
1528 void AddInitializerToDecl(Decl *dcl, Expr *init, bool DirectInit,
1529 bool TypeMayContainAuto);
1530 void ActOnUninitializedDecl(Decl *dcl, bool TypeMayContainAuto);
1531 void ActOnInitializerError(Decl *Dcl);
1532 void ActOnCXXForRangeDecl(Decl *D);
1533 void SetDeclDeleted(Decl *dcl, SourceLocation DelLoc);
1534 void SetDeclDefaulted(Decl *dcl, SourceLocation DefaultLoc);
1535 void FinalizeDeclaration(Decl *D);
1536 DeclGroupPtrTy FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
1537 ArrayRef<Decl *> Group);
1538 DeclGroupPtrTy BuildDeclaratorGroup(llvm::MutableArrayRef<Decl *> Group,
1539 bool TypeMayContainAuto = true);
1541 /// Should be called on all declarations that might have attached
1542 /// documentation comments.
1543 void ActOnDocumentableDecl(Decl *D);
1544 void ActOnDocumentableDecls(ArrayRef<Decl *> Group);
1546 void ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
1547 SourceLocation LocAfterDecls);
1548 void CheckForFunctionRedefinition(FunctionDecl *FD,
1549 const FunctionDecl *EffectiveDefinition =
1551 Decl *ActOnStartOfFunctionDef(Scope *S, Declarator &D);
1552 Decl *ActOnStartOfFunctionDef(Scope *S, Decl *D);
1553 void ActOnStartOfObjCMethodDef(Scope *S, Decl *D);
1554 bool isObjCMethodDecl(Decl *D) {
1555 return D && isa<ObjCMethodDecl>(D);
1558 /// \brief Determine whether we can skip parsing the body of a function
1559 /// definition, assuming we don't care about analyzing its body or emitting
1560 /// code for that function.
1562 /// This will be \c false only if we may need the body of the function in
1563 /// order to parse the rest of the program (for instance, if it is
1564 /// \c constexpr in C++11 or has an 'auto' return type in C++14).
1565 bool canSkipFunctionBody(Decl *D);
1567 void computeNRVO(Stmt *Body, sema::FunctionScopeInfo *Scope);
1568 Decl *ActOnFinishFunctionBody(Decl *Decl, Stmt *Body);
1569 Decl *ActOnFinishFunctionBody(Decl *Decl, Stmt *Body, bool IsInstantiation);
1570 Decl *ActOnSkippedFunctionBody(Decl *Decl);
1572 /// ActOnFinishDelayedAttribute - Invoked when we have finished parsing an
1573 /// attribute for which parsing is delayed.
1574 void ActOnFinishDelayedAttribute(Scope *S, Decl *D, ParsedAttributes &Attrs);
1576 /// \brief Diagnose any unused parameters in the given sequence of
1577 /// ParmVarDecl pointers.
1578 void DiagnoseUnusedParameters(ParmVarDecl * const *Begin,
1579 ParmVarDecl * const *End);
1581 /// \brief Diagnose whether the size of parameters or return value of a
1582 /// function or obj-c method definition is pass-by-value and larger than a
1583 /// specified threshold.
1584 void DiagnoseSizeOfParametersAndReturnValue(ParmVarDecl * const *Begin,
1585 ParmVarDecl * const *End,
1589 void DiagnoseInvalidJumps(Stmt *Body);
1590 Decl *ActOnFileScopeAsmDecl(Expr *expr,
1591 SourceLocation AsmLoc,
1592 SourceLocation RParenLoc);
1594 /// \brief Handle a C++11 empty-declaration and attribute-declaration.
1595 Decl *ActOnEmptyDeclaration(Scope *S,
1596 AttributeList *AttrList,
1597 SourceLocation SemiLoc);
1599 /// \brief The parser has processed a module import declaration.
1601 /// \param AtLoc The location of the '@' symbol, if any.
1603 /// \param ImportLoc The location of the 'import' keyword.
1605 /// \param Path The module access path.
1606 DeclResult ActOnModuleImport(SourceLocation AtLoc, SourceLocation ImportLoc,
1609 /// \brief The parser has processed a module import translated from a
1610 /// #include or similar preprocessing directive.
1611 void ActOnModuleInclude(SourceLocation DirectiveLoc, Module *Mod);
1613 /// \brief Create an implicit import of the given module at the given
1614 /// source location.
1616 /// This routine is typically used for error recovery, when the entity found
1617 /// by name lookup is actually hidden within a module that we know about but
1618 /// the user has forgotten to import.
1619 void createImplicitModuleImport(SourceLocation Loc, Module *Mod);
1621 /// \brief Retrieve a suitable printing policy.
1622 PrintingPolicy getPrintingPolicy() const {
1623 return getPrintingPolicy(Context, PP);
1626 /// \brief Retrieve a suitable printing policy.
1627 static PrintingPolicy getPrintingPolicy(const ASTContext &Ctx,
1628 const Preprocessor &PP);
1631 void ActOnPopScope(SourceLocation Loc, Scope *S);
1632 void ActOnTranslationUnitScope(Scope *S);
1634 Decl *ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS,
1636 Decl *ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS,
1638 MultiTemplateParamsArg TemplateParams,
1639 bool IsExplicitInstantiation = false);
1641 Decl *BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
1643 RecordDecl *Record);
1645 Decl *BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
1646 RecordDecl *Record);
1648 bool isAcceptableTagRedeclaration(const TagDecl *Previous,
1649 TagTypeKind NewTag, bool isDefinition,
1650 SourceLocation NewTagLoc,
1651 const IdentifierInfo &Name);
1654 TUK_Reference, // Reference to a tag: 'struct foo *X;'
1655 TUK_Declaration, // Fwd decl of a tag: 'struct foo;'
1656 TUK_Definition, // Definition of a tag: 'struct foo { int X; } Y;'
1657 TUK_Friend // Friend declaration: 'friend struct foo;'
1660 Decl *ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
1661 SourceLocation KWLoc, CXXScopeSpec &SS,
1662 IdentifierInfo *Name, SourceLocation NameLoc,
1663 AttributeList *Attr, AccessSpecifier AS,
1664 SourceLocation ModulePrivateLoc,
1665 MultiTemplateParamsArg TemplateParameterLists,
1666 bool &OwnedDecl, bool &IsDependent,
1667 SourceLocation ScopedEnumKWLoc,
1668 bool ScopedEnumUsesClassTag, TypeResult UnderlyingType);
1670 Decl *ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
1671 unsigned TagSpec, SourceLocation TagLoc,
1673 IdentifierInfo *Name, SourceLocation NameLoc,
1674 AttributeList *Attr,
1675 MultiTemplateParamsArg TempParamLists);
1677 TypeResult ActOnDependentTag(Scope *S,
1680 const CXXScopeSpec &SS,
1681 IdentifierInfo *Name,
1682 SourceLocation TagLoc,
1683 SourceLocation NameLoc);
1685 void ActOnDefs(Scope *S, Decl *TagD, SourceLocation DeclStart,
1686 IdentifierInfo *ClassName,
1687 SmallVectorImpl<Decl *> &Decls);
1688 Decl *ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
1689 Declarator &D, Expr *BitfieldWidth);
1691 FieldDecl *HandleField(Scope *S, RecordDecl *TagD, SourceLocation DeclStart,
1692 Declarator &D, Expr *BitfieldWidth,
1693 InClassInitStyle InitStyle,
1694 AccessSpecifier AS);
1695 MSPropertyDecl *HandleMSProperty(Scope *S, RecordDecl *TagD,
1696 SourceLocation DeclStart,
1697 Declarator &D, Expr *BitfieldWidth,
1698 InClassInitStyle InitStyle,
1700 AttributeList *MSPropertyAttr);
1702 FieldDecl *CheckFieldDecl(DeclarationName Name, QualType T,
1703 TypeSourceInfo *TInfo,
1704 RecordDecl *Record, SourceLocation Loc,
1705 bool Mutable, Expr *BitfieldWidth,
1706 InClassInitStyle InitStyle,
1707 SourceLocation TSSL,
1708 AccessSpecifier AS, NamedDecl *PrevDecl,
1711 bool CheckNontrivialField(FieldDecl *FD);
1712 void DiagnoseNontrivial(const CXXRecordDecl *Record, CXXSpecialMember CSM);
1713 bool SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
1714 bool Diagnose = false);
1715 CXXSpecialMember getSpecialMember(const CXXMethodDecl *MD);
1716 void ActOnLastBitfield(SourceLocation DeclStart,
1717 SmallVectorImpl<Decl *> &AllIvarDecls);
1718 Decl *ActOnIvar(Scope *S, SourceLocation DeclStart,
1719 Declarator &D, Expr *BitfieldWidth,
1720 tok::ObjCKeywordKind visibility);
1722 // This is used for both record definitions and ObjC interface declarations.
1723 void ActOnFields(Scope* S, SourceLocation RecLoc, Decl *TagDecl,
1724 ArrayRef<Decl *> Fields,
1725 SourceLocation LBrac, SourceLocation RBrac,
1726 AttributeList *AttrList);
1728 /// ActOnTagStartDefinition - Invoked when we have entered the
1729 /// scope of a tag's definition (e.g., for an enumeration, class,
1730 /// struct, or union).
1731 void ActOnTagStartDefinition(Scope *S, Decl *TagDecl);
1733 Decl *ActOnObjCContainerStartDefinition(Decl *IDecl);
1735 /// ActOnStartCXXMemberDeclarations - Invoked when we have parsed a
1736 /// C++ record definition's base-specifiers clause and are starting its
1737 /// member declarations.
1738 void ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagDecl,
1739 SourceLocation FinalLoc,
1740 bool IsFinalSpelledSealed,
1741 SourceLocation LBraceLoc);
1743 /// ActOnTagFinishDefinition - Invoked once we have finished parsing
1744 /// the definition of a tag (enumeration, class, struct, or union).
1745 void ActOnTagFinishDefinition(Scope *S, Decl *TagDecl,
1746 SourceLocation RBraceLoc);
1748 void ActOnObjCContainerFinishDefinition();
1750 /// \brief Invoked when we must temporarily exit the objective-c container
1751 /// scope for parsing/looking-up C constructs.
1753 /// Must be followed by a call to \see ActOnObjCReenterContainerContext
1754 void ActOnObjCTemporaryExitContainerContext(DeclContext *DC);
1755 void ActOnObjCReenterContainerContext(DeclContext *DC);
1757 /// ActOnTagDefinitionError - Invoked when there was an unrecoverable
1758 /// error parsing the definition of a tag.
1759 void ActOnTagDefinitionError(Scope *S, Decl *TagDecl);
1761 EnumConstantDecl *CheckEnumConstant(EnumDecl *Enum,
1762 EnumConstantDecl *LastEnumConst,
1763 SourceLocation IdLoc,
1766 bool CheckEnumUnderlyingType(TypeSourceInfo *TI);
1767 bool CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
1768 QualType EnumUnderlyingTy, const EnumDecl *Prev);
1770 Decl *ActOnEnumConstant(Scope *S, Decl *EnumDecl, Decl *LastEnumConstant,
1771 SourceLocation IdLoc, IdentifierInfo *Id,
1772 AttributeList *Attrs,
1773 SourceLocation EqualLoc, Expr *Val);
1774 void ActOnEnumBody(SourceLocation EnumLoc, SourceLocation LBraceLoc,
1775 SourceLocation RBraceLoc, Decl *EnumDecl,
1776 ArrayRef<Decl *> Elements,
1777 Scope *S, AttributeList *Attr);
1779 DeclContext *getContainingDC(DeclContext *DC);
1781 /// Set the current declaration context until it gets popped.
1782 void PushDeclContext(Scope *S, DeclContext *DC);
1783 void PopDeclContext();
1785 /// EnterDeclaratorContext - Used when we must lookup names in the context
1786 /// of a declarator's nested name specifier.
1787 void EnterDeclaratorContext(Scope *S, DeclContext *DC);
1788 void ExitDeclaratorContext(Scope *S);
1790 /// Push the parameters of D, which must be a function, into scope.
1791 void ActOnReenterFunctionContext(Scope* S, Decl* D);
1792 void ActOnExitFunctionContext();
1794 DeclContext *getFunctionLevelDeclContext();
1796 /// getCurFunctionDecl - If inside of a function body, this returns a pointer
1797 /// to the function decl for the function being parsed. If we're currently
1798 /// in a 'block', this returns the containing context.
1799 FunctionDecl *getCurFunctionDecl();
1801 /// getCurMethodDecl - If inside of a method body, this returns a pointer to
1802 /// the method decl for the method being parsed. If we're currently
1803 /// in a 'block', this returns the containing context.
1804 ObjCMethodDecl *getCurMethodDecl();
1806 /// getCurFunctionOrMethodDecl - Return the Decl for the current ObjC method
1807 /// or C function we're in, otherwise return null. If we're currently
1808 /// in a 'block', this returns the containing context.
1809 NamedDecl *getCurFunctionOrMethodDecl();
1811 /// Add this decl to the scope shadowed decl chains.
1812 void PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext = true);
1814 /// \brief Make the given externally-produced declaration visible at the
1815 /// top level scope.
1817 /// \param D The externally-produced declaration to push.
1819 /// \param Name The name of the externally-produced declaration.
1820 void pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name);
1822 /// isDeclInScope - If 'Ctx' is a function/method, isDeclInScope returns true
1823 /// if 'D' is in Scope 'S', otherwise 'S' is ignored and isDeclInScope returns
1824 /// true if 'D' belongs to the given declaration context.
1826 /// \param ExplicitInstantiationOrSpecialization When true, we are checking
1827 /// whether the declaration is in scope for the purposes of explicit template
1828 /// instantiation or specialization. The default is false.
1829 bool isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S = 0,
1830 bool ExplicitInstantiationOrSpecialization = false);
1832 /// Finds the scope corresponding to the given decl context, if it
1833 /// happens to be an enclosing scope. Otherwise return NULL.
1834 static Scope *getScopeForDeclContext(Scope *S, DeclContext *DC);
1836 /// Subroutines of ActOnDeclarator().
1837 TypedefDecl *ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
1838 TypeSourceInfo *TInfo);
1839 bool isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New);
1841 /// Attribute merging methods. Return true if a new attribute was added.
1842 AvailabilityAttr *mergeAvailabilityAttr(NamedDecl *D, SourceRange Range,
1843 IdentifierInfo *Platform,
1844 VersionTuple Introduced,
1845 VersionTuple Deprecated,
1846 VersionTuple Obsoleted,
1850 unsigned AttrSpellingListIndex);
1851 TypeVisibilityAttr *mergeTypeVisibilityAttr(Decl *D, SourceRange Range,
1852 TypeVisibilityAttr::VisibilityType Vis,
1853 unsigned AttrSpellingListIndex);
1854 VisibilityAttr *mergeVisibilityAttr(Decl *D, SourceRange Range,
1855 VisibilityAttr::VisibilityType Vis,
1856 unsigned AttrSpellingListIndex);
1857 DLLImportAttr *mergeDLLImportAttr(Decl *D, SourceRange Range,
1858 unsigned AttrSpellingListIndex);
1859 DLLExportAttr *mergeDLLExportAttr(Decl *D, SourceRange Range,
1860 unsigned AttrSpellingListIndex);
1861 FormatAttr *mergeFormatAttr(Decl *D, SourceRange Range,
1862 IdentifierInfo *Format, int FormatIdx,
1863 int FirstArg, unsigned AttrSpellingListIndex);
1864 SectionAttr *mergeSectionAttr(Decl *D, SourceRange Range, StringRef Name,
1865 unsigned AttrSpellingListIndex);
1867 /// \brief Describes the kind of merge to perform for availability
1868 /// attributes (including "deprecated", "unavailable", and "availability").
1869 enum AvailabilityMergeKind {
1870 /// \brief Don't merge availability attributes at all.
1872 /// \brief Merge availability attributes for a redeclaration, which requires
1875 /// \brief Merge availability attributes for an override, which requires
1876 /// an exact match or a weakening of constraints.
1880 void mergeDeclAttributes(NamedDecl *New, Decl *Old,
1881 AvailabilityMergeKind AMK = AMK_Redeclaration);
1882 void MergeTypedefNameDecl(TypedefNameDecl *New, LookupResult &OldDecls);
1883 bool MergeFunctionDecl(FunctionDecl *New, Decl *Old, Scope *S,
1884 bool MergeTypeWithOld);
1885 bool MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
1886 Scope *S, bool MergeTypeWithOld);
1887 void mergeObjCMethodDecls(ObjCMethodDecl *New, ObjCMethodDecl *Old);
1888 void MergeVarDecl(VarDecl *New, LookupResult &Previous);
1889 void MergeVarDeclTypes(VarDecl *New, VarDecl *Old, bool MergeTypeWithOld);
1890 void MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old);
1891 bool MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old, Scope *S);
1893 // AssignmentAction - This is used by all the assignment diagnostic functions
1894 // to represent what is actually causing the operation
1895 enum AssignmentAction {
1903 AA_Passing_CFAudited
1906 /// C++ Overloading.
1908 /// This is a legitimate overload: the existing declarations are
1909 /// functions or function templates with different signatures.
1912 /// This is not an overload because the signature exactly matches
1913 /// an existing declaration.
1916 /// This is not an overload because the lookup results contain a
1920 OverloadKind CheckOverload(Scope *S,
1922 const LookupResult &OldDecls,
1923 NamedDecl *&OldDecl,
1924 bool IsForUsingDecl);
1925 bool IsOverload(FunctionDecl *New, FunctionDecl *Old, bool IsForUsingDecl);
1927 /// \brief Checks availability of the function depending on the current
1928 /// function context.Inside an unavailable function,unavailability is ignored.
1930 /// \returns true if \p FD is unavailable and current context is inside
1931 /// an available function, false otherwise.
1932 bool isFunctionConsideredUnavailable(FunctionDecl *FD);
1934 ImplicitConversionSequence
1935 TryImplicitConversion(Expr *From, QualType ToType,
1936 bool SuppressUserConversions,
1938 bool InOverloadResolution,
1940 bool AllowObjCWritebackConversion);
1942 bool IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType);
1943 bool IsFloatingPointPromotion(QualType FromType, QualType ToType);
1944 bool IsComplexPromotion(QualType FromType, QualType ToType);
1945 bool IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
1946 bool InOverloadResolution,
1947 QualType& ConvertedType, bool &IncompatibleObjC);
1948 bool isObjCPointerConversion(QualType FromType, QualType ToType,
1949 QualType& ConvertedType, bool &IncompatibleObjC);
1950 bool isObjCWritebackConversion(QualType FromType, QualType ToType,
1951 QualType &ConvertedType);
1952 bool IsBlockPointerConversion(QualType FromType, QualType ToType,
1953 QualType& ConvertedType);
1954 bool FunctionArgTypesAreEqual(const FunctionProtoType *OldType,
1955 const FunctionProtoType *NewType,
1956 unsigned *ArgPos = 0);
1957 void HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
1958 QualType FromType, QualType ToType);
1960 CastKind PrepareCastToObjCObjectPointer(ExprResult &E);
1961 bool CheckPointerConversion(Expr *From, QualType ToType,
1963 CXXCastPath& BasePath,
1964 bool IgnoreBaseAccess);
1965 bool IsMemberPointerConversion(Expr *From, QualType FromType, QualType ToType,
1966 bool InOverloadResolution,
1967 QualType &ConvertedType);
1968 bool CheckMemberPointerConversion(Expr *From, QualType ToType,
1970 CXXCastPath &BasePath,
1971 bool IgnoreBaseAccess);
1972 bool IsQualificationConversion(QualType FromType, QualType ToType,
1973 bool CStyle, bool &ObjCLifetimeConversion);
1974 bool IsNoReturnConversion(QualType FromType, QualType ToType,
1975 QualType &ResultTy);
1976 bool DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType);
1977 bool isSameOrCompatibleFunctionType(CanQualType Param, CanQualType Arg);
1979 ExprResult PerformMoveOrCopyInitialization(const InitializedEntity &Entity,
1980 const VarDecl *NRVOCandidate,
1981 QualType ResultType,
1983 bool AllowNRVO = true);
1985 bool CanPerformCopyInitialization(const InitializedEntity &Entity,
1987 ExprResult PerformCopyInitialization(const InitializedEntity &Entity,
1988 SourceLocation EqualLoc,
1990 bool TopLevelOfInitList = false,
1991 bool AllowExplicit = false);
1992 ExprResult PerformObjectArgumentInitialization(Expr *From,
1993 NestedNameSpecifier *Qualifier,
1994 NamedDecl *FoundDecl,
1995 CXXMethodDecl *Method);
1997 ExprResult PerformContextuallyConvertToBool(Expr *From);
1998 ExprResult PerformContextuallyConvertToObjCPointer(Expr *From);
2000 /// Contexts in which a converted constant expression is required.
2002 CCEK_CaseValue, ///< Expression in a case label.
2003 CCEK_Enumerator, ///< Enumerator value with fixed underlying type.
2004 CCEK_TemplateArg, ///< Value of a non-type template parameter.
2005 CCEK_NewExpr ///< Constant expression in a noptr-new-declarator.
2007 ExprResult CheckConvertedConstantExpression(Expr *From, QualType T,
2008 llvm::APSInt &Value, CCEKind CCE);
2010 /// \brief Abstract base class used to perform a contextual implicit
2011 /// conversion from an expression to any type passing a filter.
2012 class ContextualImplicitConverter {
2015 bool SuppressConversion;
2017 ContextualImplicitConverter(bool Suppress = false,
2018 bool SuppressConversion = false)
2019 : Suppress(Suppress), SuppressConversion(SuppressConversion) {}
2021 /// \brief Determine whether the specified type is a valid destination type
2022 /// for this conversion.
2023 virtual bool match(QualType T) = 0;
2025 /// \brief Emits a diagnostic complaining that the expression does not have
2026 /// integral or enumeration type.
2027 virtual SemaDiagnosticBuilder
2028 diagnoseNoMatch(Sema &S, SourceLocation Loc, QualType T) = 0;
2030 /// \brief Emits a diagnostic when the expression has incomplete class type.
2031 virtual SemaDiagnosticBuilder
2032 diagnoseIncomplete(Sema &S, SourceLocation Loc, QualType T) = 0;
2034 /// \brief Emits a diagnostic when the only matching conversion function
2036 virtual SemaDiagnosticBuilder diagnoseExplicitConv(
2037 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) = 0;
2039 /// \brief Emits a note for the explicit conversion function.
2040 virtual SemaDiagnosticBuilder
2041 noteExplicitConv(Sema &S, CXXConversionDecl *Conv, QualType ConvTy) = 0;
2043 /// \brief Emits a diagnostic when there are multiple possible conversion
2045 virtual SemaDiagnosticBuilder
2046 diagnoseAmbiguous(Sema &S, SourceLocation Loc, QualType T) = 0;
2048 /// \brief Emits a note for one of the candidate conversions.
2049 virtual SemaDiagnosticBuilder
2050 noteAmbiguous(Sema &S, CXXConversionDecl *Conv, QualType ConvTy) = 0;
2052 /// \brief Emits a diagnostic when we picked a conversion function
2053 /// (for cases when we are not allowed to pick a conversion function).
2054 virtual SemaDiagnosticBuilder diagnoseConversion(
2055 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) = 0;
2057 virtual ~ContextualImplicitConverter() {}
2060 class ICEConvertDiagnoser : public ContextualImplicitConverter {
2061 bool AllowScopedEnumerations;
2064 ICEConvertDiagnoser(bool AllowScopedEnumerations,
2065 bool Suppress, bool SuppressConversion)
2066 : ContextualImplicitConverter(Suppress, SuppressConversion),
2067 AllowScopedEnumerations(AllowScopedEnumerations) {}
2069 /// Match an integral or (possibly scoped) enumeration type.
2070 bool match(QualType T);
2072 SemaDiagnosticBuilder
2073 diagnoseNoMatch(Sema &S, SourceLocation Loc, QualType T) {
2074 return diagnoseNotInt(S, Loc, T);
2077 /// \brief Emits a diagnostic complaining that the expression does not have
2078 /// integral or enumeration type.
2079 virtual SemaDiagnosticBuilder
2080 diagnoseNotInt(Sema &S, SourceLocation Loc, QualType T) = 0;
2083 /// Perform a contextual implicit conversion.
2084 ExprResult PerformContextualImplicitConversion(
2085 SourceLocation Loc, Expr *FromE, ContextualImplicitConverter &Converter);
2088 enum ObjCSubscriptKind {
2093 ObjCSubscriptKind CheckSubscriptingKind(Expr *FromE);
2095 // Note that LK_String is intentionally after the other literals, as
2096 // this is used for diagnostics logic.
2097 enum ObjCLiteralKind {
2106 ObjCLiteralKind CheckLiteralKind(Expr *FromE);
2108 ExprResult PerformObjectMemberConversion(Expr *From,
2109 NestedNameSpecifier *Qualifier,
2110 NamedDecl *FoundDecl,
2113 // Members have to be NamespaceDecl* or TranslationUnitDecl*.
2114 // TODO: make this is a typesafe union.
2115 typedef llvm::SmallPtrSet<DeclContext *, 16> AssociatedNamespaceSet;
2116 typedef llvm::SmallPtrSet<CXXRecordDecl *, 16> AssociatedClassSet;
2118 void AddOverloadCandidate(FunctionDecl *Function,
2119 DeclAccessPair FoundDecl,
2120 ArrayRef<Expr *> Args,
2121 OverloadCandidateSet& CandidateSet,
2122 bool SuppressUserConversions = false,
2123 bool PartialOverloading = false,
2124 bool AllowExplicit = false);
2125 void AddFunctionCandidates(const UnresolvedSetImpl &Functions,
2126 ArrayRef<Expr *> Args,
2127 OverloadCandidateSet& CandidateSet,
2128 bool SuppressUserConversions = false,
2129 TemplateArgumentListInfo *ExplicitTemplateArgs = 0);
2130 void AddMethodCandidate(DeclAccessPair FoundDecl,
2131 QualType ObjectType,
2132 Expr::Classification ObjectClassification,
2133 ArrayRef<Expr *> Args,
2134 OverloadCandidateSet& CandidateSet,
2135 bool SuppressUserConversion = false);
2136 void AddMethodCandidate(CXXMethodDecl *Method,
2137 DeclAccessPair FoundDecl,
2138 CXXRecordDecl *ActingContext, QualType ObjectType,
2139 Expr::Classification ObjectClassification,
2140 ArrayRef<Expr *> Args,
2141 OverloadCandidateSet& CandidateSet,
2142 bool SuppressUserConversions = false);
2143 void AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
2144 DeclAccessPair FoundDecl,
2145 CXXRecordDecl *ActingContext,
2146 TemplateArgumentListInfo *ExplicitTemplateArgs,
2147 QualType ObjectType,
2148 Expr::Classification ObjectClassification,
2149 ArrayRef<Expr *> Args,
2150 OverloadCandidateSet& CandidateSet,
2151 bool SuppressUserConversions = false);
2152 void AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
2153 DeclAccessPair FoundDecl,
2154 TemplateArgumentListInfo *ExplicitTemplateArgs,
2155 ArrayRef<Expr *> Args,
2156 OverloadCandidateSet& CandidateSet,
2157 bool SuppressUserConversions = false);
2158 void AddConversionCandidate(CXXConversionDecl *Conversion,
2159 DeclAccessPair FoundDecl,
2160 CXXRecordDecl *ActingContext,
2161 Expr *From, QualType ToType,
2162 OverloadCandidateSet& CandidateSet,
2163 bool AllowObjCConversionOnExplicit = false);
2164 void AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
2165 DeclAccessPair FoundDecl,
2166 CXXRecordDecl *ActingContext,
2167 Expr *From, QualType ToType,
2168 OverloadCandidateSet &CandidateSet,
2169 bool AllowObjCConversionOnExplicit = false);
2170 void AddSurrogateCandidate(CXXConversionDecl *Conversion,
2171 DeclAccessPair FoundDecl,
2172 CXXRecordDecl *ActingContext,
2173 const FunctionProtoType *Proto,
2174 Expr *Object, ArrayRef<Expr *> Args,
2175 OverloadCandidateSet& CandidateSet);
2176 void AddMemberOperatorCandidates(OverloadedOperatorKind Op,
2177 SourceLocation OpLoc, ArrayRef<Expr *> Args,
2178 OverloadCandidateSet& CandidateSet,
2179 SourceRange OpRange = SourceRange());
2180 void AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
2181 ArrayRef<Expr *> Args,
2182 OverloadCandidateSet& CandidateSet,
2183 bool IsAssignmentOperator = false,
2184 unsigned NumContextualBoolArguments = 0);
2185 void AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
2186 SourceLocation OpLoc, ArrayRef<Expr *> Args,
2187 OverloadCandidateSet& CandidateSet);
2188 void AddArgumentDependentLookupCandidates(DeclarationName Name,
2189 bool Operator, SourceLocation Loc,
2190 ArrayRef<Expr *> Args,
2191 TemplateArgumentListInfo *ExplicitTemplateArgs,
2192 OverloadCandidateSet& CandidateSet,
2193 bool PartialOverloading = false);
2195 // Emit as a 'note' the specific overload candidate
2196 void NoteOverloadCandidate(FunctionDecl *Fn, QualType DestType = QualType());
2198 // Emit as a series of 'note's all template and non-templates
2199 // identified by the expression Expr
2200 void NoteAllOverloadCandidates(Expr* E, QualType DestType = QualType());
2202 // [PossiblyAFunctionType] --> [Return]
2203 // NonFunctionType --> NonFunctionType
2205 // R (*)(A) --> R (A)
2206 // R (&)(A) --> R (A)
2207 // R (S::*)(A) --> R (A)
2208 QualType ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType);
2211 ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
2212 QualType TargetType,
2214 DeclAccessPair &Found,
2215 bool *pHadMultipleCandidates = 0);
2217 FunctionDecl *ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
2218 bool Complain = false,
2219 DeclAccessPair* Found = 0);
2221 bool ResolveAndFixSingleFunctionTemplateSpecialization(
2222 ExprResult &SrcExpr,
2223 bool DoFunctionPointerConverion = false,
2224 bool Complain = false,
2225 const SourceRange& OpRangeForComplaining = SourceRange(),
2226 QualType DestTypeForComplaining = QualType(),
2227 unsigned DiagIDForComplaining = 0);
2230 Expr *FixOverloadedFunctionReference(Expr *E,
2231 DeclAccessPair FoundDecl,
2233 ExprResult FixOverloadedFunctionReference(ExprResult,
2234 DeclAccessPair FoundDecl,
2237 void AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
2238 ArrayRef<Expr *> Args,
2239 OverloadCandidateSet &CandidateSet,
2240 bool PartialOverloading = false);
2242 // An enum used to represent the different possible results of building a
2243 // range-based for loop.
2244 enum ForRangeStatus {
2246 FRS_NoViableFunction,
2247 FRS_DiagnosticIssued
2250 // An enum to represent whether something is dealing with a call to begin()
2251 // or a call to end() in a range-based for loop.
2252 enum BeginEndFunction {
2257 ForRangeStatus BuildForRangeBeginEndCall(Scope *S, SourceLocation Loc,
2258 SourceLocation RangeLoc,
2260 BeginEndFunction BEF,
2261 const DeclarationNameInfo &NameInfo,
2262 LookupResult &MemberLookup,
2263 OverloadCandidateSet *CandidateSet,
2264 Expr *Range, ExprResult *CallExpr);
2266 ExprResult BuildOverloadedCallExpr(Scope *S, Expr *Fn,
2267 UnresolvedLookupExpr *ULE,
2268 SourceLocation LParenLoc,
2270 SourceLocation RParenLoc,
2272 bool AllowTypoCorrection=true);
2274 bool buildOverloadedCallSet(Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE,
2275 MultiExprArg Args, SourceLocation RParenLoc,
2276 OverloadCandidateSet *CandidateSet,
2277 ExprResult *Result);
2279 ExprResult CreateOverloadedUnaryOp(SourceLocation OpLoc,
2281 const UnresolvedSetImpl &Fns,
2284 ExprResult CreateOverloadedBinOp(SourceLocation OpLoc,
2286 const UnresolvedSetImpl &Fns,
2287 Expr *LHS, Expr *RHS);
2289 ExprResult CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
2290 SourceLocation RLoc,
2291 Expr *Base,Expr *Idx);
2294 BuildCallToMemberFunction(Scope *S, Expr *MemExpr,
2295 SourceLocation LParenLoc,
2297 SourceLocation RParenLoc);
2299 BuildCallToObjectOfClassType(Scope *S, Expr *Object, SourceLocation LParenLoc,
2301 SourceLocation RParenLoc);
2303 ExprResult BuildOverloadedArrowExpr(Scope *S, Expr *Base,
2304 SourceLocation OpLoc,
2305 bool *NoArrowOperatorFound = 0);
2307 /// CheckCallReturnType - Checks that a call expression's return type is
2308 /// complete. Returns true on failure. The location passed in is the location
2309 /// that best represents the call.
2310 bool CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
2311 CallExpr *CE, FunctionDecl *FD);
2313 /// Helpers for dealing with blocks and functions.
2314 bool CheckParmsForFunctionDef(ParmVarDecl *const *Param,
2315 ParmVarDecl *const *ParamEnd,
2316 bool CheckParameterNames);
2317 void CheckCXXDefaultArguments(FunctionDecl *FD);
2318 void CheckExtraCXXDefaultArguments(Declarator &D);
2319 Scope *getNonFieldDeclScope(Scope *S);
2321 /// \name Name lookup
2323 /// These routines provide name lookup that is used during semantic
2324 /// analysis to resolve the various kinds of names (identifiers,
2325 /// overloaded operator names, constructor names, etc.) into zero or
2326 /// more declarations within a particular scope. The major entry
2327 /// points are LookupName, which performs unqualified name lookup,
2328 /// and LookupQualifiedName, which performs qualified name lookup.
2330 /// All name lookup is performed based on some specific criteria,
2331 /// which specify what names will be visible to name lookup and how
2332 /// far name lookup should work. These criteria are important both
2333 /// for capturing language semantics (certain lookups will ignore
2334 /// certain names, for example) and for performance, since name
2335 /// lookup is often a bottleneck in the compilation of C++. Name
2336 /// lookup criteria is specified via the LookupCriteria enumeration.
2338 /// The results of name lookup can vary based on the kind of name
2339 /// lookup performed, the current language, and the translation
2340 /// unit. In C, for example, name lookup will either return nothing
2341 /// (no entity found) or a single declaration. In C++, name lookup
2342 /// can additionally refer to a set of overloaded functions or
2343 /// result in an ambiguity. All of the possible results of name
2344 /// lookup are captured by the LookupResult class, which provides
2345 /// the ability to distinguish among them.
2348 /// @brief Describes the kind of name lookup to perform.
2349 enum LookupNameKind {
2350 /// Ordinary name lookup, which finds ordinary names (functions,
2351 /// variables, typedefs, etc.) in C and most kinds of names
2352 /// (functions, variables, members, types, etc.) in C++.
2353 LookupOrdinaryName = 0,
2354 /// Tag name lookup, which finds the names of enums, classes,
2355 /// structs, and unions.
2357 /// Label name lookup.
2359 /// Member name lookup, which finds the names of
2360 /// class/struct/union members.
2362 /// Look up of an operator name (e.g., operator+) for use with
2363 /// operator overloading. This lookup is similar to ordinary name
2364 /// lookup, but will ignore any declarations that are class members.
2366 /// Look up of a name that precedes the '::' scope resolution
2367 /// operator in C++. This lookup completely ignores operator, object,
2368 /// function, and enumerator names (C++ [basic.lookup.qual]p1).
2369 LookupNestedNameSpecifierName,
2370 /// Look up a namespace name within a C++ using directive or
2371 /// namespace alias definition, ignoring non-namespace names (C++
2372 /// [basic.lookup.udir]p1).
2373 LookupNamespaceName,
2374 /// Look up all declarations in a scope with the given name,
2375 /// including resolved using declarations. This is appropriate
2376 /// for checking redeclarations for a using declaration.
2377 LookupUsingDeclName,
2378 /// Look up an ordinary name that is going to be redeclared as a
2379 /// name with linkage. This lookup ignores any declarations that
2380 /// are outside of the current scope unless they have linkage. See
2381 /// C99 6.2.2p4-5 and C++ [basic.link]p6.
2382 LookupRedeclarationWithLinkage,
2383 /// Look up a friend of a local class. This lookup does not look
2384 /// outside the innermost non-class scope. See C++11 [class.friend]p11.
2385 LookupLocalFriendName,
2386 /// Look up the name of an Objective-C protocol.
2387 LookupObjCProtocolName,
2388 /// Look up implicit 'self' parameter of an objective-c method.
2389 LookupObjCImplicitSelfParam,
2390 /// \brief Look up any declaration with any name.
2394 /// \brief Specifies whether (or how) name lookup is being performed for a
2395 /// redeclaration (vs. a reference).
2396 enum RedeclarationKind {
2397 /// \brief The lookup is a reference to this name that is not for the
2398 /// purpose of redeclaring the name.
2399 NotForRedeclaration = 0,
2400 /// \brief The lookup results will be used for redeclaration of a name,
2401 /// if an entity by that name already exists.
2405 /// \brief The possible outcomes of name lookup for a literal operator.
2406 enum LiteralOperatorLookupResult {
2407 /// \brief The lookup resulted in an error.
2409 /// \brief The lookup found a single 'cooked' literal operator, which
2410 /// expects a normal literal to be built and passed to it.
2412 /// \brief The lookup found a single 'raw' literal operator, which expects
2413 /// a string literal containing the spelling of the literal token.
2415 /// \brief The lookup found an overload set of literal operator templates,
2416 /// which expect the characters of the spelling of the literal token to be
2417 /// passed as a non-type template argument pack.
2419 /// \brief The lookup found an overload set of literal operator templates,
2420 /// which expect the character type and characters of the spelling of the
2421 /// string literal token to be passed as template arguments.
2425 SpecialMemberOverloadResult *LookupSpecialMember(CXXRecordDecl *D,
2426 CXXSpecialMember SM,
2434 bool CppLookupName(LookupResult &R, Scope *S);
2436 // \brief The set of known/encountered (unique, canonicalized) NamespaceDecls.
2438 // The boolean value will be true to indicate that the namespace was loaded
2439 // from an AST/PCH file, or false otherwise.
2440 llvm::MapVector<NamespaceDecl*, bool> KnownNamespaces;
2442 /// \brief Whether we have already loaded known namespaces from an extenal
2444 bool LoadedExternalKnownNamespaces;
2447 /// \brief Look up a name, looking for a single declaration. Return
2448 /// null if the results were absent, ambiguous, or overloaded.
2450 /// It is preferable to use the elaborated form and explicitly handle
2451 /// ambiguity and overloaded.
2452 NamedDecl *LookupSingleName(Scope *S, DeclarationName Name,
2454 LookupNameKind NameKind,
2455 RedeclarationKind Redecl
2456 = NotForRedeclaration);
2457 bool LookupName(LookupResult &R, Scope *S,
2458 bool AllowBuiltinCreation = false);
2459 bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
2460 bool InUnqualifiedLookup = false);
2461 bool LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS,
2462 bool AllowBuiltinCreation = false,
2463 bool EnteringContext = false);
2464 ObjCProtocolDecl *LookupProtocol(IdentifierInfo *II, SourceLocation IdLoc,
2465 RedeclarationKind Redecl
2466 = NotForRedeclaration);
2468 void LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S,
2469 QualType T1, QualType T2,
2470 UnresolvedSetImpl &Functions);
2472 LabelDecl *LookupOrCreateLabel(IdentifierInfo *II, SourceLocation IdentLoc,
2473 SourceLocation GnuLabelLoc = SourceLocation());
2475 DeclContextLookupResult LookupConstructors(CXXRecordDecl *Class);
2476 CXXConstructorDecl *LookupDefaultConstructor(CXXRecordDecl *Class);
2477 CXXConstructorDecl *LookupCopyingConstructor(CXXRecordDecl *Class,
2479 CXXMethodDecl *LookupCopyingAssignment(CXXRecordDecl *Class, unsigned Quals,
2480 bool RValueThis, unsigned ThisQuals);
2481 CXXConstructorDecl *LookupMovingConstructor(CXXRecordDecl *Class,
2483 CXXMethodDecl *LookupMovingAssignment(CXXRecordDecl *Class, unsigned Quals,
2484 bool RValueThis, unsigned ThisQuals);
2485 CXXDestructorDecl *LookupDestructor(CXXRecordDecl *Class);
2487 LiteralOperatorLookupResult LookupLiteralOperator(Scope *S, LookupResult &R,
2488 ArrayRef<QualType> ArgTys,
2491 bool AllowStringTemplate);
2492 bool isKnownName(StringRef name);
2494 void ArgumentDependentLookup(DeclarationName Name, bool Operator,
2496 ArrayRef<Expr *> Args,
2497 ADLResult &Functions);
2499 void LookupVisibleDecls(Scope *S, LookupNameKind Kind,
2500 VisibleDeclConsumer &Consumer,
2501 bool IncludeGlobalScope = true);
2502 void LookupVisibleDecls(DeclContext *Ctx, LookupNameKind Kind,
2503 VisibleDeclConsumer &Consumer,
2504 bool IncludeGlobalScope = true);
2506 TypoCorrection CorrectTypo(const DeclarationNameInfo &Typo,
2507 Sema::LookupNameKind LookupKind,
2508 Scope *S, CXXScopeSpec *SS,
2509 CorrectionCandidateCallback &CCC,
2510 DeclContext *MemberContext = 0,
2511 bool EnteringContext = false,
2512 const ObjCObjectPointerType *OPT = 0,
2513 bool RecordFailure = true);
2515 void diagnoseTypo(const TypoCorrection &Correction,
2516 const PartialDiagnostic &TypoDiag,
2517 bool ErrorRecovery = true);
2519 void diagnoseTypo(const TypoCorrection &Correction,
2520 const PartialDiagnostic &TypoDiag,
2521 const PartialDiagnostic &PrevNote,
2522 bool ErrorRecovery = true);
2524 void FindAssociatedClassesAndNamespaces(SourceLocation InstantiationLoc,
2525 ArrayRef<Expr *> Args,
2526 AssociatedNamespaceSet &AssociatedNamespaces,
2527 AssociatedClassSet &AssociatedClasses);
2529 void FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S,
2530 bool ConsiderLinkage,
2531 bool ExplicitInstantiationOrSpecialization);
2533 void DiagnoseAmbiguousLookup(LookupResult &Result);
2536 ObjCInterfaceDecl *getObjCInterfaceDecl(IdentifierInfo *&Id,
2537 SourceLocation IdLoc,
2538 bool TypoCorrection = false);
2539 NamedDecl *LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID,
2540 Scope *S, bool ForRedeclaration,
2541 SourceLocation Loc);
2542 NamedDecl *ImplicitlyDefineFunction(SourceLocation Loc, IdentifierInfo &II,
2544 void AddKnownFunctionAttributes(FunctionDecl *FD);
2546 // More parsing and symbol table subroutines.
2548 void ProcessPragmaWeak(Scope *S, Decl *D);
2549 // Decl attributes - this routine is the top level dispatcher.
2550 void ProcessDeclAttributes(Scope *S, Decl *D, const Declarator &PD);
2551 void ProcessDeclAttributeList(Scope *S, Decl *D, const AttributeList *AL,
2552 bool IncludeCXX11Attributes = true);
2553 bool ProcessAccessDeclAttributeList(AccessSpecDecl *ASDecl,
2554 const AttributeList *AttrList);
2556 void checkUnusedDeclAttributes(Declarator &D);
2558 bool CheckRegparmAttr(const AttributeList &attr, unsigned &value);
2559 bool CheckCallingConvAttr(const AttributeList &attr, CallingConv &CC,
2560 const FunctionDecl *FD = 0);
2561 bool CheckNoReturnAttr(const AttributeList &attr);
2562 bool checkStringLiteralArgumentAttr(const AttributeList &Attr,
2563 unsigned ArgNum, StringRef &Str,
2564 SourceLocation *ArgLocation = 0);
2566 void CheckAlignasUnderalignment(Decl *D);
2568 /// Adjust the calling convention of a method to be the ABI default if it
2569 /// wasn't specified explicitly. This handles method types formed from
2570 /// function type typedefs and typename template arguments.
2571 void adjustMemberFunctionCC(QualType &T, bool IsStatic);
2573 /// Get the outermost AttributedType node that sets a calling convention.
2574 /// Valid types should not have multiple attributes with different CCs.
2575 const AttributedType *getCallingConvAttributedType(QualType T) const;
2577 /// \brief Stmt attributes - this routine is the top level dispatcher.
2578 StmtResult ProcessStmtAttributes(Stmt *Stmt, AttributeList *Attrs,
2581 void WarnUndefinedMethod(SourceLocation ImpLoc, ObjCMethodDecl *method,
2582 bool &IncompleteImpl, unsigned DiagID);
2583 void WarnConflictingTypedMethods(ObjCMethodDecl *Method,
2584 ObjCMethodDecl *MethodDecl,
2585 bool IsProtocolMethodDecl);
2587 void CheckConflictingOverridingMethod(ObjCMethodDecl *Method,
2588 ObjCMethodDecl *Overridden,
2589 bool IsProtocolMethodDecl);
2591 /// WarnExactTypedMethods - This routine issues a warning if method
2592 /// implementation declaration matches exactly that of its declaration.
2593 void WarnExactTypedMethods(ObjCMethodDecl *Method,
2594 ObjCMethodDecl *MethodDecl,
2595 bool IsProtocolMethodDecl);
2597 typedef llvm::SmallPtrSet<Selector, 8> SelectorSet;
2598 typedef llvm::DenseMap<Selector, ObjCMethodDecl*> ProtocolsMethodsMap;
2600 /// CheckProtocolMethodDefs - This routine checks unimplemented
2601 /// methods declared in protocol, and those referenced by it.
2602 void CheckProtocolMethodDefs(SourceLocation ImpLoc,
2603 ObjCProtocolDecl *PDecl,
2604 bool& IncompleteImpl,
2605 const SelectorSet &InsMap,
2606 const SelectorSet &ClsMap,
2607 ObjCContainerDecl *CDecl);
2609 /// CheckImplementationIvars - This routine checks if the instance variables
2610 /// listed in the implelementation match those listed in the interface.
2611 void CheckImplementationIvars(ObjCImplementationDecl *ImpDecl,
2612 ObjCIvarDecl **Fields, unsigned nIvars,
2613 SourceLocation Loc);
2615 /// ImplMethodsVsClassMethods - This is main routine to warn if any method
2616 /// remains unimplemented in the class or category \@implementation.
2617 void ImplMethodsVsClassMethods(Scope *S, ObjCImplDecl* IMPDecl,
2618 ObjCContainerDecl* IDecl,
2619 bool IncompleteImpl = false);
2621 /// DiagnoseUnimplementedProperties - This routine warns on those properties
2622 /// which must be implemented by this implementation.
2623 void DiagnoseUnimplementedProperties(Scope *S, ObjCImplDecl* IMPDecl,
2624 ObjCContainerDecl *CDecl);
2626 /// DefaultSynthesizeProperties - This routine default synthesizes all
2627 /// properties which must be synthesized in the class's \@implementation.
2628 void DefaultSynthesizeProperties (Scope *S, ObjCImplDecl* IMPDecl,
2629 ObjCInterfaceDecl *IDecl);
2630 void DefaultSynthesizeProperties(Scope *S, Decl *D);
2632 /// CollectImmediateProperties - This routine collects all properties in
2633 /// the class and its conforming protocols; but not those it its super class.
2634 void CollectImmediateProperties(ObjCContainerDecl *CDecl,
2635 llvm::DenseMap<IdentifierInfo *, ObjCPropertyDecl*>& PropMap,
2636 llvm::DenseMap<IdentifierInfo *, ObjCPropertyDecl*>& SuperPropMap);
2638 /// IvarBacksCurrentMethodAccessor - This routine returns 'true' if 'IV' is
2639 /// an ivar synthesized for 'Method' and 'Method' is a property accessor
2640 /// declared in class 'IFace'.
2641 bool IvarBacksCurrentMethodAccessor(ObjCInterfaceDecl *IFace,
2642 ObjCMethodDecl *Method, ObjCIvarDecl *IV);
2644 /// DiagnoseUnusedBackingIvarInAccessor - Issue an 'unused' warning if ivar which
2645 /// backs the property is not used in the property's accessor.
2646 void DiagnoseUnusedBackingIvarInAccessor(Scope *S);
2648 /// GetIvarBackingPropertyAccessor - If method is a property setter/getter and
2649 /// it property has a backing ivar, returns this ivar; otherwise, returns NULL.
2650 /// It also returns ivar's property on success.
2651 ObjCIvarDecl *GetIvarBackingPropertyAccessor(const ObjCMethodDecl *Method,
2652 const ObjCPropertyDecl *&PDecl) const;
2654 /// Called by ActOnProperty to handle \@property declarations in
2655 /// class extensions.
2656 ObjCPropertyDecl *HandlePropertyInClassExtension(Scope *S,
2657 SourceLocation AtLoc,
2658 SourceLocation LParenLoc,
2659 FieldDeclarator &FD,
2662 const bool isAssign,
2663 const bool isReadWrite,
2664 const unsigned Attributes,
2665 const unsigned AttributesAsWritten,
2666 bool *isOverridingProperty,
2668 tok::ObjCKeywordKind MethodImplKind);
2670 /// Called by ActOnProperty and HandlePropertyInClassExtension to
2671 /// handle creating the ObjcPropertyDecl for a category or \@interface.
2672 ObjCPropertyDecl *CreatePropertyDecl(Scope *S,
2673 ObjCContainerDecl *CDecl,
2674 SourceLocation AtLoc,
2675 SourceLocation LParenLoc,
2676 FieldDeclarator &FD,
2679 const bool isAssign,
2680 const bool isReadWrite,
2681 const unsigned Attributes,
2682 const unsigned AttributesAsWritten,
2684 tok::ObjCKeywordKind MethodImplKind,
2685 DeclContext *lexicalDC = 0);
2687 /// AtomicPropertySetterGetterRules - This routine enforces the rule (via
2688 /// warning) when atomic property has one but not the other user-declared
2689 /// setter or getter.
2690 void AtomicPropertySetterGetterRules(ObjCImplDecl* IMPDecl,
2691 ObjCContainerDecl* IDecl);
2693 void DiagnoseOwningPropertyGetterSynthesis(const ObjCImplementationDecl *D);
2695 void DiagnoseDuplicateIvars(ObjCInterfaceDecl *ID, ObjCInterfaceDecl *SID);
2697 enum MethodMatchStrategy {
2702 /// MatchTwoMethodDeclarations - Checks if two methods' type match and returns
2703 /// true, or false, accordingly.
2704 bool MatchTwoMethodDeclarations(const ObjCMethodDecl *Method,
2705 const ObjCMethodDecl *PrevMethod,
2706 MethodMatchStrategy strategy = MMS_strict);
2708 /// MatchAllMethodDeclarations - Check methods declaraed in interface or
2709 /// or protocol against those declared in their implementations.
2710 void MatchAllMethodDeclarations(const SelectorSet &InsMap,
2711 const SelectorSet &ClsMap,
2712 SelectorSet &InsMapSeen,
2713 SelectorSet &ClsMapSeen,
2714 ObjCImplDecl* IMPDecl,
2715 ObjCContainerDecl* IDecl,
2716 bool &IncompleteImpl,
2717 bool ImmediateClass,
2718 bool WarnCategoryMethodImpl=false);
2720 /// CheckCategoryVsClassMethodMatches - Checks that methods implemented in
2721 /// category matches with those implemented in its primary class and
2722 /// warns each time an exact match is found.
2723 void CheckCategoryVsClassMethodMatches(ObjCCategoryImplDecl *CatIMP);
2725 /// \brief Add the given method to the list of globally-known methods.
2726 void addMethodToGlobalList(ObjCMethodList *List, ObjCMethodDecl *Method);
2729 /// AddMethodToGlobalPool - Add an instance or factory method to the global
2730 /// pool. See descriptoin of AddInstanceMethodToGlobalPool.
2731 void AddMethodToGlobalPool(ObjCMethodDecl *Method, bool impl, bool instance);
2733 /// LookupMethodInGlobalPool - Returns the instance or factory method and
2734 /// optionally warns if there are multiple signatures.
2735 ObjCMethodDecl *LookupMethodInGlobalPool(Selector Sel, SourceRange R,
2736 bool receiverIdOrClass,
2737 bool warn, bool instance);
2739 /// \brief Record the typo correction failure and return an empty correction.
2740 TypoCorrection FailedCorrection(IdentifierInfo *Typo, SourceLocation TypoLoc,
2741 bool RecordFailure = true,
2742 bool IsUnqualifiedLookup = false) {
2743 if (IsUnqualifiedLookup)
2744 (void)UnqualifiedTyposCorrected[Typo];
2746 TypoCorrectionFailures[Typo].insert(TypoLoc);
2747 return TypoCorrection();
2751 /// AddInstanceMethodToGlobalPool - All instance methods in a translation
2752 /// unit are added to a global pool. This allows us to efficiently associate
2753 /// a selector with a method declaraation for purposes of typechecking
2754 /// messages sent to "id" (where the class of the object is unknown).
2755 void AddInstanceMethodToGlobalPool(ObjCMethodDecl *Method, bool impl=false) {
2756 AddMethodToGlobalPool(Method, impl, /*instance*/true);
2759 /// AddFactoryMethodToGlobalPool - Same as above, but for factory methods.
2760 void AddFactoryMethodToGlobalPool(ObjCMethodDecl *Method, bool impl=false) {
2761 AddMethodToGlobalPool(Method, impl, /*instance*/false);
2764 /// AddAnyMethodToGlobalPool - Add any method, instance or factory to global
2766 void AddAnyMethodToGlobalPool(Decl *D);
2768 /// LookupInstanceMethodInGlobalPool - Returns the method and warns if
2769 /// there are multiple signatures.
2770 ObjCMethodDecl *LookupInstanceMethodInGlobalPool(Selector Sel, SourceRange R,
2771 bool receiverIdOrClass=false,
2773 return LookupMethodInGlobalPool(Sel, R, receiverIdOrClass,
2774 warn, /*instance*/true);
2777 /// LookupFactoryMethodInGlobalPool - Returns the method and warns if
2778 /// there are multiple signatures.
2779 ObjCMethodDecl *LookupFactoryMethodInGlobalPool(Selector Sel, SourceRange R,
2780 bool receiverIdOrClass=false,
2782 return LookupMethodInGlobalPool(Sel, R, receiverIdOrClass,
2783 warn, /*instance*/false);
2786 const ObjCMethodDecl *SelectorsForTypoCorrection(Selector Sel,
2787 QualType ObjectType=QualType());
2789 /// DiagnoseMismatchedMethodsInGlobalPool - This routine goes through list of
2790 /// methods in global pool and issues diagnostic on identical selectors which
2791 /// have mismathched types.
2792 void DiagnoseMismatchedMethodsInGlobalPool();
2794 /// LookupImplementedMethodInGlobalPool - Returns the method which has an
2796 ObjCMethodDecl *LookupImplementedMethodInGlobalPool(Selector Sel);
2798 /// CollectIvarsToConstructOrDestruct - Collect those ivars which require
2800 void CollectIvarsToConstructOrDestruct(ObjCInterfaceDecl *OI,
2801 SmallVectorImpl<ObjCIvarDecl*> &Ivars);
2803 //===--------------------------------------------------------------------===//
2804 // Statement Parsing Callbacks: SemaStmt.cpp.
2808 FullExprArg(Sema &actions) : E(0) { }
2810 // FIXME: The const_cast here is ugly. RValue references would make this
2811 // much nicer (or we could duplicate a bunch of the move semantics
2812 // emulation code from Ownership.h).
2813 FullExprArg(const FullExprArg& Other) : E(Other.E) {}
2815 ExprResult release() {
2819 Expr *get() const { return E; }
2821 Expr *operator->() {
2826 // FIXME: No need to make the entire Sema class a friend when it's just
2827 // Sema::MakeFullExpr that needs access to the constructor below.
2830 explicit FullExprArg(Expr *expr) : E(expr) {}
2835 FullExprArg MakeFullExpr(Expr *Arg) {
2836 return MakeFullExpr(Arg, Arg ? Arg->getExprLoc() : SourceLocation());
2838 FullExprArg MakeFullExpr(Expr *Arg, SourceLocation CC) {
2839 return FullExprArg(ActOnFinishFullExpr(Arg, CC).release());
2841 FullExprArg MakeFullDiscardedValueExpr(Expr *Arg) {
2843 ActOnFinishFullExpr(Arg, Arg ? Arg->getExprLoc() : SourceLocation(),
2844 /*DiscardedValue*/ true);
2845 return FullExprArg(FE.release());
2848 StmtResult ActOnExprStmt(ExprResult Arg);
2849 StmtResult ActOnExprStmtError();
2851 StmtResult ActOnNullStmt(SourceLocation SemiLoc,
2852 bool HasLeadingEmptyMacro = false);
2854 void ActOnStartOfCompoundStmt();
2855 void ActOnFinishOfCompoundStmt();
2856 StmtResult ActOnCompoundStmt(SourceLocation L, SourceLocation R,
2857 ArrayRef<Stmt *> Elts, bool isStmtExpr);
2859 /// \brief A RAII object to enter scope of a compound statement.
2860 class CompoundScopeRAII {
2862 CompoundScopeRAII(Sema &S): S(S) {
2863 S.ActOnStartOfCompoundStmt();
2866 ~CompoundScopeRAII() {
2867 S.ActOnFinishOfCompoundStmt();
2874 StmtResult ActOnDeclStmt(DeclGroupPtrTy Decl,
2875 SourceLocation StartLoc,
2876 SourceLocation EndLoc);
2877 void ActOnForEachDeclStmt(DeclGroupPtrTy Decl);
2878 StmtResult ActOnForEachLValueExpr(Expr *E);
2879 StmtResult ActOnCaseStmt(SourceLocation CaseLoc, Expr *LHSVal,
2880 SourceLocation DotDotDotLoc, Expr *RHSVal,
2881 SourceLocation ColonLoc);
2882 void ActOnCaseStmtBody(Stmt *CaseStmt, Stmt *SubStmt);
2884 StmtResult ActOnDefaultStmt(SourceLocation DefaultLoc,
2885 SourceLocation ColonLoc,
2886 Stmt *SubStmt, Scope *CurScope);
2887 StmtResult ActOnLabelStmt(SourceLocation IdentLoc, LabelDecl *TheDecl,
2888 SourceLocation ColonLoc, Stmt *SubStmt);
2890 StmtResult ActOnAttributedStmt(SourceLocation AttrLoc,
2891 ArrayRef<const Attr*> Attrs,
2894 StmtResult ActOnIfStmt(SourceLocation IfLoc,
2895 FullExprArg CondVal, Decl *CondVar,
2897 SourceLocation ElseLoc, Stmt *ElseVal);
2898 StmtResult ActOnStartOfSwitchStmt(SourceLocation SwitchLoc,
2901 StmtResult ActOnFinishSwitchStmt(SourceLocation SwitchLoc,
2902 Stmt *Switch, Stmt *Body);
2903 StmtResult ActOnWhileStmt(SourceLocation WhileLoc,
2905 Decl *CondVar, Stmt *Body);
2906 StmtResult ActOnDoStmt(SourceLocation DoLoc, Stmt *Body,
2907 SourceLocation WhileLoc,
2908 SourceLocation CondLParen, Expr *Cond,
2909 SourceLocation CondRParen);
2911 StmtResult ActOnForStmt(SourceLocation ForLoc,
2912 SourceLocation LParenLoc,
2913 Stmt *First, FullExprArg Second,
2916 SourceLocation RParenLoc,
2918 ExprResult CheckObjCForCollectionOperand(SourceLocation forLoc,
2920 StmtResult ActOnObjCForCollectionStmt(SourceLocation ForColLoc,
2921 Stmt *First, Expr *collection,
2922 SourceLocation RParenLoc);
2923 StmtResult FinishObjCForCollectionStmt(Stmt *ForCollection, Stmt *Body);
2925 enum BuildForRangeKind {
2926 /// Initial building of a for-range statement.
2928 /// Instantiation or recovery rebuild of a for-range statement. Don't
2929 /// attempt any typo-correction.
2931 /// Determining whether a for-range statement could be built. Avoid any
2932 /// unnecessary or irreversible actions.
2936 StmtResult ActOnCXXForRangeStmt(SourceLocation ForLoc, Stmt *LoopVar,
2937 SourceLocation ColonLoc, Expr *Collection,
2938 SourceLocation RParenLoc,
2939 BuildForRangeKind Kind);
2940 StmtResult BuildCXXForRangeStmt(SourceLocation ForLoc,
2941 SourceLocation ColonLoc,
2942 Stmt *RangeDecl, Stmt *BeginEndDecl,
2943 Expr *Cond, Expr *Inc,
2945 SourceLocation RParenLoc,
2946 BuildForRangeKind Kind);
2947 StmtResult FinishCXXForRangeStmt(Stmt *ForRange, Stmt *Body);
2949 StmtResult ActOnGotoStmt(SourceLocation GotoLoc,
2950 SourceLocation LabelLoc,
2951 LabelDecl *TheDecl);
2952 StmtResult ActOnIndirectGotoStmt(SourceLocation GotoLoc,
2953 SourceLocation StarLoc,
2955 StmtResult ActOnContinueStmt(SourceLocation ContinueLoc, Scope *CurScope);
2956 StmtResult ActOnBreakStmt(SourceLocation BreakLoc, Scope *CurScope);
2958 void ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope,
2959 CapturedRegionKind Kind, unsigned NumParams);
2960 StmtResult ActOnCapturedRegionEnd(Stmt *S);
2961 void ActOnCapturedRegionError();
2962 RecordDecl *CreateCapturedStmtRecordDecl(CapturedDecl *&CD,
2964 unsigned NumParams);
2965 const VarDecl *getCopyElisionCandidate(QualType ReturnType, Expr *E,
2966 bool AllowFunctionParameters);
2968 StmtResult ActOnReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp);
2969 StmtResult ActOnCapScopeReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp);
2971 StmtResult ActOnGCCAsmStmt(SourceLocation AsmLoc, bool IsSimple,
2972 bool IsVolatile, unsigned NumOutputs,
2973 unsigned NumInputs, IdentifierInfo **Names,
2974 MultiExprArg Constraints, MultiExprArg Exprs,
2975 Expr *AsmString, MultiExprArg Clobbers,
2976 SourceLocation RParenLoc);
2978 ExprResult LookupInlineAsmIdentifier(CXXScopeSpec &SS,
2979 SourceLocation TemplateKWLoc,
2981 InlineAsmIdentifierInfo &Info,
2982 bool IsUnevaluatedContext);
2983 bool LookupInlineAsmField(StringRef Base, StringRef Member,
2984 unsigned &Offset, SourceLocation AsmLoc);
2985 StmtResult ActOnMSAsmStmt(SourceLocation AsmLoc, SourceLocation LBraceLoc,
2986 ArrayRef<Token> AsmToks,
2987 StringRef AsmString,
2988 unsigned NumOutputs, unsigned NumInputs,
2989 ArrayRef<StringRef> Constraints,
2990 ArrayRef<StringRef> Clobbers,
2991 ArrayRef<Expr*> Exprs,
2992 SourceLocation EndLoc);
2994 VarDecl *BuildObjCExceptionDecl(TypeSourceInfo *TInfo, QualType ExceptionType,
2995 SourceLocation StartLoc,
2996 SourceLocation IdLoc, IdentifierInfo *Id,
2997 bool Invalid = false);
2999 Decl *ActOnObjCExceptionDecl(Scope *S, Declarator &D);
3001 StmtResult ActOnObjCAtCatchStmt(SourceLocation AtLoc, SourceLocation RParen,
3002 Decl *Parm, Stmt *Body);
3004 StmtResult ActOnObjCAtFinallyStmt(SourceLocation AtLoc, Stmt *Body);
3006 StmtResult ActOnObjCAtTryStmt(SourceLocation AtLoc, Stmt *Try,
3007 MultiStmtArg Catch, Stmt *Finally);
3009 StmtResult BuildObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw);
3010 StmtResult ActOnObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw,
3012 ExprResult ActOnObjCAtSynchronizedOperand(SourceLocation atLoc,
3014 StmtResult ActOnObjCAtSynchronizedStmt(SourceLocation AtLoc,
3018 StmtResult ActOnObjCAutoreleasePoolStmt(SourceLocation AtLoc, Stmt *Body);
3020 VarDecl *BuildExceptionDeclaration(Scope *S, TypeSourceInfo *TInfo,
3021 SourceLocation StartLoc,
3022 SourceLocation IdLoc,
3023 IdentifierInfo *Id);
3025 Decl *ActOnExceptionDeclarator(Scope *S, Declarator &D);
3027 StmtResult ActOnCXXCatchBlock(SourceLocation CatchLoc,
3028 Decl *ExDecl, Stmt *HandlerBlock);
3029 StmtResult ActOnCXXTryBlock(SourceLocation TryLoc, Stmt *TryBlock,
3030 ArrayRef<Stmt *> Handlers);
3032 StmtResult ActOnSEHTryBlock(bool IsCXXTry, // try (true) or __try (false) ?
3033 SourceLocation TryLoc, Stmt *TryBlock,
3036 StmtResult ActOnSEHExceptBlock(SourceLocation Loc,
3040 StmtResult ActOnSEHFinallyBlock(SourceLocation Loc,
3043 void DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock);
3045 bool ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const;
3047 /// \brief If it's a file scoped decl that must warn if not used, keep track
3049 void MarkUnusedFileScopedDecl(const DeclaratorDecl *D);
3051 /// DiagnoseUnusedExprResult - If the statement passed in is an expression
3052 /// whose result is unused, warn.
3053 void DiagnoseUnusedExprResult(const Stmt *S);
3054 void DiagnoseUnusedDecl(const NamedDecl *ND);
3056 /// Emit \p DiagID if statement located on \p StmtLoc has a suspicious null
3057 /// statement as a \p Body, and it is located on the same line.
3059 /// This helps prevent bugs due to typos, such as:
3062 void DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
3066 /// Warn if a for/while loop statement \p S, which is followed by
3067 /// \p PossibleBody, has a suspicious null statement as a body.
3068 void DiagnoseEmptyLoopBody(const Stmt *S,
3069 const Stmt *PossibleBody);
3071 ParsingDeclState PushParsingDeclaration(sema::DelayedDiagnosticPool &pool) {
3072 return DelayedDiagnostics.push(pool);
3074 void PopParsingDeclaration(ParsingDeclState state, Decl *decl);
3076 typedef ProcessingContextState ParsingClassState;
3077 ParsingClassState PushParsingClass() {
3078 return DelayedDiagnostics.pushUndelayed();
3080 void PopParsingClass(ParsingClassState state) {
3081 DelayedDiagnostics.popUndelayed(state);
3084 void redelayDiagnostics(sema::DelayedDiagnosticPool &pool);
3086 void EmitDeprecationWarning(NamedDecl *D, StringRef Message,
3088 const ObjCInterfaceDecl *UnknownObjCClass,
3089 const ObjCPropertyDecl *ObjCProperty);
3091 void HandleDelayedDeprecationCheck(sema::DelayedDiagnostic &DD, Decl *Ctx);
3093 bool makeUnavailableInSystemHeader(SourceLocation loc,
3096 //===--------------------------------------------------------------------===//
3097 // Expression Parsing Callbacks: SemaExpr.cpp.
3099 bool CanUseDecl(NamedDecl *D);
3100 bool DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc,
3101 const ObjCInterfaceDecl *UnknownObjCClass=0);
3102 void NoteDeletedFunction(FunctionDecl *FD);
3103 std::string getDeletedOrUnavailableSuffix(const FunctionDecl *FD);
3104 bool DiagnosePropertyAccessorMismatch(ObjCPropertyDecl *PD,
3105 ObjCMethodDecl *Getter,
3106 SourceLocation Loc);
3107 void DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
3108 ArrayRef<Expr *> Args);
3110 void PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
3111 Decl *LambdaContextDecl = 0,
3112 bool IsDecltype = false);
3113 enum ReuseLambdaContextDecl_t { ReuseLambdaContextDecl };
3114 void PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
3115 ReuseLambdaContextDecl_t,
3116 bool IsDecltype = false);
3117 void PopExpressionEvaluationContext();
3119 void DiscardCleanupsInEvaluationContext();
3121 ExprResult TransformToPotentiallyEvaluated(Expr *E);
3122 ExprResult HandleExprEvaluationContextForTypeof(Expr *E);
3124 ExprResult ActOnConstantExpression(ExprResult Res);
3126 // Functions for marking a declaration referenced. These functions also
3127 // contain the relevant logic for marking if a reference to a function or
3128 // variable is an odr-use (in the C++11 sense). There are separate variants
3129 // for expressions referring to a decl; these exist because odr-use marking
3130 // needs to be delayed for some constant variables when we build one of the
3131 // named expressions.
3132 void MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, bool OdrUse);
3133 void MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func);
3134 void MarkVariableReferenced(SourceLocation Loc, VarDecl *Var);
3135 void MarkDeclRefReferenced(DeclRefExpr *E);
3136 void MarkMemberReferenced(MemberExpr *E);
3138 void UpdateMarkingForLValueToRValue(Expr *E);
3139 void CleanupVarDeclMarking();
3141 enum TryCaptureKind {
3142 TryCapture_Implicit, TryCapture_ExplicitByVal, TryCapture_ExplicitByRef
3145 /// \brief Try to capture the given variable.
3147 /// \param Var The variable to capture.
3149 /// \param Loc The location at which the capture occurs.
3151 /// \param Kind The kind of capture, which may be implicit (for either a
3152 /// block or a lambda), or explicit by-value or by-reference (for a lambda).
3154 /// \param EllipsisLoc The location of the ellipsis, if one is provided in
3155 /// an explicit lambda capture.
3157 /// \param BuildAndDiagnose Whether we are actually supposed to add the
3158 /// captures or diagnose errors. If false, this routine merely check whether
3159 /// the capture can occur without performing the capture itself or complaining
3160 /// if the variable cannot be captured.
3162 /// \param CaptureType Will be set to the type of the field used to capture
3163 /// this variable in the innermost block or lambda. Only valid when the
3164 /// variable can be captured.
3166 /// \param DeclRefType Will be set to the type of a reference to the capture
3167 /// from within the current scope. Only valid when the variable can be
3170 /// \param FunctionScopeIndexToStopAt If non-null, it points to the index
3171 /// of the FunctionScopeInfo stack beyond which we do not attempt to capture.
3172 /// This is useful when enclosing lambdas must speculatively capture
3173 /// variables that may or may not be used in certain specializations of
3174 /// a nested generic lambda.
3176 /// \returns true if an error occurred (i.e., the variable cannot be
3177 /// captured) and false if the capture succeeded.
3178 bool tryCaptureVariable(VarDecl *Var, SourceLocation Loc, TryCaptureKind Kind,
3179 SourceLocation EllipsisLoc, bool BuildAndDiagnose,
3180 QualType &CaptureType,
3181 QualType &DeclRefType,
3182 const unsigned *const FunctionScopeIndexToStopAt);
3184 /// \brief Try to capture the given variable.
3185 bool tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
3186 TryCaptureKind Kind = TryCapture_Implicit,
3187 SourceLocation EllipsisLoc = SourceLocation());
3189 /// \brief Given a variable, determine the type that a reference to that
3190 /// variable will have in the given scope.
3191 QualType getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc);
3193 void MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T);
3194 void MarkDeclarationsReferencedInExpr(Expr *E,
3195 bool SkipLocalVariables = false);
3197 /// \brief Try to recover by turning the given expression into a
3198 /// call. Returns true if recovery was attempted or an error was
3199 /// emitted; this may also leave the ExprResult invalid.
3200 bool tryToRecoverWithCall(ExprResult &E, const PartialDiagnostic &PD,
3201 bool ForceComplain = false,
3202 bool (*IsPlausibleResult)(QualType) = 0);
3204 /// \brief Figure out if an expression could be turned into a call.
3205 bool tryExprAsCall(Expr &E, QualType &ZeroArgCallReturnTy,
3206 UnresolvedSetImpl &NonTemplateOverloads);
3208 /// \brief Conditionally issue a diagnostic based on the current
3209 /// evaluation context.
3211 /// \param Statement If Statement is non-null, delay reporting the
3212 /// diagnostic until the function body is parsed, and then do a basic
3213 /// reachability analysis to determine if the statement is reachable.
3214 /// If it is unreachable, the diagnostic will not be emitted.
3215 bool DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
3216 const PartialDiagnostic &PD);
3218 // Primary Expressions.
3219 SourceRange getExprRange(Expr *E) const;
3221 ExprResult ActOnIdExpression(Scope *S, CXXScopeSpec &SS,
3222 SourceLocation TemplateKWLoc,
3224 bool HasTrailingLParen, bool IsAddressOfOperand,
3225 CorrectionCandidateCallback *CCC = 0,
3226 bool IsInlineAsmIdentifier = false);
3228 void DecomposeUnqualifiedId(const UnqualifiedId &Id,
3229 TemplateArgumentListInfo &Buffer,
3230 DeclarationNameInfo &NameInfo,
3231 const TemplateArgumentListInfo *&TemplateArgs);
3233 bool DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
3234 CorrectionCandidateCallback &CCC,
3235 TemplateArgumentListInfo *ExplicitTemplateArgs = 0,
3236 ArrayRef<Expr *> Args = None);
3238 ExprResult LookupInObjCMethod(LookupResult &LookUp, Scope *S,
3240 bool AllowBuiltinCreation=false);
3242 ExprResult ActOnDependentIdExpression(const CXXScopeSpec &SS,
3243 SourceLocation TemplateKWLoc,
3244 const DeclarationNameInfo &NameInfo,
3245 bool isAddressOfOperand,
3246 const TemplateArgumentListInfo *TemplateArgs);
3248 ExprResult BuildDeclRefExpr(ValueDecl *D, QualType Ty,
3251 const CXXScopeSpec *SS = 0);
3252 ExprResult BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
3253 const DeclarationNameInfo &NameInfo,
3254 const CXXScopeSpec *SS = 0, NamedDecl *FoundD = 0,
3255 const TemplateArgumentListInfo *TemplateArgs = 0);
3257 BuildAnonymousStructUnionMemberReference(
3258 const CXXScopeSpec &SS,
3259 SourceLocation nameLoc,
3260 IndirectFieldDecl *indirectField,
3261 DeclAccessPair FoundDecl = DeclAccessPair::make(0, AS_none),
3262 Expr *baseObjectExpr = 0,
3263 SourceLocation opLoc = SourceLocation());
3265 ExprResult BuildPossibleImplicitMemberExpr(const CXXScopeSpec &SS,
3266 SourceLocation TemplateKWLoc,
3268 const TemplateArgumentListInfo *TemplateArgs);
3269 ExprResult BuildImplicitMemberExpr(const CXXScopeSpec &SS,
3270 SourceLocation TemplateKWLoc,
3272 const TemplateArgumentListInfo *TemplateArgs,
3273 bool IsDefiniteInstance);
3274 bool UseArgumentDependentLookup(const CXXScopeSpec &SS,
3275 const LookupResult &R,
3276 bool HasTrailingLParen);
3278 ExprResult BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS,
3279 const DeclarationNameInfo &NameInfo,
3280 bool IsAddressOfOperand);
3281 ExprResult BuildDependentDeclRefExpr(const CXXScopeSpec &SS,
3282 SourceLocation TemplateKWLoc,
3283 const DeclarationNameInfo &NameInfo,
3284 const TemplateArgumentListInfo *TemplateArgs);
3286 ExprResult BuildDeclarationNameExpr(const CXXScopeSpec &SS,
3289 ExprResult BuildDeclarationNameExpr(
3290 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
3291 NamedDecl *FoundD = 0, const TemplateArgumentListInfo *TemplateArgs = 0);
3293 ExprResult BuildLiteralOperatorCall(LookupResult &R,
3294 DeclarationNameInfo &SuffixInfo,
3295 ArrayRef<Expr*> Args,
3296 SourceLocation LitEndLoc,
3297 TemplateArgumentListInfo *ExplicitTemplateArgs = 0);
3299 ExprResult BuildPredefinedExpr(SourceLocation Loc,
3300 PredefinedExpr::IdentType IT);
3301 ExprResult ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind);
3302 ExprResult ActOnIntegerConstant(SourceLocation Loc, uint64_t Val);
3303 ExprResult ActOnNumericConstant(const Token &Tok, Scope *UDLScope = 0);
3304 ExprResult ActOnCharacterConstant(const Token &Tok, Scope *UDLScope = 0);
3305 ExprResult ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E);
3306 ExprResult ActOnParenListExpr(SourceLocation L,
3310 /// ActOnStringLiteral - The specified tokens were lexed as pasted string
3311 /// fragments (e.g. "foo" "bar" L"baz").
3312 ExprResult ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks,
3313 Scope *UDLScope = 0);
3315 ExprResult ActOnGenericSelectionExpr(SourceLocation KeyLoc,
3316 SourceLocation DefaultLoc,
3317 SourceLocation RParenLoc,
3318 Expr *ControllingExpr,
3319 ArrayRef<ParsedType> ArgTypes,
3320 ArrayRef<Expr *> ArgExprs);
3321 ExprResult CreateGenericSelectionExpr(SourceLocation KeyLoc,
3322 SourceLocation DefaultLoc,
3323 SourceLocation RParenLoc,
3324 Expr *ControllingExpr,
3325 ArrayRef<TypeSourceInfo *> Types,
3326 ArrayRef<Expr *> Exprs);
3328 // Binary/Unary Operators. 'Tok' is the token for the operator.
3329 ExprResult CreateBuiltinUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc,
3331 ExprResult BuildUnaryOp(Scope *S, SourceLocation OpLoc,
3332 UnaryOperatorKind Opc, Expr *Input);
3333 ExprResult ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
3334 tok::TokenKind Op, Expr *Input);
3336 QualType CheckAddressOfOperand(ExprResult &Operand, SourceLocation OpLoc);
3338 ExprResult CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
3339 SourceLocation OpLoc,
3340 UnaryExprOrTypeTrait ExprKind,
3342 ExprResult CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
3343 UnaryExprOrTypeTrait ExprKind);
3345 ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
3346 UnaryExprOrTypeTrait ExprKind,
3347 bool IsType, void *TyOrEx,
3348 const SourceRange &ArgRange);
3350 ExprResult CheckPlaceholderExpr(Expr *E);
3351 bool CheckVecStepExpr(Expr *E);
3353 bool CheckUnaryExprOrTypeTraitOperand(Expr *E, UnaryExprOrTypeTrait ExprKind);
3354 bool CheckUnaryExprOrTypeTraitOperand(QualType ExprType, SourceLocation OpLoc,
3355 SourceRange ExprRange,
3356 UnaryExprOrTypeTrait ExprKind);
3357 ExprResult ActOnSizeofParameterPackExpr(Scope *S,
3358 SourceLocation OpLoc,
3359 IdentifierInfo &Name,
3360 SourceLocation NameLoc,
3361 SourceLocation RParenLoc);
3362 ExprResult ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
3363 tok::TokenKind Kind, Expr *Input);
3365 ExprResult ActOnArraySubscriptExpr(Scope *S, Expr *Base, SourceLocation LLoc,
3366 Expr *Idx, SourceLocation RLoc);
3367 ExprResult CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
3368 Expr *Idx, SourceLocation RLoc);
3370 ExprResult BuildMemberReferenceExpr(Expr *Base, QualType BaseType,
3371 SourceLocation OpLoc, bool IsArrow,
3373 SourceLocation TemplateKWLoc,
3374 NamedDecl *FirstQualifierInScope,
3375 const DeclarationNameInfo &NameInfo,
3376 const TemplateArgumentListInfo *TemplateArgs);
3378 // This struct is for use by ActOnMemberAccess to allow
3379 // BuildMemberReferenceExpr to be able to reinvoke ActOnMemberAccess after
3380 // changing the access operator from a '.' to a '->' (to see if that is the
3381 // change needed to fix an error about an unknown member, e.g. when the class
3382 // defines a custom operator->).
3383 struct ActOnMemberAccessExtraArgs {
3387 bool HasTrailingLParen;
3390 ExprResult BuildMemberReferenceExpr(Expr *Base, QualType BaseType,
3391 SourceLocation OpLoc, bool IsArrow,
3392 const CXXScopeSpec &SS,
3393 SourceLocation TemplateKWLoc,
3394 NamedDecl *FirstQualifierInScope,
3396 const TemplateArgumentListInfo *TemplateArgs,
3397 bool SuppressQualifierCheck = false,
3398 ActOnMemberAccessExtraArgs *ExtraArgs = 0);
3400 ExprResult PerformMemberExprBaseConversion(Expr *Base, bool IsArrow);
3401 ExprResult LookupMemberExpr(LookupResult &R, ExprResult &Base,
3402 bool &IsArrow, SourceLocation OpLoc,
3405 bool HasTemplateArgs);
3407 bool CheckQualifiedMemberReference(Expr *BaseExpr, QualType BaseType,
3408 const CXXScopeSpec &SS,
3409 const LookupResult &R);
3411 ExprResult ActOnDependentMemberExpr(Expr *Base, QualType BaseType,
3412 bool IsArrow, SourceLocation OpLoc,
3413 const CXXScopeSpec &SS,
3414 SourceLocation TemplateKWLoc,
3415 NamedDecl *FirstQualifierInScope,
3416 const DeclarationNameInfo &NameInfo,
3417 const TemplateArgumentListInfo *TemplateArgs);
3419 ExprResult ActOnMemberAccessExpr(Scope *S, Expr *Base,
3420 SourceLocation OpLoc,
3421 tok::TokenKind OpKind,
3423 SourceLocation TemplateKWLoc,
3424 UnqualifiedId &Member,
3426 bool HasTrailingLParen);
3428 void ActOnDefaultCtorInitializers(Decl *CDtorDecl);
3429 bool ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
3430 FunctionDecl *FDecl,
3431 const FunctionProtoType *Proto,
3432 ArrayRef<Expr *> Args,
3433 SourceLocation RParenLoc,
3434 bool ExecConfig = false);
3435 void CheckStaticArrayArgument(SourceLocation CallLoc,
3437 const Expr *ArgExpr);
3439 /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
3440 /// This provides the location of the left/right parens and a list of comma
3442 ExprResult ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
3443 MultiExprArg ArgExprs, SourceLocation RParenLoc,
3444 Expr *ExecConfig = 0, bool IsExecConfig = false);
3445 ExprResult BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
3446 SourceLocation LParenLoc,
3447 ArrayRef<Expr *> Arg,
3448 SourceLocation RParenLoc,
3450 bool IsExecConfig = false);
3452 ExprResult ActOnCUDAExecConfigExpr(Scope *S, SourceLocation LLLLoc,
3453 MultiExprArg ExecConfig,
3454 SourceLocation GGGLoc);
3456 ExprResult ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
3457 Declarator &D, ParsedType &Ty,
3458 SourceLocation RParenLoc, Expr *CastExpr);
3459 ExprResult BuildCStyleCastExpr(SourceLocation LParenLoc,
3461 SourceLocation RParenLoc,
3463 CastKind PrepareScalarCast(ExprResult &src, QualType destType);
3465 /// \brief Build an altivec or OpenCL literal.
3466 ExprResult BuildVectorLiteral(SourceLocation LParenLoc,
3467 SourceLocation RParenLoc, Expr *E,
3468 TypeSourceInfo *TInfo);
3470 ExprResult MaybeConvertParenListExprToParenExpr(Scope *S, Expr *ME);
3472 ExprResult ActOnCompoundLiteral(SourceLocation LParenLoc,
3474 SourceLocation RParenLoc,
3477 ExprResult BuildCompoundLiteralExpr(SourceLocation LParenLoc,
3478 TypeSourceInfo *TInfo,
3479 SourceLocation RParenLoc,
3482 ExprResult ActOnInitList(SourceLocation LBraceLoc,
3483 MultiExprArg InitArgList,
3484 SourceLocation RBraceLoc);
3486 ExprResult ActOnDesignatedInitializer(Designation &Desig,
3491 ExprResult ActOnBinOp(Scope *S, SourceLocation TokLoc,
3492 tok::TokenKind Kind, Expr *LHSExpr, Expr *RHSExpr);
3493 ExprResult BuildBinOp(Scope *S, SourceLocation OpLoc,
3494 BinaryOperatorKind Opc, Expr *LHSExpr, Expr *RHSExpr);
3495 ExprResult CreateBuiltinBinOp(SourceLocation OpLoc, BinaryOperatorKind Opc,
3496 Expr *LHSExpr, Expr *RHSExpr);
3498 /// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
3499 /// in the case of a the GNU conditional expr extension.
3500 ExprResult ActOnConditionalOp(SourceLocation QuestionLoc,
3501 SourceLocation ColonLoc,
3502 Expr *CondExpr, Expr *LHSExpr, Expr *RHSExpr);
3504 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
3505 ExprResult ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
3506 LabelDecl *TheDecl);
3508 void ActOnStartStmtExpr();
3509 ExprResult ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
3510 SourceLocation RPLoc); // "({..})"
3511 void ActOnStmtExprError();
3513 // __builtin_offsetof(type, identifier(.identifier|[expr])*)
3514 struct OffsetOfComponent {
3515 SourceLocation LocStart, LocEnd;
3516 bool isBrackets; // true if [expr], false if .ident
3518 IdentifierInfo *IdentInfo;
3523 /// __builtin_offsetof(type, a.b[123][456].c)
3524 ExprResult BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
3525 TypeSourceInfo *TInfo,
3526 OffsetOfComponent *CompPtr,
3527 unsigned NumComponents,
3528 SourceLocation RParenLoc);
3529 ExprResult ActOnBuiltinOffsetOf(Scope *S,
3530 SourceLocation BuiltinLoc,
3531 SourceLocation TypeLoc,
3532 ParsedType ParsedArgTy,
3533 OffsetOfComponent *CompPtr,
3534 unsigned NumComponents,
3535 SourceLocation RParenLoc);
3537 // __builtin_choose_expr(constExpr, expr1, expr2)
3538 ExprResult ActOnChooseExpr(SourceLocation BuiltinLoc,
3539 Expr *CondExpr, Expr *LHSExpr,
3540 Expr *RHSExpr, SourceLocation RPLoc);
3542 // __builtin_va_arg(expr, type)
3543 ExprResult ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty,
3544 SourceLocation RPLoc);
3545 ExprResult BuildVAArgExpr(SourceLocation BuiltinLoc, Expr *E,
3546 TypeSourceInfo *TInfo, SourceLocation RPLoc);
3549 ExprResult ActOnGNUNullExpr(SourceLocation TokenLoc);
3551 bool CheckCaseExpression(Expr *E);
3553 /// \brief Describes the result of an "if-exists" condition check.
3554 enum IfExistsResult {
3555 /// \brief The symbol exists.
3558 /// \brief The symbol does not exist.
3561 /// \brief The name is a dependent name, so the results will differ
3562 /// from one instantiation to the next.
3565 /// \brief An error occurred.
3570 CheckMicrosoftIfExistsSymbol(Scope *S, CXXScopeSpec &SS,
3571 const DeclarationNameInfo &TargetNameInfo);
3574 CheckMicrosoftIfExistsSymbol(Scope *S, SourceLocation KeywordLoc,
3575 bool IsIfExists, CXXScopeSpec &SS,
3576 UnqualifiedId &Name);
3578 StmtResult BuildMSDependentExistsStmt(SourceLocation KeywordLoc,
3580 NestedNameSpecifierLoc QualifierLoc,
3581 DeclarationNameInfo NameInfo,
3583 StmtResult ActOnMSDependentExistsStmt(SourceLocation KeywordLoc,
3585 CXXScopeSpec &SS, UnqualifiedId &Name,
3588 //===------------------------- "Block" Extension ------------------------===//
3590 /// ActOnBlockStart - This callback is invoked when a block literal is
3592 void ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope);
3594 /// ActOnBlockArguments - This callback allows processing of block arguments.
3595 /// If there are no arguments, this is still invoked.
3596 void ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
3599 /// ActOnBlockError - If there is an error parsing a block, this callback
3600 /// is invoked to pop the information about the block from the action impl.
3601 void ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope);
3603 /// ActOnBlockStmtExpr - This is called when the body of a block statement
3604 /// literal was successfully completed. ^(int x){...}
3605 ExprResult ActOnBlockStmtExpr(SourceLocation CaretLoc, Stmt *Body,
3608 //===---------------------------- Clang Extensions ----------------------===//
3610 /// __builtin_convertvector(...)
3611 ExprResult ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy,
3612 SourceLocation BuiltinLoc,
3613 SourceLocation RParenLoc);
3615 //===---------------------------- OpenCL Features -----------------------===//
3617 /// __builtin_astype(...)
3618 ExprResult ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
3619 SourceLocation BuiltinLoc,
3620 SourceLocation RParenLoc);
3622 //===---------------------------- C++ Features --------------------------===//
3624 // Act on C++ namespaces
3625 Decl *ActOnStartNamespaceDef(Scope *S, SourceLocation InlineLoc,
3626 SourceLocation NamespaceLoc,
3627 SourceLocation IdentLoc,
3628 IdentifierInfo *Ident,
3629 SourceLocation LBrace,
3630 AttributeList *AttrList);
3631 void ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace);
3633 NamespaceDecl *getStdNamespace() const;
3634 NamespaceDecl *getOrCreateStdNamespace();
3636 CXXRecordDecl *getStdBadAlloc() const;
3638 /// \brief Tests whether Ty is an instance of std::initializer_list and, if
3639 /// it is and Element is not NULL, assigns the element type to Element.
3640 bool isStdInitializerList(QualType Ty, QualType *Element);
3642 /// \brief Looks for the std::initializer_list template and instantiates it
3643 /// with Element, or emits an error if it's not found.
3645 /// \returns The instantiated template, or null on error.
3646 QualType BuildStdInitializerList(QualType Element, SourceLocation Loc);
3648 /// \brief Determine whether Ctor is an initializer-list constructor, as
3649 /// defined in [dcl.init.list]p2.
3650 bool isInitListConstructor(const CXXConstructorDecl *Ctor);
3652 Decl *ActOnUsingDirective(Scope *CurScope,
3653 SourceLocation UsingLoc,
3654 SourceLocation NamespcLoc,
3656 SourceLocation IdentLoc,
3657 IdentifierInfo *NamespcName,
3658 AttributeList *AttrList);
3660 void PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir);
3662 Decl *ActOnNamespaceAliasDef(Scope *CurScope,
3663 SourceLocation NamespaceLoc,
3664 SourceLocation AliasLoc,
3665 IdentifierInfo *Alias,
3667 SourceLocation IdentLoc,
3668 IdentifierInfo *Ident);
3670 void HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow);
3671 bool CheckUsingShadowDecl(UsingDecl *UD, NamedDecl *Target,
3672 const LookupResult &PreviousDecls,
3673 UsingShadowDecl *&PrevShadow);
3674 UsingShadowDecl *BuildUsingShadowDecl(Scope *S, UsingDecl *UD,
3676 UsingShadowDecl *PrevDecl);
3678 bool CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
3679 bool HasTypenameKeyword,
3680 const CXXScopeSpec &SS,
3681 SourceLocation NameLoc,
3682 const LookupResult &Previous);
3683 bool CheckUsingDeclQualifier(SourceLocation UsingLoc,
3684 const CXXScopeSpec &SS,
3685 SourceLocation NameLoc);
3687 NamedDecl *BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
3688 SourceLocation UsingLoc,
3690 const DeclarationNameInfo &NameInfo,
3691 AttributeList *AttrList,
3692 bool IsInstantiation,
3693 bool HasTypenameKeyword,
3694 SourceLocation TypenameLoc);
3696 bool CheckInheritingConstructorUsingDecl(UsingDecl *UD);
3698 Decl *ActOnUsingDeclaration(Scope *CurScope,
3700 bool HasUsingKeyword,
3701 SourceLocation UsingLoc,
3703 UnqualifiedId &Name,
3704 AttributeList *AttrList,
3705 bool HasTypenameKeyword,
3706 SourceLocation TypenameLoc);
3707 Decl *ActOnAliasDeclaration(Scope *CurScope,
3709 MultiTemplateParamsArg TemplateParams,
3710 SourceLocation UsingLoc,
3711 UnqualifiedId &Name,
3712 AttributeList *AttrList,
3715 /// BuildCXXConstructExpr - Creates a complete call to a constructor,
3716 /// including handling of its default argument expressions.
3718 /// \param ConstructKind - a CXXConstructExpr::ConstructionKind
3720 BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
3721 CXXConstructorDecl *Constructor, MultiExprArg Exprs,
3722 bool HadMultipleCandidates, bool IsListInitialization,
3723 bool RequiresZeroInit, unsigned ConstructKind,
3724 SourceRange ParenRange);
3726 // FIXME: Can re remove this and have the above BuildCXXConstructExpr check if
3727 // the constructor can be elidable?
3729 BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
3730 CXXConstructorDecl *Constructor, bool Elidable,
3731 MultiExprArg Exprs, bool HadMultipleCandidates,
3732 bool IsListInitialization, bool RequiresZeroInit,
3733 unsigned ConstructKind, SourceRange ParenRange);
3735 /// BuildCXXDefaultArgExpr - Creates a CXXDefaultArgExpr, instantiating
3736 /// the default expr if needed.
3737 ExprResult BuildCXXDefaultArgExpr(SourceLocation CallLoc,
3739 ParmVarDecl *Param);
3741 /// FinalizeVarWithDestructor - Prepare for calling destructor on the
3742 /// constructed variable.
3743 void FinalizeVarWithDestructor(VarDecl *VD, const RecordType *DeclInitType);
3745 /// \brief Helper class that collects exception specifications for
3746 /// implicitly-declared special member functions.
3747 class ImplicitExceptionSpecification {
3748 // Pointer to allow copying
3750 // We order exception specifications thus:
3751 // noexcept is the most restrictive, but is only used in C++11.
3752 // throw() comes next.
3753 // Then a throw(collected exceptions)
3754 // Finally no specification, which is expressed as noexcept(false).
3755 // throw(...) is used instead if any called function uses it.
3756 ExceptionSpecificationType ComputedEST;
3757 llvm::SmallPtrSet<CanQualType, 4> ExceptionsSeen;
3758 SmallVector<QualType, 4> Exceptions;
3760 void ClearExceptions() {
3761 ExceptionsSeen.clear();
3766 explicit ImplicitExceptionSpecification(Sema &Self)
3767 : Self(&Self), ComputedEST(EST_BasicNoexcept) {
3768 if (!Self.getLangOpts().CPlusPlus11)
3769 ComputedEST = EST_DynamicNone;
3772 /// \brief Get the computed exception specification type.
3773 ExceptionSpecificationType getExceptionSpecType() const {
3774 assert(ComputedEST != EST_ComputedNoexcept &&
3775 "noexcept(expr) should not be a possible result");
3779 /// \brief The number of exceptions in the exception specification.
3780 unsigned size() const { return Exceptions.size(); }
3782 /// \brief The set of exceptions in the exception specification.
3783 const QualType *data() const { return Exceptions.data(); }
3785 /// \brief Integrate another called method into the collected data.
3786 void CalledDecl(SourceLocation CallLoc, const CXXMethodDecl *Method);
3788 /// \brief Integrate an invoked expression into the collected data.
3789 void CalledExpr(Expr *E);
3791 /// \brief Overwrite an EPI's exception specification with this
3792 /// computed exception specification.
3793 void getEPI(FunctionProtoType::ExtProtoInfo &EPI) const {
3794 EPI.ExceptionSpecType = getExceptionSpecType();
3795 if (EPI.ExceptionSpecType == EST_Dynamic) {
3796 EPI.NumExceptions = size();
3797 EPI.Exceptions = data();
3798 } else if (EPI.ExceptionSpecType == EST_None) {
3799 /// C++11 [except.spec]p14:
3800 /// The exception-specification is noexcept(false) if the set of
3801 /// potential exceptions of the special member function contains "any"
3802 EPI.ExceptionSpecType = EST_ComputedNoexcept;
3803 EPI.NoexceptExpr = Self->ActOnCXXBoolLiteral(SourceLocation(),
3804 tok::kw_false).take();
3807 FunctionProtoType::ExtProtoInfo getEPI() const {
3808 FunctionProtoType::ExtProtoInfo EPI;
3814 /// \brief Determine what sort of exception specification a defaulted
3815 /// copy constructor of a class will have.
3816 ImplicitExceptionSpecification
3817 ComputeDefaultedDefaultCtorExceptionSpec(SourceLocation Loc,
3820 /// \brief Determine what sort of exception specification a defaulted
3821 /// default constructor of a class will have, and whether the parameter
3823 ImplicitExceptionSpecification
3824 ComputeDefaultedCopyCtorExceptionSpec(CXXMethodDecl *MD);
3826 /// \brief Determine what sort of exception specification a defautled
3827 /// copy assignment operator of a class will have, and whether the
3828 /// parameter will be const.
3829 ImplicitExceptionSpecification
3830 ComputeDefaultedCopyAssignmentExceptionSpec(CXXMethodDecl *MD);
3832 /// \brief Determine what sort of exception specification a defaulted move
3833 /// constructor of a class will have.
3834 ImplicitExceptionSpecification
3835 ComputeDefaultedMoveCtorExceptionSpec(CXXMethodDecl *MD);
3837 /// \brief Determine what sort of exception specification a defaulted move
3838 /// assignment operator of a class will have.
3839 ImplicitExceptionSpecification
3840 ComputeDefaultedMoveAssignmentExceptionSpec(CXXMethodDecl *MD);
3842 /// \brief Determine what sort of exception specification a defaulted
3843 /// destructor of a class will have.
3844 ImplicitExceptionSpecification
3845 ComputeDefaultedDtorExceptionSpec(CXXMethodDecl *MD);
3847 /// \brief Determine what sort of exception specification an inheriting
3848 /// constructor of a class will have.
3849 ImplicitExceptionSpecification
3850 ComputeInheritingCtorExceptionSpec(CXXConstructorDecl *CD);
3852 /// \brief Evaluate the implicit exception specification for a defaulted
3853 /// special member function.
3854 void EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD);
3856 /// \brief Check the given exception-specification and update the
3857 /// extended prototype information with the results.
3858 void checkExceptionSpecification(ExceptionSpecificationType EST,
3859 ArrayRef<ParsedType> DynamicExceptions,
3860 ArrayRef<SourceRange> DynamicExceptionRanges,
3862 SmallVectorImpl<QualType> &Exceptions,
3863 FunctionProtoType::ExtProtoInfo &EPI);
3865 /// \brief Determine if a special member function should have a deleted
3866 /// definition when it is defaulted.
3867 bool ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
3868 bool Diagnose = false);
3870 /// \brief Declare the implicit default constructor for the given class.
3872 /// \param ClassDecl The class declaration into which the implicit
3873 /// default constructor will be added.
3875 /// \returns The implicitly-declared default constructor.
3876 CXXConstructorDecl *DeclareImplicitDefaultConstructor(
3877 CXXRecordDecl *ClassDecl);
3879 /// DefineImplicitDefaultConstructor - Checks for feasibility of
3880 /// defining this constructor as the default constructor.
3881 void DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
3882 CXXConstructorDecl *Constructor);
3884 /// \brief Declare the implicit destructor for the given class.
3886 /// \param ClassDecl The class declaration into which the implicit
3887 /// destructor will be added.
3889 /// \returns The implicitly-declared destructor.
3890 CXXDestructorDecl *DeclareImplicitDestructor(CXXRecordDecl *ClassDecl);
3892 /// DefineImplicitDestructor - Checks for feasibility of
3893 /// defining this destructor as the default destructor.
3894 void DefineImplicitDestructor(SourceLocation CurrentLocation,
3895 CXXDestructorDecl *Destructor);
3897 /// \brief Build an exception spec for destructors that don't have one.
3899 /// C++11 says that user-defined destructors with no exception spec get one
3900 /// that looks as if the destructor was implicitly declared.
3901 void AdjustDestructorExceptionSpec(CXXRecordDecl *ClassDecl,
3902 CXXDestructorDecl *Destructor);
3904 /// \brief Declare all inheriting constructors for the given class.
3906 /// \param ClassDecl The class declaration into which the inheriting
3907 /// constructors will be added.
3908 void DeclareInheritingConstructors(CXXRecordDecl *ClassDecl);
3910 /// \brief Define the specified inheriting constructor.
3911 void DefineInheritingConstructor(SourceLocation UseLoc,
3912 CXXConstructorDecl *Constructor);
3914 /// \brief Declare the implicit copy constructor for the given class.
3916 /// \param ClassDecl The class declaration into which the implicit
3917 /// copy constructor will be added.
3919 /// \returns The implicitly-declared copy constructor.
3920 CXXConstructorDecl *DeclareImplicitCopyConstructor(CXXRecordDecl *ClassDecl);
3922 /// DefineImplicitCopyConstructor - Checks for feasibility of
3923 /// defining this constructor as the copy constructor.
3924 void DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
3925 CXXConstructorDecl *Constructor);
3927 /// \brief Declare the implicit move constructor for the given class.
3929 /// \param ClassDecl The Class declaration into which the implicit
3930 /// move constructor will be added.
3932 /// \returns The implicitly-declared move constructor, or NULL if it wasn't
3934 CXXConstructorDecl *DeclareImplicitMoveConstructor(CXXRecordDecl *ClassDecl);
3936 /// DefineImplicitMoveConstructor - Checks for feasibility of
3937 /// defining this constructor as the move constructor.
3938 void DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
3939 CXXConstructorDecl *Constructor);
3941 /// \brief Declare the implicit copy assignment operator for the given class.
3943 /// \param ClassDecl The class declaration into which the implicit
3944 /// copy assignment operator will be added.
3946 /// \returns The implicitly-declared copy assignment operator.
3947 CXXMethodDecl *DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl);
3949 /// \brief Defines an implicitly-declared copy assignment operator.
3950 void DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
3951 CXXMethodDecl *MethodDecl);
3953 /// \brief Declare the implicit move assignment operator for the given class.
3955 /// \param ClassDecl The Class declaration into which the implicit
3956 /// move assignment operator will be added.
3958 /// \returns The implicitly-declared move assignment operator, or NULL if it
3959 /// wasn't declared.
3960 CXXMethodDecl *DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl);
3962 /// \brief Defines an implicitly-declared move assignment operator.
3963 void DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
3964 CXXMethodDecl *MethodDecl);
3966 /// \brief Force the declaration of any implicitly-declared members of this
3968 void ForceDeclarationOfImplicitMembers(CXXRecordDecl *Class);
3970 /// \brief Determine whether the given function is an implicitly-deleted
3971 /// special member function.
3972 bool isImplicitlyDeleted(FunctionDecl *FD);
3974 /// \brief Check whether 'this' shows up in the type of a static member
3975 /// function after the (naturally empty) cv-qualifier-seq would be.
3977 /// \returns true if an error occurred.
3978 bool checkThisInStaticMemberFunctionType(CXXMethodDecl *Method);
3980 /// \brief Whether this' shows up in the exception specification of a static
3981 /// member function.
3982 bool checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method);
3984 /// \brief Check whether 'this' shows up in the attributes of the given
3985 /// static member function.
3987 /// \returns true if an error occurred.
3988 bool checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method);
3990 /// MaybeBindToTemporary - If the passed in expression has a record type with
3991 /// a non-trivial destructor, this will return CXXBindTemporaryExpr. Otherwise
3992 /// it simply returns the passed in expression.
3993 ExprResult MaybeBindToTemporary(Expr *E);
3995 bool CompleteConstructorCall(CXXConstructorDecl *Constructor,
3996 MultiExprArg ArgsPtr,
3998 SmallVectorImpl<Expr*> &ConvertedArgs,
3999 bool AllowExplicit = false,
4000 bool IsListInitialization = false);
4002 ParsedType getInheritingConstructorName(CXXScopeSpec &SS,
4003 SourceLocation NameLoc,
4004 IdentifierInfo &Name);
4006 ParsedType getDestructorName(SourceLocation TildeLoc,
4007 IdentifierInfo &II, SourceLocation NameLoc,
4008 Scope *S, CXXScopeSpec &SS,
4009 ParsedType ObjectType,
4010 bool EnteringContext);
4012 ParsedType getDestructorType(const DeclSpec& DS, ParsedType ObjectType);
4014 // Checks that reinterpret casts don't have undefined behavior.
4015 void CheckCompatibleReinterpretCast(QualType SrcType, QualType DestType,
4016 bool IsDereference, SourceRange Range);
4018 /// ActOnCXXNamedCast - Parse {dynamic,static,reinterpret,const}_cast's.
4019 ExprResult ActOnCXXNamedCast(SourceLocation OpLoc,
4020 tok::TokenKind Kind,
4021 SourceLocation LAngleBracketLoc,
4023 SourceLocation RAngleBracketLoc,
4024 SourceLocation LParenLoc,
4026 SourceLocation RParenLoc);
4028 ExprResult BuildCXXNamedCast(SourceLocation OpLoc,
4029 tok::TokenKind Kind,
4032 SourceRange AngleBrackets,
4033 SourceRange Parens);
4035 ExprResult BuildCXXTypeId(QualType TypeInfoType,
4036 SourceLocation TypeidLoc,
4037 TypeSourceInfo *Operand,
4038 SourceLocation RParenLoc);
4039 ExprResult BuildCXXTypeId(QualType TypeInfoType,
4040 SourceLocation TypeidLoc,
4042 SourceLocation RParenLoc);
4044 /// ActOnCXXTypeid - Parse typeid( something ).
4045 ExprResult ActOnCXXTypeid(SourceLocation OpLoc,
4046 SourceLocation LParenLoc, bool isType,
4048 SourceLocation RParenLoc);
4050 ExprResult BuildCXXUuidof(QualType TypeInfoType,
4051 SourceLocation TypeidLoc,
4052 TypeSourceInfo *Operand,
4053 SourceLocation RParenLoc);
4054 ExprResult BuildCXXUuidof(QualType TypeInfoType,
4055 SourceLocation TypeidLoc,
4057 SourceLocation RParenLoc);
4059 /// ActOnCXXUuidof - Parse __uuidof( something ).
4060 ExprResult ActOnCXXUuidof(SourceLocation OpLoc,
4061 SourceLocation LParenLoc, bool isType,
4063 SourceLocation RParenLoc);
4066 //// ActOnCXXThis - Parse 'this' pointer.
4067 ExprResult ActOnCXXThis(SourceLocation loc);
4069 /// \brief Try to retrieve the type of the 'this' pointer.
4071 /// \returns The type of 'this', if possible. Otherwise, returns a NULL type.
4072 QualType getCurrentThisType();
4074 /// \brief When non-NULL, the C++ 'this' expression is allowed despite the
4075 /// current context not being a non-static member function. In such cases,
4076 /// this provides the type used for 'this'.
4077 QualType CXXThisTypeOverride;
4079 /// \brief RAII object used to temporarily allow the C++ 'this' expression
4080 /// to be used, with the given qualifiers on the current class type.
4081 class CXXThisScopeRAII {
4083 QualType OldCXXThisTypeOverride;
4087 /// \brief Introduce a new scope where 'this' may be allowed (when enabled),
4088 /// using the given declaration (which is either a class template or a
4089 /// class) along with the given qualifiers.
4090 /// along with the qualifiers placed on '*this'.
4091 CXXThisScopeRAII(Sema &S, Decl *ContextDecl, unsigned CXXThisTypeQuals,
4092 bool Enabled = true);
4094 ~CXXThisScopeRAII();
4097 /// \brief Make sure the value of 'this' is actually available in the current
4098 /// context, if it is a potentially evaluated context.
4100 /// \param Loc The location at which the capture of 'this' occurs.
4102 /// \param Explicit Whether 'this' is explicitly captured in a lambda
4105 /// \param FunctionScopeIndexToStopAt If non-null, it points to the index
4106 /// of the FunctionScopeInfo stack beyond which we do not attempt to capture.
4107 /// This is useful when enclosing lambdas must speculatively capture
4108 /// 'this' that may or may not be used in certain specializations of
4109 /// a nested generic lambda (depending on whether the name resolves to
4110 /// a non-static member function or a static function).
4111 /// \return returns 'true' if failed, 'false' if success.
4112 bool CheckCXXThisCapture(SourceLocation Loc, bool Explicit = false,
4113 bool BuildAndDiagnose = true,
4114 const unsigned *const FunctionScopeIndexToStopAt = 0);
4116 /// \brief Determine whether the given type is the type of *this that is used
4117 /// outside of the body of a member function for a type that is currently
4119 bool isThisOutsideMemberFunctionBody(QualType BaseType);
4121 /// ActOnCXXBoolLiteral - Parse {true,false} literals.
4122 ExprResult ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind);
4125 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
4126 ExprResult ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind);
4128 /// ActOnCXXNullPtrLiteral - Parse 'nullptr'.
4129 ExprResult ActOnCXXNullPtrLiteral(SourceLocation Loc);
4131 //// ActOnCXXThrow - Parse throw expressions.
4132 ExprResult ActOnCXXThrow(Scope *S, SourceLocation OpLoc, Expr *expr);
4133 ExprResult BuildCXXThrow(SourceLocation OpLoc, Expr *Ex,
4134 bool IsThrownVarInScope);
4135 ExprResult CheckCXXThrowOperand(SourceLocation ThrowLoc, Expr *E,
4136 bool IsThrownVarInScope);
4138 /// ActOnCXXTypeConstructExpr - Parse construction of a specified type.
4139 /// Can be interpreted either as function-style casting ("int(x)")
4140 /// or class type construction ("ClassType(x,y,z)")
4141 /// or creation of a value-initialized type ("int()").
4142 ExprResult ActOnCXXTypeConstructExpr(ParsedType TypeRep,
4143 SourceLocation LParenLoc,
4145 SourceLocation RParenLoc);
4147 ExprResult BuildCXXTypeConstructExpr(TypeSourceInfo *Type,
4148 SourceLocation LParenLoc,
4150 SourceLocation RParenLoc);
4152 /// ActOnCXXNew - Parsed a C++ 'new' expression.
4153 ExprResult ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
4154 SourceLocation PlacementLParen,
4155 MultiExprArg PlacementArgs,
4156 SourceLocation PlacementRParen,
4157 SourceRange TypeIdParens, Declarator &D,
4159 ExprResult BuildCXXNew(SourceRange Range, bool UseGlobal,
4160 SourceLocation PlacementLParen,
4161 MultiExprArg PlacementArgs,
4162 SourceLocation PlacementRParen,
4163 SourceRange TypeIdParens,
4165 TypeSourceInfo *AllocTypeInfo,
4167 SourceRange DirectInitRange,
4169 bool TypeMayContainAuto = true);
4171 bool CheckAllocatedType(QualType AllocType, SourceLocation Loc,
4173 bool FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,
4174 bool UseGlobal, QualType AllocType, bool IsArray,
4175 MultiExprArg PlaceArgs,
4176 FunctionDecl *&OperatorNew,
4177 FunctionDecl *&OperatorDelete);
4178 bool FindAllocationOverload(SourceLocation StartLoc, SourceRange Range,
4179 DeclarationName Name, MultiExprArg Args,
4181 bool AllowMissing, FunctionDecl *&Operator,
4182 bool Diagnose = true);
4183 void DeclareGlobalNewDelete();
4184 void DeclareGlobalAllocationFunction(DeclarationName Name, QualType Return,
4186 QualType Param2 = QualType(),
4187 bool addMallocAttr = false);
4189 bool FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD,
4190 DeclarationName Name, FunctionDecl* &Operator,
4191 bool Diagnose = true);
4192 FunctionDecl *FindUsualDeallocationFunction(SourceLocation StartLoc,
4193 bool CanProvideSize,
4194 DeclarationName Name);
4196 /// ActOnCXXDelete - Parsed a C++ 'delete' expression
4197 ExprResult ActOnCXXDelete(SourceLocation StartLoc,
4198 bool UseGlobal, bool ArrayForm,
4201 DeclResult ActOnCXXConditionDeclaration(Scope *S, Declarator &D);
4202 ExprResult CheckConditionVariable(VarDecl *ConditionVar,
4203 SourceLocation StmtLoc,
4204 bool ConvertToBoolean);
4206 ExprResult ActOnNoexceptExpr(SourceLocation KeyLoc, SourceLocation LParen,
4207 Expr *Operand, SourceLocation RParen);
4208 ExprResult BuildCXXNoexceptExpr(SourceLocation KeyLoc, Expr *Operand,
4209 SourceLocation RParen);
4211 /// ActOnUnaryTypeTrait - Parsed one of the unary type trait support
4212 /// pseudo-functions.
4213 ExprResult ActOnUnaryTypeTrait(UnaryTypeTrait OTT,
4214 SourceLocation KWLoc,
4216 SourceLocation RParen);
4218 ExprResult BuildUnaryTypeTrait(UnaryTypeTrait OTT,
4219 SourceLocation KWLoc,
4221 SourceLocation RParen);
4223 /// ActOnBinaryTypeTrait - Parsed one of the bianry type trait support
4224 /// pseudo-functions.
4225 ExprResult ActOnBinaryTypeTrait(BinaryTypeTrait OTT,
4226 SourceLocation KWLoc,
4229 SourceLocation RParen);
4231 ExprResult BuildBinaryTypeTrait(BinaryTypeTrait BTT,
4232 SourceLocation KWLoc,
4233 TypeSourceInfo *LhsT,
4234 TypeSourceInfo *RhsT,
4235 SourceLocation RParen);
4237 /// \brief Parsed one of the type trait support pseudo-functions.
4238 ExprResult ActOnTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
4239 ArrayRef<ParsedType> Args,
4240 SourceLocation RParenLoc);
4241 ExprResult BuildTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
4242 ArrayRef<TypeSourceInfo *> Args,
4243 SourceLocation RParenLoc);
4245 /// ActOnArrayTypeTrait - Parsed one of the bianry type trait support
4246 /// pseudo-functions.
4247 ExprResult ActOnArrayTypeTrait(ArrayTypeTrait ATT,
4248 SourceLocation KWLoc,
4251 SourceLocation RParen);
4253 ExprResult BuildArrayTypeTrait(ArrayTypeTrait ATT,
4254 SourceLocation KWLoc,
4255 TypeSourceInfo *TSInfo,
4257 SourceLocation RParen);
4259 /// ActOnExpressionTrait - Parsed one of the unary type trait support
4260 /// pseudo-functions.
4261 ExprResult ActOnExpressionTrait(ExpressionTrait OET,
4262 SourceLocation KWLoc,
4264 SourceLocation RParen);
4266 ExprResult BuildExpressionTrait(ExpressionTrait OET,
4267 SourceLocation KWLoc,
4269 SourceLocation RParen);
4271 ExprResult ActOnStartCXXMemberReference(Scope *S,
4273 SourceLocation OpLoc,
4274 tok::TokenKind OpKind,
4275 ParsedType &ObjectType,
4276 bool &MayBePseudoDestructor);
4278 ExprResult DiagnoseDtorReference(SourceLocation NameLoc, Expr *MemExpr);
4280 ExprResult BuildPseudoDestructorExpr(Expr *Base,
4281 SourceLocation OpLoc,
4282 tok::TokenKind OpKind,
4283 const CXXScopeSpec &SS,
4284 TypeSourceInfo *ScopeType,
4285 SourceLocation CCLoc,
4286 SourceLocation TildeLoc,
4287 PseudoDestructorTypeStorage DestroyedType,
4288 bool HasTrailingLParen);
4290 ExprResult ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
4291 SourceLocation OpLoc,
4292 tok::TokenKind OpKind,
4294 UnqualifiedId &FirstTypeName,
4295 SourceLocation CCLoc,
4296 SourceLocation TildeLoc,
4297 UnqualifiedId &SecondTypeName,
4298 bool HasTrailingLParen);
4300 ExprResult ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
4301 SourceLocation OpLoc,
4302 tok::TokenKind OpKind,
4303 SourceLocation TildeLoc,
4305 bool HasTrailingLParen);
4307 /// MaybeCreateExprWithCleanups - If the current full-expression
4308 /// requires any cleanups, surround it with a ExprWithCleanups node.
4309 /// Otherwise, just returns the passed-in expression.
4310 Expr *MaybeCreateExprWithCleanups(Expr *SubExpr);
4311 Stmt *MaybeCreateStmtWithCleanups(Stmt *SubStmt);
4312 ExprResult MaybeCreateExprWithCleanups(ExprResult SubExpr);
4314 ExprResult ActOnFinishFullExpr(Expr *Expr) {
4315 return ActOnFinishFullExpr(Expr, Expr ? Expr->getExprLoc()
4316 : SourceLocation());
4318 ExprResult ActOnFinishFullExpr(Expr *Expr, SourceLocation CC,
4319 bool DiscardedValue = false,
4320 bool IsConstexpr = false,
4321 bool IsLambdaInitCaptureInitializer = false);
4322 StmtResult ActOnFinishFullStmt(Stmt *Stmt);
4324 // Marks SS invalid if it represents an incomplete type.
4325 bool RequireCompleteDeclContext(CXXScopeSpec &SS, DeclContext *DC);
4327 DeclContext *computeDeclContext(QualType T);
4328 DeclContext *computeDeclContext(const CXXScopeSpec &SS,
4329 bool EnteringContext = false);
4330 bool isDependentScopeSpecifier(const CXXScopeSpec &SS);
4331 CXXRecordDecl *getCurrentInstantiationOf(NestedNameSpecifier *NNS);
4333 /// \brief The parser has parsed a global nested-name-specifier '::'.
4335 /// \param S The scope in which this nested-name-specifier occurs.
4337 /// \param CCLoc The location of the '::'.
4339 /// \param SS The nested-name-specifier, which will be updated in-place
4340 /// to reflect the parsed nested-name-specifier.
4342 /// \returns true if an error occurred, false otherwise.
4343 bool ActOnCXXGlobalScopeSpecifier(Scope *S, SourceLocation CCLoc,
4346 bool isAcceptableNestedNameSpecifier(const NamedDecl *SD);
4347 NamedDecl *FindFirstQualifierInScope(Scope *S, NestedNameSpecifier *NNS);
4349 bool isNonTypeNestedNameSpecifier(Scope *S, CXXScopeSpec &SS,
4350 SourceLocation IdLoc,
4352 ParsedType ObjectType);
4354 bool BuildCXXNestedNameSpecifier(Scope *S,
4355 IdentifierInfo &Identifier,
4356 SourceLocation IdentifierLoc,
4357 SourceLocation CCLoc,
4358 QualType ObjectType,
4359 bool EnteringContext,
4361 NamedDecl *ScopeLookupResult,
4362 bool ErrorRecoveryLookup);
4364 /// \brief The parser has parsed a nested-name-specifier 'identifier::'.
4366 /// \param S The scope in which this nested-name-specifier occurs.
4368 /// \param Identifier The identifier preceding the '::'.
4370 /// \param IdentifierLoc The location of the identifier.
4372 /// \param CCLoc The location of the '::'.
4374 /// \param ObjectType The type of the object, if we're parsing
4375 /// nested-name-specifier in a member access expression.
4377 /// \param EnteringContext Whether we're entering the context nominated by
4378 /// this nested-name-specifier.
4380 /// \param SS The nested-name-specifier, which is both an input
4381 /// parameter (the nested-name-specifier before this type) and an
4382 /// output parameter (containing the full nested-name-specifier,
4383 /// including this new type).
4385 /// \returns true if an error occurred, false otherwise.
4386 bool ActOnCXXNestedNameSpecifier(Scope *S,
4387 IdentifierInfo &Identifier,
4388 SourceLocation IdentifierLoc,
4389 SourceLocation CCLoc,
4390 ParsedType ObjectType,
4391 bool EnteringContext,
4394 ExprResult ActOnDecltypeExpression(Expr *E);
4396 bool ActOnCXXNestedNameSpecifierDecltype(CXXScopeSpec &SS,
4398 SourceLocation ColonColonLoc);
4400 bool IsInvalidUnlessNestedName(Scope *S, CXXScopeSpec &SS,
4401 IdentifierInfo &Identifier,
4402 SourceLocation IdentifierLoc,
4403 SourceLocation ColonLoc,
4404 ParsedType ObjectType,
4405 bool EnteringContext);
4407 /// \brief The parser has parsed a nested-name-specifier
4408 /// 'template[opt] template-name < template-args >::'.
4410 /// \param S The scope in which this nested-name-specifier occurs.
4412 /// \param SS The nested-name-specifier, which is both an input
4413 /// parameter (the nested-name-specifier before this type) and an
4414 /// output parameter (containing the full nested-name-specifier,
4415 /// including this new type).
4417 /// \param TemplateKWLoc the location of the 'template' keyword, if any.
4418 /// \param TemplateName the template name.
4419 /// \param TemplateNameLoc The location of the template name.
4420 /// \param LAngleLoc The location of the opening angle bracket ('<').
4421 /// \param TemplateArgs The template arguments.
4422 /// \param RAngleLoc The location of the closing angle bracket ('>').
4423 /// \param CCLoc The location of the '::'.
4425 /// \param EnteringContext Whether we're entering the context of the
4426 /// nested-name-specifier.
4429 /// \returns true if an error occurred, false otherwise.
4430 bool ActOnCXXNestedNameSpecifier(Scope *S,
4432 SourceLocation TemplateKWLoc,
4433 TemplateTy TemplateName,
4434 SourceLocation TemplateNameLoc,
4435 SourceLocation LAngleLoc,
4436 ASTTemplateArgsPtr TemplateArgs,
4437 SourceLocation RAngleLoc,
4438 SourceLocation CCLoc,
4439 bool EnteringContext);
4441 /// \brief Given a C++ nested-name-specifier, produce an annotation value
4442 /// that the parser can use later to reconstruct the given
4443 /// nested-name-specifier.
4445 /// \param SS A nested-name-specifier.
4447 /// \returns A pointer containing all of the information in the
4448 /// nested-name-specifier \p SS.
4449 void *SaveNestedNameSpecifierAnnotation(CXXScopeSpec &SS);
4451 /// \brief Given an annotation pointer for a nested-name-specifier, restore
4452 /// the nested-name-specifier structure.
4454 /// \param Annotation The annotation pointer, produced by
4455 /// \c SaveNestedNameSpecifierAnnotation().
4457 /// \param AnnotationRange The source range corresponding to the annotation.
4459 /// \param SS The nested-name-specifier that will be updated with the contents
4460 /// of the annotation pointer.
4461 void RestoreNestedNameSpecifierAnnotation(void *Annotation,
4462 SourceRange AnnotationRange,
4465 bool ShouldEnterDeclaratorScope(Scope *S, const CXXScopeSpec &SS);
4467 /// ActOnCXXEnterDeclaratorScope - Called when a C++ scope specifier (global
4468 /// scope or nested-name-specifier) is parsed, part of a declarator-id.
4469 /// After this method is called, according to [C++ 3.4.3p3], names should be
4470 /// looked up in the declarator-id's scope, until the declarator is parsed and
4471 /// ActOnCXXExitDeclaratorScope is called.
4472 /// The 'SS' should be a non-empty valid CXXScopeSpec.
4473 bool ActOnCXXEnterDeclaratorScope(Scope *S, CXXScopeSpec &SS);
4475 /// ActOnCXXExitDeclaratorScope - Called when a declarator that previously
4476 /// invoked ActOnCXXEnterDeclaratorScope(), is finished. 'SS' is the same
4477 /// CXXScopeSpec that was passed to ActOnCXXEnterDeclaratorScope as well.
4478 /// Used to indicate that names should revert to being looked up in the
4480 void ActOnCXXExitDeclaratorScope(Scope *S, const CXXScopeSpec &SS);
4482 /// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse an
4483 /// initializer for the declaration 'Dcl'.
4484 /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
4485 /// static data member of class X, names should be looked up in the scope of
4487 void ActOnCXXEnterDeclInitializer(Scope *S, Decl *Dcl);
4489 /// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
4490 /// initializer for the declaration 'Dcl'.
4491 void ActOnCXXExitDeclInitializer(Scope *S, Decl *Dcl);
4493 /// \brief Create a new lambda closure type.
4494 CXXRecordDecl *createLambdaClosureType(SourceRange IntroducerRange,
4495 TypeSourceInfo *Info,
4496 bool KnownDependent,
4497 LambdaCaptureDefault CaptureDefault);
4499 /// \brief Start the definition of a lambda expression.
4500 CXXMethodDecl *startLambdaDefinition(CXXRecordDecl *Class,
4501 SourceRange IntroducerRange,
4502 TypeSourceInfo *MethodType,
4503 SourceLocation EndLoc,
4504 ArrayRef<ParmVarDecl *> Params);
4506 /// \brief Endow the lambda scope info with the relevant properties.
4507 void buildLambdaScope(sema::LambdaScopeInfo *LSI,
4508 CXXMethodDecl *CallOperator,
4509 SourceRange IntroducerRange,
4510 LambdaCaptureDefault CaptureDefault,
4511 SourceLocation CaptureDefaultLoc,
4512 bool ExplicitParams,
4513 bool ExplicitResultType,
4516 /// \brief Perform initialization analysis of the init-capture and perform
4517 /// any implicit conversions such as an lvalue-to-rvalue conversion if
4518 /// not being used to initialize a reference.
4519 QualType performLambdaInitCaptureInitialization(SourceLocation Loc,
4520 bool ByRef, IdentifierInfo *Id, Expr *&Init);
4521 /// \brief Create a dummy variable within the declcontext of the lambda's
4522 /// call operator, for name lookup purposes for a lambda init capture.
4524 /// CodeGen handles emission of lambda captures, ignoring these dummy
4525 /// variables appropriately.
4526 VarDecl *createLambdaInitCaptureVarDecl(SourceLocation Loc,
4527 QualType InitCaptureType, IdentifierInfo *Id, Expr *Init);
4529 /// \brief Build the implicit field for an init-capture.
4530 FieldDecl *buildInitCaptureField(sema::LambdaScopeInfo *LSI, VarDecl *Var);
4532 /// \brief Note that we have finished the explicit captures for the
4534 void finishLambdaExplicitCaptures(sema::LambdaScopeInfo *LSI);
4536 /// \brief Introduce the lambda parameters into scope.
4537 void addLambdaParameters(CXXMethodDecl *CallOperator, Scope *CurScope);
4539 /// \brief Deduce a block or lambda's return type based on the return
4540 /// statements present in the body.
4541 void deduceClosureReturnType(sema::CapturingScopeInfo &CSI);
4543 /// ActOnStartOfLambdaDefinition - This is called just before we start
4544 /// parsing the body of a lambda; it analyzes the explicit captures and
4545 /// arguments, and sets up various data-structures for the body of the
4547 void ActOnStartOfLambdaDefinition(LambdaIntroducer &Intro,
4548 Declarator &ParamInfo, Scope *CurScope);
4550 /// ActOnLambdaError - If there is an error parsing a lambda, this callback
4551 /// is invoked to pop the information about the lambda.
4552 void ActOnLambdaError(SourceLocation StartLoc, Scope *CurScope,
4553 bool IsInstantiation = false);
4555 /// ActOnLambdaExpr - This is called when the body of a lambda expression
4556 /// was successfully completed.
4557 ExprResult ActOnLambdaExpr(SourceLocation StartLoc, Stmt *Body,
4559 bool IsInstantiation = false);
4561 /// \brief Define the "body" of the conversion from a lambda object to a
4562 /// function pointer.
4564 /// This routine doesn't actually define a sensible body; rather, it fills
4565 /// in the initialization expression needed to copy the lambda object into
4566 /// the block, and IR generation actually generates the real body of the
4567 /// block pointer conversion.
4568 void DefineImplicitLambdaToFunctionPointerConversion(
4569 SourceLocation CurrentLoc, CXXConversionDecl *Conv);
4571 /// \brief Define the "body" of the conversion from a lambda object to a
4574 /// This routine doesn't actually define a sensible body; rather, it fills
4575 /// in the initialization expression needed to copy the lambda object into
4576 /// the block, and IR generation actually generates the real body of the
4577 /// block pointer conversion.
4578 void DefineImplicitLambdaToBlockPointerConversion(SourceLocation CurrentLoc,
4579 CXXConversionDecl *Conv);
4581 ExprResult BuildBlockForLambdaConversion(SourceLocation CurrentLocation,
4582 SourceLocation ConvLocation,
4583 CXXConversionDecl *Conv,
4586 // ParseObjCStringLiteral - Parse Objective-C string literals.
4587 ExprResult ParseObjCStringLiteral(SourceLocation *AtLocs,
4589 unsigned NumStrings);
4591 ExprResult BuildObjCStringLiteral(SourceLocation AtLoc, StringLiteral *S);
4593 /// BuildObjCNumericLiteral - builds an ObjCBoxedExpr AST node for the
4594 /// numeric literal expression. Type of the expression will be "NSNumber *"
4595 /// or "id" if NSNumber is unavailable.
4596 ExprResult BuildObjCNumericLiteral(SourceLocation AtLoc, Expr *Number);
4597 ExprResult ActOnObjCBoolLiteral(SourceLocation AtLoc, SourceLocation ValueLoc,
4599 ExprResult BuildObjCArrayLiteral(SourceRange SR, MultiExprArg Elements);
4601 /// BuildObjCBoxedExpr - builds an ObjCBoxedExpr AST node for the
4602 /// '@' prefixed parenthesized expression. The type of the expression will
4603 /// either be "NSNumber *" or "NSString *" depending on the type of
4604 /// ValueType, which is allowed to be a built-in numeric type or
4605 /// "char *" or "const char *".
4606 ExprResult BuildObjCBoxedExpr(SourceRange SR, Expr *ValueExpr);
4608 ExprResult BuildObjCSubscriptExpression(SourceLocation RB, Expr *BaseExpr,
4610 ObjCMethodDecl *getterMethod,
4611 ObjCMethodDecl *setterMethod);
4613 ExprResult BuildObjCDictionaryLiteral(SourceRange SR,
4614 ObjCDictionaryElement *Elements,
4615 unsigned NumElements);
4617 ExprResult BuildObjCEncodeExpression(SourceLocation AtLoc,
4618 TypeSourceInfo *EncodedTypeInfo,
4619 SourceLocation RParenLoc);
4620 ExprResult BuildCXXMemberCallExpr(Expr *Exp, NamedDecl *FoundDecl,
4621 CXXConversionDecl *Method,
4622 bool HadMultipleCandidates);
4624 ExprResult ParseObjCEncodeExpression(SourceLocation AtLoc,
4625 SourceLocation EncodeLoc,
4626 SourceLocation LParenLoc,
4628 SourceLocation RParenLoc);
4630 /// ParseObjCSelectorExpression - Build selector expression for \@selector
4631 ExprResult ParseObjCSelectorExpression(Selector Sel,
4632 SourceLocation AtLoc,
4633 SourceLocation SelLoc,
4634 SourceLocation LParenLoc,
4635 SourceLocation RParenLoc);
4637 /// ParseObjCProtocolExpression - Build protocol expression for \@protocol
4638 ExprResult ParseObjCProtocolExpression(IdentifierInfo * ProtocolName,
4639 SourceLocation AtLoc,
4640 SourceLocation ProtoLoc,
4641 SourceLocation LParenLoc,
4642 SourceLocation ProtoIdLoc,
4643 SourceLocation RParenLoc);
4645 //===--------------------------------------------------------------------===//
4648 Decl *ActOnStartLinkageSpecification(Scope *S,
4649 SourceLocation ExternLoc,
4650 SourceLocation LangLoc,
4652 SourceLocation LBraceLoc);
4653 Decl *ActOnFinishLinkageSpecification(Scope *S,
4655 SourceLocation RBraceLoc);
4658 //===--------------------------------------------------------------------===//
4661 bool isCurrentClassName(const IdentifierInfo &II, Scope *S,
4662 const CXXScopeSpec *SS = 0);
4663 bool isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS);
4665 bool ActOnAccessSpecifier(AccessSpecifier Access,
4666 SourceLocation ASLoc,
4667 SourceLocation ColonLoc,
4668 AttributeList *Attrs = 0);
4670 NamedDecl *ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS,
4672 MultiTemplateParamsArg TemplateParameterLists,
4673 Expr *BitfieldWidth, const VirtSpecifiers &VS,
4674 InClassInitStyle InitStyle);
4675 void ActOnCXXInClassMemberInitializer(Decl *VarDecl, SourceLocation EqualLoc,
4678 MemInitResult ActOnMemInitializer(Decl *ConstructorD,
4681 IdentifierInfo *MemberOrBase,
4682 ParsedType TemplateTypeTy,
4684 SourceLocation IdLoc,
4685 SourceLocation LParenLoc,
4686 ArrayRef<Expr *> Args,
4687 SourceLocation RParenLoc,
4688 SourceLocation EllipsisLoc);
4690 MemInitResult ActOnMemInitializer(Decl *ConstructorD,
4693 IdentifierInfo *MemberOrBase,
4694 ParsedType TemplateTypeTy,
4696 SourceLocation IdLoc,
4698 SourceLocation EllipsisLoc);
4700 MemInitResult BuildMemInitializer(Decl *ConstructorD,
4703 IdentifierInfo *MemberOrBase,
4704 ParsedType TemplateTypeTy,
4706 SourceLocation IdLoc,
4708 SourceLocation EllipsisLoc);
4710 MemInitResult BuildMemberInitializer(ValueDecl *Member,
4712 SourceLocation IdLoc);
4714 MemInitResult BuildBaseInitializer(QualType BaseType,
4715 TypeSourceInfo *BaseTInfo,
4717 CXXRecordDecl *ClassDecl,
4718 SourceLocation EllipsisLoc);
4720 MemInitResult BuildDelegatingInitializer(TypeSourceInfo *TInfo,
4722 CXXRecordDecl *ClassDecl);
4724 bool SetDelegatingInitializer(CXXConstructorDecl *Constructor,
4725 CXXCtorInitializer *Initializer);
4727 bool SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
4728 ArrayRef<CXXCtorInitializer *> Initializers = None);
4730 void SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation);
4733 /// MarkBaseAndMemberDestructorsReferenced - Given a record decl,
4734 /// mark all the non-trivial destructors of its members and bases as
4736 void MarkBaseAndMemberDestructorsReferenced(SourceLocation Loc,
4737 CXXRecordDecl *Record);
4739 /// \brief The list of classes whose vtables have been used within
4740 /// this translation unit, and the source locations at which the
4741 /// first use occurred.
4742 typedef std::pair<CXXRecordDecl*, SourceLocation> VTableUse;
4744 /// \brief The list of vtables that are required but have not yet been
4746 SmallVector<VTableUse, 16> VTableUses;
4748 /// \brief The set of classes whose vtables have been used within
4749 /// this translation unit, and a bit that will be true if the vtable is
4750 /// required to be emitted (otherwise, it should be emitted only if needed
4751 /// by code generation).
4752 llvm::DenseMap<CXXRecordDecl *, bool> VTablesUsed;
4754 /// \brief Load any externally-stored vtable uses.
4755 void LoadExternalVTableUses();
4757 typedef LazyVector<CXXRecordDecl *, ExternalSemaSource,
4758 &ExternalSemaSource::ReadDynamicClasses, 2, 2>
4761 /// \brief A list of all of the dynamic classes in this translation
4763 DynamicClassesType DynamicClasses;
4765 /// \brief Note that the vtable for the given class was used at the
4767 void MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
4768 bool DefinitionRequired = false);
4770 /// \brief Mark the exception specifications of all virtual member functions
4771 /// in the given class as needed.
4772 void MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
4773 const CXXRecordDecl *RD);
4775 /// MarkVirtualMembersReferenced - Will mark all members of the given
4776 /// CXXRecordDecl referenced.
4777 void MarkVirtualMembersReferenced(SourceLocation Loc,
4778 const CXXRecordDecl *RD);
4780 /// \brief Define all of the vtables that have been used in this
4781 /// translation unit and reference any virtual members used by those
4784 /// \returns true if any work was done, false otherwise.
4785 bool DefineUsedVTables();
4787 void AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl);
4789 void ActOnMemInitializers(Decl *ConstructorDecl,
4790 SourceLocation ColonLoc,
4791 ArrayRef<CXXCtorInitializer*> MemInits,
4794 void CheckCompletedCXXClass(CXXRecordDecl *Record);
4795 void ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
4797 SourceLocation LBrac,
4798 SourceLocation RBrac,
4799 AttributeList *AttrList);
4800 void ActOnFinishCXXMemberDecls();
4802 void ActOnReenterTemplateScope(Scope *S, Decl *Template);
4803 void ActOnReenterDeclaratorTemplateScope(Scope *S, DeclaratorDecl *D);
4804 void ActOnStartDelayedMemberDeclarations(Scope *S, Decl *Record);
4805 void ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *Method);
4806 void ActOnDelayedCXXMethodParameter(Scope *S, Decl *Param);
4807 void ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *Record);
4808 void ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *Method);
4809 void ActOnFinishDelayedMemberInitializers(Decl *Record);
4810 void MarkAsLateParsedTemplate(FunctionDecl *FD, Decl *FnD,
4811 CachedTokens &Toks);
4812 void UnmarkAsLateParsedTemplate(FunctionDecl *FD);
4813 bool IsInsideALocalClassWithinATemplateFunction();
4815 Decl *ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
4817 Expr *AssertMessageExpr,
4818 SourceLocation RParenLoc);
4819 Decl *BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
4821 StringLiteral *AssertMessageExpr,
4822 SourceLocation RParenLoc,
4825 FriendDecl *CheckFriendTypeDecl(SourceLocation LocStart,
4826 SourceLocation FriendLoc,
4827 TypeSourceInfo *TSInfo);
4828 Decl *ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
4829 MultiTemplateParamsArg TemplateParams);
4830 NamedDecl *ActOnFriendFunctionDecl(Scope *S, Declarator &D,
4831 MultiTemplateParamsArg TemplateParams);
4833 QualType CheckConstructorDeclarator(Declarator &D, QualType R,
4835 void CheckConstructor(CXXConstructorDecl *Constructor);
4836 QualType CheckDestructorDeclarator(Declarator &D, QualType R,
4838 bool CheckDestructor(CXXDestructorDecl *Destructor);
4839 void CheckConversionDeclarator(Declarator &D, QualType &R,
4841 Decl *ActOnConversionDeclarator(CXXConversionDecl *Conversion);
4843 void CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD);
4844 void CheckExplicitlyDefaultedMemberExceptionSpec(CXXMethodDecl *MD,
4845 const FunctionProtoType *T);
4846 void CheckDelayedMemberExceptionSpecs();
4848 //===--------------------------------------------------------------------===//
4849 // C++ Derived Classes
4852 /// ActOnBaseSpecifier - Parsed a base specifier
4853 CXXBaseSpecifier *CheckBaseSpecifier(CXXRecordDecl *Class,
4854 SourceRange SpecifierRange,
4855 bool Virtual, AccessSpecifier Access,
4856 TypeSourceInfo *TInfo,
4857 SourceLocation EllipsisLoc);
4859 BaseResult ActOnBaseSpecifier(Decl *classdecl,
4860 SourceRange SpecifierRange,
4861 ParsedAttributes &Attrs,
4862 bool Virtual, AccessSpecifier Access,
4863 ParsedType basetype,
4864 SourceLocation BaseLoc,
4865 SourceLocation EllipsisLoc);
4867 bool AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
4869 void ActOnBaseSpecifiers(Decl *ClassDecl, CXXBaseSpecifier **Bases,
4872 bool IsDerivedFrom(QualType Derived, QualType Base);
4873 bool IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths);
4875 // FIXME: I don't like this name.
4876 void BuildBasePathArray(const CXXBasePaths &Paths, CXXCastPath &BasePath);
4878 bool BasePathInvolvesVirtualBase(const CXXCastPath &BasePath);
4880 bool CheckDerivedToBaseConversion(QualType Derived, QualType Base,
4881 SourceLocation Loc, SourceRange Range,
4882 CXXCastPath *BasePath = 0,
4883 bool IgnoreAccess = false);
4884 bool CheckDerivedToBaseConversion(QualType Derived, QualType Base,
4885 unsigned InaccessibleBaseID,
4886 unsigned AmbigiousBaseConvID,
4887 SourceLocation Loc, SourceRange Range,
4888 DeclarationName Name,
4889 CXXCastPath *BasePath);
4891 std::string getAmbiguousPathsDisplayString(CXXBasePaths &Paths);
4893 bool CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
4894 const CXXMethodDecl *Old);
4896 /// CheckOverridingFunctionReturnType - Checks whether the return types are
4897 /// covariant, according to C++ [class.virtual]p5.
4898 bool CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
4899 const CXXMethodDecl *Old);
4901 /// CheckOverridingFunctionExceptionSpec - Checks whether the exception
4902 /// spec is a subset of base spec.
4903 bool CheckOverridingFunctionExceptionSpec(const CXXMethodDecl *New,
4904 const CXXMethodDecl *Old);
4906 bool CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange);
4908 /// CheckOverrideControl - Check C++11 override control semantics.
4909 void CheckOverrideControl(NamedDecl *D);
4911 /// CheckForFunctionMarkedFinal - Checks whether a virtual member function
4912 /// overrides a virtual member function marked 'final', according to
4913 /// C++11 [class.virtual]p4.
4914 bool CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
4915 const CXXMethodDecl *Old);
4918 //===--------------------------------------------------------------------===//
4919 // C++ Access Control
4929 bool SetMemberAccessSpecifier(NamedDecl *MemberDecl,
4930 NamedDecl *PrevMemberDecl,
4931 AccessSpecifier LexicalAS);
4933 AccessResult CheckUnresolvedMemberAccess(UnresolvedMemberExpr *E,
4934 DeclAccessPair FoundDecl);
4935 AccessResult CheckUnresolvedLookupAccess(UnresolvedLookupExpr *E,
4936 DeclAccessPair FoundDecl);
4937 AccessResult CheckAllocationAccess(SourceLocation OperatorLoc,
4938 SourceRange PlacementRange,
4939 CXXRecordDecl *NamingClass,
4940 DeclAccessPair FoundDecl,
4941 bool Diagnose = true);
4942 AccessResult CheckConstructorAccess(SourceLocation Loc,
4943 CXXConstructorDecl *D,
4944 const InitializedEntity &Entity,
4945 AccessSpecifier Access,
4946 bool IsCopyBindingRefToTemp = false);
4947 AccessResult CheckConstructorAccess(SourceLocation Loc,
4948 CXXConstructorDecl *D,
4949 const InitializedEntity &Entity,
4950 AccessSpecifier Access,
4951 const PartialDiagnostic &PDiag);
4952 AccessResult CheckDestructorAccess(SourceLocation Loc,
4953 CXXDestructorDecl *Dtor,
4954 const PartialDiagnostic &PDiag,
4955 QualType objectType = QualType());
4956 AccessResult CheckFriendAccess(NamedDecl *D);
4957 AccessResult CheckMemberAccess(SourceLocation UseLoc,
4958 CXXRecordDecl *NamingClass,
4959 DeclAccessPair Found);
4960 AccessResult CheckMemberOperatorAccess(SourceLocation Loc,
4963 DeclAccessPair FoundDecl);
4964 AccessResult CheckAddressOfMemberAccess(Expr *OvlExpr,
4965 DeclAccessPair FoundDecl);
4966 AccessResult CheckBaseClassAccess(SourceLocation AccessLoc,
4967 QualType Base, QualType Derived,
4968 const CXXBasePath &Path,
4970 bool ForceCheck = false,
4971 bool ForceUnprivileged = false);
4972 void CheckLookupAccess(const LookupResult &R);
4973 bool IsSimplyAccessible(NamedDecl *decl, DeclContext *Ctx);
4974 bool isSpecialMemberAccessibleForDeletion(CXXMethodDecl *decl,
4975 AccessSpecifier access,
4976 QualType objectType);
4978 void HandleDependentAccessCheck(const DependentDiagnostic &DD,
4979 const MultiLevelTemplateArgumentList &TemplateArgs);
4980 void PerformDependentDiagnostics(const DeclContext *Pattern,
4981 const MultiLevelTemplateArgumentList &TemplateArgs);
4983 void HandleDelayedAccessCheck(sema::DelayedDiagnostic &DD, Decl *Ctx);
4985 /// \brief When true, access checking violations are treated as SFINAE
4986 /// failures rather than hard errors.
4987 bool AccessCheckingSFINAE;
4989 enum AbstractDiagSelID {
4993 AbstractVariableType,
4996 AbstractSynthesizedIvarType,
5000 bool RequireNonAbstractType(SourceLocation Loc, QualType T,
5001 TypeDiagnoser &Diagnoser);
5002 template<typename T1>
5003 bool RequireNonAbstractType(SourceLocation Loc, QualType T,
5006 BoundTypeDiagnoser1<T1> Diagnoser(DiagID, Arg1);
5007 return RequireNonAbstractType(Loc, T, Diagnoser);
5010 template<typename T1, typename T2>
5011 bool RequireNonAbstractType(SourceLocation Loc, QualType T,
5013 const T1 &Arg1, const T2 &Arg2) {
5014 BoundTypeDiagnoser2<T1, T2> Diagnoser(DiagID, Arg1, Arg2);
5015 return RequireNonAbstractType(Loc, T, Diagnoser);
5018 template<typename T1, typename T2, typename T3>
5019 bool RequireNonAbstractType(SourceLocation Loc, QualType T,
5021 const T1 &Arg1, const T2 &Arg2, const T3 &Arg3) {
5022 BoundTypeDiagnoser3<T1, T2, T3> Diagnoser(DiagID, Arg1, Arg2, Arg3);
5023 return RequireNonAbstractType(Loc, T, Diagnoser);
5026 void DiagnoseAbstractType(const CXXRecordDecl *RD);
5028 bool RequireNonAbstractType(SourceLocation Loc, QualType T, unsigned DiagID,
5029 AbstractDiagSelID SelID = AbstractNone);
5031 //===--------------------------------------------------------------------===//
5032 // C++ Overloaded Operators [C++ 13.5]
5035 bool CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl);
5037 bool CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl);
5039 //===--------------------------------------------------------------------===//
5040 // C++ Templates [C++ 14]
5042 void FilterAcceptableTemplateNames(LookupResult &R,
5043 bool AllowFunctionTemplates = true);
5044 bool hasAnyAcceptableTemplateNames(LookupResult &R,
5045 bool AllowFunctionTemplates = true);
5047 void LookupTemplateName(LookupResult &R, Scope *S, CXXScopeSpec &SS,
5048 QualType ObjectType, bool EnteringContext,
5049 bool &MemberOfUnknownSpecialization);
5051 TemplateNameKind isTemplateName(Scope *S,
5053 bool hasTemplateKeyword,
5054 UnqualifiedId &Name,
5055 ParsedType ObjectType,
5056 bool EnteringContext,
5057 TemplateTy &Template,
5058 bool &MemberOfUnknownSpecialization);
5060 bool DiagnoseUnknownTemplateName(const IdentifierInfo &II,
5061 SourceLocation IILoc,
5063 const CXXScopeSpec *SS,
5064 TemplateTy &SuggestedTemplate,
5065 TemplateNameKind &SuggestedKind);
5067 void DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl);
5068 TemplateDecl *AdjustDeclIfTemplate(Decl *&Decl);
5070 Decl *ActOnTypeParameter(Scope *S, bool Typename, bool Ellipsis,
5071 SourceLocation EllipsisLoc,
5072 SourceLocation KeyLoc,
5073 IdentifierInfo *ParamName,
5074 SourceLocation ParamNameLoc,
5075 unsigned Depth, unsigned Position,
5076 SourceLocation EqualLoc,
5077 ParsedType DefaultArg);
5079 QualType CheckNonTypeTemplateParameterType(QualType T, SourceLocation Loc);
5080 Decl *ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
5083 SourceLocation EqualLoc,
5085 Decl *ActOnTemplateTemplateParameter(Scope *S,
5086 SourceLocation TmpLoc,
5087 TemplateParameterList *Params,
5088 SourceLocation EllipsisLoc,
5089 IdentifierInfo *ParamName,
5090 SourceLocation ParamNameLoc,
5093 SourceLocation EqualLoc,
5094 ParsedTemplateArgument DefaultArg);
5096 TemplateParameterList *
5097 ActOnTemplateParameterList(unsigned Depth,
5098 SourceLocation ExportLoc,
5099 SourceLocation TemplateLoc,
5100 SourceLocation LAngleLoc,
5101 Decl **Params, unsigned NumParams,
5102 SourceLocation RAngleLoc);
5104 /// \brief The context in which we are checking a template parameter list.
5105 enum TemplateParamListContext {
5108 TPC_FunctionTemplate,
5109 TPC_ClassTemplateMember,
5110 TPC_FriendClassTemplate,
5111 TPC_FriendFunctionTemplate,
5112 TPC_FriendFunctionTemplateDefinition,
5113 TPC_TypeAliasTemplate
5116 bool CheckTemplateParameterList(TemplateParameterList *NewParams,
5117 TemplateParameterList *OldParams,
5118 TemplateParamListContext TPC);
5119 TemplateParameterList *MatchTemplateParametersToScopeSpecifier(
5120 SourceLocation DeclStartLoc, SourceLocation DeclLoc,
5121 const CXXScopeSpec &SS, ArrayRef<TemplateParameterList *> ParamLists,
5122 bool IsFriend, bool &IsExplicitSpecialization, bool &Invalid);
5124 DeclResult CheckClassTemplate(Scope *S, unsigned TagSpec, TagUseKind TUK,
5125 SourceLocation KWLoc, CXXScopeSpec &SS,
5126 IdentifierInfo *Name, SourceLocation NameLoc,
5127 AttributeList *Attr,
5128 TemplateParameterList *TemplateParams,
5130 SourceLocation ModulePrivateLoc,
5131 unsigned NumOuterTemplateParamLists,
5132 TemplateParameterList **OuterTemplateParamLists);
5134 void translateTemplateArguments(const ASTTemplateArgsPtr &In,
5135 TemplateArgumentListInfo &Out);
5137 void NoteAllFoundTemplates(TemplateName Name);
5139 QualType CheckTemplateIdType(TemplateName Template,
5140 SourceLocation TemplateLoc,
5141 TemplateArgumentListInfo &TemplateArgs);
5144 ActOnTemplateIdType(CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
5145 TemplateTy Template, SourceLocation TemplateLoc,
5146 SourceLocation LAngleLoc,
5147 ASTTemplateArgsPtr TemplateArgs,
5148 SourceLocation RAngleLoc,
5149 bool IsCtorOrDtorName = false);
5151 /// \brief Parsed an elaborated-type-specifier that refers to a template-id,
5152 /// such as \c class T::template apply<U>.
5153 TypeResult ActOnTagTemplateIdType(TagUseKind TUK,
5154 TypeSpecifierType TagSpec,
5155 SourceLocation TagLoc,
5157 SourceLocation TemplateKWLoc,
5158 TemplateTy TemplateD,
5159 SourceLocation TemplateLoc,
5160 SourceLocation LAngleLoc,
5161 ASTTemplateArgsPtr TemplateArgsIn,
5162 SourceLocation RAngleLoc);
5164 DeclResult ActOnVarTemplateSpecialization(
5165 Scope *S, VarTemplateDecl *VarTemplate, Declarator &D, TypeSourceInfo *DI,
5166 SourceLocation TemplateKWLoc, TemplateParameterList *TemplateParams,
5167 StorageClass SC, bool IsPartialSpecialization);
5169 DeclResult CheckVarTemplateId(VarTemplateDecl *Template,
5170 SourceLocation TemplateLoc,
5171 SourceLocation TemplateNameLoc,
5172 const TemplateArgumentListInfo &TemplateArgs);
5174 ExprResult CheckVarTemplateId(const CXXScopeSpec &SS,
5175 const DeclarationNameInfo &NameInfo,
5176 VarTemplateDecl *Template,
5177 SourceLocation TemplateLoc,
5178 const TemplateArgumentListInfo *TemplateArgs);
5180 ExprResult BuildTemplateIdExpr(const CXXScopeSpec &SS,
5181 SourceLocation TemplateKWLoc,
5184 const TemplateArgumentListInfo *TemplateArgs);
5186 ExprResult BuildQualifiedTemplateIdExpr(CXXScopeSpec &SS,
5187 SourceLocation TemplateKWLoc,
5188 const DeclarationNameInfo &NameInfo,
5189 const TemplateArgumentListInfo *TemplateArgs);
5191 TemplateNameKind ActOnDependentTemplateName(Scope *S,
5193 SourceLocation TemplateKWLoc,
5194 UnqualifiedId &Name,
5195 ParsedType ObjectType,
5196 bool EnteringContext,
5197 TemplateTy &Template);
5200 ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec, TagUseKind TUK,
5201 SourceLocation KWLoc,
5202 SourceLocation ModulePrivateLoc,
5204 TemplateTy Template,
5205 SourceLocation TemplateNameLoc,
5206 SourceLocation LAngleLoc,
5207 ASTTemplateArgsPtr TemplateArgs,
5208 SourceLocation RAngleLoc,
5209 AttributeList *Attr,
5210 MultiTemplateParamsArg TemplateParameterLists);
5212 Decl *ActOnTemplateDeclarator(Scope *S,
5213 MultiTemplateParamsArg TemplateParameterLists,
5216 Decl *ActOnStartOfFunctionTemplateDef(Scope *FnBodyScope,
5217 MultiTemplateParamsArg TemplateParameterLists,
5221 CheckSpecializationInstantiationRedecl(SourceLocation NewLoc,
5222 TemplateSpecializationKind NewTSK,
5223 NamedDecl *PrevDecl,
5224 TemplateSpecializationKind PrevTSK,
5225 SourceLocation PrevPtOfInstantiation,
5228 bool CheckDependentFunctionTemplateSpecialization(FunctionDecl *FD,
5229 const TemplateArgumentListInfo &ExplicitTemplateArgs,
5230 LookupResult &Previous);
5232 bool CheckFunctionTemplateSpecialization(FunctionDecl *FD,
5233 TemplateArgumentListInfo *ExplicitTemplateArgs,
5234 LookupResult &Previous);
5235 bool CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous);
5238 ActOnExplicitInstantiation(Scope *S,
5239 SourceLocation ExternLoc,
5240 SourceLocation TemplateLoc,
5242 SourceLocation KWLoc,
5243 const CXXScopeSpec &SS,
5244 TemplateTy Template,
5245 SourceLocation TemplateNameLoc,
5246 SourceLocation LAngleLoc,
5247 ASTTemplateArgsPtr TemplateArgs,
5248 SourceLocation RAngleLoc,
5249 AttributeList *Attr);
5252 ActOnExplicitInstantiation(Scope *S,
5253 SourceLocation ExternLoc,
5254 SourceLocation TemplateLoc,
5256 SourceLocation KWLoc,
5258 IdentifierInfo *Name,
5259 SourceLocation NameLoc,
5260 AttributeList *Attr);
5262 DeclResult ActOnExplicitInstantiation(Scope *S,
5263 SourceLocation ExternLoc,
5264 SourceLocation TemplateLoc,
5268 SubstDefaultTemplateArgumentIfAvailable(TemplateDecl *Template,
5269 SourceLocation TemplateLoc,
5270 SourceLocation RAngleLoc,
5272 SmallVectorImpl<TemplateArgument>
5274 bool &HasDefaultArg);
5276 /// \brief Specifies the context in which a particular template
5277 /// argument is being checked.
5278 enum CheckTemplateArgumentKind {
5279 /// \brief The template argument was specified in the code or was
5280 /// instantiated with some deduced template arguments.
5283 /// \brief The template argument was deduced via template argument
5287 /// \brief The template argument was deduced from an array bound
5288 /// via template argument deduction.
5289 CTAK_DeducedFromArrayBound
5292 bool CheckTemplateArgument(NamedDecl *Param,
5293 const TemplateArgumentLoc &Arg,
5294 NamedDecl *Template,
5295 SourceLocation TemplateLoc,
5296 SourceLocation RAngleLoc,
5297 unsigned ArgumentPackIndex,
5298 SmallVectorImpl<TemplateArgument> &Converted,
5299 CheckTemplateArgumentKind CTAK = CTAK_Specified);
5301 /// \brief Check that the given template arguments can be be provided to
5302 /// the given template, converting the arguments along the way.
5304 /// \param Template The template to which the template arguments are being
5307 /// \param TemplateLoc The location of the template name in the source.
5309 /// \param TemplateArgs The list of template arguments. If the template is
5310 /// a template template parameter, this function may extend the set of
5311 /// template arguments to also include substituted, defaulted template
5314 /// \param PartialTemplateArgs True if the list of template arguments is
5315 /// intentionally partial, e.g., because we're checking just the initial
5316 /// set of template arguments.
5318 /// \param Converted Will receive the converted, canonicalized template
5322 /// \param ExpansionIntoFixedList If non-NULL, will be set true to indicate
5323 /// when the template arguments contain a pack expansion that is being
5324 /// expanded into a fixed parameter list.
5326 /// \returns True if an error occurred, false otherwise.
5327 bool CheckTemplateArgumentList(TemplateDecl *Template,
5328 SourceLocation TemplateLoc,
5329 TemplateArgumentListInfo &TemplateArgs,
5330 bool PartialTemplateArgs,
5331 SmallVectorImpl<TemplateArgument> &Converted,
5332 bool *ExpansionIntoFixedList = 0);
5334 bool CheckTemplateTypeArgument(TemplateTypeParmDecl *Param,
5335 const TemplateArgumentLoc &Arg,
5336 SmallVectorImpl<TemplateArgument> &Converted);
5338 bool CheckTemplateArgument(TemplateTypeParmDecl *Param,
5339 TypeSourceInfo *Arg);
5340 ExprResult CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
5341 QualType InstantiatedParamType, Expr *Arg,
5342 TemplateArgument &Converted,
5343 CheckTemplateArgumentKind CTAK = CTAK_Specified);
5344 bool CheckTemplateArgument(TemplateTemplateParmDecl *Param,
5345 const TemplateArgumentLoc &Arg,
5346 unsigned ArgumentPackIndex);
5349 BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg,
5351 SourceLocation Loc);
5353 BuildExpressionFromIntegralTemplateArgument(const TemplateArgument &Arg,
5354 SourceLocation Loc);
5356 /// \brief Enumeration describing how template parameter lists are compared
5358 enum TemplateParameterListEqualKind {
5359 /// \brief We are matching the template parameter lists of two templates
5360 /// that might be redeclarations.
5363 /// template<typename T> struct X;
5364 /// template<typename T> struct X;
5368 /// \brief We are matching the template parameter lists of two template
5369 /// template parameters as part of matching the template parameter lists
5370 /// of two templates that might be redeclarations.
5373 /// template<template<int I> class TT> struct X;
5374 /// template<template<int Value> class Other> struct X;
5376 TPL_TemplateTemplateParmMatch,
5378 /// \brief We are matching the template parameter lists of a template
5379 /// template argument against the template parameter lists of a template
5380 /// template parameter.
5383 /// template<template<int Value> class Metafun> struct X;
5384 /// template<int Value> struct integer_c;
5385 /// X<integer_c> xic;
5387 TPL_TemplateTemplateArgumentMatch
5390 bool TemplateParameterListsAreEqual(TemplateParameterList *New,
5391 TemplateParameterList *Old,
5393 TemplateParameterListEqualKind Kind,
5394 SourceLocation TemplateArgLoc
5395 = SourceLocation());
5397 bool CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams);
5399 /// \brief Called when the parser has parsed a C++ typename
5400 /// specifier, e.g., "typename T::type".
5402 /// \param S The scope in which this typename type occurs.
5403 /// \param TypenameLoc the location of the 'typename' keyword
5404 /// \param SS the nested-name-specifier following the typename (e.g., 'T::').
5405 /// \param II the identifier we're retrieving (e.g., 'type' in the example).
5406 /// \param IdLoc the location of the identifier.
5408 ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
5409 const CXXScopeSpec &SS, const IdentifierInfo &II,
5410 SourceLocation IdLoc);
5412 /// \brief Called when the parser has parsed a C++ typename
5413 /// specifier that ends in a template-id, e.g.,
5414 /// "typename MetaFun::template apply<T1, T2>".
5416 /// \param S The scope in which this typename type occurs.
5417 /// \param TypenameLoc the location of the 'typename' keyword
5418 /// \param SS the nested-name-specifier following the typename (e.g., 'T::').
5419 /// \param TemplateLoc the location of the 'template' keyword, if any.
5420 /// \param TemplateName The template name.
5421 /// \param TemplateNameLoc The location of the template name.
5422 /// \param LAngleLoc The location of the opening angle bracket ('<').
5423 /// \param TemplateArgs The template arguments.
5424 /// \param RAngleLoc The location of the closing angle bracket ('>').
5426 ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
5427 const CXXScopeSpec &SS,
5428 SourceLocation TemplateLoc,
5429 TemplateTy TemplateName,
5430 SourceLocation TemplateNameLoc,
5431 SourceLocation LAngleLoc,
5432 ASTTemplateArgsPtr TemplateArgs,
5433 SourceLocation RAngleLoc);
5435 QualType CheckTypenameType(ElaboratedTypeKeyword Keyword,
5436 SourceLocation KeywordLoc,
5437 NestedNameSpecifierLoc QualifierLoc,
5438 const IdentifierInfo &II,
5439 SourceLocation IILoc);
5441 TypeSourceInfo *RebuildTypeInCurrentInstantiation(TypeSourceInfo *T,
5443 DeclarationName Name);
5444 bool RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS);
5446 ExprResult RebuildExprInCurrentInstantiation(Expr *E);
5447 bool RebuildTemplateParamsInCurrentInstantiation(
5448 TemplateParameterList *Params);
5451 getTemplateArgumentBindingsText(const TemplateParameterList *Params,
5452 const TemplateArgumentList &Args);
5455 getTemplateArgumentBindingsText(const TemplateParameterList *Params,
5456 const TemplateArgument *Args,
5459 //===--------------------------------------------------------------------===//
5460 // C++ Variadic Templates (C++0x [temp.variadic])
5461 //===--------------------------------------------------------------------===//
5463 /// \brief The context in which an unexpanded parameter pack is
5464 /// being diagnosed.
5466 /// Note that the values of this enumeration line up with the first
5467 /// argument to the \c err_unexpanded_parameter_pack diagnostic.
5468 enum UnexpandedParameterPackContext {
5469 /// \brief An arbitrary expression.
5470 UPPC_Expression = 0,
5472 /// \brief The base type of a class type.
5475 /// \brief The type of an arbitrary declaration.
5476 UPPC_DeclarationType,
5478 /// \brief The type of a data member.
5479 UPPC_DataMemberType,
5481 /// \brief The size of a bit-field.
5484 /// \brief The expression in a static assertion.
5485 UPPC_StaticAssertExpression,
5487 /// \brief The fixed underlying type of an enumeration.
5488 UPPC_FixedUnderlyingType,
5490 /// \brief The enumerator value.
5491 UPPC_EnumeratorValue,
5493 /// \brief A using declaration.
5494 UPPC_UsingDeclaration,
5496 /// \brief A friend declaration.
5497 UPPC_FriendDeclaration,
5499 /// \brief A declaration qualifier.
5500 UPPC_DeclarationQualifier,
5502 /// \brief An initializer.
5505 /// \brief A default argument.
5506 UPPC_DefaultArgument,
5508 /// \brief The type of a non-type template parameter.
5509 UPPC_NonTypeTemplateParameterType,
5511 /// \brief The type of an exception.
5514 /// \brief Partial specialization.
5515 UPPC_PartialSpecialization,
5517 /// \brief Microsoft __if_exists.
5520 /// \brief Microsoft __if_not_exists.
5523 /// \brief Lambda expression.
5526 /// \brief Block expression,
5530 /// \brief Diagnose unexpanded parameter packs.
5532 /// \param Loc The location at which we should emit the diagnostic.
5534 /// \param UPPC The context in which we are diagnosing unexpanded
5535 /// parameter packs.
5537 /// \param Unexpanded the set of unexpanded parameter packs.
5539 /// \returns true if an error occurred, false otherwise.
5540 bool DiagnoseUnexpandedParameterPacks(SourceLocation Loc,
5541 UnexpandedParameterPackContext UPPC,
5542 ArrayRef<UnexpandedParameterPack> Unexpanded);
5544 /// \brief If the given type contains an unexpanded parameter pack,
5545 /// diagnose the error.
5547 /// \param Loc The source location where a diagnostc should be emitted.
5549 /// \param T The type that is being checked for unexpanded parameter
5552 /// \returns true if an error occurred, false otherwise.
5553 bool DiagnoseUnexpandedParameterPack(SourceLocation Loc, TypeSourceInfo *T,
5554 UnexpandedParameterPackContext UPPC);
5556 /// \brief If the given expression contains an unexpanded parameter
5557 /// pack, diagnose the error.
5559 /// \param E The expression that is being checked for unexpanded
5560 /// parameter packs.
5562 /// \returns true if an error occurred, false otherwise.
5563 bool DiagnoseUnexpandedParameterPack(Expr *E,
5564 UnexpandedParameterPackContext UPPC = UPPC_Expression);
5566 /// \brief If the given nested-name-specifier contains an unexpanded
5567 /// parameter pack, diagnose the error.
5569 /// \param SS The nested-name-specifier that is being checked for
5570 /// unexpanded parameter packs.
5572 /// \returns true if an error occurred, false otherwise.
5573 bool DiagnoseUnexpandedParameterPack(const CXXScopeSpec &SS,
5574 UnexpandedParameterPackContext UPPC);
5576 /// \brief If the given name contains an unexpanded parameter pack,
5577 /// diagnose the error.
5579 /// \param NameInfo The name (with source location information) that
5580 /// is being checked for unexpanded parameter packs.
5582 /// \returns true if an error occurred, false otherwise.
5583 bool DiagnoseUnexpandedParameterPack(const DeclarationNameInfo &NameInfo,
5584 UnexpandedParameterPackContext UPPC);
5586 /// \brief If the given template name contains an unexpanded parameter pack,
5587 /// diagnose the error.
5589 /// \param Loc The location of the template name.
5591 /// \param Template The template name that is being checked for unexpanded
5592 /// parameter packs.
5594 /// \returns true if an error occurred, false otherwise.
5595 bool DiagnoseUnexpandedParameterPack(SourceLocation Loc,
5596 TemplateName Template,
5597 UnexpandedParameterPackContext UPPC);
5599 /// \brief If the given template argument contains an unexpanded parameter
5600 /// pack, diagnose the error.
5602 /// \param Arg The template argument that is being checked for unexpanded
5603 /// parameter packs.
5605 /// \returns true if an error occurred, false otherwise.
5606 bool DiagnoseUnexpandedParameterPack(TemplateArgumentLoc Arg,
5607 UnexpandedParameterPackContext UPPC);
5609 /// \brief Collect the set of unexpanded parameter packs within the given
5610 /// template argument.
5612 /// \param Arg The template argument that will be traversed to find
5613 /// unexpanded parameter packs.
5614 void collectUnexpandedParameterPacks(TemplateArgument Arg,
5615 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
5617 /// \brief Collect the set of unexpanded parameter packs within the given
5618 /// template argument.
5620 /// \param Arg The template argument that will be traversed to find
5621 /// unexpanded parameter packs.
5622 void collectUnexpandedParameterPacks(TemplateArgumentLoc Arg,
5623 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
5625 /// \brief Collect the set of unexpanded parameter packs within the given
5628 /// \param T The type that will be traversed to find
5629 /// unexpanded parameter packs.
5630 void collectUnexpandedParameterPacks(QualType T,
5631 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
5633 /// \brief Collect the set of unexpanded parameter packs within the given
5636 /// \param TL The type that will be traversed to find
5637 /// unexpanded parameter packs.
5638 void collectUnexpandedParameterPacks(TypeLoc TL,
5639 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
5641 /// \brief Collect the set of unexpanded parameter packs within the given
5642 /// nested-name-specifier.
5644 /// \param SS The nested-name-specifier that will be traversed to find
5645 /// unexpanded parameter packs.
5646 void collectUnexpandedParameterPacks(CXXScopeSpec &SS,
5647 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
5649 /// \brief Collect the set of unexpanded parameter packs within the given
5652 /// \param NameInfo The name that will be traversed to find
5653 /// unexpanded parameter packs.
5654 void collectUnexpandedParameterPacks(const DeclarationNameInfo &NameInfo,
5655 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
5657 /// \brief Invoked when parsing a template argument followed by an
5658 /// ellipsis, which creates a pack expansion.
5660 /// \param Arg The template argument preceding the ellipsis, which
5661 /// may already be invalid.
5663 /// \param EllipsisLoc The location of the ellipsis.
5664 ParsedTemplateArgument ActOnPackExpansion(const ParsedTemplateArgument &Arg,
5665 SourceLocation EllipsisLoc);
5667 /// \brief Invoked when parsing a type followed by an ellipsis, which
5668 /// creates a pack expansion.
5670 /// \param Type The type preceding the ellipsis, which will become
5671 /// the pattern of the pack expansion.
5673 /// \param EllipsisLoc The location of the ellipsis.
5674 TypeResult ActOnPackExpansion(ParsedType Type, SourceLocation EllipsisLoc);
5676 /// \brief Construct a pack expansion type from the pattern of the pack
5678 TypeSourceInfo *CheckPackExpansion(TypeSourceInfo *Pattern,
5679 SourceLocation EllipsisLoc,
5680 Optional<unsigned> NumExpansions);
5682 /// \brief Construct a pack expansion type from the pattern of the pack
5684 QualType CheckPackExpansion(QualType Pattern,
5685 SourceRange PatternRange,
5686 SourceLocation EllipsisLoc,
5687 Optional<unsigned> NumExpansions);
5689 /// \brief Invoked when parsing an expression followed by an ellipsis, which
5690 /// creates a pack expansion.
5692 /// \param Pattern The expression preceding the ellipsis, which will become
5693 /// the pattern of the pack expansion.
5695 /// \param EllipsisLoc The location of the ellipsis.
5696 ExprResult ActOnPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc);
5698 /// \brief Invoked when parsing an expression followed by an ellipsis, which
5699 /// creates a pack expansion.
5701 /// \param Pattern The expression preceding the ellipsis, which will become
5702 /// the pattern of the pack expansion.
5704 /// \param EllipsisLoc The location of the ellipsis.
5705 ExprResult CheckPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc,
5706 Optional<unsigned> NumExpansions);
5708 /// \brief Determine whether we could expand a pack expansion with the
5709 /// given set of parameter packs into separate arguments by repeatedly
5710 /// transforming the pattern.
5712 /// \param EllipsisLoc The location of the ellipsis that identifies the
5715 /// \param PatternRange The source range that covers the entire pattern of
5716 /// the pack expansion.
5718 /// \param Unexpanded The set of unexpanded parameter packs within the
5721 /// \param ShouldExpand Will be set to \c true if the transformer should
5722 /// expand the corresponding pack expansions into separate arguments. When
5723 /// set, \c NumExpansions must also be set.
5725 /// \param RetainExpansion Whether the caller should add an unexpanded
5726 /// pack expansion after all of the expanded arguments. This is used
5727 /// when extending explicitly-specified template argument packs per
5728 /// C++0x [temp.arg.explicit]p9.
5730 /// \param NumExpansions The number of separate arguments that will be in
5731 /// the expanded form of the corresponding pack expansion. This is both an
5732 /// input and an output parameter, which can be set by the caller if the
5733 /// number of expansions is known a priori (e.g., due to a prior substitution)
5734 /// and will be set by the callee when the number of expansions is known.
5735 /// The callee must set this value when \c ShouldExpand is \c true; it may
5736 /// set this value in other cases.
5738 /// \returns true if an error occurred (e.g., because the parameter packs
5739 /// are to be instantiated with arguments of different lengths), false
5740 /// otherwise. If false, \c ShouldExpand (and possibly \c NumExpansions)
5742 bool CheckParameterPacksForExpansion(SourceLocation EllipsisLoc,
5743 SourceRange PatternRange,
5744 ArrayRef<UnexpandedParameterPack> Unexpanded,
5745 const MultiLevelTemplateArgumentList &TemplateArgs,
5747 bool &RetainExpansion,
5748 Optional<unsigned> &NumExpansions);
5750 /// \brief Determine the number of arguments in the given pack expansion
5753 /// This routine assumes that the number of arguments in the expansion is
5754 /// consistent across all of the unexpanded parameter packs in its pattern.
5756 /// Returns an empty Optional if the type can't be expanded.
5757 Optional<unsigned> getNumArgumentsInExpansion(QualType T,
5758 const MultiLevelTemplateArgumentList &TemplateArgs);
5760 /// \brief Determine whether the given declarator contains any unexpanded
5761 /// parameter packs.
5763 /// This routine is used by the parser to disambiguate function declarators
5764 /// with an ellipsis prior to the ')', e.g.,
5770 /// To determine whether we have an (unnamed) function parameter pack or
5771 /// a variadic function.
5773 /// \returns true if the declarator contains any unexpanded parameter packs,
5774 /// false otherwise.
5775 bool containsUnexpandedParameterPacks(Declarator &D);
5777 /// \brief Returns the pattern of the pack expansion for a template argument.
5779 /// \param OrigLoc The template argument to expand.
5781 /// \param Ellipsis Will be set to the location of the ellipsis.
5783 /// \param NumExpansions Will be set to the number of expansions that will
5784 /// be generated from this pack expansion, if known a priori.
5785 TemplateArgumentLoc getTemplateArgumentPackExpansionPattern(
5786 TemplateArgumentLoc OrigLoc,
5787 SourceLocation &Ellipsis,
5788 Optional<unsigned> &NumExpansions) const;
5790 //===--------------------------------------------------------------------===//
5791 // C++ Template Argument Deduction (C++ [temp.deduct])
5792 //===--------------------------------------------------------------------===//
5794 QualType adjustCCAndNoReturn(QualType ArgFunctionType, QualType FunctionType);
5796 /// \brief Describes the result of template argument deduction.
5798 /// The TemplateDeductionResult enumeration describes the result of
5799 /// template argument deduction, as returned from
5800 /// DeduceTemplateArguments(). The separate TemplateDeductionInfo
5801 /// structure provides additional information about the results of
5802 /// template argument deduction, e.g., the deduced template argument
5803 /// list (if successful) or the specific template parameters or
5804 /// deduced arguments that were involved in the failure.
5805 enum TemplateDeductionResult {
5806 /// \brief Template argument deduction was successful.
5808 /// \brief The declaration was invalid; do nothing.
5810 /// \brief Template argument deduction exceeded the maximum template
5811 /// instantiation depth (which has already been diagnosed).
5812 TDK_InstantiationDepth,
5813 /// \brief Template argument deduction did not deduce a value
5814 /// for every template parameter.
5816 /// \brief Template argument deduction produced inconsistent
5817 /// deduced values for the given template parameter.
5819 /// \brief Template argument deduction failed due to inconsistent
5820 /// cv-qualifiers on a template parameter type that would
5821 /// otherwise be deduced, e.g., we tried to deduce T in "const T"
5822 /// but were given a non-const "X".
5824 /// \brief Substitution of the deduced template argument values
5825 /// resulted in an error.
5826 TDK_SubstitutionFailure,
5827 /// \brief A non-depnedent component of the parameter did not match the
5828 /// corresponding component of the argument.
5829 TDK_NonDeducedMismatch,
5830 /// \brief When performing template argument deduction for a function
5831 /// template, there were too many call arguments.
5832 TDK_TooManyArguments,
5833 /// \brief When performing template argument deduction for a function
5834 /// template, there were too few call arguments.
5835 TDK_TooFewArguments,
5836 /// \brief The explicitly-specified template arguments were not valid
5837 /// template arguments for the given template.
5838 TDK_InvalidExplicitArguments,
5839 /// \brief The arguments included an overloaded function name that could
5840 /// not be resolved to a suitable function.
5841 TDK_FailedOverloadResolution,
5842 /// \brief Deduction failed; that's all we know.
5843 TDK_MiscellaneousDeductionFailure
5846 TemplateDeductionResult
5847 DeduceTemplateArguments(ClassTemplatePartialSpecializationDecl *Partial,
5848 const TemplateArgumentList &TemplateArgs,
5849 sema::TemplateDeductionInfo &Info);
5851 TemplateDeductionResult
5852 DeduceTemplateArguments(VarTemplatePartialSpecializationDecl *Partial,
5853 const TemplateArgumentList &TemplateArgs,
5854 sema::TemplateDeductionInfo &Info);
5856 TemplateDeductionResult SubstituteExplicitTemplateArguments(
5857 FunctionTemplateDecl *FunctionTemplate,
5858 TemplateArgumentListInfo &ExplicitTemplateArgs,
5859 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
5860 SmallVectorImpl<QualType> &ParamTypes, QualType *FunctionType,
5861 sema::TemplateDeductionInfo &Info);
5863 /// brief A function argument from which we performed template argument
5864 // deduction for a call.
5865 struct OriginalCallArg {
5866 OriginalCallArg(QualType OriginalParamType,
5868 QualType OriginalArgType)
5869 : OriginalParamType(OriginalParamType), ArgIdx(ArgIdx),
5870 OriginalArgType(OriginalArgType) { }
5872 QualType OriginalParamType;
5874 QualType OriginalArgType;
5877 TemplateDeductionResult
5878 FinishTemplateArgumentDeduction(FunctionTemplateDecl *FunctionTemplate,
5879 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
5880 unsigned NumExplicitlySpecified,
5881 FunctionDecl *&Specialization,
5882 sema::TemplateDeductionInfo &Info,
5883 SmallVectorImpl<OriginalCallArg> const *OriginalCallArgs = 0);
5885 TemplateDeductionResult
5886 DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
5887 TemplateArgumentListInfo *ExplicitTemplateArgs,
5888 ArrayRef<Expr *> Args,
5889 FunctionDecl *&Specialization,
5890 sema::TemplateDeductionInfo &Info);
5892 TemplateDeductionResult
5893 DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
5894 TemplateArgumentListInfo *ExplicitTemplateArgs,
5895 QualType ArgFunctionType,
5896 FunctionDecl *&Specialization,
5897 sema::TemplateDeductionInfo &Info,
5898 bool InOverloadResolution = false);
5900 TemplateDeductionResult
5901 DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
5903 CXXConversionDecl *&Specialization,
5904 sema::TemplateDeductionInfo &Info);
5906 TemplateDeductionResult
5907 DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
5908 TemplateArgumentListInfo *ExplicitTemplateArgs,
5909 FunctionDecl *&Specialization,
5910 sema::TemplateDeductionInfo &Info,
5911 bool InOverloadResolution = false);
5913 /// \brief Substitute Replacement for \p auto in \p TypeWithAuto
5914 QualType SubstAutoType(QualType TypeWithAuto, QualType Replacement);
5915 /// \brief Substitute Replacement for auto in TypeWithAuto
5916 TypeSourceInfo* SubstAutoTypeSourceInfo(TypeSourceInfo *TypeWithAuto,
5917 QualType Replacement);
5919 /// \brief Result type of DeduceAutoType.
5920 enum DeduceAutoResult {
5923 DAR_FailedAlreadyDiagnosed
5926 DeduceAutoResult DeduceAutoType(TypeSourceInfo *AutoType, Expr *&Initializer,
5928 DeduceAutoResult DeduceAutoType(TypeLoc AutoTypeLoc, Expr *&Initializer,
5930 void DiagnoseAutoDeductionFailure(VarDecl *VDecl, Expr *Init);
5931 bool DeduceReturnType(FunctionDecl *FD, SourceLocation Loc,
5932 bool Diagnose = true);
5934 bool DeduceFunctionTypeFromReturnExpr(FunctionDecl *FD,
5935 SourceLocation ReturnLoc,
5936 Expr *&RetExpr, AutoType *AT);
5938 FunctionTemplateDecl *getMoreSpecializedTemplate(FunctionTemplateDecl *FT1,
5939 FunctionTemplateDecl *FT2,
5941 TemplatePartialOrderingContext TPOC,
5942 unsigned NumCallArguments1,
5943 unsigned NumCallArguments2);
5944 UnresolvedSetIterator
5945 getMostSpecialized(UnresolvedSetIterator SBegin, UnresolvedSetIterator SEnd,
5946 TemplateSpecCandidateSet &FailedCandidates,
5948 const PartialDiagnostic &NoneDiag,
5949 const PartialDiagnostic &AmbigDiag,
5950 const PartialDiagnostic &CandidateDiag,
5951 bool Complain = true, QualType TargetType = QualType());
5953 ClassTemplatePartialSpecializationDecl *
5954 getMoreSpecializedPartialSpecialization(
5955 ClassTemplatePartialSpecializationDecl *PS1,
5956 ClassTemplatePartialSpecializationDecl *PS2,
5957 SourceLocation Loc);
5959 VarTemplatePartialSpecializationDecl *getMoreSpecializedPartialSpecialization(
5960 VarTemplatePartialSpecializationDecl *PS1,
5961 VarTemplatePartialSpecializationDecl *PS2, SourceLocation Loc);
5963 void MarkUsedTemplateParameters(const TemplateArgumentList &TemplateArgs,
5966 llvm::SmallBitVector &Used);
5967 void MarkDeducedTemplateParameters(
5968 const FunctionTemplateDecl *FunctionTemplate,
5969 llvm::SmallBitVector &Deduced) {
5970 return MarkDeducedTemplateParameters(Context, FunctionTemplate, Deduced);
5972 static void MarkDeducedTemplateParameters(ASTContext &Ctx,
5973 const FunctionTemplateDecl *FunctionTemplate,
5974 llvm::SmallBitVector &Deduced);
5976 //===--------------------------------------------------------------------===//
5977 // C++ Template Instantiation
5980 MultiLevelTemplateArgumentList getTemplateInstantiationArgs(NamedDecl *D,
5981 const TemplateArgumentList *Innermost = 0,
5982 bool RelativeToPrimary = false,
5983 const FunctionDecl *Pattern = 0);
5985 /// \brief A template instantiation that is currently in progress.
5986 struct ActiveTemplateInstantiation {
5987 /// \brief The kind of template instantiation we are performing
5988 enum InstantiationKind {
5989 /// We are instantiating a template declaration. The entity is
5990 /// the declaration we're instantiating (e.g., a CXXRecordDecl).
5991 TemplateInstantiation,
5993 /// We are instantiating a default argument for a template
5994 /// parameter. The Entity is the template, and
5995 /// TemplateArgs/NumTemplateArguments provides the template
5996 /// arguments as specified.
5997 /// FIXME: Use a TemplateArgumentList
5998 DefaultTemplateArgumentInstantiation,
6000 /// We are instantiating a default argument for a function.
6001 /// The Entity is the ParmVarDecl, and TemplateArgs/NumTemplateArgs
6002 /// provides the template arguments as specified.
6003 DefaultFunctionArgumentInstantiation,
6005 /// We are substituting explicit template arguments provided for
6006 /// a function template. The entity is a FunctionTemplateDecl.
6007 ExplicitTemplateArgumentSubstitution,
6009 /// We are substituting template argument determined as part of
6010 /// template argument deduction for either a class template
6011 /// partial specialization or a function template. The
6012 /// Entity is either a ClassTemplatePartialSpecializationDecl or
6013 /// a FunctionTemplateDecl.
6014 DeducedTemplateArgumentSubstitution,
6016 /// We are substituting prior template arguments into a new
6017 /// template parameter. The template parameter itself is either a
6018 /// NonTypeTemplateParmDecl or a TemplateTemplateParmDecl.
6019 PriorTemplateArgumentSubstitution,
6021 /// We are checking the validity of a default template argument that
6022 /// has been used when naming a template-id.
6023 DefaultTemplateArgumentChecking,
6025 /// We are instantiating the exception specification for a function
6026 /// template which was deferred until it was needed.
6027 ExceptionSpecInstantiation
6030 /// \brief The point of instantiation within the source code.
6031 SourceLocation PointOfInstantiation;
6033 /// \brief The template (or partial specialization) in which we are
6034 /// performing the instantiation, for substitutions of prior template
6036 NamedDecl *Template;
6038 /// \brief The entity that is being instantiated.
6041 /// \brief The list of template arguments we are substituting, if they
6042 /// are not part of the entity.
6043 const TemplateArgument *TemplateArgs;
6045 /// \brief The number of template arguments in TemplateArgs.
6046 unsigned NumTemplateArgs;
6048 /// \brief The template deduction info object associated with the
6049 /// substitution or checking of explicit or deduced template arguments.
6050 sema::TemplateDeductionInfo *DeductionInfo;
6052 /// \brief The source range that covers the construct that cause
6053 /// the instantiation, e.g., the template-id that causes a class
6054 /// template instantiation.
6055 SourceRange InstantiationRange;
6057 ActiveTemplateInstantiation()
6058 : Kind(TemplateInstantiation), Template(0), Entity(0), TemplateArgs(0),
6059 NumTemplateArgs(0), DeductionInfo(0) {}
6061 /// \brief Determines whether this template is an actual instantiation
6062 /// that should be counted toward the maximum instantiation depth.
6063 bool isInstantiationRecord() const;
6065 friend bool operator==(const ActiveTemplateInstantiation &X,
6066 const ActiveTemplateInstantiation &Y) {
6067 if (X.Kind != Y.Kind)
6070 if (X.Entity != Y.Entity)
6074 case TemplateInstantiation:
6075 case ExceptionSpecInstantiation:
6078 case PriorTemplateArgumentSubstitution:
6079 case DefaultTemplateArgumentChecking:
6080 return X.Template == Y.Template && X.TemplateArgs == Y.TemplateArgs;
6082 case DefaultTemplateArgumentInstantiation:
6083 case ExplicitTemplateArgumentSubstitution:
6084 case DeducedTemplateArgumentSubstitution:
6085 case DefaultFunctionArgumentInstantiation:
6086 return X.TemplateArgs == Y.TemplateArgs;
6090 llvm_unreachable("Invalid InstantiationKind!");
6093 friend bool operator!=(const ActiveTemplateInstantiation &X,
6094 const ActiveTemplateInstantiation &Y) {
6099 /// \brief List of active template instantiations.
6101 /// This vector is treated as a stack. As one template instantiation
6102 /// requires another template instantiation, additional
6103 /// instantiations are pushed onto the stack up to a
6104 /// user-configurable limit LangOptions::InstantiationDepth.
6105 SmallVector<ActiveTemplateInstantiation, 16>
6106 ActiveTemplateInstantiations;
6108 /// \brief Extra modules inspected when performing a lookup during a template
6109 /// instantiation. Computed lazily.
6110 SmallVector<Module*, 16> ActiveTemplateInstantiationLookupModules;
6112 /// \brief Cache of additional modules that should be used for name lookup
6113 /// within the current template instantiation. Computed lazily; use
6114 /// getLookupModules() to get a complete set.
6115 llvm::DenseSet<Module*> LookupModulesCache;
6117 /// \brief Get the set of additional modules that should be checked during
6118 /// name lookup. A module and its imports become visible when instanting a
6119 /// template defined within it.
6120 llvm::DenseSet<Module*> &getLookupModules();
6122 /// \brief Whether we are in a SFINAE context that is not associated with
6123 /// template instantiation.
6125 /// This is used when setting up a SFINAE trap (\c see SFINAETrap) outside
6126 /// of a template instantiation or template argument deduction.
6127 bool InNonInstantiationSFINAEContext;
6129 /// \brief The number of ActiveTemplateInstantiation entries in
6130 /// \c ActiveTemplateInstantiations that are not actual instantiations and,
6131 /// therefore, should not be counted as part of the instantiation depth.
6132 unsigned NonInstantiationEntries;
6134 /// \brief The last template from which a template instantiation
6135 /// error or warning was produced.
6137 /// This value is used to suppress printing of redundant template
6138 /// instantiation backtraces when there are multiple errors in the
6139 /// same instantiation. FIXME: Does this belong in Sema? It's tough
6140 /// to implement it anywhere else.
6141 ActiveTemplateInstantiation LastTemplateInstantiationErrorContext;
6143 /// \brief The current index into pack expansion arguments that will be
6144 /// used for substitution of parameter packs.
6146 /// The pack expansion index will be -1 to indicate that parameter packs
6147 /// should be instantiated as themselves. Otherwise, the index specifies
6148 /// which argument within the parameter pack will be used for substitution.
6149 int ArgumentPackSubstitutionIndex;
6151 /// \brief RAII object used to change the argument pack substitution index
6152 /// within a \c Sema object.
6154 /// See \c ArgumentPackSubstitutionIndex for more information.
6155 class ArgumentPackSubstitutionIndexRAII {
6157 int OldSubstitutionIndex;
6160 ArgumentPackSubstitutionIndexRAII(Sema &Self, int NewSubstitutionIndex)
6161 : Self(Self), OldSubstitutionIndex(Self.ArgumentPackSubstitutionIndex) {
6162 Self.ArgumentPackSubstitutionIndex = NewSubstitutionIndex;
6165 ~ArgumentPackSubstitutionIndexRAII() {
6166 Self.ArgumentPackSubstitutionIndex = OldSubstitutionIndex;
6170 friend class ArgumentPackSubstitutionRAII;
6172 /// \brief The stack of calls expression undergoing template instantiation.
6174 /// The top of this stack is used by a fixit instantiating unresolved
6175 /// function calls to fix the AST to match the textual change it prints.
6176 SmallVector<CallExpr *, 8> CallsUndergoingInstantiation;
6178 /// \brief For each declaration that involved template argument deduction, the
6179 /// set of diagnostics that were suppressed during that template argument
6182 /// FIXME: Serialize this structure to the AST file.
6183 typedef llvm::DenseMap<Decl *, SmallVector<PartialDiagnosticAt, 1> >
6184 SuppressedDiagnosticsMap;
6185 SuppressedDiagnosticsMap SuppressedDiagnostics;
6187 /// \brief A stack object to be created when performing template
6190 /// Construction of an object of type \c InstantiatingTemplate
6191 /// pushes the current instantiation onto the stack of active
6192 /// instantiations. If the size of this stack exceeds the maximum
6193 /// number of recursive template instantiations, construction
6194 /// produces an error and evaluates true.
6196 /// Destruction of this object will pop the named instantiation off
6198 struct InstantiatingTemplate {
6199 /// \brief Note that we are instantiating a class template,
6200 /// function template, or a member thereof.
6201 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
6203 SourceRange InstantiationRange = SourceRange());
6205 struct ExceptionSpecification {};
6206 /// \brief Note that we are instantiating an exception specification
6207 /// of a function template.
6208 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
6209 FunctionDecl *Entity, ExceptionSpecification,
6210 SourceRange InstantiationRange = SourceRange());
6212 /// \brief Note that we are instantiating a default argument in a
6214 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
6215 TemplateDecl *Template,
6216 ArrayRef<TemplateArgument> TemplateArgs,
6217 SourceRange InstantiationRange = SourceRange());
6219 /// \brief Note that we are instantiating a default argument in a
6221 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
6222 FunctionTemplateDecl *FunctionTemplate,
6223 ArrayRef<TemplateArgument> TemplateArgs,
6224 ActiveTemplateInstantiation::InstantiationKind Kind,
6225 sema::TemplateDeductionInfo &DeductionInfo,
6226 SourceRange InstantiationRange = SourceRange());
6228 /// \brief Note that we are instantiating as part of template
6229 /// argument deduction for a class template partial
6231 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
6232 ClassTemplatePartialSpecializationDecl *PartialSpec,
6233 ArrayRef<TemplateArgument> TemplateArgs,
6234 sema::TemplateDeductionInfo &DeductionInfo,
6235 SourceRange InstantiationRange = SourceRange());
6237 /// \brief Note that we are instantiating as part of template
6238 /// argument deduction for a variable template partial
6240 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
6241 VarTemplatePartialSpecializationDecl *PartialSpec,
6242 ArrayRef<TemplateArgument> TemplateArgs,
6243 sema::TemplateDeductionInfo &DeductionInfo,
6244 SourceRange InstantiationRange = SourceRange());
6246 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
6248 ArrayRef<TemplateArgument> TemplateArgs,
6249 SourceRange InstantiationRange = SourceRange());
6251 /// \brief Note that we are substituting prior template arguments into a
6252 /// non-type or template template parameter.
6253 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
6254 NamedDecl *Template,
6255 NonTypeTemplateParmDecl *Param,
6256 ArrayRef<TemplateArgument> TemplateArgs,
6257 SourceRange InstantiationRange);
6259 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
6260 NamedDecl *Template,
6261 TemplateTemplateParmDecl *Param,
6262 ArrayRef<TemplateArgument> TemplateArgs,
6263 SourceRange InstantiationRange);
6265 /// \brief Note that we are checking the default template argument
6266 /// against the template parameter for a given template-id.
6267 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
6268 TemplateDecl *Template,
6270 ArrayRef<TemplateArgument> TemplateArgs,
6271 SourceRange InstantiationRange);
6274 /// \brief Note that we have finished instantiating this template.
6277 ~InstantiatingTemplate() { Clear(); }
6279 /// \brief Determines whether we have exceeded the maximum
6280 /// recursive template instantiations.
6281 bool isInvalid() const { return Invalid; }
6286 bool SavedInNonInstantiationSFINAEContext;
6287 bool CheckInstantiationDepth(SourceLocation PointOfInstantiation,
6288 SourceRange InstantiationRange);
6290 InstantiatingTemplate(const InstantiatingTemplate&) LLVM_DELETED_FUNCTION;
6292 InstantiatingTemplate&
6293 operator=(const InstantiatingTemplate&) LLVM_DELETED_FUNCTION;
6296 void PrintInstantiationStack();
6298 /// \brief Determines whether we are currently in a context where
6299 /// template argument substitution failures are not considered
6302 /// \returns An empty \c Optional if we're not in a SFINAE context.
6303 /// Otherwise, contains a pointer that, if non-NULL, contains the nearest
6304 /// template-deduction context object, which can be used to capture
6305 /// diagnostics that will be suppressed.
6306 Optional<sema::TemplateDeductionInfo *> isSFINAEContext() const;
6308 /// \brief Determines whether we are currently in a context that
6309 /// is not evaluated as per C++ [expr] p5.
6310 bool isUnevaluatedContext() const {
6311 assert(!ExprEvalContexts.empty() &&
6312 "Must be in an expression evaluation context");
6313 return ExprEvalContexts.back().isUnevaluated();
6316 /// \brief RAII class used to determine whether SFINAE has
6317 /// trapped any errors that occur during template argument
6321 unsigned PrevSFINAEErrors;
6322 bool PrevInNonInstantiationSFINAEContext;
6323 bool PrevAccessCheckingSFINAE;
6326 explicit SFINAETrap(Sema &SemaRef, bool AccessCheckingSFINAE = false)
6327 : SemaRef(SemaRef), PrevSFINAEErrors(SemaRef.NumSFINAEErrors),
6328 PrevInNonInstantiationSFINAEContext(
6329 SemaRef.InNonInstantiationSFINAEContext),
6330 PrevAccessCheckingSFINAE(SemaRef.AccessCheckingSFINAE)
6332 if (!SemaRef.isSFINAEContext())
6333 SemaRef.InNonInstantiationSFINAEContext = true;
6334 SemaRef.AccessCheckingSFINAE = AccessCheckingSFINAE;
6338 SemaRef.NumSFINAEErrors = PrevSFINAEErrors;
6339 SemaRef.InNonInstantiationSFINAEContext
6340 = PrevInNonInstantiationSFINAEContext;
6341 SemaRef.AccessCheckingSFINAE = PrevAccessCheckingSFINAE;
6344 /// \brief Determine whether any SFINAE errors have been trapped.
6345 bool hasErrorOccurred() const {
6346 return SemaRef.NumSFINAEErrors > PrevSFINAEErrors;
6350 /// \brief RAII class used to indicate that we are performing provisional
6351 /// semantic analysis to determine the validity of a construct, so
6352 /// typo-correction and diagnostics in the immediate context (not within
6353 /// implicitly-instantiated templates) should be suppressed.
6354 class TentativeAnalysisScope {
6356 // FIXME: Using a SFINAETrap for this is a hack.
6358 bool PrevDisableTypoCorrection;
6360 explicit TentativeAnalysisScope(Sema &SemaRef)
6361 : SemaRef(SemaRef), Trap(SemaRef, true),
6362 PrevDisableTypoCorrection(SemaRef.DisableTypoCorrection) {
6363 SemaRef.DisableTypoCorrection = true;
6365 ~TentativeAnalysisScope() {
6366 SemaRef.DisableTypoCorrection = PrevDisableTypoCorrection;
6370 /// \brief The current instantiation scope used to store local
6372 LocalInstantiationScope *CurrentInstantiationScope;
6374 /// \brief Tracks whether we are in a context where typo correction is
6376 bool DisableTypoCorrection;
6378 /// \brief The number of typos corrected by CorrectTypo.
6379 unsigned TyposCorrected;
6381 typedef llvm::DenseMap<IdentifierInfo *, TypoCorrection>
6382 UnqualifiedTyposCorrectedMap;
6384 /// \brief A cache containing the results of typo correction for unqualified
6387 /// The string is the string that we corrected to (which may be empty, if
6388 /// there was no correction), while the boolean will be true when the
6389 /// string represents a keyword.
6390 UnqualifiedTyposCorrectedMap UnqualifiedTyposCorrected;
6392 typedef llvm::SmallSet<SourceLocation, 2> SrcLocSet;
6393 typedef llvm::DenseMap<IdentifierInfo *, SrcLocSet> IdentifierSourceLocations;
6395 /// \brief A cache containing identifiers for which typo correction failed and
6396 /// their locations, so that repeated attempts to correct an identifier in a
6397 /// given location are ignored if typo correction already failed for it.
6398 IdentifierSourceLocations TypoCorrectionFailures;
6400 /// \brief Worker object for performing CFG-based warnings.
6401 sema::AnalysisBasedWarnings AnalysisWarnings;
6403 /// \brief An entity for which implicit template instantiation is required.
6405 /// The source location associated with the declaration is the first place in
6406 /// the source code where the declaration was "used". It is not necessarily
6407 /// the point of instantiation (which will be either before or after the
6408 /// namespace-scope declaration that triggered this implicit instantiation),
6409 /// However, it is the location that diagnostics should generally refer to,
6410 /// because users will need to know what code triggered the instantiation.
6411 typedef std::pair<ValueDecl *, SourceLocation> PendingImplicitInstantiation;
6413 /// \brief The queue of implicit template instantiations that are required
6414 /// but have not yet been performed.
6415 std::deque<PendingImplicitInstantiation> PendingInstantiations;
6417 /// \brief The queue of implicit template instantiations that are required
6418 /// and must be performed within the current local scope.
6420 /// This queue is only used for member functions of local classes in
6421 /// templates, which must be instantiated in the same scope as their
6422 /// enclosing function, so that they can reference function-local
6423 /// types, static variables, enumerators, etc.
6424 std::deque<PendingImplicitInstantiation> PendingLocalImplicitInstantiations;
6426 class SavePendingLocalImplicitInstantiationsRAII {
6428 SavePendingLocalImplicitInstantiationsRAII(Sema &S): S(S) {
6429 SavedPendingLocalImplicitInstantiations.swap(
6430 S.PendingLocalImplicitInstantiations);
6433 ~SavePendingLocalImplicitInstantiationsRAII() {
6434 assert(S.PendingLocalImplicitInstantiations.empty() &&
6435 "there shouldn't be any pending local implicit instantiations");
6436 SavedPendingLocalImplicitInstantiations.swap(
6437 S.PendingLocalImplicitInstantiations);
6442 std::deque<PendingImplicitInstantiation>
6443 SavedPendingLocalImplicitInstantiations;
6446 void PerformPendingInstantiations(bool LocalOnly = false);
6448 TypeSourceInfo *SubstType(TypeSourceInfo *T,
6449 const MultiLevelTemplateArgumentList &TemplateArgs,
6450 SourceLocation Loc, DeclarationName Entity);
6452 QualType SubstType(QualType T,
6453 const MultiLevelTemplateArgumentList &TemplateArgs,
6454 SourceLocation Loc, DeclarationName Entity);
6456 TypeSourceInfo *SubstType(TypeLoc TL,
6457 const MultiLevelTemplateArgumentList &TemplateArgs,
6458 SourceLocation Loc, DeclarationName Entity);
6460 TypeSourceInfo *SubstFunctionDeclType(TypeSourceInfo *T,
6461 const MultiLevelTemplateArgumentList &TemplateArgs,
6463 DeclarationName Entity,
6464 CXXRecordDecl *ThisContext,
6465 unsigned ThisTypeQuals);
6466 ParmVarDecl *SubstParmVarDecl(ParmVarDecl *D,
6467 const MultiLevelTemplateArgumentList &TemplateArgs,
6468 int indexAdjustment,
6469 Optional<unsigned> NumExpansions,
6470 bool ExpectParameterPack);
6471 bool SubstParmTypes(SourceLocation Loc,
6472 ParmVarDecl **Params, unsigned NumParams,
6473 const MultiLevelTemplateArgumentList &TemplateArgs,
6474 SmallVectorImpl<QualType> &ParamTypes,
6475 SmallVectorImpl<ParmVarDecl *> *OutParams = 0);
6476 ExprResult SubstExpr(Expr *E,
6477 const MultiLevelTemplateArgumentList &TemplateArgs);
6479 /// \brief Substitute the given template arguments into a list of
6480 /// expressions, expanding pack expansions if required.
6482 /// \param Exprs The list of expressions to substitute into.
6484 /// \param NumExprs The number of expressions in \p Exprs.
6486 /// \param IsCall Whether this is some form of call, in which case
6487 /// default arguments will be dropped.
6489 /// \param TemplateArgs The set of template arguments to substitute.
6491 /// \param Outputs Will receive all of the substituted arguments.
6493 /// \returns true if an error occurred, false otherwise.
6494 bool SubstExprs(Expr **Exprs, unsigned NumExprs, bool IsCall,
6495 const MultiLevelTemplateArgumentList &TemplateArgs,
6496 SmallVectorImpl<Expr *> &Outputs);
6498 StmtResult SubstStmt(Stmt *S,
6499 const MultiLevelTemplateArgumentList &TemplateArgs);
6501 Decl *SubstDecl(Decl *D, DeclContext *Owner,
6502 const MultiLevelTemplateArgumentList &TemplateArgs);
6504 ExprResult SubstInitializer(Expr *E,
6505 const MultiLevelTemplateArgumentList &TemplateArgs,
6506 bool CXXDirectInit);
6509 SubstBaseSpecifiers(CXXRecordDecl *Instantiation,
6510 CXXRecordDecl *Pattern,
6511 const MultiLevelTemplateArgumentList &TemplateArgs);
6514 InstantiateClass(SourceLocation PointOfInstantiation,
6515 CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern,
6516 const MultiLevelTemplateArgumentList &TemplateArgs,
6517 TemplateSpecializationKind TSK,
6518 bool Complain = true);
6520 bool InstantiateEnum(SourceLocation PointOfInstantiation,
6521 EnumDecl *Instantiation, EnumDecl *Pattern,
6522 const MultiLevelTemplateArgumentList &TemplateArgs,
6523 TemplateSpecializationKind TSK);
6525 struct LateInstantiatedAttribute {
6526 const Attr *TmplAttr;
6527 LocalInstantiationScope *Scope;
6530 LateInstantiatedAttribute(const Attr *A, LocalInstantiationScope *S,
6532 : TmplAttr(A), Scope(S), NewDecl(D)
6535 typedef SmallVector<LateInstantiatedAttribute, 16> LateInstantiatedAttrVec;
6537 void InstantiateAttrs(const MultiLevelTemplateArgumentList &TemplateArgs,
6538 const Decl *Pattern, Decl *Inst,
6539 LateInstantiatedAttrVec *LateAttrs = 0,
6540 LocalInstantiationScope *OuterMostScope = 0);
6543 InstantiateClassTemplateSpecialization(SourceLocation PointOfInstantiation,
6544 ClassTemplateSpecializationDecl *ClassTemplateSpec,
6545 TemplateSpecializationKind TSK,
6546 bool Complain = true);
6548 void InstantiateClassMembers(SourceLocation PointOfInstantiation,
6549 CXXRecordDecl *Instantiation,
6550 const MultiLevelTemplateArgumentList &TemplateArgs,
6551 TemplateSpecializationKind TSK);
6553 void InstantiateClassTemplateSpecializationMembers(
6554 SourceLocation PointOfInstantiation,
6555 ClassTemplateSpecializationDecl *ClassTemplateSpec,
6556 TemplateSpecializationKind TSK);
6558 NestedNameSpecifierLoc
6559 SubstNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS,
6560 const MultiLevelTemplateArgumentList &TemplateArgs);
6563 SubstDeclarationNameInfo(const DeclarationNameInfo &NameInfo,
6564 const MultiLevelTemplateArgumentList &TemplateArgs);
6566 SubstTemplateName(NestedNameSpecifierLoc QualifierLoc, TemplateName Name,
6568 const MultiLevelTemplateArgumentList &TemplateArgs);
6569 bool Subst(const TemplateArgumentLoc *Args, unsigned NumArgs,
6570 TemplateArgumentListInfo &Result,
6571 const MultiLevelTemplateArgumentList &TemplateArgs);
6573 void InstantiateExceptionSpec(SourceLocation PointOfInstantiation,
6574 FunctionDecl *Function);
6575 void InstantiateFunctionDefinition(SourceLocation PointOfInstantiation,
6576 FunctionDecl *Function,
6577 bool Recursive = false,
6578 bool DefinitionRequired = false);
6579 VarTemplateSpecializationDecl *BuildVarTemplateInstantiation(
6580 VarTemplateDecl *VarTemplate, VarDecl *FromVar,
6581 const TemplateArgumentList &TemplateArgList,
6582 const TemplateArgumentListInfo &TemplateArgsInfo,
6583 SmallVectorImpl<TemplateArgument> &Converted,
6584 SourceLocation PointOfInstantiation, void *InsertPos,
6585 LateInstantiatedAttrVec *LateAttrs = 0,
6586 LocalInstantiationScope *StartingScope = 0);
6587 VarTemplateSpecializationDecl *CompleteVarTemplateSpecializationDecl(
6588 VarTemplateSpecializationDecl *VarSpec, VarDecl *PatternDecl,
6589 const MultiLevelTemplateArgumentList &TemplateArgs);
6591 BuildVariableInstantiation(VarDecl *NewVar, VarDecl *OldVar,
6592 const MultiLevelTemplateArgumentList &TemplateArgs,
6593 LateInstantiatedAttrVec *LateAttrs,
6595 LocalInstantiationScope *StartingScope,
6596 bool InstantiatingVarTemplate = false);
6597 void InstantiateVariableInitializer(
6598 VarDecl *Var, VarDecl *OldVar,
6599 const MultiLevelTemplateArgumentList &TemplateArgs);
6600 void InstantiateVariableDefinition(SourceLocation PointOfInstantiation,
6601 VarDecl *Var, bool Recursive = false,
6602 bool DefinitionRequired = false);
6603 void InstantiateStaticDataMemberDefinition(
6604 SourceLocation PointOfInstantiation,
6606 bool Recursive = false,
6607 bool DefinitionRequired = false);
6609 void InstantiateMemInitializers(CXXConstructorDecl *New,
6610 const CXXConstructorDecl *Tmpl,
6611 const MultiLevelTemplateArgumentList &TemplateArgs);
6613 NamedDecl *FindInstantiatedDecl(SourceLocation Loc, NamedDecl *D,
6614 const MultiLevelTemplateArgumentList &TemplateArgs);
6615 DeclContext *FindInstantiatedContext(SourceLocation Loc, DeclContext *DC,
6616 const MultiLevelTemplateArgumentList &TemplateArgs);
6618 // Objective-C declarations.
6619 enum ObjCContainerKind {
6626 OCK_CategoryImplementation
6628 ObjCContainerKind getObjCContainerKind() const;
6630 Decl *ActOnStartClassInterface(SourceLocation AtInterfaceLoc,
6631 IdentifierInfo *ClassName,
6632 SourceLocation ClassLoc,
6633 IdentifierInfo *SuperName,
6634 SourceLocation SuperLoc,
6635 Decl * const *ProtoRefs,
6636 unsigned NumProtoRefs,
6637 const SourceLocation *ProtoLocs,
6638 SourceLocation EndProtoLoc,
6639 AttributeList *AttrList);
6641 void ActOnTypedefedProtocols(SmallVectorImpl<Decl *> &ProtocolRefs,
6642 IdentifierInfo *SuperName,
6643 SourceLocation SuperLoc);
6645 Decl *ActOnCompatibilityAlias(
6646 SourceLocation AtCompatibilityAliasLoc,
6647 IdentifierInfo *AliasName, SourceLocation AliasLocation,
6648 IdentifierInfo *ClassName, SourceLocation ClassLocation);
6650 bool CheckForwardProtocolDeclarationForCircularDependency(
6651 IdentifierInfo *PName,
6652 SourceLocation &PLoc, SourceLocation PrevLoc,
6653 const ObjCList<ObjCProtocolDecl> &PList);
6655 Decl *ActOnStartProtocolInterface(
6656 SourceLocation AtProtoInterfaceLoc,
6657 IdentifierInfo *ProtocolName, SourceLocation ProtocolLoc,
6658 Decl * const *ProtoRefNames, unsigned NumProtoRefs,
6659 const SourceLocation *ProtoLocs,
6660 SourceLocation EndProtoLoc,
6661 AttributeList *AttrList);
6663 Decl *ActOnStartCategoryInterface(SourceLocation AtInterfaceLoc,
6664 IdentifierInfo *ClassName,
6665 SourceLocation ClassLoc,
6666 IdentifierInfo *CategoryName,
6667 SourceLocation CategoryLoc,
6668 Decl * const *ProtoRefs,
6669 unsigned NumProtoRefs,
6670 const SourceLocation *ProtoLocs,
6671 SourceLocation EndProtoLoc);
6673 Decl *ActOnStartClassImplementation(
6674 SourceLocation AtClassImplLoc,
6675 IdentifierInfo *ClassName, SourceLocation ClassLoc,
6676 IdentifierInfo *SuperClassname,
6677 SourceLocation SuperClassLoc);
6679 Decl *ActOnStartCategoryImplementation(SourceLocation AtCatImplLoc,
6680 IdentifierInfo *ClassName,
6681 SourceLocation ClassLoc,
6682 IdentifierInfo *CatName,
6683 SourceLocation CatLoc);
6685 DeclGroupPtrTy ActOnFinishObjCImplementation(Decl *ObjCImpDecl,
6686 ArrayRef<Decl *> Decls);
6688 DeclGroupPtrTy ActOnForwardClassDeclaration(SourceLocation Loc,
6689 IdentifierInfo **IdentList,
6690 SourceLocation *IdentLocs,
6693 DeclGroupPtrTy ActOnForwardProtocolDeclaration(SourceLocation AtProtoclLoc,
6694 const IdentifierLocPair *IdentList,
6696 AttributeList *attrList);
6698 void FindProtocolDeclaration(bool WarnOnDeclarations,
6699 const IdentifierLocPair *ProtocolId,
6700 unsigned NumProtocols,
6701 SmallVectorImpl<Decl *> &Protocols);
6703 /// Ensure attributes are consistent with type.
6704 /// \param [in, out] Attributes The attributes to check; they will
6705 /// be modified to be consistent with \p PropertyTy.
6706 void CheckObjCPropertyAttributes(Decl *PropertyPtrTy,
6708 unsigned &Attributes,
6709 bool propertyInPrimaryClass);
6711 /// Process the specified property declaration and create decls for the
6712 /// setters and getters as needed.
6713 /// \param property The property declaration being processed
6714 /// \param CD The semantic container for the property
6715 /// \param redeclaredProperty Declaration for property if redeclared
6716 /// in class extension.
6717 /// \param lexicalDC Container for redeclaredProperty.
6718 void ProcessPropertyDecl(ObjCPropertyDecl *property,
6719 ObjCContainerDecl *CD,
6720 ObjCPropertyDecl *redeclaredProperty = 0,
6721 ObjCContainerDecl *lexicalDC = 0);
6724 void DiagnosePropertyMismatch(ObjCPropertyDecl *Property,
6725 ObjCPropertyDecl *SuperProperty,
6726 const IdentifierInfo *Name,
6727 bool OverridingProtocolProperty);
6729 void DiagnoseClassExtensionDupMethods(ObjCCategoryDecl *CAT,
6730 ObjCInterfaceDecl *ID);
6732 Decl *ActOnAtEnd(Scope *S, SourceRange AtEnd,
6733 ArrayRef<Decl *> allMethods = None,
6734 ArrayRef<DeclGroupPtrTy> allTUVars = None);
6736 Decl *ActOnProperty(Scope *S, SourceLocation AtLoc,
6737 SourceLocation LParenLoc,
6738 FieldDeclarator &FD, ObjCDeclSpec &ODS,
6739 Selector GetterSel, Selector SetterSel,
6740 bool *OverridingProperty,
6741 tok::ObjCKeywordKind MethodImplKind,
6742 DeclContext *lexicalDC = 0);
6744 Decl *ActOnPropertyImplDecl(Scope *S,
6745 SourceLocation AtLoc,
6746 SourceLocation PropertyLoc,
6748 IdentifierInfo *PropertyId,
6749 IdentifierInfo *PropertyIvar,
6750 SourceLocation PropertyIvarLoc);
6752 enum ObjCSpecialMethodKind {
6758 OSMK_NonRetainingInit
6761 struct ObjCArgInfo {
6762 IdentifierInfo *Name;
6763 SourceLocation NameLoc;
6764 // The Type is null if no type was specified, and the DeclSpec is invalid
6767 ObjCDeclSpec DeclSpec;
6769 /// ArgAttrs - Attribute list for this argument.
6770 AttributeList *ArgAttrs;
6773 Decl *ActOnMethodDeclaration(
6775 SourceLocation BeginLoc, // location of the + or -.
6776 SourceLocation EndLoc, // location of the ; or {.
6777 tok::TokenKind MethodType,
6778 ObjCDeclSpec &ReturnQT, ParsedType ReturnType,
6779 ArrayRef<SourceLocation> SelectorLocs, Selector Sel,
6780 // optional arguments. The number of types/arguments is obtained
6781 // from the Sel.getNumArgs().
6782 ObjCArgInfo *ArgInfo,
6783 DeclaratorChunk::ParamInfo *CParamInfo, unsigned CNumArgs, // c-style args
6784 AttributeList *AttrList, tok::ObjCKeywordKind MethodImplKind,
6785 bool isVariadic, bool MethodDefinition);
6787 ObjCMethodDecl *LookupMethodInQualifiedType(Selector Sel,
6788 const ObjCObjectPointerType *OPT,
6790 ObjCMethodDecl *LookupMethodInObjectType(Selector Sel, QualType Ty,
6793 bool CheckARCMethodDecl(ObjCMethodDecl *method);
6794 bool inferObjCARCLifetime(ValueDecl *decl);
6797 HandleExprPropertyRefExpr(const ObjCObjectPointerType *OPT,
6799 SourceLocation OpLoc,
6800 DeclarationName MemberName,
6801 SourceLocation MemberLoc,
6802 SourceLocation SuperLoc, QualType SuperType,
6806 ActOnClassPropertyRefExpr(IdentifierInfo &receiverName,
6807 IdentifierInfo &propertyName,
6808 SourceLocation receiverNameLoc,
6809 SourceLocation propertyNameLoc);
6811 ObjCMethodDecl *tryCaptureObjCSelf(SourceLocation Loc);
6813 /// \brief Describes the kind of message expression indicated by a message
6814 /// send that starts with an identifier.
6815 enum ObjCMessageKind {
6816 /// \brief The message is sent to 'super'.
6818 /// \brief The message is an instance message.
6819 ObjCInstanceMessage,
6820 /// \brief The message is a class message, and the identifier is a type
6825 ObjCMessageKind getObjCMessageKind(Scope *S,
6826 IdentifierInfo *Name,
6827 SourceLocation NameLoc,
6829 bool HasTrailingDot,
6830 ParsedType &ReceiverType);
6832 ExprResult ActOnSuperMessage(Scope *S, SourceLocation SuperLoc,
6834 SourceLocation LBracLoc,
6835 ArrayRef<SourceLocation> SelectorLocs,
6836 SourceLocation RBracLoc,
6839 ExprResult BuildClassMessage(TypeSourceInfo *ReceiverTypeInfo,
6840 QualType ReceiverType,
6841 SourceLocation SuperLoc,
6843 ObjCMethodDecl *Method,
6844 SourceLocation LBracLoc,
6845 ArrayRef<SourceLocation> SelectorLocs,
6846 SourceLocation RBracLoc,
6848 bool isImplicit = false);
6850 ExprResult BuildClassMessageImplicit(QualType ReceiverType,
6851 bool isSuperReceiver,
6854 ObjCMethodDecl *Method,
6857 ExprResult ActOnClassMessage(Scope *S,
6858 ParsedType Receiver,
6860 SourceLocation LBracLoc,
6861 ArrayRef<SourceLocation> SelectorLocs,
6862 SourceLocation RBracLoc,
6865 ExprResult BuildInstanceMessage(Expr *Receiver,
6866 QualType ReceiverType,
6867 SourceLocation SuperLoc,
6869 ObjCMethodDecl *Method,
6870 SourceLocation LBracLoc,
6871 ArrayRef<SourceLocation> SelectorLocs,
6872 SourceLocation RBracLoc,
6874 bool isImplicit = false);
6876 ExprResult BuildInstanceMessageImplicit(Expr *Receiver,
6877 QualType ReceiverType,
6880 ObjCMethodDecl *Method,
6883 ExprResult ActOnInstanceMessage(Scope *S,
6886 SourceLocation LBracLoc,
6887 ArrayRef<SourceLocation> SelectorLocs,
6888 SourceLocation RBracLoc,
6891 ExprResult BuildObjCBridgedCast(SourceLocation LParenLoc,
6892 ObjCBridgeCastKind Kind,
6893 SourceLocation BridgeKeywordLoc,
6894 TypeSourceInfo *TSInfo,
6897 ExprResult ActOnObjCBridgedCast(Scope *S,
6898 SourceLocation LParenLoc,
6899 ObjCBridgeCastKind Kind,
6900 SourceLocation BridgeKeywordLoc,
6902 SourceLocation RParenLoc,
6905 bool checkInitMethod(ObjCMethodDecl *method, QualType receiverTypeIfCall);
6907 /// \brief Check whether the given new method is a valid override of the
6908 /// given overridden method, and set any properties that should be inherited.
6909 void CheckObjCMethodOverride(ObjCMethodDecl *NewMethod,
6910 const ObjCMethodDecl *Overridden);
6912 /// \brief Describes the compatibility of a result type with its method.
6913 enum ResultTypeCompatibilityKind {
6919 void CheckObjCMethodOverrides(ObjCMethodDecl *ObjCMethod,
6920 ObjCInterfaceDecl *CurrentClass,
6921 ResultTypeCompatibilityKind RTC);
6923 enum PragmaOptionsAlignKind {
6924 POAK_Native, // #pragma options align=native
6925 POAK_Natural, // #pragma options align=natural
6926 POAK_Packed, // #pragma options align=packed
6927 POAK_Power, // #pragma options align=power
6928 POAK_Mac68k, // #pragma options align=mac68k
6929 POAK_Reset // #pragma options align=reset
6932 /// ActOnPragmaOptionsAlign - Called on well formed \#pragma options align.
6933 void ActOnPragmaOptionsAlign(PragmaOptionsAlignKind Kind,
6934 SourceLocation PragmaLoc);
6936 enum PragmaPackKind {
6937 PPK_Default, // #pragma pack([n])
6938 PPK_Show, // #pragma pack(show), only supported by MSVC.
6939 PPK_Push, // #pragma pack(push, [identifier], [n])
6940 PPK_Pop // #pragma pack(pop, [identifier], [n])
6943 enum PragmaMSStructKind {
6944 PMSST_OFF, // #pragms ms_struct off
6945 PMSST_ON // #pragms ms_struct on
6948 enum PragmaMSCommentKind {
6950 PCK_Linker, // #pragma comment(linker, ...)
6951 PCK_Lib, // #pragma comment(lib, ...)
6952 PCK_Compiler, // #pragma comment(compiler, ...)
6953 PCK_ExeStr, // #pragma comment(exestr, ...)
6954 PCK_User // #pragma comment(user, ...)
6957 /// ActOnPragmaPack - Called on well formed \#pragma pack(...).
6958 void ActOnPragmaPack(PragmaPackKind Kind,
6959 IdentifierInfo *Name,
6961 SourceLocation PragmaLoc,
6962 SourceLocation LParenLoc,
6963 SourceLocation RParenLoc);
6965 /// ActOnPragmaMSStruct - Called on well formed \#pragma ms_struct [on|off].
6966 void ActOnPragmaMSStruct(PragmaMSStructKind Kind);
6968 /// ActOnPragmaMSComment - Called on well formed
6969 /// \#pragma comment(kind, "arg").
6970 void ActOnPragmaMSComment(PragmaMSCommentKind Kind, StringRef Arg);
6972 /// ActOnPragmaDetectMismatch - Call on well-formed \#pragma detect_mismatch
6973 void ActOnPragmaDetectMismatch(StringRef Name, StringRef Value);
6975 /// ActOnPragmaUnused - Called on well-formed '\#pragma unused'.
6976 void ActOnPragmaUnused(const Token &Identifier,
6978 SourceLocation PragmaLoc);
6980 /// ActOnPragmaVisibility - Called on well formed \#pragma GCC visibility... .
6981 void ActOnPragmaVisibility(const IdentifierInfo* VisType,
6982 SourceLocation PragmaLoc);
6984 NamedDecl *DeclClonePragmaWeak(NamedDecl *ND, IdentifierInfo *II,
6985 SourceLocation Loc);
6986 void DeclApplyPragmaWeak(Scope *S, NamedDecl *ND, WeakInfo &W);
6988 /// ActOnPragmaWeakID - Called on well formed \#pragma weak ident.
6989 void ActOnPragmaWeakID(IdentifierInfo* WeakName,
6990 SourceLocation PragmaLoc,
6991 SourceLocation WeakNameLoc);
6993 /// ActOnPragmaRedefineExtname - Called on well formed
6994 /// \#pragma redefine_extname oldname newname.
6995 void ActOnPragmaRedefineExtname(IdentifierInfo* WeakName,
6996 IdentifierInfo* AliasName,
6997 SourceLocation PragmaLoc,
6998 SourceLocation WeakNameLoc,
6999 SourceLocation AliasNameLoc);
7001 /// ActOnPragmaWeakAlias - Called on well formed \#pragma weak ident = ident.
7002 void ActOnPragmaWeakAlias(IdentifierInfo* WeakName,
7003 IdentifierInfo* AliasName,
7004 SourceLocation PragmaLoc,
7005 SourceLocation WeakNameLoc,
7006 SourceLocation AliasNameLoc);
7008 /// ActOnPragmaFPContract - Called on well formed
7009 /// \#pragma {STDC,OPENCL} FP_CONTRACT
7010 void ActOnPragmaFPContract(tok::OnOffSwitch OOS);
7012 /// AddAlignmentAttributesForRecord - Adds any needed alignment attributes to
7013 /// a the record decl, to handle '\#pragma pack' and '\#pragma options align'.
7014 void AddAlignmentAttributesForRecord(RecordDecl *RD);
7016 /// AddMsStructLayoutForRecord - Adds ms_struct layout attribute to record.
7017 void AddMsStructLayoutForRecord(RecordDecl *RD);
7019 /// FreePackedContext - Deallocate and null out PackContext.
7020 void FreePackedContext();
7022 /// PushNamespaceVisibilityAttr - Note that we've entered a
7023 /// namespace with a visibility attribute.
7024 void PushNamespaceVisibilityAttr(const VisibilityAttr *Attr,
7025 SourceLocation Loc);
7027 /// AddPushedVisibilityAttribute - If '\#pragma GCC visibility' was used,
7028 /// add an appropriate visibility attribute.
7029 void AddPushedVisibilityAttribute(Decl *RD);
7031 /// PopPragmaVisibility - Pop the top element of the visibility stack; used
7032 /// for '\#pragma GCC visibility' and visibility attributes on namespaces.
7033 void PopPragmaVisibility(bool IsNamespaceEnd, SourceLocation EndLoc);
7035 /// FreeVisContext - Deallocate and null out VisContext.
7036 void FreeVisContext();
7038 /// AddCFAuditedAttribute - Check whether we're currently within
7039 /// '\#pragma clang arc_cf_code_audited' and, if so, consider adding
7040 /// the appropriate attribute.
7041 void AddCFAuditedAttribute(Decl *D);
7043 /// AddAlignedAttr - Adds an aligned attribute to a particular declaration.
7044 void AddAlignedAttr(SourceRange AttrRange, Decl *D, Expr *E,
7045 unsigned SpellingListIndex, bool IsPackExpansion);
7046 void AddAlignedAttr(SourceRange AttrRange, Decl *D, TypeSourceInfo *T,
7047 unsigned SpellingListIndex, bool IsPackExpansion);
7049 // OpenMP directives and clauses.
7051 void *VarDataSharingAttributesStack;
7052 /// \brief Initialization of data-sharing attributes stack.
7053 void InitDataSharingAttributesStack();
7054 void DestroyDataSharingAttributesStack();
7056 /// \brief Called on start of new data sharing attribute block.
7057 void StartOpenMPDSABlock(OpenMPDirectiveKind K,
7058 const DeclarationNameInfo &DirName,
7060 /// \brief Called on end of data sharing attribute block.
7061 void EndOpenMPDSABlock(Stmt *CurDirective);
7063 // OpenMP directives and clauses.
7064 /// \brief Called on correct id-expression from the '#pragma omp
7066 ExprResult ActOnOpenMPIdExpression(Scope *CurScope,
7067 CXXScopeSpec &ScopeSpec,
7068 const DeclarationNameInfo &Id);
7069 /// \brief Called on well-formed '#pragma omp threadprivate'.
7070 DeclGroupPtrTy ActOnOpenMPThreadprivateDirective(
7072 ArrayRef<Expr *> VarList);
7073 // \brief Builds a new OpenMPThreadPrivateDecl and checks its correctness.
7074 OMPThreadPrivateDecl *CheckOMPThreadPrivateDecl(
7076 ArrayRef<Expr *> VarList);
7078 StmtResult ActOnOpenMPExecutableDirective(OpenMPDirectiveKind Kind,
7079 ArrayRef<OMPClause *> Clauses,
7081 SourceLocation StartLoc,
7082 SourceLocation EndLoc);
7083 /// \brief Called on well-formed '\#pragma omp parallel' after parsing
7084 /// of the associated statement.
7085 StmtResult ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses,
7087 SourceLocation StartLoc,
7088 SourceLocation EndLoc);
7090 OMPClause *ActOnOpenMPSimpleClause(OpenMPClauseKind Kind,
7092 SourceLocation ArgumentLoc,
7093 SourceLocation StartLoc,
7094 SourceLocation LParenLoc,
7095 SourceLocation EndLoc);
7096 /// \brief Called on well-formed 'default' clause.
7097 OMPClause *ActOnOpenMPDefaultClause(OpenMPDefaultClauseKind Kind,
7098 SourceLocation KindLoc,
7099 SourceLocation StartLoc,
7100 SourceLocation LParenLoc,
7101 SourceLocation EndLoc);
7103 OMPClause *ActOnOpenMPVarListClause(OpenMPClauseKind Kind,
7104 ArrayRef<Expr *> Vars,
7105 SourceLocation StartLoc,
7106 SourceLocation LParenLoc,
7107 SourceLocation EndLoc);
7108 /// \brief Called on well-formed 'private' clause.
7109 OMPClause *ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList,
7110 SourceLocation StartLoc,
7111 SourceLocation LParenLoc,
7112 SourceLocation EndLoc);
7113 /// \brief Called on well-formed 'firstprivate' clause.
7114 OMPClause *ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList,
7115 SourceLocation StartLoc,
7116 SourceLocation LParenLoc,
7117 SourceLocation EndLoc);
7118 /// \brief Called on well-formed 'shared' clause.
7119 OMPClause *ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList,
7120 SourceLocation StartLoc,
7121 SourceLocation LParenLoc,
7122 SourceLocation EndLoc);
7124 /// \brief The kind of conversion being performed.
7125 enum CheckedConversionKind {
7126 /// \brief An implicit conversion.
7127 CCK_ImplicitConversion,
7128 /// \brief A C-style cast.
7130 /// \brief A functional-style cast.
7132 /// \brief A cast other than a C-style cast.
7136 /// ImpCastExprToType - If Expr is not of type 'Type', insert an implicit
7137 /// cast. If there is already an implicit cast, merge into the existing one.
7138 /// If isLvalue, the result of the cast is an lvalue.
7139 ExprResult ImpCastExprToType(Expr *E, QualType Type, CastKind CK,
7140 ExprValueKind VK = VK_RValue,
7141 const CXXCastPath *BasePath = 0,
7142 CheckedConversionKind CCK
7143 = CCK_ImplicitConversion);
7145 /// ScalarTypeToBooleanCastKind - Returns the cast kind corresponding
7146 /// to the conversion from scalar type ScalarTy to the Boolean type.
7147 static CastKind ScalarTypeToBooleanCastKind(QualType ScalarTy);
7149 /// IgnoredValueConversions - Given that an expression's result is
7150 /// syntactically ignored, perform any conversions that are
7152 ExprResult IgnoredValueConversions(Expr *E);
7154 // UsualUnaryConversions - promotes integers (C99 6.3.1.1p2) and converts
7155 // functions and arrays to their respective pointers (C99 6.3.2.1).
7156 ExprResult UsualUnaryConversions(Expr *E);
7158 // DefaultFunctionArrayConversion - converts functions and arrays
7159 // to their respective pointers (C99 6.3.2.1).
7160 ExprResult DefaultFunctionArrayConversion(Expr *E);
7162 // DefaultFunctionArrayLvalueConversion - converts functions and
7163 // arrays to their respective pointers and performs the
7164 // lvalue-to-rvalue conversion.
7165 ExprResult DefaultFunctionArrayLvalueConversion(Expr *E);
7167 // DefaultLvalueConversion - performs lvalue-to-rvalue conversion on
7168 // the operand. This is DefaultFunctionArrayLvalueConversion,
7169 // except that it assumes the operand isn't of function or array
7171 ExprResult DefaultLvalueConversion(Expr *E);
7173 // DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
7174 // do not have a prototype. Integer promotions are performed on each
7175 // argument, and arguments that have type float are promoted to double.
7176 ExprResult DefaultArgumentPromotion(Expr *E);
7178 // Used for emitting the right warning by DefaultVariadicArgumentPromotion
7179 enum VariadicCallType {
7183 VariadicConstructor,
7184 VariadicDoesNotApply
7187 VariadicCallType getVariadicCallType(FunctionDecl *FDecl,
7188 const FunctionProtoType *Proto,
7191 // Used for determining in which context a type is allowed to be passed to a
7200 // Determines which VarArgKind fits an expression.
7201 VarArgKind isValidVarArgType(const QualType &Ty);
7203 /// Check to see if the given expression is a valid argument to a variadic
7204 /// function, issuing a diagnostic if not.
7205 void checkVariadicArgument(const Expr *E, VariadicCallType CT);
7207 /// GatherArgumentsForCall - Collector argument expressions for various
7208 /// form of call prototypes.
7209 bool GatherArgumentsForCall(SourceLocation CallLoc,
7210 FunctionDecl *FDecl,
7211 const FunctionProtoType *Proto,
7212 unsigned FirstProtoArg,
7213 ArrayRef<Expr *> Args,
7214 SmallVectorImpl<Expr *> &AllArgs,
7215 VariadicCallType CallType = VariadicDoesNotApply,
7216 bool AllowExplicit = false,
7217 bool IsListInitialization = false);
7219 // DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
7220 // will create a runtime trap if the resulting type is not a POD type.
7221 ExprResult DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
7222 FunctionDecl *FDecl);
7224 // UsualArithmeticConversions - performs the UsualUnaryConversions on it's
7225 // operands and then handles various conversions that are common to binary
7226 // operators (C99 6.3.1.8). If both operands aren't arithmetic, this
7227 // routine returns the first non-arithmetic type found. The client is
7228 // responsible for emitting appropriate error diagnostics.
7229 QualType UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
7230 bool IsCompAssign = false);
7232 /// AssignConvertType - All of the 'assignment' semantic checks return this
7233 /// enum to indicate whether the assignment was allowed. These checks are
7234 /// done for simple assignments, as well as initialization, return from
7235 /// function, argument passing, etc. The query is phrased in terms of a
7236 /// source and destination type.
7237 enum AssignConvertType {
7238 /// Compatible - the types are compatible according to the standard.
7241 /// PointerToInt - The assignment converts a pointer to an int, which we
7242 /// accept as an extension.
7245 /// IntToPointer - The assignment converts an int to a pointer, which we
7246 /// accept as an extension.
7249 /// FunctionVoidPointer - The assignment is between a function pointer and
7250 /// void*, which the standard doesn't allow, but we accept as an extension.
7251 FunctionVoidPointer,
7253 /// IncompatiblePointer - The assignment is between two pointers types that
7254 /// are not compatible, but we accept them as an extension.
7255 IncompatiblePointer,
7257 /// IncompatiblePointer - The assignment is between two pointers types which
7258 /// point to integers which have a different sign, but are otherwise
7259 /// identical. This is a subset of the above, but broken out because it's by
7260 /// far the most common case of incompatible pointers.
7261 IncompatiblePointerSign,
7263 /// CompatiblePointerDiscardsQualifiers - The assignment discards
7264 /// c/v/r qualifiers, which we accept as an extension.
7265 CompatiblePointerDiscardsQualifiers,
7267 /// IncompatiblePointerDiscardsQualifiers - The assignment
7268 /// discards qualifiers that we don't permit to be discarded,
7269 /// like address spaces.
7270 IncompatiblePointerDiscardsQualifiers,
7272 /// IncompatibleNestedPointerQualifiers - The assignment is between two
7273 /// nested pointer types, and the qualifiers other than the first two
7274 /// levels differ e.g. char ** -> const char **, but we accept them as an
7276 IncompatibleNestedPointerQualifiers,
7278 /// IncompatibleVectors - The assignment is between two vector types that
7279 /// have the same size, which we accept as an extension.
7280 IncompatibleVectors,
7282 /// IntToBlockPointer - The assignment converts an int to a block
7283 /// pointer. We disallow this.
7286 /// IncompatibleBlockPointer - The assignment is between two block
7287 /// pointers types that are not compatible.
7288 IncompatibleBlockPointer,
7290 /// IncompatibleObjCQualifiedId - The assignment is between a qualified
7291 /// id type and something else (that is incompatible with it). For example,
7292 /// "id <XXX>" = "Foo *", where "Foo *" doesn't implement the XXX protocol.
7293 IncompatibleObjCQualifiedId,
7295 /// IncompatibleObjCWeakRef - Assigning a weak-unavailable object to an
7296 /// object with __weak qualifier.
7297 IncompatibleObjCWeakRef,
7299 /// Incompatible - We reject this conversion outright, it is invalid to
7300 /// represent it in the AST.
7304 /// DiagnoseAssignmentResult - Emit a diagnostic, if required, for the
7305 /// assignment conversion type specified by ConvTy. This returns true if the
7306 /// conversion was invalid or false if the conversion was accepted.
7307 bool DiagnoseAssignmentResult(AssignConvertType ConvTy,
7309 QualType DstType, QualType SrcType,
7310 Expr *SrcExpr, AssignmentAction Action,
7311 bool *Complained = 0);
7313 /// DiagnoseAssignmentEnum - Warn if assignment to enum is a constant
7314 /// integer not in the range of enum values.
7315 void DiagnoseAssignmentEnum(QualType DstType, QualType SrcType,
7318 /// CheckAssignmentConstraints - Perform type checking for assignment,
7319 /// argument passing, variable initialization, and function return values.
7321 AssignConvertType CheckAssignmentConstraints(SourceLocation Loc,
7325 /// Check assignment constraints and prepare for a conversion of the
7326 /// RHS to the LHS type.
7327 AssignConvertType CheckAssignmentConstraints(QualType LHSType,
7331 // CheckSingleAssignmentConstraints - Currently used by
7332 // CheckAssignmentOperands, and ActOnReturnStmt. Prior to type checking,
7333 // this routine performs the default function/array converions.
7334 AssignConvertType CheckSingleAssignmentConstraints(QualType LHSType,
7336 bool Diagnose = true,
7337 bool DiagnoseCFAudited = false);
7339 // \brief If the lhs type is a transparent union, check whether we
7340 // can initialize the transparent union with the given expression.
7341 AssignConvertType CheckTransparentUnionArgumentConstraints(QualType ArgType,
7344 bool IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType);
7346 bool CheckExceptionSpecCompatibility(Expr *From, QualType ToType);
7348 ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
7349 AssignmentAction Action,
7350 bool AllowExplicit = false);
7351 ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
7352 AssignmentAction Action,
7354 ImplicitConversionSequence& ICS);
7355 ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
7356 const ImplicitConversionSequence& ICS,
7357 AssignmentAction Action,
7358 CheckedConversionKind CCK
7359 = CCK_ImplicitConversion);
7360 ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
7361 const StandardConversionSequence& SCS,
7362 AssignmentAction Action,
7363 CheckedConversionKind CCK);
7365 /// the following "Check" methods will return a valid/converted QualType
7366 /// or a null QualType (indicating an error diagnostic was issued).
7368 /// type checking binary operators (subroutines of CreateBuiltinBinOp).
7369 QualType InvalidOperands(SourceLocation Loc, ExprResult &LHS,
7371 QualType CheckPointerToMemberOperands( // C++ 5.5
7372 ExprResult &LHS, ExprResult &RHS, ExprValueKind &VK,
7373 SourceLocation OpLoc, bool isIndirect);
7374 QualType CheckMultiplyDivideOperands( // C99 6.5.5
7375 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign,
7377 QualType CheckRemainderOperands( // C99 6.5.5
7378 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
7379 bool IsCompAssign = false);
7380 QualType CheckAdditionOperands( // C99 6.5.6
7381 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc,
7382 QualType* CompLHSTy = 0);
7383 QualType CheckSubtractionOperands( // C99 6.5.6
7384 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
7385 QualType* CompLHSTy = 0);
7386 QualType CheckShiftOperands( // C99 6.5.7
7387 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc,
7388 bool IsCompAssign = false);
7389 QualType CheckCompareOperands( // C99 6.5.8/9
7390 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned OpaqueOpc,
7392 QualType CheckBitwiseOperands( // C99 6.5.[10...12]
7393 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
7394 bool IsCompAssign = false);
7395 QualType CheckLogicalOperands( // C99 6.5.[13,14]
7396 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc);
7397 // CheckAssignmentOperands is used for both simple and compound assignment.
7398 // For simple assignment, pass both expressions and a null converted type.
7399 // For compound assignment, pass both expressions and the converted type.
7400 QualType CheckAssignmentOperands( // C99 6.5.16.[1,2]
7401 Expr *LHSExpr, ExprResult &RHS, SourceLocation Loc, QualType CompoundType);
7403 ExprResult checkPseudoObjectIncDec(Scope *S, SourceLocation OpLoc,
7404 UnaryOperatorKind Opcode, Expr *Op);
7405 ExprResult checkPseudoObjectAssignment(Scope *S, SourceLocation OpLoc,
7406 BinaryOperatorKind Opcode,
7407 Expr *LHS, Expr *RHS);
7408 ExprResult checkPseudoObjectRValue(Expr *E);
7409 Expr *recreateSyntacticForm(PseudoObjectExpr *E);
7411 QualType CheckConditionalOperands( // C99 6.5.15
7412 ExprResult &Cond, ExprResult &LHS, ExprResult &RHS,
7413 ExprValueKind &VK, ExprObjectKind &OK, SourceLocation QuestionLoc);
7414 QualType CXXCheckConditionalOperands( // C++ 5.16
7415 ExprResult &cond, ExprResult &lhs, ExprResult &rhs,
7416 ExprValueKind &VK, ExprObjectKind &OK, SourceLocation questionLoc);
7417 QualType FindCompositePointerType(SourceLocation Loc, Expr *&E1, Expr *&E2,
7418 bool *NonStandardCompositeType = 0);
7419 QualType FindCompositePointerType(SourceLocation Loc,
7420 ExprResult &E1, ExprResult &E2,
7421 bool *NonStandardCompositeType = 0) {
7422 Expr *E1Tmp = E1.take(), *E2Tmp = E2.take();
7423 QualType Composite = FindCompositePointerType(Loc, E1Tmp, E2Tmp,
7424 NonStandardCompositeType);
7430 QualType FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
7431 SourceLocation QuestionLoc);
7433 bool DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
7434 SourceLocation QuestionLoc);
7436 /// type checking for vector binary operators.
7437 QualType CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
7438 SourceLocation Loc, bool IsCompAssign);
7439 QualType GetSignedVectorType(QualType V);
7440 QualType CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
7441 SourceLocation Loc, bool isRelational);
7442 QualType CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
7443 SourceLocation Loc);
7445 /// type checking declaration initializers (C99 6.7.8)
7446 bool CheckForConstantInitializer(Expr *e, QualType t);
7448 // type checking C++ declaration initializers (C++ [dcl.init]).
7450 /// ReferenceCompareResult - Expresses the result of comparing two
7451 /// types (cv1 T1 and cv2 T2) to determine their compatibility for the
7452 /// purposes of initialization by reference (C++ [dcl.init.ref]p4).
7453 enum ReferenceCompareResult {
7454 /// Ref_Incompatible - The two types are incompatible, so direct
7455 /// reference binding is not possible.
7456 Ref_Incompatible = 0,
7457 /// Ref_Related - The two types are reference-related, which means
7458 /// that their unqualified forms (T1 and T2) are either the same
7459 /// or T1 is a base class of T2.
7461 /// Ref_Compatible_With_Added_Qualification - The two types are
7462 /// reference-compatible with added qualification, meaning that
7463 /// they are reference-compatible and the qualifiers on T1 (cv1)
7464 /// are greater than the qualifiers on T2 (cv2).
7465 Ref_Compatible_With_Added_Qualification,
7466 /// Ref_Compatible - The two types are reference-compatible and
7467 /// have equivalent qualifiers (cv1 == cv2).
7471 ReferenceCompareResult CompareReferenceRelationship(SourceLocation Loc,
7472 QualType T1, QualType T2,
7473 bool &DerivedToBase,
7474 bool &ObjCConversion,
7475 bool &ObjCLifetimeConversion);
7477 ExprResult checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
7478 Expr *CastExpr, CastKind &CastKind,
7479 ExprValueKind &VK, CXXCastPath &Path);
7481 /// \brief Force an expression with unknown-type to an expression of the
7483 ExprResult forceUnknownAnyToType(Expr *E, QualType ToType);
7485 /// \brief Type-check an expression that's being passed to an
7486 /// __unknown_anytype parameter.
7487 ExprResult checkUnknownAnyArg(SourceLocation callLoc,
7488 Expr *result, QualType ¶mType);
7490 // CheckVectorCast - check type constraints for vectors.
7491 // Since vectors are an extension, there are no C standard reference for this.
7492 // We allow casting between vectors and integer datatypes of the same size.
7493 // returns true if the cast is invalid
7494 bool CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
7497 // CheckExtVectorCast - check type constraints for extended vectors.
7498 // Since vectors are an extension, there are no C standard reference for this.
7499 // We allow casting between vectors and integer datatypes of the same size,
7500 // or vectors and the element type of that vector.
7501 // returns the cast expr
7502 ExprResult CheckExtVectorCast(SourceRange R, QualType DestTy, Expr *CastExpr,
7505 ExprResult BuildCXXFunctionalCastExpr(TypeSourceInfo *TInfo,
7506 SourceLocation LParenLoc,
7508 SourceLocation RParenLoc);
7510 enum ARCConversionResult { ACR_okay, ACR_unbridged };
7512 /// \brief Checks for invalid conversions and casts between
7513 /// retainable pointers and other pointer kinds.
7514 ARCConversionResult CheckObjCARCConversion(SourceRange castRange,
7515 QualType castType, Expr *&op,
7516 CheckedConversionKind CCK,
7517 bool DiagnoseCFAudited = false);
7519 Expr *stripARCUnbridgedCast(Expr *e);
7520 void diagnoseARCUnbridgedCast(Expr *e);
7522 bool CheckObjCARCUnavailableWeakConversion(QualType castType,
7525 /// checkRetainCycles - Check whether an Objective-C message send
7526 /// might create an obvious retain cycle.
7527 void checkRetainCycles(ObjCMessageExpr *msg);
7528 void checkRetainCycles(Expr *receiver, Expr *argument);
7529 void checkRetainCycles(VarDecl *Var, Expr *Init);
7531 /// checkUnsafeAssigns - Check whether +1 expr is being assigned
7532 /// to weak/__unsafe_unretained type.
7533 bool checkUnsafeAssigns(SourceLocation Loc, QualType LHS, Expr *RHS);
7535 /// checkUnsafeExprAssigns - Check whether +1 expr is being assigned
7536 /// to weak/__unsafe_unretained expression.
7537 void checkUnsafeExprAssigns(SourceLocation Loc, Expr *LHS, Expr *RHS);
7539 /// CheckMessageArgumentTypes - Check types in an Obj-C message send.
7540 /// \param Method - May be null.
7541 /// \param [out] ReturnType - The return type of the send.
7542 /// \return true iff there were any incompatible types.
7543 bool CheckMessageArgumentTypes(QualType ReceiverType,
7544 MultiExprArg Args, Selector Sel,
7545 ArrayRef<SourceLocation> SelectorLocs,
7546 ObjCMethodDecl *Method, bool isClassMessage,
7547 bool isSuperMessage,
7548 SourceLocation lbrac, SourceLocation rbrac,
7549 QualType &ReturnType, ExprValueKind &VK);
7551 /// \brief Determine the result of a message send expression based on
7552 /// the type of the receiver, the method expected to receive the message,
7553 /// and the form of the message send.
7554 QualType getMessageSendResultType(QualType ReceiverType,
7555 ObjCMethodDecl *Method,
7556 bool isClassMessage, bool isSuperMessage);
7558 /// \brief If the given expression involves a message send to a method
7559 /// with a related result type, emit a note describing what happened.
7560 void EmitRelatedResultTypeNote(const Expr *E);
7562 /// \brief Given that we had incompatible pointer types in a return
7563 /// statement, check whether we're in a method with a related result
7564 /// type, and if so, emit a note describing what happened.
7565 void EmitRelatedResultTypeNoteForReturn(QualType destType);
7567 /// CheckBooleanCondition - Diagnose problems involving the use of
7568 /// the given expression as a boolean condition (e.g. in an if
7569 /// statement). Also performs the standard function and array
7570 /// decays, possibly changing the input variable.
7572 /// \param Loc - A location associated with the condition, e.g. the
7574 /// \return true iff there were any errors
7575 ExprResult CheckBooleanCondition(Expr *E, SourceLocation Loc);
7577 ExprResult ActOnBooleanCondition(Scope *S, SourceLocation Loc,
7580 /// DiagnoseAssignmentAsCondition - Given that an expression is
7581 /// being used as a boolean condition, warn if it's an assignment.
7582 void DiagnoseAssignmentAsCondition(Expr *E);
7584 /// \brief Redundant parentheses over an equality comparison can indicate
7585 /// that the user intended an assignment used as condition.
7586 void DiagnoseEqualityWithExtraParens(ParenExpr *ParenE);
7588 /// CheckCXXBooleanCondition - Returns true if conversion to bool is invalid.
7589 ExprResult CheckCXXBooleanCondition(Expr *CondExpr);
7591 /// ConvertIntegerToTypeWarnOnOverflow - Convert the specified APInt to have
7592 /// the specified width and sign. If an overflow occurs, detect it and emit
7593 /// the specified diagnostic.
7594 void ConvertIntegerToTypeWarnOnOverflow(llvm::APSInt &OldVal,
7595 unsigned NewWidth, bool NewSign,
7596 SourceLocation Loc, unsigned DiagID);
7598 /// Checks that the Objective-C declaration is declared in the global scope.
7599 /// Emits an error and marks the declaration as invalid if it's not declared
7600 /// in the global scope.
7601 bool CheckObjCDeclScope(Decl *D);
7603 /// \brief Abstract base class used for diagnosing integer constant
7604 /// expression violations.
7605 class VerifyICEDiagnoser {
7609 VerifyICEDiagnoser(bool Suppress = false) : Suppress(Suppress) { }
7611 virtual void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) =0;
7612 virtual void diagnoseFold(Sema &S, SourceLocation Loc, SourceRange SR);
7613 virtual ~VerifyICEDiagnoser() { }
7616 /// VerifyIntegerConstantExpression - Verifies that an expression is an ICE,
7617 /// and reports the appropriate diagnostics. Returns false on success.
7618 /// Can optionally return the value of the expression.
7619 ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
7620 VerifyICEDiagnoser &Diagnoser,
7621 bool AllowFold = true);
7622 ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
7624 bool AllowFold = true);
7625 ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result=0);
7627 /// VerifyBitField - verifies that a bit field expression is an ICE and has
7628 /// the correct width, and that the field type is valid.
7629 /// Returns false on success.
7630 /// Can optionally return whether the bit-field is of width 0
7631 ExprResult VerifyBitField(SourceLocation FieldLoc, IdentifierInfo *FieldName,
7632 QualType FieldTy, bool IsMsStruct,
7633 Expr *BitWidth, bool *ZeroWidth = 0);
7635 enum CUDAFunctionTarget {
7642 CUDAFunctionTarget IdentifyCUDATarget(const FunctionDecl *D);
7644 bool CheckCUDATarget(CUDAFunctionTarget CallerTarget,
7645 CUDAFunctionTarget CalleeTarget);
7647 bool CheckCUDATarget(const FunctionDecl *Caller, const FunctionDecl *Callee) {
7648 return CheckCUDATarget(IdentifyCUDATarget(Caller),
7649 IdentifyCUDATarget(Callee));
7652 /// \name Code completion
7654 /// \brief Describes the context in which code completion occurs.
7655 enum ParserCompletionContext {
7656 /// \brief Code completion occurs at top-level or namespace context.
7658 /// \brief Code completion occurs within a class, struct, or union.
7660 /// \brief Code completion occurs within an Objective-C interface, protocol,
7663 /// \brief Code completion occurs within an Objective-C implementation or
7664 /// category implementation
7665 PCC_ObjCImplementation,
7666 /// \brief Code completion occurs within the list of instance variables
7667 /// in an Objective-C interface, protocol, category, or implementation.
7668 PCC_ObjCInstanceVariableList,
7669 /// \brief Code completion occurs following one or more template
7672 /// \brief Code completion occurs following one or more template
7673 /// headers within a class.
7675 /// \brief Code completion occurs within an expression.
7677 /// \brief Code completion occurs within a statement, which may
7678 /// also be an expression or a declaration.
7680 /// \brief Code completion occurs at the beginning of the
7681 /// initialization statement (or expression) in a for loop.
7683 /// \brief Code completion occurs within the condition of an if,
7684 /// while, switch, or for statement.
7686 /// \brief Code completion occurs within the body of a function on a
7687 /// recovery path, where we do not have a specific handle on our position
7689 PCC_RecoveryInFunction,
7690 /// \brief Code completion occurs where only a type is permitted.
7692 /// \brief Code completion occurs in a parenthesized expression, which
7693 /// might also be a type cast.
7694 PCC_ParenthesizedExpression,
7695 /// \brief Code completion occurs within a sequence of declaration
7696 /// specifiers within a function, method, or block.
7697 PCC_LocalDeclarationSpecifiers
7700 void CodeCompleteModuleImport(SourceLocation ImportLoc, ModuleIdPath Path);
7701 void CodeCompleteOrdinaryName(Scope *S,
7702 ParserCompletionContext CompletionContext);
7703 void CodeCompleteDeclSpec(Scope *S, DeclSpec &DS,
7704 bool AllowNonIdentifiers,
7705 bool AllowNestedNameSpecifiers);
7707 struct CodeCompleteExpressionData;
7708 void CodeCompleteExpression(Scope *S,
7709 const CodeCompleteExpressionData &Data);
7710 void CodeCompleteMemberReferenceExpr(Scope *S, Expr *Base,
7711 SourceLocation OpLoc,
7713 void CodeCompletePostfixExpression(Scope *S, ExprResult LHS);
7714 void CodeCompleteTag(Scope *S, unsigned TagSpec);
7715 void CodeCompleteTypeQualifiers(DeclSpec &DS);
7716 void CodeCompleteCase(Scope *S);
7717 void CodeCompleteCall(Scope *S, Expr *Fn, ArrayRef<Expr *> Args);
7718 void CodeCompleteInitializer(Scope *S, Decl *D);
7719 void CodeCompleteReturn(Scope *S);
7720 void CodeCompleteAfterIf(Scope *S);
7721 void CodeCompleteAssignmentRHS(Scope *S, Expr *LHS);
7723 void CodeCompleteQualifiedId(Scope *S, CXXScopeSpec &SS,
7724 bool EnteringContext);
7725 void CodeCompleteUsing(Scope *S);
7726 void CodeCompleteUsingDirective(Scope *S);
7727 void CodeCompleteNamespaceDecl(Scope *S);
7728 void CodeCompleteNamespaceAliasDecl(Scope *S);
7729 void CodeCompleteOperatorName(Scope *S);
7730 void CodeCompleteConstructorInitializer(
7732 ArrayRef<CXXCtorInitializer *> Initializers);
7734 void CodeCompleteLambdaIntroducer(Scope *S, LambdaIntroducer &Intro,
7735 bool AfterAmpersand);
7737 void CodeCompleteObjCAtDirective(Scope *S);
7738 void CodeCompleteObjCAtVisibility(Scope *S);
7739 void CodeCompleteObjCAtStatement(Scope *S);
7740 void CodeCompleteObjCAtExpression(Scope *S);
7741 void CodeCompleteObjCPropertyFlags(Scope *S, ObjCDeclSpec &ODS);
7742 void CodeCompleteObjCPropertyGetter(Scope *S);
7743 void CodeCompleteObjCPropertySetter(Scope *S);
7744 void CodeCompleteObjCPassingType(Scope *S, ObjCDeclSpec &DS,
7746 void CodeCompleteObjCMessageReceiver(Scope *S);
7747 void CodeCompleteObjCSuperMessage(Scope *S, SourceLocation SuperLoc,
7748 ArrayRef<IdentifierInfo *> SelIdents,
7749 bool AtArgumentExpression);
7750 void CodeCompleteObjCClassMessage(Scope *S, ParsedType Receiver,
7751 ArrayRef<IdentifierInfo *> SelIdents,
7752 bool AtArgumentExpression,
7753 bool IsSuper = false);
7754 void CodeCompleteObjCInstanceMessage(Scope *S, Expr *Receiver,
7755 ArrayRef<IdentifierInfo *> SelIdents,
7756 bool AtArgumentExpression,
7757 ObjCInterfaceDecl *Super = 0);
7758 void CodeCompleteObjCForCollection(Scope *S,
7759 DeclGroupPtrTy IterationVar);
7760 void CodeCompleteObjCSelector(Scope *S,
7761 ArrayRef<IdentifierInfo *> SelIdents);
7762 void CodeCompleteObjCProtocolReferences(IdentifierLocPair *Protocols,
7763 unsigned NumProtocols);
7764 void CodeCompleteObjCProtocolDecl(Scope *S);
7765 void CodeCompleteObjCInterfaceDecl(Scope *S);
7766 void CodeCompleteObjCSuperclass(Scope *S,
7767 IdentifierInfo *ClassName,
7768 SourceLocation ClassNameLoc);
7769 void CodeCompleteObjCImplementationDecl(Scope *S);
7770 void CodeCompleteObjCInterfaceCategory(Scope *S,
7771 IdentifierInfo *ClassName,
7772 SourceLocation ClassNameLoc);
7773 void CodeCompleteObjCImplementationCategory(Scope *S,
7774 IdentifierInfo *ClassName,
7775 SourceLocation ClassNameLoc);
7776 void CodeCompleteObjCPropertyDefinition(Scope *S);
7777 void CodeCompleteObjCPropertySynthesizeIvar(Scope *S,
7778 IdentifierInfo *PropertyName);
7779 void CodeCompleteObjCMethodDecl(Scope *S,
7780 bool IsInstanceMethod,
7781 ParsedType ReturnType);
7782 void CodeCompleteObjCMethodDeclSelector(Scope *S,
7783 bool IsInstanceMethod,
7784 bool AtParameterName,
7785 ParsedType ReturnType,
7786 ArrayRef<IdentifierInfo *> SelIdents);
7787 void CodeCompletePreprocessorDirective(bool InConditional);
7788 void CodeCompleteInPreprocessorConditionalExclusion(Scope *S);
7789 void CodeCompletePreprocessorMacroName(bool IsDefinition);
7790 void CodeCompletePreprocessorExpression();
7791 void CodeCompletePreprocessorMacroArgument(Scope *S,
7792 IdentifierInfo *Macro,
7793 MacroInfo *MacroInfo,
7795 void CodeCompleteNaturalLanguage();
7796 void GatherGlobalCodeCompletions(CodeCompletionAllocator &Allocator,
7797 CodeCompletionTUInfo &CCTUInfo,
7798 SmallVectorImpl<CodeCompletionResult> &Results);
7801 //===--------------------------------------------------------------------===//
7802 // Extra semantic analysis beyond the C type system
7805 SourceLocation getLocationOfStringLiteralByte(const StringLiteral *SL,
7806 unsigned ByteNo) const;
7809 void CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
7810 const ArraySubscriptExpr *ASE=0,
7811 bool AllowOnePastEnd=true, bool IndexNegated=false);
7812 void CheckArrayAccess(const Expr *E);
7813 // Used to grab the relevant information from a FormatAttr and a
7814 // FunctionDeclaration.
7815 struct FormatStringInfo {
7817 unsigned FirstDataArg;
7821 bool getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
7822 FormatStringInfo *FSI);
7823 bool CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
7824 const FunctionProtoType *Proto);
7825 bool CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation loc,
7826 ArrayRef<const Expr *> Args);
7827 bool CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
7828 const FunctionProtoType *Proto);
7829 bool CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto);
7830 void CheckConstructorCall(FunctionDecl *FDecl,
7831 ArrayRef<const Expr *> Args,
7832 const FunctionProtoType *Proto,
7833 SourceLocation Loc);
7835 void checkCall(NamedDecl *FDecl, ArrayRef<const Expr *> Args,
7836 unsigned NumProtoArgs, bool IsMemberFunction,
7837 SourceLocation Loc, SourceRange Range,
7838 VariadicCallType CallType);
7841 bool CheckObjCString(Expr *Arg);
7843 ExprResult CheckBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
7845 bool CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall);
7846 bool CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
7847 bool CheckAArch64BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
7848 bool CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
7850 bool SemaBuiltinVAStart(CallExpr *TheCall);
7851 bool SemaBuiltinUnorderedCompare(CallExpr *TheCall);
7852 bool SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs);
7855 // Used by C++ template instantiation.
7856 ExprResult SemaBuiltinShuffleVector(CallExpr *TheCall);
7857 ExprResult SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
7858 SourceLocation BuiltinLoc,
7859 SourceLocation RParenLoc);
7862 bool SemaBuiltinPrefetch(CallExpr *TheCall);
7863 bool SemaBuiltinObjectSize(CallExpr *TheCall);
7864 bool SemaBuiltinLongjmp(CallExpr *TheCall);
7865 ExprResult SemaBuiltinAtomicOverloaded(ExprResult TheCallResult);
7866 ExprResult SemaAtomicOpsOverloaded(ExprResult TheCallResult,
7867 AtomicExpr::AtomicOp Op);
7868 bool SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
7869 llvm::APSInt &Result);
7872 enum FormatStringType {
7881 static FormatStringType GetFormatStringType(const FormatAttr *Format);
7883 void CheckFormatString(const StringLiteral *FExpr, const Expr *OrigFormatExpr,
7884 ArrayRef<const Expr *> Args, bool HasVAListArg,
7885 unsigned format_idx, unsigned firstDataArg,
7886 FormatStringType Type, bool inFunctionCall,
7887 VariadicCallType CallType,
7888 llvm::SmallBitVector &CheckedVarArgs);
7891 bool CheckFormatArguments(const FormatAttr *Format,
7892 ArrayRef<const Expr *> Args,
7894 VariadicCallType CallType,
7895 SourceLocation Loc, SourceRange Range,
7896 llvm::SmallBitVector &CheckedVarArgs);
7897 bool CheckFormatArguments(ArrayRef<const Expr *> Args,
7898 bool HasVAListArg, unsigned format_idx,
7899 unsigned firstDataArg, FormatStringType Type,
7900 VariadicCallType CallType,
7901 SourceLocation Loc, SourceRange range,
7902 llvm::SmallBitVector &CheckedVarArgs);
7904 void CheckNonNullArguments(const NonNullAttr *NonNull,
7905 const Expr * const *ExprArgs,
7906 SourceLocation CallSiteLoc);
7908 void CheckMemaccessArguments(const CallExpr *Call,
7910 IdentifierInfo *FnName);
7912 void CheckStrlcpycatArguments(const CallExpr *Call,
7913 IdentifierInfo *FnName);
7915 void CheckStrncatArguments(const CallExpr *Call,
7916 IdentifierInfo *FnName);
7918 void CheckReturnStackAddr(Expr *RetValExp, QualType lhsType,
7919 SourceLocation ReturnLoc);
7920 void CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr* RHS);
7921 void CheckImplicitConversions(Expr *E, SourceLocation CC = SourceLocation());
7922 void CheckForIntOverflow(Expr *E);
7923 void CheckUnsequencedOperations(Expr *E);
7925 /// \brief Perform semantic checks on a completed expression. This will either
7926 /// be a full-expression or a default argument expression.
7927 void CheckCompletedExpr(Expr *E, SourceLocation CheckLoc = SourceLocation(),
7928 bool IsConstexpr = false);
7930 void CheckBitFieldInitialization(SourceLocation InitLoc, FieldDecl *Field,
7934 /// \brief Register a magic integral constant to be used as a type tag.
7935 void RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
7936 uint64_t MagicValue, QualType Type,
7937 bool LayoutCompatible, bool MustBeNull);
7939 struct TypeTagData {
7942 TypeTagData(QualType Type, bool LayoutCompatible, bool MustBeNull) :
7943 Type(Type), LayoutCompatible(LayoutCompatible),
7944 MustBeNull(MustBeNull)
7949 /// If true, \c Type should be compared with other expression's types for
7950 /// layout-compatibility.
7951 unsigned LayoutCompatible : 1;
7952 unsigned MustBeNull : 1;
7955 /// A pair of ArgumentKind identifier and magic value. This uniquely
7956 /// identifies the magic value.
7957 typedef std::pair<const IdentifierInfo *, uint64_t> TypeTagMagicValue;
7960 /// \brief A map from magic value to type information.
7961 OwningPtr<llvm::DenseMap<TypeTagMagicValue, TypeTagData> >
7962 TypeTagForDatatypeMagicValues;
7964 /// \brief Peform checks on a call of a function with argument_with_type_tag
7965 /// or pointer_with_type_tag attributes.
7966 void CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
7967 const Expr * const *ExprArgs);
7969 /// \brief The parser's current scope.
7971 /// The parser maintains this state here.
7974 mutable IdentifierInfo *Ident_super;
7975 mutable IdentifierInfo *Ident___float128;
7978 friend class Parser;
7979 friend class InitializationSequence;
7980 friend class ASTReader;
7981 friend class ASTWriter;
7984 /// \brief Retrieve the parser's current scope.
7986 /// This routine must only be used when it is certain that semantic analysis
7987 /// and the parser are in precisely the same context, which is not the case
7988 /// when, e.g., we are performing any kind of template instantiation.
7989 /// Therefore, the only safe places to use this scope are in the parser
7990 /// itself and in routines directly invoked from the parser and *never* from
7991 /// template substitution or instantiation.
7992 Scope *getCurScope() const { return CurScope; }
7994 IdentifierInfo *getSuperIdentifier() const;
7995 IdentifierInfo *getFloat128Identifier() const;
7997 Decl *getObjCDeclContext() const;
7999 DeclContext *getCurLexicalContext() const {
8000 return OriginalLexicalContext ? OriginalLexicalContext : CurContext;
8003 AvailabilityResult getCurContextAvailability() const;
8005 const DeclContext *getCurObjCLexicalContext() const {
8006 const DeclContext *DC = getCurLexicalContext();
8007 // A category implicitly has the attribute of the interface.
8008 if (const ObjCCategoryDecl *CatD = dyn_cast<ObjCCategoryDecl>(DC))
8009 DC = CatD->getClassInterface();
8014 /// \brief RAII object that enters a new expression evaluation context.
8015 class EnterExpressionEvaluationContext {
8019 EnterExpressionEvaluationContext(Sema &Actions,
8020 Sema::ExpressionEvaluationContext NewContext,
8021 Decl *LambdaContextDecl = 0,
8022 bool IsDecltype = false)
8023 : Actions(Actions) {
8024 Actions.PushExpressionEvaluationContext(NewContext, LambdaContextDecl,
8027 EnterExpressionEvaluationContext(Sema &Actions,
8028 Sema::ExpressionEvaluationContext NewContext,
8029 Sema::ReuseLambdaContextDecl_t,
8030 bool IsDecltype = false)
8031 : Actions(Actions) {
8032 Actions.PushExpressionEvaluationContext(NewContext,
8033 Sema::ReuseLambdaContextDecl,
8037 ~EnterExpressionEvaluationContext() {
8038 Actions.PopExpressionEvaluationContext();
8042 DeductionFailureInfo
8043 MakeDeductionFailureInfo(ASTContext &Context, Sema::TemplateDeductionResult TDK,
8044 sema::TemplateDeductionInfo &Info);
8046 /// \brief Contains a late templated function.
8047 /// Will be parsed at the end of the translation unit, used by Sema & Parser.
8048 struct LateParsedTemplate {
8050 /// \brief The template function declaration to be late parsed.
8054 } // end namespace clang