• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 //===--- Sema.h - Semantic Analysis & AST Building --------------*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines the Sema class, which performs semantic analysis and
11 // builds ASTs.
12 //
13 //===----------------------------------------------------------------------===//
14 
15 #ifndef LLVM_CLANG_SEMA_SEMA_H
16 #define LLVM_CLANG_SEMA_SEMA_H
17 
18 #include "clang/Sema/Ownership.h"
19 #include "clang/Sema/AnalysisBasedWarnings.h"
20 #include "clang/Sema/IdentifierResolver.h"
21 #include "clang/Sema/ObjCMethodList.h"
22 #include "clang/Sema/DeclSpec.h"
23 #include "clang/Sema/ExternalSemaSource.h"
24 #include "clang/Sema/LocInfoType.h"
25 #include "clang/Sema/TypoCorrection.h"
26 #include "clang/Sema/Weak.h"
27 #include "clang/AST/Expr.h"
28 #include "clang/AST/ExprObjC.h"
29 #include "clang/AST/DeclarationName.h"
30 #include "clang/AST/ExternalASTSource.h"
31 #include "clang/AST/LambdaMangleContext.h"
32 #include "clang/AST/TypeLoc.h"
33 #include "clang/AST/NSAPI.h"
34 #include "clang/Lex/ModuleLoader.h"
35 #include "clang/Basic/Specifiers.h"
36 #include "clang/Basic/TemplateKinds.h"
37 #include "clang/Basic/TypeTraits.h"
38 #include "clang/Basic/ExpressionTraits.h"
39 #include "llvm/ADT/ArrayRef.h"
40 #include "llvm/ADT/Optional.h"
41 #include "llvm/ADT/OwningPtr.h"
42 #include "llvm/ADT/SetVector.h"
43 #include "llvm/ADT/SmallPtrSet.h"
44 #include "llvm/ADT/SmallVector.h"
45 #include <deque>
46 #include <string>
47 
48 namespace llvm {
49   class APSInt;
50   template <typename ValueT> struct DenseMapInfo;
51   template <typename ValueT, typename ValueInfoT> class DenseSet;
52   class SmallBitVector;
53 }
54 
55 namespace clang {
56   class ADLResult;
57   class ASTConsumer;
58   class ASTContext;
59   class ASTMutationListener;
60   class ASTReader;
61   class ASTWriter;
62   class ArrayType;
63   class AttributeList;
64   class BlockDecl;
65   class CXXBasePath;
66   class CXXBasePaths;
67   class CXXBindTemporaryExpr;
68   typedef SmallVector<CXXBaseSpecifier*, 4> CXXCastPath;
69   class CXXConstructorDecl;
70   class CXXConversionDecl;
71   class CXXDestructorDecl;
72   class CXXFieldCollector;
73   class CXXMemberCallExpr;
74   class CXXMethodDecl;
75   class CXXScopeSpec;
76   class CXXTemporary;
77   class CXXTryStmt;
78   class CallExpr;
79   class ClassTemplateDecl;
80   class ClassTemplatePartialSpecializationDecl;
81   class ClassTemplateSpecializationDecl;
82   class CodeCompleteConsumer;
83   class CodeCompletionAllocator;
84   class CodeCompletionTUInfo;
85   class CodeCompletionResult;
86   class Decl;
87   class DeclAccessPair;
88   class DeclContext;
89   class DeclRefExpr;
90   class DeclaratorDecl;
91   class DeducedTemplateArgument;
92   class DependentDiagnostic;
93   class DesignatedInitExpr;
94   class Designation;
95   class EnumConstantDecl;
96   class Expr;
97   class ExtVectorType;
98   class ExternalSemaSource;
99   class FormatAttr;
100   class FriendDecl;
101   class FunctionDecl;
102   class FunctionProtoType;
103   class FunctionTemplateDecl;
104   class ImplicitConversionSequence;
105   class InitListExpr;
106   class InitializationKind;
107   class InitializationSequence;
108   class InitializedEntity;
109   class IntegerLiteral;
110   class LabelStmt;
111   class LambdaExpr;
112   class LangOptions;
113   class LocalInstantiationScope;
114   class LookupResult;
115   class MacroInfo;
116   class MultiLevelTemplateArgumentList;
117   class NamedDecl;
118   class NonNullAttr;
119   class ObjCCategoryDecl;
120   class ObjCCategoryImplDecl;
121   class ObjCCompatibleAliasDecl;
122   class ObjCContainerDecl;
123   class ObjCImplDecl;
124   class ObjCImplementationDecl;
125   class ObjCInterfaceDecl;
126   class ObjCIvarDecl;
127   template <class T> class ObjCList;
128   class ObjCMessageExpr;
129   class ObjCMethodDecl;
130   class ObjCPropertyDecl;
131   class ObjCProtocolDecl;
132   class OverloadCandidateSet;
133   class OverloadExpr;
134   class ParenListExpr;
135   class ParmVarDecl;
136   class Preprocessor;
137   class PseudoDestructorTypeStorage;
138   class PseudoObjectExpr;
139   class QualType;
140   class StandardConversionSequence;
141   class Stmt;
142   class StringLiteral;
143   class SwitchStmt;
144   class TargetAttributesSema;
145   class TemplateArgument;
146   class TemplateArgumentList;
147   class TemplateArgumentLoc;
148   class TemplateDecl;
149   class TemplateParameterList;
150   class TemplatePartialOrderingContext;
151   class TemplateTemplateParmDecl;
152   class Token;
153   class TypeAliasDecl;
154   class TypedefDecl;
155   class TypedefNameDecl;
156   class TypeLoc;
157   class UnqualifiedId;
158   class UnresolvedLookupExpr;
159   class UnresolvedMemberExpr;
160   class UnresolvedSetImpl;
161   class UnresolvedSetIterator;
162   class UsingDecl;
163   class UsingShadowDecl;
164   class ValueDecl;
165   class VarDecl;
166   class VisibilityAttr;
167   class VisibleDeclConsumer;
168   class IndirectFieldDecl;
169 
170 namespace sema {
171   class AccessedEntity;
172   class BlockScopeInfo;
173   class CapturingScopeInfo;
174   class CompoundScopeInfo;
175   class DelayedDiagnostic;
176   class DelayedDiagnosticPool;
177   class FunctionScopeInfo;
178   class LambdaScopeInfo;
179   class PossiblyUnreachableDiag;
180   class TemplateDeductionInfo;
181 }
182 
183 // FIXME: No way to easily map from TemplateTypeParmTypes to
184 // TemplateTypeParmDecls, so we have this horrible PointerUnion.
185 typedef std::pair<llvm::PointerUnion<const TemplateTypeParmType*, NamedDecl*>,
186                   SourceLocation> UnexpandedParameterPack;
187 
188 /// Sema - This implements semantic analysis and AST building for C.
189 class Sema {
190   Sema(const Sema&);           // DO NOT IMPLEMENT
191   void operator=(const Sema&); // DO NOT IMPLEMENT
192   mutable const TargetAttributesSema* TheTargetAttributesSema;
193 public:
194   typedef OpaquePtr<DeclGroupRef> DeclGroupPtrTy;
195   typedef OpaquePtr<TemplateName> TemplateTy;
196   typedef OpaquePtr<QualType> TypeTy;
197 
198   OpenCLOptions OpenCLFeatures;
199   FPOptions FPFeatures;
200 
201   const LangOptions &LangOpts;
202   Preprocessor &PP;
203   ASTContext &Context;
204   ASTConsumer &Consumer;
205   DiagnosticsEngine &Diags;
206   SourceManager &SourceMgr;
207 
208   /// \brief Flag indicating whether or not to collect detailed statistics.
209   bool CollectStats;
210 
211   /// \brief Source of additional semantic information.
212   ExternalSemaSource *ExternalSource;
213 
214   /// \brief Code-completion consumer.
215   CodeCompleteConsumer *CodeCompleter;
216 
217   /// CurContext - This is the current declaration context of parsing.
218   DeclContext *CurContext;
219 
220   /// \brief Generally null except when we temporarily switch decl contexts,
221   /// like in \see ActOnObjCTemporaryExitContainerContext.
222   DeclContext *OriginalLexicalContext;
223 
224   /// VAListTagName - The declaration name corresponding to __va_list_tag.
225   /// This is used as part of a hack to omit that class from ADL results.
226   DeclarationName VAListTagName;
227 
228   /// PackContext - Manages the stack for \#pragma pack. An alignment
229   /// of 0 indicates default alignment.
230   void *PackContext; // Really a "PragmaPackStack*"
231 
232   bool MSStructPragmaOn; // True when \#pragma ms_struct on
233 
234   /// VisContext - Manages the stack for \#pragma GCC visibility.
235   void *VisContext; // Really a "PragmaVisStack*"
236 
237   /// ExprNeedsCleanups - True if the current evaluation context
238   /// requires cleanups to be run at its conclusion.
239   bool ExprNeedsCleanups;
240 
241   /// ExprCleanupObjects - This is the stack of objects requiring
242   /// cleanup that are created by the current full expression.  The
243   /// element type here is ExprWithCleanups::Object.
244   SmallVector<BlockDecl*, 8> ExprCleanupObjects;
245 
246   llvm::SmallPtrSet<Expr*, 8> MaybeODRUseExprs;
247 
248   /// \brief Stack containing information about each of the nested
249   /// function, block, and method scopes that are currently active.
250   ///
251   /// This array is never empty.  Clients should ignore the first
252   /// element, which is used to cache a single FunctionScopeInfo
253   /// that's used to parse every top-level function.
254   SmallVector<sema::FunctionScopeInfo *, 4> FunctionScopes;
255 
256   typedef LazyVector<TypedefNameDecl *, ExternalSemaSource,
257                      &ExternalSemaSource::ReadExtVectorDecls, 2, 2>
258     ExtVectorDeclsType;
259 
260   /// ExtVectorDecls - This is a list all the extended vector types. This allows
261   /// us to associate a raw vector type with one of the ext_vector type names.
262   /// This is only necessary for issuing pretty diagnostics.
263   ExtVectorDeclsType ExtVectorDecls;
264 
265   /// \brief The set of types for which we have already complained about the
266   /// definitions being hidden.
267   ///
268   /// This set is used to suppress redundant diagnostics.
269   llvm::SmallPtrSet<NamedDecl *, 4> HiddenDefinitions;
270 
271   /// FieldCollector - Collects CXXFieldDecls during parsing of C++ classes.
272   OwningPtr<CXXFieldCollector> FieldCollector;
273 
274   typedef llvm::SmallSetVector<const NamedDecl*, 16> NamedDeclSetType;
275 
276   /// \brief Set containing all declared private fields that are not used.
277   NamedDeclSetType UnusedPrivateFields;
278 
279   typedef llvm::SmallPtrSet<const CXXRecordDecl*, 8> RecordDeclSetTy;
280 
281   /// PureVirtualClassDiagSet - a set of class declarations which we have
282   /// emitted a list of pure virtual functions. Used to prevent emitting the
283   /// same list more than once.
284   OwningPtr<RecordDeclSetTy> PureVirtualClassDiagSet;
285 
286   /// ParsingInitForAutoVars - a set of declarations with auto types for which
287   /// we are currently parsing the initializer.
288   llvm::SmallPtrSet<const Decl*, 4> ParsingInitForAutoVars;
289 
290   /// \brief A mapping from external names to the most recent
291   /// locally-scoped external declaration with that name.
292   ///
293   /// This map contains external declarations introduced in local
294   /// scoped, e.g.,
295   ///
296   /// \code
297   /// void f() {
298   ///   void foo(int, int);
299   /// }
300   /// \endcode
301   ///
302   /// Here, the name "foo" will be associated with the declaration on
303   /// "foo" within f. This name is not visible outside of
304   /// "f". However, we still find it in two cases:
305   ///
306   ///   - If we are declaring another external with the name "foo", we
307   ///     can find "foo" as a previous declaration, so that the types
308   ///     of this external declaration can be checked for
309   ///     compatibility.
310   ///
311   ///   - If we would implicitly declare "foo" (e.g., due to a call to
312   ///     "foo" in C when no prototype or definition is visible), then
313   ///     we find this declaration of "foo" and complain that it is
314   ///     not visible.
315   llvm::DenseMap<DeclarationName, NamedDecl *> LocallyScopedExternalDecls;
316 
317   /// \brief Look for a locally scoped external declaration by the given name.
318   llvm::DenseMap<DeclarationName, NamedDecl *>::iterator
319   findLocallyScopedExternalDecl(DeclarationName Name);
320 
321   typedef LazyVector<VarDecl *, ExternalSemaSource,
322                      &ExternalSemaSource::ReadTentativeDefinitions, 2, 2>
323     TentativeDefinitionsType;
324 
325   /// \brief All the tentative definitions encountered in the TU.
326   TentativeDefinitionsType TentativeDefinitions;
327 
328   typedef LazyVector<const DeclaratorDecl *, ExternalSemaSource,
329                      &ExternalSemaSource::ReadUnusedFileScopedDecls, 2, 2>
330     UnusedFileScopedDeclsType;
331 
332   /// \brief The set of file scoped decls seen so far that have not been used
333   /// and must warn if not used. Only contains the first declaration.
334   UnusedFileScopedDeclsType UnusedFileScopedDecls;
335 
336   typedef LazyVector<CXXConstructorDecl *, ExternalSemaSource,
337                      &ExternalSemaSource::ReadDelegatingConstructors, 2, 2>
338     DelegatingCtorDeclsType;
339 
340   /// \brief All the delegating constructors seen so far in the file, used for
341   /// cycle detection at the end of the TU.
342   DelegatingCtorDeclsType DelegatingCtorDecls;
343 
344   /// \brief All the destructors seen during a class definition that had their
345   /// exception spec computation delayed because it depended on an unparsed
346   /// exception spec.
347   SmallVector<CXXDestructorDecl*, 2> DelayedDestructorExceptionSpecs;
348 
349   /// \brief All the overriding destructors seen during a class definition
350   /// (there could be multiple due to nested classes) that had their exception
351   /// spec checks delayed, plus the overridden destructor.
352   SmallVector<std::pair<const CXXDestructorDecl*,
353                               const CXXDestructorDecl*>, 2>
354       DelayedDestructorExceptionSpecChecks;
355 
356   /// \brief Callback to the parser to parse templated functions when needed.
357   typedef void LateTemplateParserCB(void *P, const FunctionDecl *FD);
358   LateTemplateParserCB *LateTemplateParser;
359   void *OpaqueParser;
360 
SetLateTemplateParser(LateTemplateParserCB * LTP,void * P)361   void SetLateTemplateParser(LateTemplateParserCB *LTP, void *P) {
362     LateTemplateParser = LTP;
363     OpaqueParser = P;
364   }
365 
366   class DelayedDiagnostics;
367 
368   class DelayedDiagnosticsState {
369     sema::DelayedDiagnosticPool *SavedPool;
370     friend class Sema::DelayedDiagnostics;
371   };
372   typedef DelayedDiagnosticsState ParsingDeclState;
373   typedef DelayedDiagnosticsState ProcessingContextState;
374 
375   /// A class which encapsulates the logic for delaying diagnostics
376   /// during parsing and other processing.
377   class DelayedDiagnostics {
378     /// \brief The current pool of diagnostics into which delayed
379     /// diagnostics should go.
380     sema::DelayedDiagnosticPool *CurPool;
381 
382   public:
DelayedDiagnostics()383     DelayedDiagnostics() : CurPool(0) {}
384 
385     /// Adds a delayed diagnostic.
386     void add(const sema::DelayedDiagnostic &diag); // in DelayedDiagnostic.h
387 
388     /// Determines whether diagnostics should be delayed.
shouldDelayDiagnostics()389     bool shouldDelayDiagnostics() { return CurPool != 0; }
390 
391     /// Returns the current delayed-diagnostics pool.
getCurrentPool()392     sema::DelayedDiagnosticPool *getCurrentPool() const {
393       return CurPool;
394     }
395 
396     /// Enter a new scope.  Access and deprecation diagnostics will be
397     /// collected in this pool.
push(sema::DelayedDiagnosticPool & pool)398     DelayedDiagnosticsState push(sema::DelayedDiagnosticPool &pool) {
399       DelayedDiagnosticsState state;
400       state.SavedPool = CurPool;
401       CurPool = &pool;
402       return state;
403     }
404 
405     /// Leave a delayed-diagnostic state that was previously pushed.
406     /// Do not emit any of the diagnostics.  This is performed as part
407     /// of the bookkeeping of popping a pool "properly".
popWithoutEmitting(DelayedDiagnosticsState state)408     void popWithoutEmitting(DelayedDiagnosticsState state) {
409       CurPool = state.SavedPool;
410     }
411 
412     /// Enter a new scope where access and deprecation diagnostics are
413     /// not delayed.
pushUndelayed()414     DelayedDiagnosticsState pushUndelayed() {
415       DelayedDiagnosticsState state;
416       state.SavedPool = CurPool;
417       CurPool = 0;
418       return state;
419     }
420 
421     /// Undo a previous pushUndelayed().
popUndelayed(DelayedDiagnosticsState state)422     void popUndelayed(DelayedDiagnosticsState state) {
423       assert(CurPool == NULL);
424       CurPool = state.SavedPool;
425     }
426   } DelayedDiagnostics;
427 
428   /// A RAII object to temporarily push a declaration context.
429   class ContextRAII {
430   private:
431     Sema &S;
432     DeclContext *SavedContext;
433     ProcessingContextState SavedContextState;
434     QualType SavedCXXThisTypeOverride;
435 
436   public:
ContextRAII(Sema & S,DeclContext * ContextToPush)437     ContextRAII(Sema &S, DeclContext *ContextToPush)
438       : S(S), SavedContext(S.CurContext),
439         SavedContextState(S.DelayedDiagnostics.pushUndelayed()),
440         SavedCXXThisTypeOverride(S.CXXThisTypeOverride)
441     {
442       assert(ContextToPush && "pushing null context");
443       S.CurContext = ContextToPush;
444     }
445 
pop()446     void pop() {
447       if (!SavedContext) return;
448       S.CurContext = SavedContext;
449       S.DelayedDiagnostics.popUndelayed(SavedContextState);
450       S.CXXThisTypeOverride = SavedCXXThisTypeOverride;
451       SavedContext = 0;
452     }
453 
~ContextRAII()454     ~ContextRAII() {
455       pop();
456     }
457   };
458 
459   /// WeakUndeclaredIdentifiers - Identifiers contained in
460   /// \#pragma weak before declared. rare. may alias another
461   /// identifier, declared or undeclared
462   llvm::DenseMap<IdentifierInfo*,WeakInfo> WeakUndeclaredIdentifiers;
463 
464   /// ExtnameUndeclaredIdentifiers - Identifiers contained in
465   /// \#pragma redefine_extname before declared.  Used in Solaris system headers
466   /// to define functions that occur in multiple standards to call the version
467   /// in the currently selected standard.
468   llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*> ExtnameUndeclaredIdentifiers;
469 
470 
471   /// \brief Load weak undeclared identifiers from the external source.
472   void LoadExternalWeakUndeclaredIdentifiers();
473 
474   /// WeakTopLevelDecl - Translation-unit scoped declarations generated by
475   /// \#pragma weak during processing of other Decls.
476   /// I couldn't figure out a clean way to generate these in-line, so
477   /// we store them here and handle separately -- which is a hack.
478   /// It would be best to refactor this.
479   SmallVector<Decl*,2> WeakTopLevelDecl;
480 
481   IdentifierResolver IdResolver;
482 
483   /// Translation Unit Scope - useful to Objective-C actions that need
484   /// to lookup file scope declarations in the "ordinary" C decl namespace.
485   /// For example, user-defined classes, built-in "id" type, etc.
486   Scope *TUScope;
487 
488   /// \brief The C++ "std" namespace, where the standard library resides.
489   LazyDeclPtr StdNamespace;
490 
491   /// \brief The C++ "std::bad_alloc" class, which is defined by the C++
492   /// standard library.
493   LazyDeclPtr StdBadAlloc;
494 
495   /// \brief The C++ "std::initializer_list" template, which is defined in
496   /// \<initializer_list>.
497   ClassTemplateDecl *StdInitializerList;
498 
499   /// \brief The C++ "type_info" declaration, which is defined in \<typeinfo>.
500   RecordDecl *CXXTypeInfoDecl;
501 
502   /// \brief The MSVC "_GUID" struct, which is defined in MSVC header files.
503   RecordDecl *MSVCGuidDecl;
504 
505   /// \brief Caches identifiers/selectors for NSFoundation APIs.
506   llvm::OwningPtr<NSAPI> NSAPIObj;
507 
508   /// \brief The declaration of the Objective-C NSNumber class.
509   ObjCInterfaceDecl *NSNumberDecl;
510 
511   /// \brief Pointer to NSNumber type (NSNumber *).
512   QualType NSNumberPointer;
513 
514   /// \brief The Objective-C NSNumber methods used to create NSNumber literals.
515   ObjCMethodDecl *NSNumberLiteralMethods[NSAPI::NumNSNumberLiteralMethods];
516 
517   /// \brief The declaration of the Objective-C NSString class.
518   ObjCInterfaceDecl *NSStringDecl;
519 
520   /// \brief Pointer to NSString type (NSString *).
521   QualType NSStringPointer;
522 
523   /// \brief The declaration of the stringWithUTF8String: method.
524   ObjCMethodDecl *StringWithUTF8StringMethod;
525 
526   /// \brief The declaration of the Objective-C NSArray class.
527   ObjCInterfaceDecl *NSArrayDecl;
528 
529   /// \brief The declaration of the arrayWithObjects:count: method.
530   ObjCMethodDecl *ArrayWithObjectsMethod;
531 
532   /// \brief The declaration of the Objective-C NSDictionary class.
533   ObjCInterfaceDecl *NSDictionaryDecl;
534 
535   /// \brief The declaration of the dictionaryWithObjects:forKeys:count: method.
536   ObjCMethodDecl *DictionaryWithObjectsMethod;
537 
538   /// \brief id<NSCopying> type.
539   QualType QIDNSCopying;
540 
541   /// A flag to remember whether the implicit forms of operator new and delete
542   /// have been declared.
543   bool GlobalNewDeleteDeclared;
544 
545   /// \brief Describes how the expressions currently being parsed are
546   /// evaluated at run-time, if at all.
547   enum ExpressionEvaluationContext {
548     /// \brief The current expression and its subexpressions occur within an
549     /// unevaluated operand (C++11 [expr]p7), such as the subexpression of
550     /// \c sizeof, where the type of the expression may be significant but
551     /// no code will be generated to evaluate the value of the expression at
552     /// run time.
553     Unevaluated,
554 
555     /// \brief The current context is "potentially evaluated" in C++11 terms,
556     /// but the expression is evaluated at compile-time (like the values of
557     /// cases in a switch statment).
558     ConstantEvaluated,
559 
560     /// \brief The current expression is potentially evaluated at run time,
561     /// which means that code may be generated to evaluate the value of the
562     /// expression at run time.
563     PotentiallyEvaluated,
564 
565     /// \brief The current expression is potentially evaluated, but any
566     /// declarations referenced inside that expression are only used if
567     /// in fact the current expression is used.
568     ///
569     /// This value is used when parsing default function arguments, for which
570     /// we would like to provide diagnostics (e.g., passing non-POD arguments
571     /// through varargs) but do not want to mark declarations as "referenced"
572     /// until the default argument is used.
573     PotentiallyEvaluatedIfUsed
574   };
575 
576   /// \brief Data structure used to record current or nested
577   /// expression evaluation contexts.
578   struct ExpressionEvaluationContextRecord {
579     /// \brief The expression evaluation context.
580     ExpressionEvaluationContext Context;
581 
582     /// \brief Whether the enclosing context needed a cleanup.
583     bool ParentNeedsCleanups;
584 
585     /// \brief Whether we are in a decltype expression.
586     bool IsDecltype;
587 
588     /// \brief The number of active cleanup objects when we entered
589     /// this expression evaluation context.
590     unsigned NumCleanupObjects;
591 
592     llvm::SmallPtrSet<Expr*, 8> SavedMaybeODRUseExprs;
593 
594     /// \brief The lambdas that are present within this context, if it
595     /// is indeed an unevaluated context.
596     llvm::SmallVector<LambdaExpr *, 2> Lambdas;
597 
598     /// \brief The declaration that provides context for the lambda expression
599     /// if the normal declaration context does not suffice, e.g., in a
600     /// default function argument.
601     Decl *LambdaContextDecl;
602 
603     /// \brief The context information used to mangle lambda expressions
604     /// within this context.
605     ///
606     /// This mangling information is allocated lazily, since most contexts
607     /// do not have lambda expressions.
608     LambdaMangleContext *LambdaMangle;
609 
610     /// \brief If we are processing a decltype type, a set of call expressions
611     /// for which we have deferred checking the completeness of the return type.
612     llvm::SmallVector<CallExpr*, 8> DelayedDecltypeCalls;
613 
614     /// \brief If we are processing a decltype type, a set of temporary binding
615     /// expressions for which we have deferred checking the destructor.
616     llvm::SmallVector<CXXBindTemporaryExpr*, 8> DelayedDecltypeBinds;
617 
ExpressionEvaluationContextRecordExpressionEvaluationContextRecord618     ExpressionEvaluationContextRecord(ExpressionEvaluationContext Context,
619                                       unsigned NumCleanupObjects,
620                                       bool ParentNeedsCleanups,
621                                       Decl *LambdaContextDecl,
622                                       bool IsDecltype)
623       : Context(Context), ParentNeedsCleanups(ParentNeedsCleanups),
624         IsDecltype(IsDecltype), NumCleanupObjects(NumCleanupObjects),
625         LambdaContextDecl(LambdaContextDecl), LambdaMangle() { }
626 
~ExpressionEvaluationContextRecordExpressionEvaluationContextRecord627     ~ExpressionEvaluationContextRecord() {
628       delete LambdaMangle;
629     }
630 
631     /// \brief Retrieve the mangling context for lambdas.
getLambdaMangleContextExpressionEvaluationContextRecord632     LambdaMangleContext &getLambdaMangleContext() {
633       assert(LambdaContextDecl && "Need to have a lambda context declaration");
634       if (!LambdaMangle)
635         LambdaMangle = new LambdaMangleContext;
636       return *LambdaMangle;
637     }
638   };
639 
640   /// A stack of expression evaluation contexts.
641   SmallVector<ExpressionEvaluationContextRecord, 8> ExprEvalContexts;
642 
643   /// SpecialMemberOverloadResult - The overloading result for a special member
644   /// function.
645   ///
646   /// This is basically a wrapper around PointerIntPair. The lowest bits of the
647   /// integer are used to determine whether overload resolution succeeded.
648   class SpecialMemberOverloadResult : public llvm::FastFoldingSetNode {
649   public:
650     enum Kind {
651       NoMemberOrDeleted,
652       Ambiguous,
653       Success
654     };
655 
656   private:
657     llvm::PointerIntPair<CXXMethodDecl*, 2> Pair;
658 
659   public:
SpecialMemberOverloadResult(const llvm::FoldingSetNodeID & ID)660     SpecialMemberOverloadResult(const llvm::FoldingSetNodeID &ID)
661       : FastFoldingSetNode(ID)
662     {}
663 
getMethod()664     CXXMethodDecl *getMethod() const { return Pair.getPointer(); }
setMethod(CXXMethodDecl * MD)665     void setMethod(CXXMethodDecl *MD) { Pair.setPointer(MD); }
666 
getKind()667     Kind getKind() const { return static_cast<Kind>(Pair.getInt()); }
setKind(Kind K)668     void setKind(Kind K) { Pair.setInt(K); }
669   };
670 
671   /// \brief A cache of special member function overload resolution results
672   /// for C++ records.
673   llvm::FoldingSet<SpecialMemberOverloadResult> SpecialMemberCache;
674 
675   /// \brief The kind of translation unit we are processing.
676   ///
677   /// When we're processing a complete translation unit, Sema will perform
678   /// end-of-translation-unit semantic tasks (such as creating
679   /// initializers for tentative definitions in C) once parsing has
680   /// completed. Modules and precompiled headers perform different kinds of
681   /// checks.
682   TranslationUnitKind TUKind;
683 
684   llvm::BumpPtrAllocator BumpAlloc;
685 
686   /// \brief The number of SFINAE diagnostics that have been trapped.
687   unsigned NumSFINAEErrors;
688 
689   typedef llvm::DenseMap<ParmVarDecl *, SmallVector<ParmVarDecl *, 1> >
690     UnparsedDefaultArgInstantiationsMap;
691 
692   /// \brief A mapping from parameters with unparsed default arguments to the
693   /// set of instantiations of each parameter.
694   ///
695   /// This mapping is a temporary data structure used when parsing
696   /// nested class templates or nested classes of class templates,
697   /// where we might end up instantiating an inner class before the
698   /// default arguments of its methods have been parsed.
699   UnparsedDefaultArgInstantiationsMap UnparsedDefaultArgInstantiations;
700 
701   // Contains the locations of the beginning of unparsed default
702   // argument locations.
703   llvm::DenseMap<ParmVarDecl *,SourceLocation> UnparsedDefaultArgLocs;
704 
705   /// UndefinedInternals - all the used, undefined objects with
706   /// internal linkage in this translation unit.
707   llvm::DenseMap<NamedDecl*, SourceLocation> UndefinedInternals;
708 
709   typedef std::pair<ObjCMethodList, ObjCMethodList> GlobalMethods;
710   typedef llvm::DenseMap<Selector, GlobalMethods> GlobalMethodPool;
711 
712   /// Method Pool - allows efficient lookup when typechecking messages to "id".
713   /// We need to maintain a list, since selectors can have differing signatures
714   /// across classes. In Cocoa, this happens to be extremely uncommon (only 1%
715   /// of selectors are "overloaded").
716   GlobalMethodPool MethodPool;
717 
718   /// Method selectors used in a \@selector expression. Used for implementation
719   /// of -Wselector.
720   llvm::DenseMap<Selector, SourceLocation> ReferencedSelectors;
721 
722   void ReadMethodPool(Selector Sel);
723 
724   /// Private Helper predicate to check for 'self'.
725   bool isSelfExpr(Expr *RExpr);
726 
727   /// \brief Cause the active diagnostic on the DiagosticsEngine to be
728   /// emitted. This is closely coupled to the SemaDiagnosticBuilder class and
729   /// should not be used elsewhere.
730   void EmitCurrentDiagnostic(unsigned DiagID);
731 
732 public:
733   Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer,
734        TranslationUnitKind TUKind = TU_Complete,
735        CodeCompleteConsumer *CompletionConsumer = 0);
736   ~Sema();
737 
738   /// \brief Perform initialization that occurs after the parser has been
739   /// initialized but before it parses anything.
740   void Initialize();
741 
getLangOpts()742   const LangOptions &getLangOpts() const { return LangOpts; }
getOpenCLOptions()743   OpenCLOptions &getOpenCLOptions() { return OpenCLFeatures; }
getFPOptions()744   FPOptions     &getFPOptions() { return FPFeatures; }
745 
getDiagnostics()746   DiagnosticsEngine &getDiagnostics() const { return Diags; }
getSourceManager()747   SourceManager &getSourceManager() const { return SourceMgr; }
748   const TargetAttributesSema &getTargetAttributesSema() const;
getPreprocessor()749   Preprocessor &getPreprocessor() const { return PP; }
getASTContext()750   ASTContext &getASTContext() const { return Context; }
getASTConsumer()751   ASTConsumer &getASTConsumer() const { return Consumer; }
752   ASTMutationListener *getASTMutationListener() const;
753 
754   void PrintStats() const;
755 
756   /// \brief Helper class that creates diagnostics with optional
757   /// template instantiation stacks.
758   ///
759   /// This class provides a wrapper around the basic DiagnosticBuilder
760   /// class that emits diagnostics. SemaDiagnosticBuilder is
761   /// responsible for emitting the diagnostic (as DiagnosticBuilder
762   /// does) and, if the diagnostic comes from inside a template
763   /// instantiation, printing the template instantiation stack as
764   /// well.
765   class SemaDiagnosticBuilder : public DiagnosticBuilder {
766     Sema &SemaRef;
767     unsigned DiagID;
768 
769   public:
SemaDiagnosticBuilder(DiagnosticBuilder & DB,Sema & SemaRef,unsigned DiagID)770     SemaDiagnosticBuilder(DiagnosticBuilder &DB, Sema &SemaRef, unsigned DiagID)
771       : DiagnosticBuilder(DB), SemaRef(SemaRef), DiagID(DiagID) { }
772 
~SemaDiagnosticBuilder()773     ~SemaDiagnosticBuilder() {
774       // If we aren't active, there is nothing to do.
775       if (!isActive()) return;
776 
777       // Otherwise, we need to emit the diagnostic. First flush the underlying
778       // DiagnosticBuilder data, and clear the diagnostic builder itself so it
779       // won't emit the diagnostic in its own destructor.
780       //
781       // This seems wasteful, in that as written the DiagnosticBuilder dtor will
782       // do its own needless checks to see if the diagnostic needs to be
783       // emitted. However, because we take care to ensure that the builder
784       // objects never escape, a sufficiently smart compiler will be able to
785       // eliminate that code.
786       FlushCounts();
787       Clear();
788 
789       // Dispatch to Sema to emit the diagnostic.
790       SemaRef.EmitCurrentDiagnostic(DiagID);
791     }
792   };
793 
794   /// \brief Emit a diagnostic.
Diag(SourceLocation Loc,unsigned DiagID)795   SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID) {
796     DiagnosticBuilder DB = Diags.Report(Loc, DiagID);
797     return SemaDiagnosticBuilder(DB, *this, DiagID);
798   }
799 
800   /// \brief Emit a partial diagnostic.
801   SemaDiagnosticBuilder Diag(SourceLocation Loc, const PartialDiagnostic& PD);
802 
803   /// \brief Build a partial diagnostic.
804   PartialDiagnostic PDiag(unsigned DiagID = 0); // in SemaInternal.h
805 
806   bool findMacroSpelling(SourceLocation &loc, StringRef name);
807 
808   /// \brief Get a string to suggest for zero-initialization of a type.
809   std::string getFixItZeroInitializerForType(QualType T) const;
810   std::string getFixItZeroLiteralForType(QualType T) const;
811 
Owned(Expr * E)812   ExprResult Owned(Expr* E) { return E; }
Owned(ExprResult R)813   ExprResult Owned(ExprResult R) { return R; }
Owned(Stmt * S)814   StmtResult Owned(Stmt* S) { return S; }
815 
816   void ActOnEndOfTranslationUnit();
817 
818   void CheckDelegatingCtorCycles();
819 
820   Scope *getScopeForContext(DeclContext *Ctx);
821 
822   void PushFunctionScope();
823   void PushBlockScope(Scope *BlockScope, BlockDecl *Block);
824   void PushLambdaScope(CXXRecordDecl *Lambda, CXXMethodDecl *CallOperator);
825   void PopFunctionScopeInfo(const sema::AnalysisBasedWarnings::Policy *WP =0,
826                             const Decl *D = 0, const BlockExpr *blkExpr = 0);
827 
getCurFunction()828   sema::FunctionScopeInfo *getCurFunction() const {
829     return FunctionScopes.back();
830   }
831 
832   void PushCompoundScope();
833   void PopCompoundScope();
834 
835   sema::CompoundScopeInfo &getCurCompoundScope() const;
836 
837   bool hasAnyUnrecoverableErrorsInThisFunction() const;
838 
839   /// \brief Retrieve the current block, if any.
840   sema::BlockScopeInfo *getCurBlock();
841 
842   /// \brief Retrieve the current lambda expression, if any.
843   sema::LambdaScopeInfo *getCurLambda();
844 
845   /// WeakTopLevelDeclDecls - access to \#pragma weak-generated Decls
WeakTopLevelDecls()846   SmallVector<Decl*,2> &WeakTopLevelDecls() { return WeakTopLevelDecl; }
847 
848   void ActOnComment(SourceRange Comment);
849 
850   //===--------------------------------------------------------------------===//
851   // Type Analysis / Processing: SemaType.cpp.
852   //
853 
854   QualType BuildQualifiedType(QualType T, SourceLocation Loc, Qualifiers Qs);
BuildQualifiedType(QualType T,SourceLocation Loc,unsigned CVR)855   QualType BuildQualifiedType(QualType T, SourceLocation Loc, unsigned CVR) {
856     return BuildQualifiedType(T, Loc, Qualifiers::fromCVRMask(CVR));
857   }
858   QualType BuildPointerType(QualType T,
859                             SourceLocation Loc, DeclarationName Entity);
860   QualType BuildReferenceType(QualType T, bool LValueRef,
861                               SourceLocation Loc, DeclarationName Entity);
862   QualType BuildArrayType(QualType T, ArrayType::ArraySizeModifier ASM,
863                           Expr *ArraySize, unsigned Quals,
864                           SourceRange Brackets, DeclarationName Entity);
865   QualType BuildExtVectorType(QualType T, Expr *ArraySize,
866                               SourceLocation AttrLoc);
867   QualType BuildFunctionType(QualType T,
868                              QualType *ParamTypes, unsigned NumParamTypes,
869                              bool Variadic, bool HasTrailingReturn,
870                              unsigned Quals, RefQualifierKind RefQualifier,
871                              SourceLocation Loc, DeclarationName Entity,
872                              FunctionType::ExtInfo Info);
873   QualType BuildMemberPointerType(QualType T, QualType Class,
874                                   SourceLocation Loc,
875                                   DeclarationName Entity);
876   QualType BuildBlockPointerType(QualType T,
877                                  SourceLocation Loc, DeclarationName Entity);
878   QualType BuildParenType(QualType T);
879   QualType BuildAtomicType(QualType T, SourceLocation Loc);
880 
881   TypeSourceInfo *GetTypeForDeclarator(Declarator &D, Scope *S);
882   TypeSourceInfo *GetTypeForDeclaratorCast(Declarator &D, QualType FromTy);
883   TypeSourceInfo *GetTypeSourceInfoForDeclarator(Declarator &D, QualType T,
884                                                TypeSourceInfo *ReturnTypeInfo);
885 
886   /// \brief Package the given type and TSI into a ParsedType.
887   ParsedType CreateParsedType(QualType T, TypeSourceInfo *TInfo);
888   DeclarationNameInfo GetNameForDeclarator(Declarator &D);
889   DeclarationNameInfo GetNameFromUnqualifiedId(const UnqualifiedId &Name);
890   static QualType GetTypeFromParser(ParsedType Ty, TypeSourceInfo **TInfo = 0);
891   CanThrowResult canThrow(const Expr *E);
892   const FunctionProtoType *ResolveExceptionSpec(SourceLocation Loc,
893                                                 const FunctionProtoType *FPT);
894   bool CheckSpecifiedExceptionType(QualType T, const SourceRange &Range);
895   bool CheckDistantExceptionSpec(QualType T);
896   bool CheckEquivalentExceptionSpec(FunctionDecl *Old, FunctionDecl *New);
897   bool CheckEquivalentExceptionSpec(
898       const FunctionProtoType *Old, SourceLocation OldLoc,
899       const FunctionProtoType *New, SourceLocation NewLoc);
900   bool CheckEquivalentExceptionSpec(
901       const PartialDiagnostic &DiagID, const PartialDiagnostic & NoteID,
902       const FunctionProtoType *Old, SourceLocation OldLoc,
903       const FunctionProtoType *New, SourceLocation NewLoc,
904       bool *MissingExceptionSpecification = 0,
905       bool *MissingEmptyExceptionSpecification = 0,
906       bool AllowNoexceptAllMatchWithNoSpec = false,
907       bool IsOperatorNew = false);
908   bool CheckExceptionSpecSubset(
909       const PartialDiagnostic &DiagID, const PartialDiagnostic & NoteID,
910       const FunctionProtoType *Superset, SourceLocation SuperLoc,
911       const FunctionProtoType *Subset, SourceLocation SubLoc);
912   bool CheckParamExceptionSpec(const PartialDiagnostic & NoteID,
913       const FunctionProtoType *Target, SourceLocation TargetLoc,
914       const FunctionProtoType *Source, SourceLocation SourceLoc);
915 
916   TypeResult ActOnTypeName(Scope *S, Declarator &D);
917 
918   /// \brief The parser has parsed the context-sensitive type 'instancetype'
919   /// in an Objective-C message declaration. Return the appropriate type.
920   ParsedType ActOnObjCInstanceType(SourceLocation Loc);
921 
922   /// \brief Abstract class used to diagnose incomplete types.
923   struct TypeDiagnoser {
924     bool Suppressed;
925 
SuppressedTypeDiagnoser926     TypeDiagnoser(bool Suppressed = false) : Suppressed(Suppressed) { }
927 
928     virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) = 0;
~TypeDiagnoserTypeDiagnoser929     virtual ~TypeDiagnoser() {}
930   };
931 
getPrintable(int I)932   static int getPrintable(int I) { return I; }
getPrintable(unsigned I)933   static unsigned getPrintable(unsigned I) { return I; }
getPrintable(bool B)934   static bool getPrintable(bool B) { return B; }
getPrintable(const char * S)935   static const char * getPrintable(const char *S) { return S; }
getPrintable(StringRef S)936   static StringRef getPrintable(StringRef S) { return S; }
getPrintable(const std::string & S)937   static const std::string &getPrintable(const std::string &S) { return S; }
getPrintable(const IdentifierInfo * II)938   static const IdentifierInfo *getPrintable(const IdentifierInfo *II) {
939     return II;
940   }
getPrintable(DeclarationName N)941   static DeclarationName getPrintable(DeclarationName N) { return N; }
getPrintable(QualType T)942   static QualType getPrintable(QualType T) { return T; }
getPrintable(SourceRange R)943   static SourceRange getPrintable(SourceRange R) { return R; }
getPrintable(SourceLocation L)944   static SourceRange getPrintable(SourceLocation L) { return L; }
getPrintable(Expr * E)945   static SourceRange getPrintable(Expr *E) { return E->getSourceRange(); }
getPrintable(TypeLoc TL)946   static SourceRange getPrintable(TypeLoc TL) { return TL.getSourceRange();}
947 
948   template<typename T1>
949   class BoundTypeDiagnoser1 : public TypeDiagnoser {
950     unsigned DiagID;
951     const T1 &Arg1;
952 
953   public:
BoundTypeDiagnoser1(unsigned DiagID,const T1 & Arg1)954     BoundTypeDiagnoser1(unsigned DiagID, const T1 &Arg1)
955       : TypeDiagnoser(DiagID == 0), DiagID(DiagID), Arg1(Arg1) { }
diagnose(Sema & S,SourceLocation Loc,QualType T)956     virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) {
957       if (Suppressed) return;
958       S.Diag(Loc, DiagID) << getPrintable(Arg1) << T;
959     }
960 
~BoundTypeDiagnoser1()961     virtual ~BoundTypeDiagnoser1() { }
962   };
963 
964   template<typename T1, typename T2>
965   class BoundTypeDiagnoser2 : public TypeDiagnoser {
966     unsigned DiagID;
967     const T1 &Arg1;
968     const T2 &Arg2;
969 
970   public:
BoundTypeDiagnoser2(unsigned DiagID,const T1 & Arg1,const T2 & Arg2)971     BoundTypeDiagnoser2(unsigned DiagID, const T1 &Arg1,
972                                   const T2 &Arg2)
973       : TypeDiagnoser(DiagID == 0), DiagID(DiagID), Arg1(Arg1),
974         Arg2(Arg2) { }
975 
diagnose(Sema & S,SourceLocation Loc,QualType T)976     virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) {
977       if (Suppressed) return;
978       S.Diag(Loc, DiagID) << getPrintable(Arg1) << getPrintable(Arg2) << T;
979     }
980 
~BoundTypeDiagnoser2()981     virtual ~BoundTypeDiagnoser2() { }
982   };
983 
984   template<typename T1, typename T2, typename T3>
985   class BoundTypeDiagnoser3 : public TypeDiagnoser {
986     unsigned DiagID;
987     const T1 &Arg1;
988     const T2 &Arg2;
989     const T3 &Arg3;
990 
991   public:
BoundTypeDiagnoser3(unsigned DiagID,const T1 & Arg1,const T2 & Arg2,const T3 & Arg3)992     BoundTypeDiagnoser3(unsigned DiagID, const T1 &Arg1,
993                                   const T2 &Arg2, const T3 &Arg3)
994     : TypeDiagnoser(DiagID == 0), DiagID(DiagID), Arg1(Arg1),
995       Arg2(Arg2), Arg3(Arg3) { }
996 
diagnose(Sema & S,SourceLocation Loc,QualType T)997     virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) {
998       if (Suppressed) return;
999       S.Diag(Loc, DiagID)
1000         << getPrintable(Arg1) << getPrintable(Arg2) << getPrintable(Arg3) << T;
1001     }
1002 
~BoundTypeDiagnoser3()1003     virtual ~BoundTypeDiagnoser3() { }
1004   };
1005 
1006   bool RequireCompleteType(SourceLocation Loc, QualType T,
1007                            TypeDiagnoser &Diagnoser);
1008   bool RequireCompleteType(SourceLocation Loc, QualType T,
1009                            unsigned DiagID);
1010 
1011   template<typename T1>
RequireCompleteType(SourceLocation Loc,QualType T,unsigned DiagID,const T1 & Arg1)1012   bool RequireCompleteType(SourceLocation Loc, QualType T,
1013                            unsigned DiagID, const T1 &Arg1) {
1014     BoundTypeDiagnoser1<T1> Diagnoser(DiagID, Arg1);
1015     return RequireCompleteType(Loc, T, Diagnoser);
1016   }
1017 
1018   template<typename T1, typename T2>
RequireCompleteType(SourceLocation Loc,QualType T,unsigned DiagID,const T1 & Arg1,const T2 & Arg2)1019   bool RequireCompleteType(SourceLocation Loc, QualType T,
1020                            unsigned DiagID, const T1 &Arg1, const T2 &Arg2) {
1021     BoundTypeDiagnoser2<T1, T2> Diagnoser(DiagID, Arg1, Arg2);
1022     return RequireCompleteType(Loc, T, Diagnoser);
1023   }
1024 
1025   template<typename T1, typename T2, typename T3>
RequireCompleteType(SourceLocation Loc,QualType T,unsigned DiagID,const T1 & Arg1,const T2 & Arg2,const T3 & Arg3)1026   bool RequireCompleteType(SourceLocation Loc, QualType T,
1027                            unsigned DiagID, const T1 &Arg1, const T2 &Arg2,
1028                            const T3 &Arg3) {
1029     BoundTypeDiagnoser3<T1, T2, T3> Diagnoser(DiagID, Arg1, Arg2,
1030                                                         Arg3);
1031     return RequireCompleteType(Loc, T, Diagnoser);
1032   }
1033 
1034   bool RequireCompleteExprType(Expr *E, TypeDiagnoser &Diagnoser);
1035   bool RequireCompleteExprType(Expr *E, unsigned DiagID);
1036 
1037   template<typename T1>
RequireCompleteExprType(Expr * E,unsigned DiagID,const T1 & Arg1)1038   bool RequireCompleteExprType(Expr *E, unsigned DiagID, const T1 &Arg1) {
1039     BoundTypeDiagnoser1<T1> Diagnoser(DiagID, Arg1);
1040     return RequireCompleteExprType(E, Diagnoser);
1041   }
1042 
1043   template<typename T1, typename T2>
RequireCompleteExprType(Expr * E,unsigned DiagID,const T1 & Arg1,const T2 & Arg2)1044   bool RequireCompleteExprType(Expr *E, unsigned DiagID, const T1 &Arg1,
1045                                const T2 &Arg2) {
1046     BoundTypeDiagnoser2<T1, T2> Diagnoser(DiagID, Arg1, Arg2);
1047     return RequireCompleteExprType(E, Diagnoser);
1048   }
1049 
1050   template<typename T1, typename T2, typename T3>
RequireCompleteExprType(Expr * E,unsigned DiagID,const T1 & Arg1,const T2 & Arg2,const T3 & Arg3)1051   bool RequireCompleteExprType(Expr *E, unsigned DiagID, const T1 &Arg1,
1052                                const T2 &Arg2, const T3 &Arg3) {
1053     BoundTypeDiagnoser3<T1, T2, T3> Diagnoser(DiagID, Arg1, Arg2,
1054                                                         Arg3);
1055     return RequireCompleteExprType(E, Diagnoser);
1056   }
1057 
1058   bool RequireLiteralType(SourceLocation Loc, QualType T,
1059                           TypeDiagnoser &Diagnoser);
1060   bool RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID);
1061 
1062   template<typename T1>
RequireLiteralType(SourceLocation Loc,QualType T,unsigned DiagID,const T1 & Arg1)1063   bool RequireLiteralType(SourceLocation Loc, QualType T,
1064                           unsigned DiagID, const T1 &Arg1) {
1065     BoundTypeDiagnoser1<T1> Diagnoser(DiagID, Arg1);
1066     return RequireLiteralType(Loc, T, Diagnoser);
1067   }
1068 
1069   template<typename T1, typename T2>
RequireLiteralType(SourceLocation Loc,QualType T,unsigned DiagID,const T1 & Arg1,const T2 & Arg2)1070   bool RequireLiteralType(SourceLocation Loc, QualType T,
1071                           unsigned DiagID, const T1 &Arg1, const T2 &Arg2) {
1072     BoundTypeDiagnoser2<T1, T2> Diagnoser(DiagID, Arg1, Arg2);
1073     return RequireLiteralType(Loc, T, Diagnoser);
1074   }
1075 
1076   template<typename T1, typename T2, typename T3>
RequireLiteralType(SourceLocation Loc,QualType T,unsigned DiagID,const T1 & Arg1,const T2 & Arg2,const T3 & Arg3)1077   bool RequireLiteralType(SourceLocation Loc, QualType T,
1078                           unsigned DiagID, const T1 &Arg1, const T2 &Arg2,
1079                           const T3 &Arg3) {
1080     BoundTypeDiagnoser3<T1, T2, T3> Diagnoser(DiagID, Arg1, Arg2,
1081                                                         Arg3);
1082     return RequireLiteralType(Loc, T, Diagnoser);
1083   }
1084 
1085   QualType getElaboratedType(ElaboratedTypeKeyword Keyword,
1086                              const CXXScopeSpec &SS, QualType T);
1087 
1088   QualType BuildTypeofExprType(Expr *E, SourceLocation Loc);
1089   QualType BuildDecltypeType(Expr *E, SourceLocation Loc);
1090   QualType BuildUnaryTransformType(QualType BaseType,
1091                                    UnaryTransformType::UTTKind UKind,
1092                                    SourceLocation Loc);
1093 
1094   //===--------------------------------------------------------------------===//
1095   // Symbol table / Decl tracking callbacks: SemaDecl.cpp.
1096   //
1097 
1098   /// List of decls defined in a function prototype. This contains EnumConstants
1099   /// that incorrectly end up in translation unit scope because there is no
1100   /// function to pin them on. ActOnFunctionDeclarator reads this list and patches
1101   /// them into the FunctionDecl.
1102   std::vector<NamedDecl*> DeclsInPrototypeScope;
1103   /// Nonzero if we are currently parsing a function declarator. This is a counter
1104   /// as opposed to a boolean so we can deal with nested function declarators
1105   /// such as:
1106   ///     void f(void (*g)(), ...)
1107   unsigned InFunctionDeclarator;
1108 
1109   DeclGroupPtrTy ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType = 0);
1110 
1111   void DiagnoseUseOfUnimplementedSelectors();
1112 
1113   bool isSimpleTypeSpecifier(tok::TokenKind Kind) const;
1114 
1115   ParsedType getTypeName(IdentifierInfo &II, SourceLocation NameLoc,
1116                          Scope *S, CXXScopeSpec *SS = 0,
1117                          bool isClassName = false,
1118                          bool HasTrailingDot = false,
1119                          ParsedType ObjectType = ParsedType(),
1120                          bool IsCtorOrDtorName = false,
1121                          bool WantNontrivialTypeSourceInfo = false,
1122                          IdentifierInfo **CorrectedII = 0);
1123   TypeSpecifierType isTagName(IdentifierInfo &II, Scope *S);
1124   bool isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S);
1125   bool DiagnoseUnknownTypeName(IdentifierInfo *&II,
1126                                SourceLocation IILoc,
1127                                Scope *S,
1128                                CXXScopeSpec *SS,
1129                                ParsedType &SuggestedType);
1130 
1131   /// \brief Describes the result of the name lookup and resolution performed
1132   /// by \c ClassifyName().
1133   enum NameClassificationKind {
1134     NC_Unknown,
1135     NC_Error,
1136     NC_Keyword,
1137     NC_Type,
1138     NC_Expression,
1139     NC_NestedNameSpecifier,
1140     NC_TypeTemplate,
1141     NC_FunctionTemplate
1142   };
1143 
1144   class NameClassification {
1145     NameClassificationKind Kind;
1146     ExprResult Expr;
1147     TemplateName Template;
1148     ParsedType Type;
1149     const IdentifierInfo *Keyword;
1150 
NameClassification(NameClassificationKind Kind)1151     explicit NameClassification(NameClassificationKind Kind) : Kind(Kind) {}
1152 
1153   public:
NameClassification(ExprResult Expr)1154     NameClassification(ExprResult Expr) : Kind(NC_Expression), Expr(Expr) {}
1155 
NameClassification(ParsedType Type)1156     NameClassification(ParsedType Type) : Kind(NC_Type), Type(Type) {}
1157 
NameClassification(const IdentifierInfo * Keyword)1158     NameClassification(const IdentifierInfo *Keyword)
1159       : Kind(NC_Keyword), Keyword(Keyword) { }
1160 
Error()1161     static NameClassification Error() {
1162       return NameClassification(NC_Error);
1163     }
1164 
Unknown()1165     static NameClassification Unknown() {
1166       return NameClassification(NC_Unknown);
1167     }
1168 
NestedNameSpecifier()1169     static NameClassification NestedNameSpecifier() {
1170       return NameClassification(NC_NestedNameSpecifier);
1171     }
1172 
TypeTemplate(TemplateName Name)1173     static NameClassification TypeTemplate(TemplateName Name) {
1174       NameClassification Result(NC_TypeTemplate);
1175       Result.Template = Name;
1176       return Result;
1177     }
1178 
FunctionTemplate(TemplateName Name)1179     static NameClassification FunctionTemplate(TemplateName Name) {
1180       NameClassification Result(NC_FunctionTemplate);
1181       Result.Template = Name;
1182       return Result;
1183     }
1184 
getKind()1185     NameClassificationKind getKind() const { return Kind; }
1186 
getType()1187     ParsedType getType() const {
1188       assert(Kind == NC_Type);
1189       return Type;
1190     }
1191 
getExpression()1192     ExprResult getExpression() const {
1193       assert(Kind == NC_Expression);
1194       return Expr;
1195     }
1196 
getTemplateName()1197     TemplateName getTemplateName() const {
1198       assert(Kind == NC_TypeTemplate || Kind == NC_FunctionTemplate);
1199       return Template;
1200     }
1201 
getTemplateNameKind()1202     TemplateNameKind getTemplateNameKind() const {
1203       assert(Kind == NC_TypeTemplate || Kind == NC_FunctionTemplate);
1204       return Kind == NC_TypeTemplate? TNK_Type_template : TNK_Function_template;
1205     }
1206   };
1207 
1208   /// \brief Perform name lookup on the given name, classifying it based on
1209   /// the results of name lookup and the following token.
1210   ///
1211   /// This routine is used by the parser to resolve identifiers and help direct
1212   /// parsing. When the identifier cannot be found, this routine will attempt
1213   /// to correct the typo and classify based on the resulting name.
1214   ///
1215   /// \param S The scope in which we're performing name lookup.
1216   ///
1217   /// \param SS The nested-name-specifier that precedes the name.
1218   ///
1219   /// \param Name The identifier. If typo correction finds an alternative name,
1220   /// this pointer parameter will be updated accordingly.
1221   ///
1222   /// \param NameLoc The location of the identifier.
1223   ///
1224   /// \param NextToken The token following the identifier. Used to help
1225   /// disambiguate the name.
1226   ///
1227   /// \param IsAddressOfOperand True if this name is the operand of a unary
1228   ///        address of ('&') expression, assuming it is classified as an
1229   ///        expression.
1230   ///
1231   /// \param CCC The correction callback, if typo correction is desired.
1232   NameClassification ClassifyName(Scope *S,
1233                                   CXXScopeSpec &SS,
1234                                   IdentifierInfo *&Name,
1235                                   SourceLocation NameLoc,
1236                                   const Token &NextToken,
1237                                   bool IsAddressOfOperand,
1238                                   CorrectionCandidateCallback *CCC = 0);
1239 
1240   Decl *ActOnDeclarator(Scope *S, Declarator &D);
1241 
1242   Decl *HandleDeclarator(Scope *S, Declarator &D,
1243                          MultiTemplateParamsArg TemplateParameterLists);
1244   void RegisterLocallyScopedExternCDecl(NamedDecl *ND,
1245                                         const LookupResult &Previous,
1246                                         Scope *S);
1247   bool DiagnoseClassNameShadow(DeclContext *DC, DeclarationNameInfo Info);
1248   bool diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
1249                                     DeclarationName Name,
1250                                     SourceLocation Loc);
1251   void DiagnoseFunctionSpecifiers(Declarator& D);
1252   void CheckShadow(Scope *S, VarDecl *D, const LookupResult& R);
1253   void CheckShadow(Scope *S, VarDecl *D);
1254   void CheckCastAlign(Expr *Op, QualType T, SourceRange TRange);
1255   void CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *D);
1256   NamedDecl* ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
1257                                     TypeSourceInfo *TInfo,
1258                                     LookupResult &Previous);
1259   NamedDecl* ActOnTypedefNameDecl(Scope* S, DeclContext* DC, TypedefNameDecl *D,
1260                                   LookupResult &Previous, bool &Redeclaration);
1261   NamedDecl* ActOnVariableDeclarator(Scope* S, Declarator& D, DeclContext* DC,
1262                                      TypeSourceInfo *TInfo,
1263                                      LookupResult &Previous,
1264                                      MultiTemplateParamsArg TemplateParamLists);
1265   // Returns true if the variable declaration is a redeclaration
1266   bool CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous);
1267   void CheckCompleteVariableDeclaration(VarDecl *var);
1268   void ActOnStartFunctionDeclarator();
1269   void ActOnEndFunctionDeclarator();
1270   NamedDecl* ActOnFunctionDeclarator(Scope* S, Declarator& D, DeclContext* DC,
1271                                      TypeSourceInfo *TInfo,
1272                                      LookupResult &Previous,
1273                                      MultiTemplateParamsArg TemplateParamLists,
1274                                      bool &AddToScope);
1275   bool AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD);
1276 
1277   bool CheckConstexprFunctionDecl(const FunctionDecl *FD);
1278   bool CheckConstexprFunctionBody(const FunctionDecl *FD, Stmt *Body);
1279 
1280   void DiagnoseHiddenVirtualMethods(CXXRecordDecl *DC, CXXMethodDecl *MD);
1281   // Returns true if the function declaration is a redeclaration
1282   bool CheckFunctionDeclaration(Scope *S,
1283                                 FunctionDecl *NewFD, LookupResult &Previous,
1284                                 bool IsExplicitSpecialization);
1285   void CheckMain(FunctionDecl *FD, const DeclSpec &D);
1286   Decl *ActOnParamDeclarator(Scope *S, Declarator &D);
1287   ParmVarDecl *BuildParmVarDeclForTypedef(DeclContext *DC,
1288                                           SourceLocation Loc,
1289                                           QualType T);
1290   ParmVarDecl *CheckParameter(DeclContext *DC, SourceLocation StartLoc,
1291                               SourceLocation NameLoc, IdentifierInfo *Name,
1292                               QualType T, TypeSourceInfo *TSInfo,
1293                               StorageClass SC, StorageClass SCAsWritten);
1294   void ActOnParamDefaultArgument(Decl *param,
1295                                  SourceLocation EqualLoc,
1296                                  Expr *defarg);
1297   void ActOnParamUnparsedDefaultArgument(Decl *param,
1298                                          SourceLocation EqualLoc,
1299                                          SourceLocation ArgLoc);
1300   void ActOnParamDefaultArgumentError(Decl *param);
1301   bool SetParamDefaultArgument(ParmVarDecl *Param, Expr *DefaultArg,
1302                                SourceLocation EqualLoc);
1303 
1304   void CheckSelfReference(Decl *OrigDecl, Expr *E);
1305   void AddInitializerToDecl(Decl *dcl, Expr *init, bool DirectInit,
1306                             bool TypeMayContainAuto);
1307   void ActOnUninitializedDecl(Decl *dcl, bool TypeMayContainAuto);
1308   void ActOnInitializerError(Decl *Dcl);
1309   void ActOnCXXForRangeDecl(Decl *D);
1310   void SetDeclDeleted(Decl *dcl, SourceLocation DelLoc);
1311   void SetDeclDefaulted(Decl *dcl, SourceLocation DefaultLoc);
1312   void FinalizeDeclaration(Decl *D);
1313   DeclGroupPtrTy FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
1314                                          Decl **Group,
1315                                          unsigned NumDecls);
1316   DeclGroupPtrTy BuildDeclaratorGroup(Decl **Group, unsigned NumDecls,
1317                                       bool TypeMayContainAuto = true);
1318 
1319   /// Should be called on all declarations that might have attached
1320   /// documentation comments.
1321   void ActOnDocumentableDecl(Decl *D);
1322   void ActOnDocumentableDecls(Decl **Group, unsigned NumDecls);
1323 
1324   void ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
1325                                        SourceLocation LocAfterDecls);
1326   void CheckForFunctionRedefinition(FunctionDecl *FD);
1327   Decl *ActOnStartOfFunctionDef(Scope *S, Declarator &D);
1328   Decl *ActOnStartOfFunctionDef(Scope *S, Decl *D);
1329   void ActOnStartOfObjCMethodDef(Scope *S, Decl *D);
isObjCMethodDecl(Decl * D)1330   bool isObjCMethodDecl(Decl *D) {
1331     return D && isa<ObjCMethodDecl>(D);
1332   }
1333 
1334   void computeNRVO(Stmt *Body, sema::FunctionScopeInfo *Scope);
1335   Decl *ActOnFinishFunctionBody(Decl *Decl, Stmt *Body);
1336   Decl *ActOnFinishFunctionBody(Decl *Decl, Stmt *Body, bool IsInstantiation);
1337 
1338   /// ActOnFinishDelayedAttribute - Invoked when we have finished parsing an
1339   /// attribute for which parsing is delayed.
1340   void ActOnFinishDelayedAttribute(Scope *S, Decl *D, ParsedAttributes &Attrs);
1341 
1342   /// \brief Diagnose any unused parameters in the given sequence of
1343   /// ParmVarDecl pointers.
1344   void DiagnoseUnusedParameters(ParmVarDecl * const *Begin,
1345                                 ParmVarDecl * const *End);
1346 
1347   /// \brief Diagnose whether the size of parameters or return value of a
1348   /// function or obj-c method definition is pass-by-value and larger than a
1349   /// specified threshold.
1350   void DiagnoseSizeOfParametersAndReturnValue(ParmVarDecl * const *Begin,
1351                                               ParmVarDecl * const *End,
1352                                               QualType ReturnTy,
1353                                               NamedDecl *D);
1354 
1355   void DiagnoseInvalidJumps(Stmt *Body);
1356   Decl *ActOnFileScopeAsmDecl(Expr *expr,
1357                               SourceLocation AsmLoc,
1358                               SourceLocation RParenLoc);
1359 
1360   /// \brief The parser has processed a module import declaration.
1361   ///
1362   /// \param AtLoc The location of the '@' symbol, if any.
1363   ///
1364   /// \param ImportLoc The location of the 'import' keyword.
1365   ///
1366   /// \param Path The module access path.
1367   DeclResult ActOnModuleImport(SourceLocation AtLoc, SourceLocation ImportLoc,
1368                                ModuleIdPath Path);
1369 
1370   /// \brief Retrieve a suitable printing policy.
getPrintingPolicy()1371   PrintingPolicy getPrintingPolicy() const {
1372     return getPrintingPolicy(Context, PP);
1373   }
1374 
1375   /// \brief Retrieve a suitable printing policy.
1376   static PrintingPolicy getPrintingPolicy(const ASTContext &Ctx,
1377                                           const Preprocessor &PP);
1378 
1379   /// Scope actions.
1380   void ActOnPopScope(SourceLocation Loc, Scope *S);
1381   void ActOnTranslationUnitScope(Scope *S);
1382 
1383   Decl *ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS,
1384                                    DeclSpec &DS);
1385   Decl *ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS,
1386                                    DeclSpec &DS,
1387                                    MultiTemplateParamsArg TemplateParams);
1388 
1389   Decl *BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
1390                                     AccessSpecifier AS,
1391                                     RecordDecl *Record);
1392 
1393   Decl *BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
1394                                        RecordDecl *Record);
1395 
1396   bool isAcceptableTagRedeclaration(const TagDecl *Previous,
1397                                     TagTypeKind NewTag, bool isDefinition,
1398                                     SourceLocation NewTagLoc,
1399                                     const IdentifierInfo &Name);
1400 
1401   enum TagUseKind {
1402     TUK_Reference,   // Reference to a tag:  'struct foo *X;'
1403     TUK_Declaration, // Fwd decl of a tag:   'struct foo;'
1404     TUK_Definition,  // Definition of a tag: 'struct foo { int X; } Y;'
1405     TUK_Friend       // Friend declaration:  'friend struct foo;'
1406   };
1407 
1408   Decl *ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
1409                  SourceLocation KWLoc, CXXScopeSpec &SS,
1410                  IdentifierInfo *Name, SourceLocation NameLoc,
1411                  AttributeList *Attr, AccessSpecifier AS,
1412                  SourceLocation ModulePrivateLoc,
1413                  MultiTemplateParamsArg TemplateParameterLists,
1414                  bool &OwnedDecl, bool &IsDependent,
1415                  SourceLocation ScopedEnumKWLoc,
1416                  bool ScopedEnumUsesClassTag, TypeResult UnderlyingType);
1417 
1418   Decl *ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
1419                                 unsigned TagSpec, SourceLocation TagLoc,
1420                                 CXXScopeSpec &SS,
1421                                 IdentifierInfo *Name, SourceLocation NameLoc,
1422                                 AttributeList *Attr,
1423                                 MultiTemplateParamsArg TempParamLists);
1424 
1425   TypeResult ActOnDependentTag(Scope *S,
1426                                unsigned TagSpec,
1427                                TagUseKind TUK,
1428                                const CXXScopeSpec &SS,
1429                                IdentifierInfo *Name,
1430                                SourceLocation TagLoc,
1431                                SourceLocation NameLoc);
1432 
1433   void ActOnDefs(Scope *S, Decl *TagD, SourceLocation DeclStart,
1434                  IdentifierInfo *ClassName,
1435                  SmallVectorImpl<Decl *> &Decls);
1436   Decl *ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
1437                    Declarator &D, Expr *BitfieldWidth);
1438 
1439   FieldDecl *HandleField(Scope *S, RecordDecl *TagD, SourceLocation DeclStart,
1440                          Declarator &D, Expr *BitfieldWidth,
1441                          InClassInitStyle InitStyle,
1442                          AccessSpecifier AS);
1443 
1444   FieldDecl *CheckFieldDecl(DeclarationName Name, QualType T,
1445                             TypeSourceInfo *TInfo,
1446                             RecordDecl *Record, SourceLocation Loc,
1447                             bool Mutable, Expr *BitfieldWidth,
1448                             InClassInitStyle InitStyle,
1449                             SourceLocation TSSL,
1450                             AccessSpecifier AS, NamedDecl *PrevDecl,
1451                             Declarator *D = 0);
1452 
1453   enum CXXSpecialMember {
1454     CXXDefaultConstructor,
1455     CXXCopyConstructor,
1456     CXXMoveConstructor,
1457     CXXCopyAssignment,
1458     CXXMoveAssignment,
1459     CXXDestructor,
1460     CXXInvalid
1461   };
1462   bool CheckNontrivialField(FieldDecl *FD);
1463   void DiagnoseNontrivial(const RecordType* Record, CXXSpecialMember mem);
1464   CXXSpecialMember getSpecialMember(const CXXMethodDecl *MD);
1465   void ActOnLastBitfield(SourceLocation DeclStart,
1466                          SmallVectorImpl<Decl *> &AllIvarDecls);
1467   Decl *ActOnIvar(Scope *S, SourceLocation DeclStart,
1468                   Declarator &D, Expr *BitfieldWidth,
1469                   tok::ObjCKeywordKind visibility);
1470 
1471   // This is used for both record definitions and ObjC interface declarations.
1472   void ActOnFields(Scope* S, SourceLocation RecLoc, Decl *TagDecl,
1473                    llvm::ArrayRef<Decl *> Fields,
1474                    SourceLocation LBrac, SourceLocation RBrac,
1475                    AttributeList *AttrList);
1476 
1477   /// ActOnTagStartDefinition - Invoked when we have entered the
1478   /// scope of a tag's definition (e.g., for an enumeration, class,
1479   /// struct, or union).
1480   void ActOnTagStartDefinition(Scope *S, Decl *TagDecl);
1481 
1482   Decl *ActOnObjCContainerStartDefinition(Decl *IDecl);
1483 
1484   /// ActOnStartCXXMemberDeclarations - Invoked when we have parsed a
1485   /// C++ record definition's base-specifiers clause and are starting its
1486   /// member declarations.
1487   void ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagDecl,
1488                                        SourceLocation FinalLoc,
1489                                        SourceLocation LBraceLoc);
1490 
1491   /// ActOnTagFinishDefinition - Invoked once we have finished parsing
1492   /// the definition of a tag (enumeration, class, struct, or union).
1493   void ActOnTagFinishDefinition(Scope *S, Decl *TagDecl,
1494                                 SourceLocation RBraceLoc);
1495 
1496   void ActOnObjCContainerFinishDefinition();
1497 
1498   /// \brief Invoked when we must temporarily exit the objective-c container
1499   /// scope for parsing/looking-up C constructs.
1500   ///
1501   /// Must be followed by a call to \see ActOnObjCReenterContainerContext
1502   void ActOnObjCTemporaryExitContainerContext(DeclContext *DC);
1503   void ActOnObjCReenterContainerContext(DeclContext *DC);
1504 
1505   /// ActOnTagDefinitionError - Invoked when there was an unrecoverable
1506   /// error parsing the definition of a tag.
1507   void ActOnTagDefinitionError(Scope *S, Decl *TagDecl);
1508 
1509   EnumConstantDecl *CheckEnumConstant(EnumDecl *Enum,
1510                                       EnumConstantDecl *LastEnumConst,
1511                                       SourceLocation IdLoc,
1512                                       IdentifierInfo *Id,
1513                                       Expr *val);
1514   bool CheckEnumUnderlyingType(TypeSourceInfo *TI);
1515   bool CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
1516                               QualType EnumUnderlyingTy, const EnumDecl *Prev);
1517 
1518   Decl *ActOnEnumConstant(Scope *S, Decl *EnumDecl, Decl *LastEnumConstant,
1519                           SourceLocation IdLoc, IdentifierInfo *Id,
1520                           AttributeList *Attrs,
1521                           SourceLocation EqualLoc, Expr *Val);
1522   void ActOnEnumBody(SourceLocation EnumLoc, SourceLocation LBraceLoc,
1523                      SourceLocation RBraceLoc, Decl *EnumDecl,
1524                      Decl **Elements, unsigned NumElements,
1525                      Scope *S, AttributeList *Attr);
1526 
1527   DeclContext *getContainingDC(DeclContext *DC);
1528 
1529   /// Set the current declaration context until it gets popped.
1530   void PushDeclContext(Scope *S, DeclContext *DC);
1531   void PopDeclContext();
1532 
1533   /// EnterDeclaratorContext - Used when we must lookup names in the context
1534   /// of a declarator's nested name specifier.
1535   void EnterDeclaratorContext(Scope *S, DeclContext *DC);
1536   void ExitDeclaratorContext(Scope *S);
1537 
1538   /// Push the parameters of D, which must be a function, into scope.
1539   void ActOnReenterFunctionContext(Scope* S, Decl* D);
1540   void ActOnExitFunctionContext();
1541 
1542   DeclContext *getFunctionLevelDeclContext();
1543 
1544   /// getCurFunctionDecl - If inside of a function body, this returns a pointer
1545   /// to the function decl for the function being parsed.  If we're currently
1546   /// in a 'block', this returns the containing context.
1547   FunctionDecl *getCurFunctionDecl();
1548 
1549   /// getCurMethodDecl - If inside of a method body, this returns a pointer to
1550   /// the method decl for the method being parsed.  If we're currently
1551   /// in a 'block', this returns the containing context.
1552   ObjCMethodDecl *getCurMethodDecl();
1553 
1554   /// getCurFunctionOrMethodDecl - Return the Decl for the current ObjC method
1555   /// or C function we're in, otherwise return null.  If we're currently
1556   /// in a 'block', this returns the containing context.
1557   NamedDecl *getCurFunctionOrMethodDecl();
1558 
1559   /// Add this decl to the scope shadowed decl chains.
1560   void PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext = true);
1561 
1562   /// \brief Make the given externally-produced declaration visible at the
1563   /// top level scope.
1564   ///
1565   /// \param D The externally-produced declaration to push.
1566   ///
1567   /// \param Name The name of the externally-produced declaration.
1568   void pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name);
1569 
1570   /// isDeclInScope - If 'Ctx' is a function/method, isDeclInScope returns true
1571   /// if 'D' is in Scope 'S', otherwise 'S' is ignored and isDeclInScope returns
1572   /// true if 'D' belongs to the given declaration context.
1573   ///
1574   /// \param ExplicitInstantiationOrSpecialization When true, we are checking
1575   /// whether the declaration is in scope for the purposes of explicit template
1576   /// instantiation or specialization. The default is false.
1577   bool isDeclInScope(NamedDecl *&D, DeclContext *Ctx, Scope *S = 0,
1578                      bool ExplicitInstantiationOrSpecialization = false);
1579 
1580   /// Finds the scope corresponding to the given decl context, if it
1581   /// happens to be an enclosing scope.  Otherwise return NULL.
1582   static Scope *getScopeForDeclContext(Scope *S, DeclContext *DC);
1583 
1584   /// Subroutines of ActOnDeclarator().
1585   TypedefDecl *ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
1586                                 TypeSourceInfo *TInfo);
1587   bool isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New);
1588 
1589   /// Attribute merging methods. Return true if a new attribute was added.
1590   AvailabilityAttr *mergeAvailabilityAttr(Decl *D, SourceRange Range,
1591                                           IdentifierInfo *Platform,
1592                                           VersionTuple Introduced,
1593                                           VersionTuple Deprecated,
1594                                           VersionTuple Obsoleted,
1595                                           bool IsUnavailable,
1596                                           StringRef Message);
1597   VisibilityAttr *mergeVisibilityAttr(Decl *D, SourceRange Range,
1598                                       VisibilityAttr::VisibilityType Vis);
1599   DLLImportAttr *mergeDLLImportAttr(Decl *D, SourceRange Range);
1600   DLLExportAttr *mergeDLLExportAttr(Decl *D, SourceRange Range);
1601   FormatAttr *mergeFormatAttr(Decl *D, SourceRange Range, StringRef Format,
1602                               int FormatIdx, int FirstArg);
1603   SectionAttr *mergeSectionAttr(Decl *D, SourceRange Range, StringRef Name);
1604   bool mergeDeclAttribute(Decl *New, InheritableAttr *Attr);
1605 
1606   void mergeDeclAttributes(Decl *New, Decl *Old, bool MergeDeprecation = true);
1607   void MergeTypedefNameDecl(TypedefNameDecl *New, LookupResult &OldDecls);
1608   bool MergeFunctionDecl(FunctionDecl *New, Decl *Old, Scope *S);
1609   bool MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
1610                                     Scope *S);
1611   void mergeObjCMethodDecls(ObjCMethodDecl *New, ObjCMethodDecl *Old);
1612   void MergeVarDecl(VarDecl *New, LookupResult &OldDecls);
1613   void MergeVarDeclTypes(VarDecl *New, VarDecl *Old);
1614   void MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old);
1615   bool MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old, Scope *S);
1616 
1617   // AssignmentAction - This is used by all the assignment diagnostic functions
1618   // to represent what is actually causing the operation
1619   enum AssignmentAction {
1620     AA_Assigning,
1621     AA_Passing,
1622     AA_Returning,
1623     AA_Converting,
1624     AA_Initializing,
1625     AA_Sending,
1626     AA_Casting
1627   };
1628 
1629   /// C++ Overloading.
1630   enum OverloadKind {
1631     /// This is a legitimate overload: the existing declarations are
1632     /// functions or function templates with different signatures.
1633     Ovl_Overload,
1634 
1635     /// This is not an overload because the signature exactly matches
1636     /// an existing declaration.
1637     Ovl_Match,
1638 
1639     /// This is not an overload because the lookup results contain a
1640     /// non-function.
1641     Ovl_NonFunction
1642   };
1643   OverloadKind CheckOverload(Scope *S,
1644                              FunctionDecl *New,
1645                              const LookupResult &OldDecls,
1646                              NamedDecl *&OldDecl,
1647                              bool IsForUsingDecl);
1648   bool IsOverload(FunctionDecl *New, FunctionDecl *Old, bool IsForUsingDecl);
1649 
1650   /// \brief Checks availability of the function depending on the current
1651   /// function context.Inside an unavailable function,unavailability is ignored.
1652   ///
1653   /// \returns true if \arg FD is unavailable and current context is inside
1654   /// an available function, false otherwise.
1655   bool isFunctionConsideredUnavailable(FunctionDecl *FD);
1656 
1657   ImplicitConversionSequence
1658   TryImplicitConversion(Expr *From, QualType ToType,
1659                         bool SuppressUserConversions,
1660                         bool AllowExplicit,
1661                         bool InOverloadResolution,
1662                         bool CStyle,
1663                         bool AllowObjCWritebackConversion);
1664 
1665   bool IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType);
1666   bool IsFloatingPointPromotion(QualType FromType, QualType ToType);
1667   bool IsComplexPromotion(QualType FromType, QualType ToType);
1668   bool IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
1669                            bool InOverloadResolution,
1670                            QualType& ConvertedType, bool &IncompatibleObjC);
1671   bool isObjCPointerConversion(QualType FromType, QualType ToType,
1672                                QualType& ConvertedType, bool &IncompatibleObjC);
1673   bool isObjCWritebackConversion(QualType FromType, QualType ToType,
1674                                  QualType &ConvertedType);
1675   bool IsBlockPointerConversion(QualType FromType, QualType ToType,
1676                                 QualType& ConvertedType);
1677   bool FunctionArgTypesAreEqual(const FunctionProtoType *OldType,
1678                                 const FunctionProtoType *NewType,
1679                                 unsigned *ArgPos = 0);
1680   void HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
1681                                   QualType FromType, QualType ToType);
1682 
1683   CastKind PrepareCastToObjCObjectPointer(ExprResult &E);
1684   bool CheckPointerConversion(Expr *From, QualType ToType,
1685                               CastKind &Kind,
1686                               CXXCastPath& BasePath,
1687                               bool IgnoreBaseAccess);
1688   bool IsMemberPointerConversion(Expr *From, QualType FromType, QualType ToType,
1689                                  bool InOverloadResolution,
1690                                  QualType &ConvertedType);
1691   bool CheckMemberPointerConversion(Expr *From, QualType ToType,
1692                                     CastKind &Kind,
1693                                     CXXCastPath &BasePath,
1694                                     bool IgnoreBaseAccess);
1695   bool IsQualificationConversion(QualType FromType, QualType ToType,
1696                                  bool CStyle, bool &ObjCLifetimeConversion);
1697   bool IsNoReturnConversion(QualType FromType, QualType ToType,
1698                             QualType &ResultTy);
1699   bool DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType);
1700 
1701 
1702   ExprResult PerformMoveOrCopyInitialization(const InitializedEntity &Entity,
1703                                              const VarDecl *NRVOCandidate,
1704                                              QualType ResultType,
1705                                              Expr *Value,
1706                                              bool AllowNRVO = true);
1707 
1708   bool CanPerformCopyInitialization(const InitializedEntity &Entity,
1709                                     ExprResult Init);
1710   ExprResult PerformCopyInitialization(const InitializedEntity &Entity,
1711                                        SourceLocation EqualLoc,
1712                                        ExprResult Init,
1713                                        bool TopLevelOfInitList = false,
1714                                        bool AllowExplicit = false);
1715   ExprResult PerformObjectArgumentInitialization(Expr *From,
1716                                                  NestedNameSpecifier *Qualifier,
1717                                                  NamedDecl *FoundDecl,
1718                                                  CXXMethodDecl *Method);
1719 
1720   ExprResult PerformContextuallyConvertToBool(Expr *From);
1721   ExprResult PerformContextuallyConvertToObjCPointer(Expr *From);
1722 
1723   /// Contexts in which a converted constant expression is required.
1724   enum CCEKind {
1725     CCEK_CaseValue,  ///< Expression in a case label.
1726     CCEK_Enumerator, ///< Enumerator value with fixed underlying type.
1727     CCEK_TemplateArg ///< Value of a non-type template parameter.
1728   };
1729   ExprResult CheckConvertedConstantExpression(Expr *From, QualType T,
1730                                               llvm::APSInt &Value, CCEKind CCE);
1731 
1732   /// \brief Abstract base class used to diagnose problems that occur while
1733   /// trying to convert an expression to integral or enumeration type.
1734   class ICEConvertDiagnoser {
1735   public:
1736     bool Suppress;
1737     bool SuppressConversion;
1738 
1739     ICEConvertDiagnoser(bool Suppress = false,
1740                         bool SuppressConversion = false)
Suppress(Suppress)1741       : Suppress(Suppress), SuppressConversion(SuppressConversion) { }
1742 
1743     /// \brief Emits a diagnostic complaining that the expression does not have
1744     /// integral or enumeration type.
1745     virtual DiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
1746                                              QualType T) = 0;
1747 
1748     /// \brief Emits a diagnostic when the expression has incomplete class type.
1749     virtual DiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
1750                                                  QualType T) = 0;
1751 
1752     /// \brief Emits a diagnostic when the only matching conversion function
1753     /// is explicit.
1754     virtual DiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc,
1755                                                    QualType T,
1756                                                    QualType ConvTy) = 0;
1757 
1758     /// \brief Emits a note for the explicit conversion function.
1759     virtual DiagnosticBuilder
1760     noteExplicitConv(Sema &S, CXXConversionDecl *Conv, QualType ConvTy) = 0;
1761 
1762     /// \brief Emits a diagnostic when there are multiple possible conversion
1763     /// functions.
1764     virtual DiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
1765                                                 QualType T) = 0;
1766 
1767     /// \brief Emits a note for one of the candidate conversions.
1768     virtual DiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,
1769                                             QualType ConvTy) = 0;
1770 
1771     /// \brief Emits a diagnostic when we picked a conversion function
1772     /// (for cases when we are not allowed to pick a conversion function).
1773     virtual DiagnosticBuilder diagnoseConversion(Sema &S, SourceLocation Loc,
1774                                                  QualType T,
1775                                                  QualType ConvTy) = 0;
1776 
~ICEConvertDiagnoser()1777     virtual ~ICEConvertDiagnoser() {}
1778   };
1779 
1780   ExprResult
1781   ConvertToIntegralOrEnumerationType(SourceLocation Loc, Expr *FromE,
1782                                      ICEConvertDiagnoser &Diagnoser,
1783                                      bool AllowScopedEnumerations);
1784 
1785   enum ObjCSubscriptKind {
1786     OS_Array,
1787     OS_Dictionary,
1788     OS_Error
1789   };
1790   ObjCSubscriptKind CheckSubscriptingKind(Expr *FromE);
1791 
1792   ExprResult PerformObjectMemberConversion(Expr *From,
1793                                            NestedNameSpecifier *Qualifier,
1794                                            NamedDecl *FoundDecl,
1795                                            NamedDecl *Member);
1796 
1797   // Members have to be NamespaceDecl* or TranslationUnitDecl*.
1798   // TODO: make this is a typesafe union.
1799   typedef llvm::SmallPtrSet<DeclContext   *, 16> AssociatedNamespaceSet;
1800   typedef llvm::SmallPtrSet<CXXRecordDecl *, 16> AssociatedClassSet;
1801 
1802   void AddOverloadCandidate(FunctionDecl *Function,
1803                             DeclAccessPair FoundDecl,
1804                             llvm::ArrayRef<Expr *> Args,
1805                             OverloadCandidateSet& CandidateSet,
1806                             bool SuppressUserConversions = false,
1807                             bool PartialOverloading = false,
1808                             bool AllowExplicit = false);
1809   void AddFunctionCandidates(const UnresolvedSetImpl &Functions,
1810                              llvm::ArrayRef<Expr *> Args,
1811                              OverloadCandidateSet& CandidateSet,
1812                              bool SuppressUserConversions = false,
1813                             TemplateArgumentListInfo *ExplicitTemplateArgs = 0);
1814   void AddMethodCandidate(DeclAccessPair FoundDecl,
1815                           QualType ObjectType,
1816                           Expr::Classification ObjectClassification,
1817                           Expr **Args, unsigned NumArgs,
1818                           OverloadCandidateSet& CandidateSet,
1819                           bool SuppressUserConversion = false);
1820   void AddMethodCandidate(CXXMethodDecl *Method,
1821                           DeclAccessPair FoundDecl,
1822                           CXXRecordDecl *ActingContext, QualType ObjectType,
1823                           Expr::Classification ObjectClassification,
1824                           llvm::ArrayRef<Expr *> Args,
1825                           OverloadCandidateSet& CandidateSet,
1826                           bool SuppressUserConversions = false);
1827   void AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
1828                                   DeclAccessPair FoundDecl,
1829                                   CXXRecordDecl *ActingContext,
1830                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
1831                                   QualType ObjectType,
1832                                   Expr::Classification ObjectClassification,
1833                                   llvm::ArrayRef<Expr *> Args,
1834                                   OverloadCandidateSet& CandidateSet,
1835                                   bool SuppressUserConversions = false);
1836   void AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
1837                                     DeclAccessPair FoundDecl,
1838                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
1839                                     llvm::ArrayRef<Expr *> Args,
1840                                     OverloadCandidateSet& CandidateSet,
1841                                     bool SuppressUserConversions = false);
1842   void AddConversionCandidate(CXXConversionDecl *Conversion,
1843                               DeclAccessPair FoundDecl,
1844                               CXXRecordDecl *ActingContext,
1845                               Expr *From, QualType ToType,
1846                               OverloadCandidateSet& CandidateSet);
1847   void AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
1848                                       DeclAccessPair FoundDecl,
1849                                       CXXRecordDecl *ActingContext,
1850                                       Expr *From, QualType ToType,
1851                                       OverloadCandidateSet &CandidateSet);
1852   void AddSurrogateCandidate(CXXConversionDecl *Conversion,
1853                              DeclAccessPair FoundDecl,
1854                              CXXRecordDecl *ActingContext,
1855                              const FunctionProtoType *Proto,
1856                              Expr *Object, llvm::ArrayRef<Expr*> Args,
1857                              OverloadCandidateSet& CandidateSet);
1858   void AddMemberOperatorCandidates(OverloadedOperatorKind Op,
1859                                    SourceLocation OpLoc,
1860                                    Expr **Args, unsigned NumArgs,
1861                                    OverloadCandidateSet& CandidateSet,
1862                                    SourceRange OpRange = SourceRange());
1863   void AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
1864                            Expr **Args, unsigned NumArgs,
1865                            OverloadCandidateSet& CandidateSet,
1866                            bool IsAssignmentOperator = false,
1867                            unsigned NumContextualBoolArguments = 0);
1868   void AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
1869                                     SourceLocation OpLoc,
1870                                     Expr **Args, unsigned NumArgs,
1871                                     OverloadCandidateSet& CandidateSet);
1872   void AddArgumentDependentLookupCandidates(DeclarationName Name,
1873                                             bool Operator, SourceLocation Loc,
1874                                             llvm::ArrayRef<Expr *> Args,
1875                                 TemplateArgumentListInfo *ExplicitTemplateArgs,
1876                                             OverloadCandidateSet& CandidateSet,
1877                                             bool PartialOverloading = false,
1878                                         bool StdNamespaceIsAssociated = false);
1879 
1880   // Emit as a 'note' the specific overload candidate
1881   void NoteOverloadCandidate(FunctionDecl *Fn, QualType DestType = QualType());
1882 
1883   // Emit as a series of 'note's all template and non-templates
1884   // identified by the expression Expr
1885   void NoteAllOverloadCandidates(Expr* E, QualType DestType = QualType());
1886 
1887   // [PossiblyAFunctionType]  -->   [Return]
1888   // NonFunctionType --> NonFunctionType
1889   // R (A) --> R(A)
1890   // R (*)(A) --> R (A)
1891   // R (&)(A) --> R (A)
1892   // R (S::*)(A) --> R (A)
1893   QualType ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType);
1894 
1895   FunctionDecl *
1896   ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
1897                                      QualType TargetType,
1898                                      bool Complain,
1899                                      DeclAccessPair &Found,
1900                                      bool *pHadMultipleCandidates = 0);
1901 
1902   FunctionDecl *ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
1903                                                    bool Complain = false,
1904                                                    DeclAccessPair* Found = 0);
1905 
1906   bool ResolveAndFixSingleFunctionTemplateSpecialization(
1907                       ExprResult &SrcExpr,
1908                       bool DoFunctionPointerConverion = false,
1909                       bool Complain = false,
1910                       const SourceRange& OpRangeForComplaining = SourceRange(),
1911                       QualType DestTypeForComplaining = QualType(),
1912                       unsigned DiagIDForComplaining = 0);
1913 
1914 
1915   Expr *FixOverloadedFunctionReference(Expr *E,
1916                                        DeclAccessPair FoundDecl,
1917                                        FunctionDecl *Fn);
1918   ExprResult FixOverloadedFunctionReference(ExprResult,
1919                                             DeclAccessPair FoundDecl,
1920                                             FunctionDecl *Fn);
1921 
1922   void AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
1923                                    llvm::ArrayRef<Expr *> Args,
1924                                    OverloadCandidateSet &CandidateSet,
1925                                    bool PartialOverloading = false);
1926 
1927   // An enum used to represent the different possible results of building a
1928   // range-based for loop.
1929   enum ForRangeStatus {
1930     FRS_Success,
1931     FRS_NoViableFunction,
1932     FRS_DiagnosticIssued
1933   };
1934 
1935   // An enum to represent whether something is dealing with a call to begin()
1936   // or a call to end() in a range-based for loop.
1937   enum BeginEndFunction {
1938     BEF_begin,
1939     BEF_end
1940   };
1941 
1942   ForRangeStatus BuildForRangeBeginEndCall(Scope *S, SourceLocation Loc,
1943                                            SourceLocation RangeLoc,
1944                                            VarDecl *Decl,
1945                                            BeginEndFunction BEF,
1946                                            const DeclarationNameInfo &NameInfo,
1947                                            LookupResult &MemberLookup,
1948                                            OverloadCandidateSet *CandidateSet,
1949                                            Expr *Range, ExprResult *CallExpr);
1950 
1951   ExprResult BuildOverloadedCallExpr(Scope *S, Expr *Fn,
1952                                      UnresolvedLookupExpr *ULE,
1953                                      SourceLocation LParenLoc,
1954                                      Expr **Args, unsigned NumArgs,
1955                                      SourceLocation RParenLoc,
1956                                      Expr *ExecConfig,
1957                                      bool AllowTypoCorrection=true);
1958 
1959   bool buildOverloadedCallSet(Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE,
1960                               Expr **Args, unsigned NumArgs,
1961                               SourceLocation RParenLoc,
1962                               OverloadCandidateSet *CandidateSet,
1963                               ExprResult *Result);
1964 
1965   ExprResult CreateOverloadedUnaryOp(SourceLocation OpLoc,
1966                                      unsigned Opc,
1967                                      const UnresolvedSetImpl &Fns,
1968                                      Expr *input);
1969 
1970   ExprResult CreateOverloadedBinOp(SourceLocation OpLoc,
1971                                    unsigned Opc,
1972                                    const UnresolvedSetImpl &Fns,
1973                                    Expr *LHS, Expr *RHS);
1974 
1975   ExprResult CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
1976                                                 SourceLocation RLoc,
1977                                                 Expr *Base,Expr *Idx);
1978 
1979   ExprResult
1980   BuildCallToMemberFunction(Scope *S, Expr *MemExpr,
1981                             SourceLocation LParenLoc, Expr **Args,
1982                             unsigned NumArgs, SourceLocation RParenLoc);
1983   ExprResult
1984   BuildCallToObjectOfClassType(Scope *S, Expr *Object, SourceLocation LParenLoc,
1985                                Expr **Args, unsigned NumArgs,
1986                                SourceLocation RParenLoc);
1987 
1988   ExprResult BuildOverloadedArrowExpr(Scope *S, Expr *Base,
1989                                       SourceLocation OpLoc);
1990 
1991   /// CheckCallReturnType - Checks that a call expression's return type is
1992   /// complete. Returns true on failure. The location passed in is the location
1993   /// that best represents the call.
1994   bool CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
1995                            CallExpr *CE, FunctionDecl *FD);
1996 
1997   /// Helpers for dealing with blocks and functions.
1998   bool CheckParmsForFunctionDef(ParmVarDecl **Param, ParmVarDecl **ParamEnd,
1999                                 bool CheckParameterNames);
2000   void CheckCXXDefaultArguments(FunctionDecl *FD);
2001   void CheckExtraCXXDefaultArguments(Declarator &D);
2002   Scope *getNonFieldDeclScope(Scope *S);
2003 
2004   /// \name Name lookup
2005   ///
2006   /// These routines provide name lookup that is used during semantic
2007   /// analysis to resolve the various kinds of names (identifiers,
2008   /// overloaded operator names, constructor names, etc.) into zero or
2009   /// more declarations within a particular scope. The major entry
2010   /// points are LookupName, which performs unqualified name lookup,
2011   /// and LookupQualifiedName, which performs qualified name lookup.
2012   ///
2013   /// All name lookup is performed based on some specific criteria,
2014   /// which specify what names will be visible to name lookup and how
2015   /// far name lookup should work. These criteria are important both
2016   /// for capturing language semantics (certain lookups will ignore
2017   /// certain names, for example) and for performance, since name
2018   /// lookup is often a bottleneck in the compilation of C++. Name
2019   /// lookup criteria is specified via the LookupCriteria enumeration.
2020   ///
2021   /// The results of name lookup can vary based on the kind of name
2022   /// lookup performed, the current language, and the translation
2023   /// unit. In C, for example, name lookup will either return nothing
2024   /// (no entity found) or a single declaration. In C++, name lookup
2025   /// can additionally refer to a set of overloaded functions or
2026   /// result in an ambiguity. All of the possible results of name
2027   /// lookup are captured by the LookupResult class, which provides
2028   /// the ability to distinguish among them.
2029   //@{
2030 
2031   /// @brief Describes the kind of name lookup to perform.
2032   enum LookupNameKind {
2033     /// Ordinary name lookup, which finds ordinary names (functions,
2034     /// variables, typedefs, etc.) in C and most kinds of names
2035     /// (functions, variables, members, types, etc.) in C++.
2036     LookupOrdinaryName = 0,
2037     /// Tag name lookup, which finds the names of enums, classes,
2038     /// structs, and unions.
2039     LookupTagName,
2040     /// Label name lookup.
2041     LookupLabel,
2042     /// Member name lookup, which finds the names of
2043     /// class/struct/union members.
2044     LookupMemberName,
2045     /// Look up of an operator name (e.g., operator+) for use with
2046     /// operator overloading. This lookup is similar to ordinary name
2047     /// lookup, but will ignore any declarations that are class members.
2048     LookupOperatorName,
2049     /// Look up of a name that precedes the '::' scope resolution
2050     /// operator in C++. This lookup completely ignores operator, object,
2051     /// function, and enumerator names (C++ [basic.lookup.qual]p1).
2052     LookupNestedNameSpecifierName,
2053     /// Look up a namespace name within a C++ using directive or
2054     /// namespace alias definition, ignoring non-namespace names (C++
2055     /// [basic.lookup.udir]p1).
2056     LookupNamespaceName,
2057     /// Look up all declarations in a scope with the given name,
2058     /// including resolved using declarations.  This is appropriate
2059     /// for checking redeclarations for a using declaration.
2060     LookupUsingDeclName,
2061     /// Look up an ordinary name that is going to be redeclared as a
2062     /// name with linkage. This lookup ignores any declarations that
2063     /// are outside of the current scope unless they have linkage. See
2064     /// C99 6.2.2p4-5 and C++ [basic.link]p6.
2065     LookupRedeclarationWithLinkage,
2066     /// Look up the name of an Objective-C protocol.
2067     LookupObjCProtocolName,
2068     /// Look up implicit 'self' parameter of an objective-c method.
2069     LookupObjCImplicitSelfParam,
2070     /// \brief Look up any declaration with any name.
2071     LookupAnyName
2072   };
2073 
2074   /// \brief Specifies whether (or how) name lookup is being performed for a
2075   /// redeclaration (vs. a reference).
2076   enum RedeclarationKind {
2077     /// \brief The lookup is a reference to this name that is not for the
2078     /// purpose of redeclaring the name.
2079     NotForRedeclaration = 0,
2080     /// \brief The lookup results will be used for redeclaration of a name,
2081     /// if an entity by that name already exists.
2082     ForRedeclaration
2083   };
2084 
2085   /// \brief The possible outcomes of name lookup for a literal operator.
2086   enum LiteralOperatorLookupResult {
2087     /// \brief The lookup resulted in an error.
2088     LOLR_Error,
2089     /// \brief The lookup found a single 'cooked' literal operator, which
2090     /// expects a normal literal to be built and passed to it.
2091     LOLR_Cooked,
2092     /// \brief The lookup found a single 'raw' literal operator, which expects
2093     /// a string literal containing the spelling of the literal token.
2094     LOLR_Raw,
2095     /// \brief The lookup found an overload set of literal operator templates,
2096     /// which expect the characters of the spelling of the literal token to be
2097     /// passed as a non-type template argument pack.
2098     LOLR_Template
2099   };
2100 
2101   SpecialMemberOverloadResult *LookupSpecialMember(CXXRecordDecl *D,
2102                                                    CXXSpecialMember SM,
2103                                                    bool ConstArg,
2104                                                    bool VolatileArg,
2105                                                    bool RValueThis,
2106                                                    bool ConstThis,
2107                                                    bool VolatileThis);
2108 
2109 private:
2110   bool CppLookupName(LookupResult &R, Scope *S);
2111 
2112   // \brief The set of known/encountered (unique, canonicalized) NamespaceDecls.
2113   //
2114   // The boolean value will be true to indicate that the namespace was loaded
2115   // from an AST/PCH file, or false otherwise.
2116   llvm::DenseMap<NamespaceDecl*, bool> KnownNamespaces;
2117 
2118   /// \brief Whether we have already loaded known namespaces from an extenal
2119   /// source.
2120   bool LoadedExternalKnownNamespaces;
2121 
2122 public:
2123   /// \brief Look up a name, looking for a single declaration.  Return
2124   /// null if the results were absent, ambiguous, or overloaded.
2125   ///
2126   /// It is preferable to use the elaborated form and explicitly handle
2127   /// ambiguity and overloaded.
2128   NamedDecl *LookupSingleName(Scope *S, DeclarationName Name,
2129                               SourceLocation Loc,
2130                               LookupNameKind NameKind,
2131                               RedeclarationKind Redecl
2132                                 = NotForRedeclaration);
2133   bool LookupName(LookupResult &R, Scope *S,
2134                   bool AllowBuiltinCreation = false);
2135   bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
2136                            bool InUnqualifiedLookup = false);
2137   bool LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS,
2138                         bool AllowBuiltinCreation = false,
2139                         bool EnteringContext = false);
2140   ObjCProtocolDecl *LookupProtocol(IdentifierInfo *II, SourceLocation IdLoc,
2141                                    RedeclarationKind Redecl
2142                                      = NotForRedeclaration);
2143 
2144   void LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S,
2145                                     QualType T1, QualType T2,
2146                                     UnresolvedSetImpl &Functions);
2147 
2148   LabelDecl *LookupOrCreateLabel(IdentifierInfo *II, SourceLocation IdentLoc,
2149                                  SourceLocation GnuLabelLoc = SourceLocation());
2150 
2151   DeclContextLookupResult LookupConstructors(CXXRecordDecl *Class);
2152   CXXConstructorDecl *LookupDefaultConstructor(CXXRecordDecl *Class);
2153   CXXConstructorDecl *LookupCopyingConstructor(CXXRecordDecl *Class,
2154                                                unsigned Quals);
2155   CXXMethodDecl *LookupCopyingAssignment(CXXRecordDecl *Class, unsigned Quals,
2156                                          bool RValueThis, unsigned ThisQuals);
2157   CXXConstructorDecl *LookupMovingConstructor(CXXRecordDecl *Class,
2158                                               unsigned Quals);
2159   CXXMethodDecl *LookupMovingAssignment(CXXRecordDecl *Class, unsigned Quals,
2160                                         bool RValueThis, unsigned ThisQuals);
2161   CXXDestructorDecl *LookupDestructor(CXXRecordDecl *Class);
2162 
2163   LiteralOperatorLookupResult LookupLiteralOperator(Scope *S, LookupResult &R,
2164                                                     ArrayRef<QualType> ArgTys,
2165                                                     bool AllowRawAndTemplate);
2166   bool isKnownName(StringRef name);
2167 
2168   void ArgumentDependentLookup(DeclarationName Name, bool Operator,
2169                                SourceLocation Loc,
2170                                llvm::ArrayRef<Expr *> Args,
2171                                ADLResult &Functions,
2172                                bool StdNamespaceIsAssociated = false);
2173 
2174   void LookupVisibleDecls(Scope *S, LookupNameKind Kind,
2175                           VisibleDeclConsumer &Consumer,
2176                           bool IncludeGlobalScope = true);
2177   void LookupVisibleDecls(DeclContext *Ctx, LookupNameKind Kind,
2178                           VisibleDeclConsumer &Consumer,
2179                           bool IncludeGlobalScope = true);
2180 
2181   TypoCorrection CorrectTypo(const DeclarationNameInfo &Typo,
2182                              Sema::LookupNameKind LookupKind,
2183                              Scope *S, CXXScopeSpec *SS,
2184                              CorrectionCandidateCallback &CCC,
2185                              DeclContext *MemberContext = 0,
2186                              bool EnteringContext = false,
2187                              const ObjCObjectPointerType *OPT = 0);
2188 
2189   void FindAssociatedClassesAndNamespaces(SourceLocation InstantiationLoc,
2190                                           llvm::ArrayRef<Expr *> Args,
2191                                    AssociatedNamespaceSet &AssociatedNamespaces,
2192                                    AssociatedClassSet &AssociatedClasses);
2193 
2194   void FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S,
2195                             bool ConsiderLinkage,
2196                             bool ExplicitInstantiationOrSpecialization);
2197 
2198   bool DiagnoseAmbiguousLookup(LookupResult &Result);
2199   //@}
2200 
2201   ObjCInterfaceDecl *getObjCInterfaceDecl(IdentifierInfo *&Id,
2202                                           SourceLocation IdLoc,
2203                                           bool TypoCorrection = false);
2204   NamedDecl *LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID,
2205                                  Scope *S, bool ForRedeclaration,
2206                                  SourceLocation Loc);
2207   NamedDecl *ImplicitlyDefineFunction(SourceLocation Loc, IdentifierInfo &II,
2208                                       Scope *S);
2209   void AddKnownFunctionAttributes(FunctionDecl *FD);
2210 
2211   // More parsing and symbol table subroutines.
2212 
2213   // Decl attributes - this routine is the top level dispatcher.
2214   void ProcessDeclAttributes(Scope *S, Decl *D, const Declarator &PD,
2215                            bool NonInheritable = true, bool Inheritable = true);
2216   void ProcessDeclAttributeList(Scope *S, Decl *D, const AttributeList *AL,
2217                            bool NonInheritable = true, bool Inheritable = true);
2218   bool ProcessAccessDeclAttributeList(AccessSpecDecl *ASDecl,
2219                                       const AttributeList *AttrList);
2220 
2221   void checkUnusedDeclAttributes(Declarator &D);
2222 
2223   bool CheckRegparmAttr(const AttributeList &attr, unsigned &value);
2224   bool CheckCallingConvAttr(const AttributeList &attr, CallingConv &CC);
2225   bool CheckNoReturnAttr(const AttributeList &attr);
2226 
2227   /// \brief Stmt attributes - this routine is the top level dispatcher.
2228   StmtResult ProcessStmtAttributes(Stmt *Stmt, AttributeList *Attrs,
2229                                    SourceRange Range);
2230 
2231   void WarnUndefinedMethod(SourceLocation ImpLoc, ObjCMethodDecl *method,
2232                            bool &IncompleteImpl, unsigned DiagID);
2233   void WarnConflictingTypedMethods(ObjCMethodDecl *Method,
2234                                    ObjCMethodDecl *MethodDecl,
2235                                    bool IsProtocolMethodDecl);
2236 
2237   void CheckConflictingOverridingMethod(ObjCMethodDecl *Method,
2238                                    ObjCMethodDecl *Overridden,
2239                                    bool IsProtocolMethodDecl);
2240 
2241   /// WarnExactTypedMethods - This routine issues a warning if method
2242   /// implementation declaration matches exactly that of its declaration.
2243   void WarnExactTypedMethods(ObjCMethodDecl *Method,
2244                              ObjCMethodDecl *MethodDecl,
2245                              bool IsProtocolMethodDecl);
2246 
2247   bool isPropertyReadonly(ObjCPropertyDecl *PropertyDecl,
2248                           ObjCInterfaceDecl *IDecl);
2249 
2250   typedef llvm::SmallPtrSet<Selector, 8> SelectorSet;
2251   typedef llvm::DenseMap<Selector, ObjCMethodDecl*> ProtocolsMethodsMap;
2252 
2253   /// CheckProtocolMethodDefs - This routine checks unimplemented
2254   /// methods declared in protocol, and those referenced by it.
2255   void CheckProtocolMethodDefs(SourceLocation ImpLoc,
2256                                ObjCProtocolDecl *PDecl,
2257                                bool& IncompleteImpl,
2258                                const SelectorSet &InsMap,
2259                                const SelectorSet &ClsMap,
2260                                ObjCContainerDecl *CDecl);
2261 
2262   /// CheckImplementationIvars - This routine checks if the instance variables
2263   /// listed in the implelementation match those listed in the interface.
2264   void CheckImplementationIvars(ObjCImplementationDecl *ImpDecl,
2265                                 ObjCIvarDecl **Fields, unsigned nIvars,
2266                                 SourceLocation Loc);
2267 
2268   /// ImplMethodsVsClassMethods - This is main routine to warn if any method
2269   /// remains unimplemented in the class or category \@implementation.
2270   void ImplMethodsVsClassMethods(Scope *S, ObjCImplDecl* IMPDecl,
2271                                  ObjCContainerDecl* IDecl,
2272                                  bool IncompleteImpl = false);
2273 
2274   /// DiagnoseUnimplementedProperties - This routine warns on those properties
2275   /// which must be implemented by this implementation.
2276   void DiagnoseUnimplementedProperties(Scope *S, ObjCImplDecl* IMPDecl,
2277                                        ObjCContainerDecl *CDecl,
2278                                        const SelectorSet &InsMap);
2279 
2280   /// DefaultSynthesizeProperties - This routine default synthesizes all
2281   /// properties which must be synthesized in the class's \@implementation.
2282   void DefaultSynthesizeProperties (Scope *S, ObjCImplDecl* IMPDecl,
2283                                     ObjCInterfaceDecl *IDecl);
2284   void DefaultSynthesizeProperties(Scope *S, Decl *D);
2285 
2286   /// CollectImmediateProperties - This routine collects all properties in
2287   /// the class and its conforming protocols; but not those it its super class.
2288   void CollectImmediateProperties(ObjCContainerDecl *CDecl,
2289             llvm::DenseMap<IdentifierInfo *, ObjCPropertyDecl*>& PropMap,
2290             llvm::DenseMap<IdentifierInfo *, ObjCPropertyDecl*>& SuperPropMap);
2291 
2292 
2293   /// LookupPropertyDecl - Looks up a property in the current class and all
2294   /// its protocols.
2295   ObjCPropertyDecl *LookupPropertyDecl(const ObjCContainerDecl *CDecl,
2296                                        IdentifierInfo *II);
2297 
2298   /// Called by ActOnProperty to handle \@property declarations in
2299   /// class extensions.
2300   Decl *HandlePropertyInClassExtension(Scope *S,
2301                                        SourceLocation AtLoc,
2302                                        SourceLocation LParenLoc,
2303                                        FieldDeclarator &FD,
2304                                        Selector GetterSel,
2305                                        Selector SetterSel,
2306                                        const bool isAssign,
2307                                        const bool isReadWrite,
2308                                        const unsigned Attributes,
2309                                        const unsigned AttributesAsWritten,
2310                                        bool *isOverridingProperty,
2311                                        TypeSourceInfo *T,
2312                                        tok::ObjCKeywordKind MethodImplKind);
2313 
2314   /// Called by ActOnProperty and HandlePropertyInClassExtension to
2315   /// handle creating the ObjcPropertyDecl for a category or \@interface.
2316   ObjCPropertyDecl *CreatePropertyDecl(Scope *S,
2317                                        ObjCContainerDecl *CDecl,
2318                                        SourceLocation AtLoc,
2319                                        SourceLocation LParenLoc,
2320                                        FieldDeclarator &FD,
2321                                        Selector GetterSel,
2322                                        Selector SetterSel,
2323                                        const bool isAssign,
2324                                        const bool isReadWrite,
2325                                        const unsigned Attributes,
2326                                        const unsigned AttributesAsWritten,
2327                                        TypeSourceInfo *T,
2328                                        tok::ObjCKeywordKind MethodImplKind,
2329                                        DeclContext *lexicalDC = 0);
2330 
2331   /// AtomicPropertySetterGetterRules - This routine enforces the rule (via
2332   /// warning) when atomic property has one but not the other user-declared
2333   /// setter or getter.
2334   void AtomicPropertySetterGetterRules(ObjCImplDecl* IMPDecl,
2335                                        ObjCContainerDecl* IDecl);
2336 
2337   void DiagnoseOwningPropertyGetterSynthesis(const ObjCImplementationDecl *D);
2338 
2339   void DiagnoseDuplicateIvars(ObjCInterfaceDecl *ID, ObjCInterfaceDecl *SID);
2340 
2341   enum MethodMatchStrategy {
2342     MMS_loose,
2343     MMS_strict
2344   };
2345 
2346   /// MatchTwoMethodDeclarations - Checks if two methods' type match and returns
2347   /// true, or false, accordingly.
2348   bool MatchTwoMethodDeclarations(const ObjCMethodDecl *Method,
2349                                   const ObjCMethodDecl *PrevMethod,
2350                                   MethodMatchStrategy strategy = MMS_strict);
2351 
2352   /// MatchAllMethodDeclarations - Check methods declaraed in interface or
2353   /// or protocol against those declared in their implementations.
2354   void MatchAllMethodDeclarations(const SelectorSet &InsMap,
2355                                   const SelectorSet &ClsMap,
2356                                   SelectorSet &InsMapSeen,
2357                                   SelectorSet &ClsMapSeen,
2358                                   ObjCImplDecl* IMPDecl,
2359                                   ObjCContainerDecl* IDecl,
2360                                   bool &IncompleteImpl,
2361                                   bool ImmediateClass,
2362                                   bool WarnCategoryMethodImpl=false);
2363 
2364   /// CheckCategoryVsClassMethodMatches - Checks that methods implemented in
2365   /// category matches with those implemented in its primary class and
2366   /// warns each time an exact match is found.
2367   void CheckCategoryVsClassMethodMatches(ObjCCategoryImplDecl *CatIMP);
2368 
2369   /// \brief Add the given method to the list of globally-known methods.
2370   void addMethodToGlobalList(ObjCMethodList *List, ObjCMethodDecl *Method);
2371 
2372 private:
2373   /// AddMethodToGlobalPool - Add an instance or factory method to the global
2374   /// pool. See descriptoin of AddInstanceMethodToGlobalPool.
2375   void AddMethodToGlobalPool(ObjCMethodDecl *Method, bool impl, bool instance);
2376 
2377   /// LookupMethodInGlobalPool - Returns the instance or factory method and
2378   /// optionally warns if there are multiple signatures.
2379   ObjCMethodDecl *LookupMethodInGlobalPool(Selector Sel, SourceRange R,
2380                                            bool receiverIdOrClass,
2381                                            bool warn, bool instance);
2382 
2383 public:
2384   /// AddInstanceMethodToGlobalPool - All instance methods in a translation
2385   /// unit are added to a global pool. This allows us to efficiently associate
2386   /// a selector with a method declaraation for purposes of typechecking
2387   /// messages sent to "id" (where the class of the object is unknown).
2388   void AddInstanceMethodToGlobalPool(ObjCMethodDecl *Method, bool impl=false) {
2389     AddMethodToGlobalPool(Method, impl, /*instance*/true);
2390   }
2391 
2392   /// AddFactoryMethodToGlobalPool - Same as above, but for factory methods.
2393   void AddFactoryMethodToGlobalPool(ObjCMethodDecl *Method, bool impl=false) {
2394     AddMethodToGlobalPool(Method, impl, /*instance*/false);
2395   }
2396 
2397   /// AddAnyMethodToGlobalPool - Add any method, instance or factory to global
2398   /// pool.
2399   void AddAnyMethodToGlobalPool(Decl *D);
2400 
2401   /// LookupInstanceMethodInGlobalPool - Returns the method and warns if
2402   /// there are multiple signatures.
2403   ObjCMethodDecl *LookupInstanceMethodInGlobalPool(Selector Sel, SourceRange R,
2404                                                    bool receiverIdOrClass=false,
2405                                                    bool warn=true) {
2406     return LookupMethodInGlobalPool(Sel, R, receiverIdOrClass,
2407                                     warn, /*instance*/true);
2408   }
2409 
2410   /// LookupFactoryMethodInGlobalPool - Returns the method and warns if
2411   /// there are multiple signatures.
2412   ObjCMethodDecl *LookupFactoryMethodInGlobalPool(Selector Sel, SourceRange R,
2413                                                   bool receiverIdOrClass=false,
2414                                                   bool warn=true) {
2415     return LookupMethodInGlobalPool(Sel, R, receiverIdOrClass,
2416                                     warn, /*instance*/false);
2417   }
2418 
2419   /// LookupImplementedMethodInGlobalPool - Returns the method which has an
2420   /// implementation.
2421   ObjCMethodDecl *LookupImplementedMethodInGlobalPool(Selector Sel);
2422 
2423   /// CollectIvarsToConstructOrDestruct - Collect those ivars which require
2424   /// initialization.
2425   void CollectIvarsToConstructOrDestruct(ObjCInterfaceDecl *OI,
2426                                   SmallVectorImpl<ObjCIvarDecl*> &Ivars);
2427 
2428   //===--------------------------------------------------------------------===//
2429   // Statement Parsing Callbacks: SemaStmt.cpp.
2430 public:
2431   class FullExprArg {
2432   public:
FullExprArg(Sema & actions)2433     FullExprArg(Sema &actions) : E(0) { }
2434 
2435     // FIXME: The const_cast here is ugly. RValue references would make this
2436     // much nicer (or we could duplicate a bunch of the move semantics
2437     // emulation code from Ownership.h).
FullExprArg(const FullExprArg & Other)2438     FullExprArg(const FullExprArg& Other) : E(Other.E) {}
2439 
release()2440     ExprResult release() {
2441       return E;
2442     }
2443 
get()2444     Expr *get() const { return E; }
2445 
2446     Expr *operator->() {
2447       return E;
2448     }
2449 
2450   private:
2451     // FIXME: No need to make the entire Sema class a friend when it's just
2452     // Sema::MakeFullExpr that needs access to the constructor below.
2453     friend class Sema;
2454 
FullExprArg(Expr * expr)2455     explicit FullExprArg(Expr *expr) : E(expr) {}
2456 
2457     Expr *E;
2458   };
2459 
MakeFullExpr(Expr * Arg)2460   FullExprArg MakeFullExpr(Expr *Arg) {
2461     return MakeFullExpr(Arg, Arg ? Arg->getExprLoc() : SourceLocation());
2462   }
MakeFullExpr(Expr * Arg,SourceLocation CC)2463   FullExprArg MakeFullExpr(Expr *Arg, SourceLocation CC) {
2464     return FullExprArg(ActOnFinishFullExpr(Arg, CC).release());
2465   }
2466 
2467   StmtResult ActOnExprStmt(FullExprArg Expr);
2468 
2469   StmtResult ActOnNullStmt(SourceLocation SemiLoc,
2470                            bool HasLeadingEmptyMacro = false);
2471 
2472   void ActOnStartOfCompoundStmt();
2473   void ActOnFinishOfCompoundStmt();
2474   StmtResult ActOnCompoundStmt(SourceLocation L, SourceLocation R,
2475                                        MultiStmtArg Elts,
2476                                        bool isStmtExpr);
2477 
2478   /// \brief A RAII object to enter scope of a compound statement.
2479   class CompoundScopeRAII {
2480   public:
CompoundScopeRAII(Sema & S)2481     CompoundScopeRAII(Sema &S): S(S) {
2482       S.ActOnStartOfCompoundStmt();
2483     }
2484 
~CompoundScopeRAII()2485     ~CompoundScopeRAII() {
2486       S.ActOnFinishOfCompoundStmt();
2487     }
2488 
2489   private:
2490     Sema &S;
2491   };
2492 
2493   StmtResult ActOnDeclStmt(DeclGroupPtrTy Decl,
2494                                    SourceLocation StartLoc,
2495                                    SourceLocation EndLoc);
2496   void ActOnForEachDeclStmt(DeclGroupPtrTy Decl);
2497   StmtResult ActOnForEachLValueExpr(Expr *E);
2498   StmtResult ActOnCaseStmt(SourceLocation CaseLoc, Expr *LHSVal,
2499                                    SourceLocation DotDotDotLoc, Expr *RHSVal,
2500                                    SourceLocation ColonLoc);
2501   void ActOnCaseStmtBody(Stmt *CaseStmt, Stmt *SubStmt);
2502 
2503   StmtResult ActOnDefaultStmt(SourceLocation DefaultLoc,
2504                                       SourceLocation ColonLoc,
2505                                       Stmt *SubStmt, Scope *CurScope);
2506   StmtResult ActOnLabelStmt(SourceLocation IdentLoc, LabelDecl *TheDecl,
2507                             SourceLocation ColonLoc, Stmt *SubStmt);
2508 
2509   StmtResult ActOnAttributedStmt(SourceLocation AttrLoc,
2510                                  ArrayRef<const Attr*> Attrs,
2511                                  Stmt *SubStmt);
2512 
2513   StmtResult ActOnIfStmt(SourceLocation IfLoc,
2514                          FullExprArg CondVal, Decl *CondVar,
2515                          Stmt *ThenVal,
2516                          SourceLocation ElseLoc, Stmt *ElseVal);
2517   StmtResult ActOnStartOfSwitchStmt(SourceLocation SwitchLoc,
2518                                             Expr *Cond,
2519                                             Decl *CondVar);
2520   StmtResult ActOnFinishSwitchStmt(SourceLocation SwitchLoc,
2521                                            Stmt *Switch, Stmt *Body);
2522   StmtResult ActOnWhileStmt(SourceLocation WhileLoc,
2523                             FullExprArg Cond,
2524                             Decl *CondVar, Stmt *Body);
2525   StmtResult ActOnDoStmt(SourceLocation DoLoc, Stmt *Body,
2526                                  SourceLocation WhileLoc,
2527                                  SourceLocation CondLParen, Expr *Cond,
2528                                  SourceLocation CondRParen);
2529 
2530   StmtResult ActOnForStmt(SourceLocation ForLoc,
2531                           SourceLocation LParenLoc,
2532                           Stmt *First, FullExprArg Second,
2533                           Decl *SecondVar,
2534                           FullExprArg Third,
2535                           SourceLocation RParenLoc,
2536                           Stmt *Body);
2537   ExprResult CheckObjCForCollectionOperand(SourceLocation forLoc,
2538                                            Expr *collection);
2539   StmtResult ActOnObjCForCollectionStmt(SourceLocation ForColLoc,
2540                                         Stmt *First, Expr *collection,
2541                                         SourceLocation RParenLoc);
2542   StmtResult FinishObjCForCollectionStmt(Stmt *ForCollection, Stmt *Body);
2543 
2544   StmtResult ActOnCXXForRangeStmt(SourceLocation ForLoc, Stmt *LoopVar,
2545                                   SourceLocation ColonLoc, Expr *Collection,
2546                                   SourceLocation RParenLoc,
2547                                   bool ShouldTryDeref);
2548   StmtResult BuildCXXForRangeStmt(SourceLocation ForLoc,
2549                                   SourceLocation ColonLoc,
2550                                   Stmt *RangeDecl, Stmt *BeginEndDecl,
2551                                   Expr *Cond, Expr *Inc,
2552                                   Stmt *LoopVarDecl,
2553                                   SourceLocation RParenLoc,
2554                                   bool ShouldTryDeref);
2555   StmtResult FinishCXXForRangeStmt(Stmt *ForRange, Stmt *Body);
2556 
2557   StmtResult ActOnGotoStmt(SourceLocation GotoLoc,
2558                            SourceLocation LabelLoc,
2559                            LabelDecl *TheDecl);
2560   StmtResult ActOnIndirectGotoStmt(SourceLocation GotoLoc,
2561                                    SourceLocation StarLoc,
2562                                    Expr *DestExp);
2563   StmtResult ActOnContinueStmt(SourceLocation ContinueLoc, Scope *CurScope);
2564   StmtResult ActOnBreakStmt(SourceLocation GotoLoc, Scope *CurScope);
2565 
2566   const VarDecl *getCopyElisionCandidate(QualType ReturnType, Expr *E,
2567                                          bool AllowFunctionParameters);
2568 
2569   StmtResult ActOnReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp);
2570   StmtResult ActOnCapScopeReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp);
2571 
2572   StmtResult ActOnGCCAsmStmt(SourceLocation AsmLoc, bool IsSimple,
2573                              bool IsVolatile, unsigned NumOutputs,
2574                              unsigned NumInputs, IdentifierInfo **Names,
2575                              MultiExprArg Constraints, MultiExprArg Exprs,
2576                              Expr *AsmString, MultiExprArg Clobbers,
2577                              SourceLocation RParenLoc);
2578 
2579   StmtResult ActOnMSAsmStmt(SourceLocation AsmLoc, SourceLocation LBraceLoc,
2580                             ArrayRef<Token> AsmToks, SourceLocation EndLoc);
2581 
2582   VarDecl *BuildObjCExceptionDecl(TypeSourceInfo *TInfo, QualType ExceptionType,
2583                                   SourceLocation StartLoc,
2584                                   SourceLocation IdLoc, IdentifierInfo *Id,
2585                                   bool Invalid = false);
2586 
2587   Decl *ActOnObjCExceptionDecl(Scope *S, Declarator &D);
2588 
2589   StmtResult ActOnObjCAtCatchStmt(SourceLocation AtLoc, SourceLocation RParen,
2590                                   Decl *Parm, Stmt *Body);
2591 
2592   StmtResult ActOnObjCAtFinallyStmt(SourceLocation AtLoc, Stmt *Body);
2593 
2594   StmtResult ActOnObjCAtTryStmt(SourceLocation AtLoc, Stmt *Try,
2595                                 MultiStmtArg Catch, Stmt *Finally);
2596 
2597   StmtResult BuildObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw);
2598   StmtResult ActOnObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw,
2599                                   Scope *CurScope);
2600   ExprResult ActOnObjCAtSynchronizedOperand(SourceLocation atLoc,
2601                                             Expr *operand);
2602   StmtResult ActOnObjCAtSynchronizedStmt(SourceLocation AtLoc,
2603                                          Expr *SynchExpr,
2604                                          Stmt *SynchBody);
2605 
2606   StmtResult ActOnObjCAutoreleasePoolStmt(SourceLocation AtLoc, Stmt *Body);
2607 
2608   VarDecl *BuildExceptionDeclaration(Scope *S, TypeSourceInfo *TInfo,
2609                                      SourceLocation StartLoc,
2610                                      SourceLocation IdLoc,
2611                                      IdentifierInfo *Id);
2612 
2613   Decl *ActOnExceptionDeclarator(Scope *S, Declarator &D);
2614 
2615   StmtResult ActOnCXXCatchBlock(SourceLocation CatchLoc,
2616                                 Decl *ExDecl, Stmt *HandlerBlock);
2617   StmtResult ActOnCXXTryBlock(SourceLocation TryLoc, Stmt *TryBlock,
2618                               MultiStmtArg Handlers);
2619 
2620   StmtResult ActOnSEHTryBlock(bool IsCXXTry, // try (true) or __try (false) ?
2621                               SourceLocation TryLoc,
2622                               Stmt *TryBlock,
2623                               Stmt *Handler);
2624 
2625   StmtResult ActOnSEHExceptBlock(SourceLocation Loc,
2626                                  Expr *FilterExpr,
2627                                  Stmt *Block);
2628 
2629   StmtResult ActOnSEHFinallyBlock(SourceLocation Loc,
2630                                   Stmt *Block);
2631 
2632   void DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock);
2633 
2634   bool ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const;
2635 
2636   /// \brief If it's a file scoped decl that must warn if not used, keep track
2637   /// of it.
2638   void MarkUnusedFileScopedDecl(const DeclaratorDecl *D);
2639 
2640   /// DiagnoseUnusedExprResult - If the statement passed in is an expression
2641   /// whose result is unused, warn.
2642   void DiagnoseUnusedExprResult(const Stmt *S);
2643   void DiagnoseUnusedDecl(const NamedDecl *ND);
2644 
2645   /// Emit \p DiagID if statement located on \p StmtLoc has a suspicious null
2646   /// statement as a \p Body, and it is located on the same line.
2647   ///
2648   /// This helps prevent bugs due to typos, such as:
2649   ///     if (condition);
2650   ///       do_stuff();
2651   void DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
2652                              const Stmt *Body,
2653                              unsigned DiagID);
2654 
2655   /// Warn if a for/while loop statement \p S, which is followed by
2656   /// \p PossibleBody, has a suspicious null statement as a body.
2657   void DiagnoseEmptyLoopBody(const Stmt *S,
2658                              const Stmt *PossibleBody);
2659 
PushParsingDeclaration(sema::DelayedDiagnosticPool & pool)2660   ParsingDeclState PushParsingDeclaration(sema::DelayedDiagnosticPool &pool) {
2661     return DelayedDiagnostics.push(pool);
2662   }
2663   void PopParsingDeclaration(ParsingDeclState state, Decl *decl);
2664 
2665   typedef ProcessingContextState ParsingClassState;
PushParsingClass()2666   ParsingClassState PushParsingClass() {
2667     return DelayedDiagnostics.pushUndelayed();
2668   }
PopParsingClass(ParsingClassState state)2669   void PopParsingClass(ParsingClassState state) {
2670     DelayedDiagnostics.popUndelayed(state);
2671   }
2672 
2673   void redelayDiagnostics(sema::DelayedDiagnosticPool &pool);
2674 
2675   void EmitDeprecationWarning(NamedDecl *D, StringRef Message,
2676                               SourceLocation Loc,
2677                               const ObjCInterfaceDecl *UnknownObjCClass=0);
2678 
2679   void HandleDelayedDeprecationCheck(sema::DelayedDiagnostic &DD, Decl *Ctx);
2680 
2681   bool makeUnavailableInSystemHeader(SourceLocation loc,
2682                                      StringRef message);
2683 
2684   //===--------------------------------------------------------------------===//
2685   // Expression Parsing Callbacks: SemaExpr.cpp.
2686 
2687   bool CanUseDecl(NamedDecl *D);
2688   bool DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc,
2689                          const ObjCInterfaceDecl *UnknownObjCClass=0);
2690   void NoteDeletedFunction(FunctionDecl *FD);
2691   std::string getDeletedOrUnavailableSuffix(const FunctionDecl *FD);
2692   bool DiagnosePropertyAccessorMismatch(ObjCPropertyDecl *PD,
2693                                         ObjCMethodDecl *Getter,
2694                                         SourceLocation Loc);
2695   void DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
2696                              Expr **Args, unsigned NumArgs);
2697 
2698   void PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
2699                                        Decl *LambdaContextDecl = 0,
2700                                        bool IsDecltype = false);
2701 
2702   void PopExpressionEvaluationContext();
2703 
2704   void DiscardCleanupsInEvaluationContext();
2705 
2706   ExprResult TranformToPotentiallyEvaluated(Expr *E);
2707   ExprResult HandleExprEvaluationContextForTypeof(Expr *E);
2708 
2709   ExprResult ActOnConstantExpression(ExprResult Res);
2710 
2711   // Functions for marking a declaration referenced.  These functions also
2712   // contain the relevant logic for marking if a reference to a function or
2713   // variable is an odr-use (in the C++11 sense).  There are separate variants
2714   // for expressions referring to a decl; these exist because odr-use marking
2715   // needs to be delayed for some constant variables when we build one of the
2716   // named expressions.
2717   void MarkAnyDeclReferenced(SourceLocation Loc, Decl *D);
2718   void MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func);
2719   void MarkVariableReferenced(SourceLocation Loc, VarDecl *Var);
2720   void MarkDeclRefReferenced(DeclRefExpr *E);
2721   void MarkMemberReferenced(MemberExpr *E);
2722 
2723   void UpdateMarkingForLValueToRValue(Expr *E);
2724   void CleanupVarDeclMarking();
2725 
2726   enum TryCaptureKind {
2727     TryCapture_Implicit, TryCapture_ExplicitByVal, TryCapture_ExplicitByRef
2728   };
2729 
2730   /// \brief Try to capture the given variable.
2731   ///
2732   /// \param Var The variable to capture.
2733   ///
2734   /// \param Loc The location at which the capture occurs.
2735   ///
2736   /// \param Kind The kind of capture, which may be implicit (for either a
2737   /// block or a lambda), or explicit by-value or by-reference (for a lambda).
2738   ///
2739   /// \param EllipsisLoc The location of the ellipsis, if one is provided in
2740   /// an explicit lambda capture.
2741   ///
2742   /// \param BuildAndDiagnose Whether we are actually supposed to add the
2743   /// captures or diagnose errors. If false, this routine merely check whether
2744   /// the capture can occur without performing the capture itself or complaining
2745   /// if the variable cannot be captured.
2746   ///
2747   /// \param CaptureType Will be set to the type of the field used to capture
2748   /// this variable in the innermost block or lambda. Only valid when the
2749   /// variable can be captured.
2750   ///
2751   /// \param DeclRefType Will be set to the type of a reference to the capture
2752   /// from within the current scope. Only valid when the variable can be
2753   /// captured.
2754   ///
2755   /// \returns true if an error occurred (i.e., the variable cannot be
2756   /// captured) and false if the capture succeeded.
2757   bool tryCaptureVariable(VarDecl *Var, SourceLocation Loc, TryCaptureKind Kind,
2758                           SourceLocation EllipsisLoc, bool BuildAndDiagnose,
2759                           QualType &CaptureType,
2760                           QualType &DeclRefType);
2761 
2762   /// \brief Try to capture the given variable.
2763   bool tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
2764                           TryCaptureKind Kind = TryCapture_Implicit,
2765                           SourceLocation EllipsisLoc = SourceLocation());
2766 
2767   /// \brief Given a variable, determine the type that a reference to that
2768   /// variable will have in the given scope.
2769   QualType getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc);
2770 
2771   void MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T);
2772   void MarkDeclarationsReferencedInExpr(Expr *E,
2773                                         bool SkipLocalVariables = false);
2774 
2775   /// \brief Try to recover by turning the given expression into a
2776   /// call.  Returns true if recovery was attempted or an error was
2777   /// emitted; this may also leave the ExprResult invalid.
2778   bool tryToRecoverWithCall(ExprResult &E, const PartialDiagnostic &PD,
2779                             bool ForceComplain = false,
2780                             bool (*IsPlausibleResult)(QualType) = 0);
2781 
2782   /// \brief Figure out if an expression could be turned into a call.
2783   bool isExprCallable(const Expr &E, QualType &ZeroArgCallReturnTy,
2784                       UnresolvedSetImpl &NonTemplateOverloads);
2785 
2786   /// \brief Conditionally issue a diagnostic based on the current
2787   /// evaluation context.
2788   ///
2789   /// \param Statement If Statement is non-null, delay reporting the
2790   /// diagnostic until the function body is parsed, and then do a basic
2791   /// reachability analysis to determine if the statement is reachable.
2792   /// If it is unreachable, the diagnostic will not be emitted.
2793   bool DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
2794                            const PartialDiagnostic &PD);
2795 
2796   // Primary Expressions.
2797   SourceRange getExprRange(Expr *E) const;
2798 
2799   ExprResult ActOnIdExpression(Scope *S, CXXScopeSpec &SS,
2800                                SourceLocation TemplateKWLoc,
2801                                UnqualifiedId &Id,
2802                                bool HasTrailingLParen, bool IsAddressOfOperand,
2803                                CorrectionCandidateCallback *CCC = 0);
2804 
2805   void DecomposeUnqualifiedId(const UnqualifiedId &Id,
2806                               TemplateArgumentListInfo &Buffer,
2807                               DeclarationNameInfo &NameInfo,
2808                               const TemplateArgumentListInfo *&TemplateArgs);
2809 
2810   bool DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
2811                            CorrectionCandidateCallback &CCC,
2812                            TemplateArgumentListInfo *ExplicitTemplateArgs = 0,
2813                        llvm::ArrayRef<Expr *> Args = llvm::ArrayRef<Expr *>());
2814 
2815   ExprResult LookupInObjCMethod(LookupResult &LookUp, Scope *S,
2816                                 IdentifierInfo *II,
2817                                 bool AllowBuiltinCreation=false);
2818 
2819   ExprResult ActOnDependentIdExpression(const CXXScopeSpec &SS,
2820                                         SourceLocation TemplateKWLoc,
2821                                         const DeclarationNameInfo &NameInfo,
2822                                         bool isAddressOfOperand,
2823                                 const TemplateArgumentListInfo *TemplateArgs);
2824 
2825   ExprResult BuildDeclRefExpr(ValueDecl *D, QualType Ty,
2826                               ExprValueKind VK,
2827                               SourceLocation Loc,
2828                               const CXXScopeSpec *SS = 0);
2829   ExprResult BuildDeclRefExpr(ValueDecl *D, QualType Ty,
2830                               ExprValueKind VK,
2831                               const DeclarationNameInfo &NameInfo,
2832                               const CXXScopeSpec *SS = 0);
2833   ExprResult
2834   BuildAnonymousStructUnionMemberReference(const CXXScopeSpec &SS,
2835                                            SourceLocation nameLoc,
2836                                            IndirectFieldDecl *indirectField,
2837                                            Expr *baseObjectExpr = 0,
2838                                       SourceLocation opLoc = SourceLocation());
2839   ExprResult BuildPossibleImplicitMemberExpr(const CXXScopeSpec &SS,
2840                                              SourceLocation TemplateKWLoc,
2841                                              LookupResult &R,
2842                                 const TemplateArgumentListInfo *TemplateArgs);
2843   ExprResult BuildImplicitMemberExpr(const CXXScopeSpec &SS,
2844                                      SourceLocation TemplateKWLoc,
2845                                      LookupResult &R,
2846                                 const TemplateArgumentListInfo *TemplateArgs,
2847                                      bool IsDefiniteInstance);
2848   bool UseArgumentDependentLookup(const CXXScopeSpec &SS,
2849                                   const LookupResult &R,
2850                                   bool HasTrailingLParen);
2851 
2852   ExprResult BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS,
2853                                          const DeclarationNameInfo &NameInfo);
2854   ExprResult BuildDependentDeclRefExpr(const CXXScopeSpec &SS,
2855                                        SourceLocation TemplateKWLoc,
2856                                 const DeclarationNameInfo &NameInfo,
2857                                 const TemplateArgumentListInfo *TemplateArgs);
2858 
2859   ExprResult BuildDeclarationNameExpr(const CXXScopeSpec &SS,
2860                                       LookupResult &R,
2861                                       bool NeedsADL);
2862   ExprResult BuildDeclarationNameExpr(const CXXScopeSpec &SS,
2863                                       const DeclarationNameInfo &NameInfo,
2864                                       NamedDecl *D);
2865 
2866   ExprResult BuildLiteralOperatorCall(LookupResult &R,
2867                                       DeclarationNameInfo &SuffixInfo,
2868                                       ArrayRef<Expr*> Args,
2869                                       SourceLocation LitEndLoc,
2870                             TemplateArgumentListInfo *ExplicitTemplateArgs = 0);
2871 
2872   ExprResult ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind);
2873   ExprResult ActOnIntegerConstant(SourceLocation Loc, uint64_t Val);
2874   ExprResult ActOnNumericConstant(const Token &Tok, Scope *UDLScope = 0);
2875   ExprResult ActOnCharacterConstant(const Token &Tok, Scope *UDLScope = 0);
2876   ExprResult ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E);
2877   ExprResult ActOnParenListExpr(SourceLocation L,
2878                                 SourceLocation R,
2879                                 MultiExprArg Val);
2880 
2881   /// ActOnStringLiteral - The specified tokens were lexed as pasted string
2882   /// fragments (e.g. "foo" "bar" L"baz").
2883   ExprResult ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks,
2884                                 Scope *UDLScope = 0);
2885 
2886   ExprResult ActOnGenericSelectionExpr(SourceLocation KeyLoc,
2887                                        SourceLocation DefaultLoc,
2888                                        SourceLocation RParenLoc,
2889                                        Expr *ControllingExpr,
2890                                        MultiTypeArg ArgTypes,
2891                                        MultiExprArg ArgExprs);
2892   ExprResult CreateGenericSelectionExpr(SourceLocation KeyLoc,
2893                                         SourceLocation DefaultLoc,
2894                                         SourceLocation RParenLoc,
2895                                         Expr *ControllingExpr,
2896                                         TypeSourceInfo **Types,
2897                                         Expr **Exprs,
2898                                         unsigned NumAssocs);
2899 
2900   // Binary/Unary Operators.  'Tok' is the token for the operator.
2901   ExprResult CreateBuiltinUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc,
2902                                   Expr *InputExpr);
2903   ExprResult BuildUnaryOp(Scope *S, SourceLocation OpLoc,
2904                           UnaryOperatorKind Opc, Expr *Input);
2905   ExprResult ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
2906                           tok::TokenKind Op, Expr *Input);
2907 
2908   ExprResult CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
2909                                             SourceLocation OpLoc,
2910                                             UnaryExprOrTypeTrait ExprKind,
2911                                             SourceRange R);
2912   ExprResult CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
2913                                             UnaryExprOrTypeTrait ExprKind);
2914   ExprResult
2915     ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
2916                                   UnaryExprOrTypeTrait ExprKind,
2917                                   bool IsType, void *TyOrEx,
2918                                   const SourceRange &ArgRange);
2919 
2920   ExprResult CheckPlaceholderExpr(Expr *E);
2921   bool CheckVecStepExpr(Expr *E);
2922 
2923   bool CheckUnaryExprOrTypeTraitOperand(Expr *E, UnaryExprOrTypeTrait ExprKind);
2924   bool CheckUnaryExprOrTypeTraitOperand(QualType ExprType, SourceLocation OpLoc,
2925                                         SourceRange ExprRange,
2926                                         UnaryExprOrTypeTrait ExprKind);
2927   ExprResult ActOnSizeofParameterPackExpr(Scope *S,
2928                                           SourceLocation OpLoc,
2929                                           IdentifierInfo &Name,
2930                                           SourceLocation NameLoc,
2931                                           SourceLocation RParenLoc);
2932   ExprResult ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
2933                                  tok::TokenKind Kind, Expr *Input);
2934 
2935   ExprResult ActOnArraySubscriptExpr(Scope *S, Expr *Base, SourceLocation LLoc,
2936                                      Expr *Idx, SourceLocation RLoc);
2937   ExprResult CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
2938                                              Expr *Idx, SourceLocation RLoc);
2939 
2940   ExprResult BuildMemberReferenceExpr(Expr *Base, QualType BaseType,
2941                                       SourceLocation OpLoc, bool IsArrow,
2942                                       CXXScopeSpec &SS,
2943                                       SourceLocation TemplateKWLoc,
2944                                       NamedDecl *FirstQualifierInScope,
2945                                 const DeclarationNameInfo &NameInfo,
2946                                 const TemplateArgumentListInfo *TemplateArgs);
2947 
2948   // This struct is for use by ActOnMemberAccess to allow
2949   // BuildMemberReferenceExpr to be able to reinvoke ActOnMemberAccess after
2950   // changing the access operator from a '.' to a '->' (to see if that is the
2951   // change needed to fix an error about an unknown member, e.g. when the class
2952   // defines a custom operator->).
2953   struct ActOnMemberAccessExtraArgs {
2954     Scope *S;
2955     UnqualifiedId &Id;
2956     Decl *ObjCImpDecl;
2957     bool HasTrailingLParen;
2958   };
2959 
2960   ExprResult BuildMemberReferenceExpr(Expr *Base, QualType BaseType,
2961                                       SourceLocation OpLoc, bool IsArrow,
2962                                       const CXXScopeSpec &SS,
2963                                       SourceLocation TemplateKWLoc,
2964                                       NamedDecl *FirstQualifierInScope,
2965                                       LookupResult &R,
2966                                  const TemplateArgumentListInfo *TemplateArgs,
2967                                       bool SuppressQualifierCheck = false,
2968                                      ActOnMemberAccessExtraArgs *ExtraArgs = 0);
2969 
2970   ExprResult PerformMemberExprBaseConversion(Expr *Base, bool IsArrow);
2971   ExprResult LookupMemberExpr(LookupResult &R, ExprResult &Base,
2972                               bool &IsArrow, SourceLocation OpLoc,
2973                               CXXScopeSpec &SS,
2974                               Decl *ObjCImpDecl,
2975                               bool HasTemplateArgs);
2976 
2977   bool CheckQualifiedMemberReference(Expr *BaseExpr, QualType BaseType,
2978                                      const CXXScopeSpec &SS,
2979                                      const LookupResult &R);
2980 
2981   ExprResult ActOnDependentMemberExpr(Expr *Base, QualType BaseType,
2982                                       bool IsArrow, SourceLocation OpLoc,
2983                                       const CXXScopeSpec &SS,
2984                                       SourceLocation TemplateKWLoc,
2985                                       NamedDecl *FirstQualifierInScope,
2986                                const DeclarationNameInfo &NameInfo,
2987                                const TemplateArgumentListInfo *TemplateArgs);
2988 
2989   ExprResult ActOnMemberAccessExpr(Scope *S, Expr *Base,
2990                                    SourceLocation OpLoc,
2991                                    tok::TokenKind OpKind,
2992                                    CXXScopeSpec &SS,
2993                                    SourceLocation TemplateKWLoc,
2994                                    UnqualifiedId &Member,
2995                                    Decl *ObjCImpDecl,
2996                                    bool HasTrailingLParen);
2997 
2998   void ActOnDefaultCtorInitializers(Decl *CDtorDecl);
2999   bool ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
3000                                FunctionDecl *FDecl,
3001                                const FunctionProtoType *Proto,
3002                                Expr **Args, unsigned NumArgs,
3003                                SourceLocation RParenLoc,
3004                                bool ExecConfig = false);
3005   void CheckStaticArrayArgument(SourceLocation CallLoc,
3006                                 ParmVarDecl *Param,
3007                                 const Expr *ArgExpr);
3008 
3009   /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
3010   /// This provides the location of the left/right parens and a list of comma
3011   /// locations.
3012   ExprResult ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
3013                            MultiExprArg ArgExprs, SourceLocation RParenLoc,
3014                            Expr *ExecConfig = 0, bool IsExecConfig = false);
3015   ExprResult BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
3016                                    SourceLocation LParenLoc,
3017                                    Expr **Args, unsigned NumArgs,
3018                                    SourceLocation RParenLoc,
3019                                    Expr *Config = 0,
3020                                    bool IsExecConfig = false);
3021 
3022   ExprResult ActOnCUDAExecConfigExpr(Scope *S, SourceLocation LLLLoc,
3023                                      MultiExprArg ExecConfig,
3024                                      SourceLocation GGGLoc);
3025 
3026   ExprResult ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
3027                            Declarator &D, ParsedType &Ty,
3028                            SourceLocation RParenLoc, Expr *CastExpr);
3029   ExprResult BuildCStyleCastExpr(SourceLocation LParenLoc,
3030                                  TypeSourceInfo *Ty,
3031                                  SourceLocation RParenLoc,
3032                                  Expr *Op);
3033   CastKind PrepareScalarCast(ExprResult &src, QualType destType);
3034 
3035   /// \brief Build an altivec or OpenCL literal.
3036   ExprResult BuildVectorLiteral(SourceLocation LParenLoc,
3037                                 SourceLocation RParenLoc, Expr *E,
3038                                 TypeSourceInfo *TInfo);
3039 
3040   ExprResult MaybeConvertParenListExprToParenExpr(Scope *S, Expr *ME);
3041 
3042   ExprResult ActOnCompoundLiteral(SourceLocation LParenLoc,
3043                                   ParsedType Ty,
3044                                   SourceLocation RParenLoc,
3045                                   Expr *InitExpr);
3046 
3047   ExprResult BuildCompoundLiteralExpr(SourceLocation LParenLoc,
3048                                       TypeSourceInfo *TInfo,
3049                                       SourceLocation RParenLoc,
3050                                       Expr *LiteralExpr);
3051 
3052   ExprResult ActOnInitList(SourceLocation LBraceLoc,
3053                            MultiExprArg InitArgList,
3054                            SourceLocation RBraceLoc);
3055 
3056   ExprResult ActOnDesignatedInitializer(Designation &Desig,
3057                                         SourceLocation Loc,
3058                                         bool GNUSyntax,
3059                                         ExprResult Init);
3060 
3061   ExprResult ActOnBinOp(Scope *S, SourceLocation TokLoc,
3062                         tok::TokenKind Kind, Expr *LHSExpr, Expr *RHSExpr);
3063   ExprResult BuildBinOp(Scope *S, SourceLocation OpLoc,
3064                         BinaryOperatorKind Opc, Expr *LHSExpr, Expr *RHSExpr);
3065   ExprResult CreateBuiltinBinOp(SourceLocation OpLoc, BinaryOperatorKind Opc,
3066                                 Expr *LHSExpr, Expr *RHSExpr);
3067 
3068   /// ActOnConditionalOp - Parse a ?: operation.  Note that 'LHS' may be null
3069   /// in the case of a the GNU conditional expr extension.
3070   ExprResult ActOnConditionalOp(SourceLocation QuestionLoc,
3071                                 SourceLocation ColonLoc,
3072                                 Expr *CondExpr, Expr *LHSExpr, Expr *RHSExpr);
3073 
3074   /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
3075   ExprResult ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
3076                             LabelDecl *TheDecl);
3077 
3078   void ActOnStartStmtExpr();
3079   ExprResult ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
3080                            SourceLocation RPLoc); // "({..})"
3081   void ActOnStmtExprError();
3082 
3083   // __builtin_offsetof(type, identifier(.identifier|[expr])*)
3084   struct OffsetOfComponent {
3085     SourceLocation LocStart, LocEnd;
3086     bool isBrackets;  // true if [expr], false if .ident
3087     union {
3088       IdentifierInfo *IdentInfo;
3089       Expr *E;
3090     } U;
3091   };
3092 
3093   /// __builtin_offsetof(type, a.b[123][456].c)
3094   ExprResult BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
3095                                   TypeSourceInfo *TInfo,
3096                                   OffsetOfComponent *CompPtr,
3097                                   unsigned NumComponents,
3098                                   SourceLocation RParenLoc);
3099   ExprResult ActOnBuiltinOffsetOf(Scope *S,
3100                                   SourceLocation BuiltinLoc,
3101                                   SourceLocation TypeLoc,
3102                                   ParsedType ParsedArgTy,
3103                                   OffsetOfComponent *CompPtr,
3104                                   unsigned NumComponents,
3105                                   SourceLocation RParenLoc);
3106 
3107   // __builtin_choose_expr(constExpr, expr1, expr2)
3108   ExprResult ActOnChooseExpr(SourceLocation BuiltinLoc,
3109                              Expr *CondExpr, Expr *LHSExpr,
3110                              Expr *RHSExpr, SourceLocation RPLoc);
3111 
3112   // __builtin_va_arg(expr, type)
3113   ExprResult ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty,
3114                         SourceLocation RPLoc);
3115   ExprResult BuildVAArgExpr(SourceLocation BuiltinLoc, Expr *E,
3116                             TypeSourceInfo *TInfo, SourceLocation RPLoc);
3117 
3118   // __null
3119   ExprResult ActOnGNUNullExpr(SourceLocation TokenLoc);
3120 
3121   bool CheckCaseExpression(Expr *E);
3122 
3123   /// \brief Describes the result of an "if-exists" condition check.
3124   enum IfExistsResult {
3125     /// \brief The symbol exists.
3126     IER_Exists,
3127 
3128     /// \brief The symbol does not exist.
3129     IER_DoesNotExist,
3130 
3131     /// \brief The name is a dependent name, so the results will differ
3132     /// from one instantiation to the next.
3133     IER_Dependent,
3134 
3135     /// \brief An error occurred.
3136     IER_Error
3137   };
3138 
3139   IfExistsResult
3140   CheckMicrosoftIfExistsSymbol(Scope *S, CXXScopeSpec &SS,
3141                                const DeclarationNameInfo &TargetNameInfo);
3142 
3143   IfExistsResult
3144   CheckMicrosoftIfExistsSymbol(Scope *S, SourceLocation KeywordLoc,
3145                                bool IsIfExists, CXXScopeSpec &SS,
3146                                UnqualifiedId &Name);
3147 
3148   StmtResult BuildMSDependentExistsStmt(SourceLocation KeywordLoc,
3149                                         bool IsIfExists,
3150                                         NestedNameSpecifierLoc QualifierLoc,
3151                                         DeclarationNameInfo NameInfo,
3152                                         Stmt *Nested);
3153   StmtResult ActOnMSDependentExistsStmt(SourceLocation KeywordLoc,
3154                                         bool IsIfExists,
3155                                         CXXScopeSpec &SS, UnqualifiedId &Name,
3156                                         Stmt *Nested);
3157 
3158   //===------------------------- "Block" Extension ------------------------===//
3159 
3160   /// ActOnBlockStart - This callback is invoked when a block literal is
3161   /// started.
3162   void ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope);
3163 
3164   /// ActOnBlockArguments - This callback allows processing of block arguments.
3165   /// If there are no arguments, this is still invoked.
3166   void ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
3167                            Scope *CurScope);
3168 
3169   /// ActOnBlockError - If there is an error parsing a block, this callback
3170   /// is invoked to pop the information about the block from the action impl.
3171   void ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope);
3172 
3173   /// ActOnBlockStmtExpr - This is called when the body of a block statement
3174   /// literal was successfully completed.  ^(int x){...}
3175   ExprResult ActOnBlockStmtExpr(SourceLocation CaretLoc, Stmt *Body,
3176                                 Scope *CurScope);
3177 
3178   //===---------------------------- OpenCL Features -----------------------===//
3179 
3180   /// __builtin_astype(...)
3181   ExprResult ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
3182                              SourceLocation BuiltinLoc,
3183                              SourceLocation RParenLoc);
3184 
3185   //===---------------------------- C++ Features --------------------------===//
3186 
3187   // Act on C++ namespaces
3188   Decl *ActOnStartNamespaceDef(Scope *S, SourceLocation InlineLoc,
3189                                SourceLocation NamespaceLoc,
3190                                SourceLocation IdentLoc,
3191                                IdentifierInfo *Ident,
3192                                SourceLocation LBrace,
3193                                AttributeList *AttrList);
3194   void ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace);
3195 
3196   NamespaceDecl *getStdNamespace() const;
3197   NamespaceDecl *getOrCreateStdNamespace();
3198 
3199   CXXRecordDecl *getStdBadAlloc() const;
3200 
3201   /// \brief Tests whether Ty is an instance of std::initializer_list and, if
3202   /// it is and Element is not NULL, assigns the element type to Element.
3203   bool isStdInitializerList(QualType Ty, QualType *Element);
3204 
3205   /// \brief Looks for the std::initializer_list template and instantiates it
3206   /// with Element, or emits an error if it's not found.
3207   ///
3208   /// \returns The instantiated template, or null on error.
3209   QualType BuildStdInitializerList(QualType Element, SourceLocation Loc);
3210 
3211   /// \brief Determine whether Ctor is an initializer-list constructor, as
3212   /// defined in [dcl.init.list]p2.
3213   bool isInitListConstructor(const CXXConstructorDecl *Ctor);
3214 
3215   Decl *ActOnUsingDirective(Scope *CurScope,
3216                             SourceLocation UsingLoc,
3217                             SourceLocation NamespcLoc,
3218                             CXXScopeSpec &SS,
3219                             SourceLocation IdentLoc,
3220                             IdentifierInfo *NamespcName,
3221                             AttributeList *AttrList);
3222 
3223   void PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir);
3224 
3225   Decl *ActOnNamespaceAliasDef(Scope *CurScope,
3226                                SourceLocation NamespaceLoc,
3227                                SourceLocation AliasLoc,
3228                                IdentifierInfo *Alias,
3229                                CXXScopeSpec &SS,
3230                                SourceLocation IdentLoc,
3231                                IdentifierInfo *Ident);
3232 
3233   void HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow);
3234   bool CheckUsingShadowDecl(UsingDecl *UD, NamedDecl *Target,
3235                             const LookupResult &PreviousDecls);
3236   UsingShadowDecl *BuildUsingShadowDecl(Scope *S, UsingDecl *UD,
3237                                         NamedDecl *Target);
3238 
3239   bool CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
3240                                    bool isTypeName,
3241                                    const CXXScopeSpec &SS,
3242                                    SourceLocation NameLoc,
3243                                    const LookupResult &Previous);
3244   bool CheckUsingDeclQualifier(SourceLocation UsingLoc,
3245                                const CXXScopeSpec &SS,
3246                                SourceLocation NameLoc);
3247 
3248   NamedDecl *BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
3249                                    SourceLocation UsingLoc,
3250                                    CXXScopeSpec &SS,
3251                                    const DeclarationNameInfo &NameInfo,
3252                                    AttributeList *AttrList,
3253                                    bool IsInstantiation,
3254                                    bool IsTypeName,
3255                                    SourceLocation TypenameLoc);
3256 
3257   bool CheckInheritingConstructorUsingDecl(UsingDecl *UD);
3258 
3259   Decl *ActOnUsingDeclaration(Scope *CurScope,
3260                               AccessSpecifier AS,
3261                               bool HasUsingKeyword,
3262                               SourceLocation UsingLoc,
3263                               CXXScopeSpec &SS,
3264                               UnqualifiedId &Name,
3265                               AttributeList *AttrList,
3266                               bool IsTypeName,
3267                               SourceLocation TypenameLoc);
3268   Decl *ActOnAliasDeclaration(Scope *CurScope,
3269                               AccessSpecifier AS,
3270                               MultiTemplateParamsArg TemplateParams,
3271                               SourceLocation UsingLoc,
3272                               UnqualifiedId &Name,
3273                               TypeResult Type);
3274 
3275   /// InitializeVarWithConstructor - Creates an CXXConstructExpr
3276   /// and sets it as the initializer for the passed in VarDecl.
3277   bool InitializeVarWithConstructor(VarDecl *VD,
3278                                     CXXConstructorDecl *Constructor,
3279                                     MultiExprArg Exprs,
3280                                     bool HadMultipleCandidates);
3281 
3282   /// BuildCXXConstructExpr - Creates a complete call to a constructor,
3283   /// including handling of its default argument expressions.
3284   ///
3285   /// \param ConstructKind - a CXXConstructExpr::ConstructionKind
3286   ExprResult
3287   BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
3288                         CXXConstructorDecl *Constructor, MultiExprArg Exprs,
3289                         bool HadMultipleCandidates, bool RequiresZeroInit,
3290                         unsigned ConstructKind, SourceRange ParenRange);
3291 
3292   // FIXME: Can re remove this and have the above BuildCXXConstructExpr check if
3293   // the constructor can be elidable?
3294   ExprResult
3295   BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
3296                         CXXConstructorDecl *Constructor, bool Elidable,
3297                         MultiExprArg Exprs, bool HadMultipleCandidates,
3298                         bool RequiresZeroInit, unsigned ConstructKind,
3299                         SourceRange ParenRange);
3300 
3301   /// BuildCXXDefaultArgExpr - Creates a CXXDefaultArgExpr, instantiating
3302   /// the default expr if needed.
3303   ExprResult BuildCXXDefaultArgExpr(SourceLocation CallLoc,
3304                                     FunctionDecl *FD,
3305                                     ParmVarDecl *Param);
3306 
3307   /// FinalizeVarWithDestructor - Prepare for calling destructor on the
3308   /// constructed variable.
3309   void FinalizeVarWithDestructor(VarDecl *VD, const RecordType *DeclInitType);
3310 
3311   /// \brief Helper class that collects exception specifications for
3312   /// implicitly-declared special member functions.
3313   class ImplicitExceptionSpecification {
3314     // Pointer to allow copying
3315     Sema *Self;
3316     // We order exception specifications thus:
3317     // noexcept is the most restrictive, but is only used in C++0x.
3318     // throw() comes next.
3319     // Then a throw(collected exceptions)
3320     // Finally no specification.
3321     // throw(...) is used instead if any called function uses it.
3322     //
3323     // If this exception specification cannot be known yet (for instance,
3324     // because this is the exception specification for a defaulted default
3325     // constructor and we haven't finished parsing the deferred parts of the
3326     // class yet), the C++0x standard does not specify how to behave. We
3327     // record this as an 'unknown' exception specification, which overrules
3328     // any other specification (even 'none', to keep this rule simple).
3329     ExceptionSpecificationType ComputedEST;
3330     llvm::SmallPtrSet<CanQualType, 4> ExceptionsSeen;
3331     SmallVector<QualType, 4> Exceptions;
3332 
ClearExceptions()3333     void ClearExceptions() {
3334       ExceptionsSeen.clear();
3335       Exceptions.clear();
3336     }
3337 
3338   public:
ImplicitExceptionSpecification(Sema & Self)3339     explicit ImplicitExceptionSpecification(Sema &Self)
3340       : Self(&Self), ComputedEST(EST_BasicNoexcept) {
3341       if (!Self.getLangOpts().CPlusPlus0x)
3342         ComputedEST = EST_DynamicNone;
3343     }
3344 
3345     /// \brief Get the computed exception specification type.
getExceptionSpecType()3346     ExceptionSpecificationType getExceptionSpecType() const {
3347       assert(ComputedEST != EST_ComputedNoexcept &&
3348              "noexcept(expr) should not be a possible result");
3349       return ComputedEST;
3350     }
3351 
3352     /// \brief The number of exceptions in the exception specification.
size()3353     unsigned size() const { return Exceptions.size(); }
3354 
3355     /// \brief The set of exceptions in the exception specification.
data()3356     const QualType *data() const { return Exceptions.data(); }
3357 
3358     /// \brief Integrate another called method into the collected data.
3359     void CalledDecl(SourceLocation CallLoc, CXXMethodDecl *Method);
3360 
3361     /// \brief Integrate an invoked expression into the collected data.
3362     void CalledExpr(Expr *E);
3363 
3364     /// \brief Overwrite an EPI's exception specification with this
3365     /// computed exception specification.
getEPI(FunctionProtoType::ExtProtoInfo & EPI)3366     void getEPI(FunctionProtoType::ExtProtoInfo &EPI) const {
3367       EPI.ExceptionSpecType = getExceptionSpecType();
3368       EPI.NumExceptions = size();
3369       EPI.Exceptions = data();
3370     }
getEPI()3371     FunctionProtoType::ExtProtoInfo getEPI() const {
3372       FunctionProtoType::ExtProtoInfo EPI;
3373       getEPI(EPI);
3374       return EPI;
3375     }
3376   };
3377 
3378   /// \brief Determine what sort of exception specification a defaulted
3379   /// copy constructor of a class will have.
3380   ImplicitExceptionSpecification
3381   ComputeDefaultedDefaultCtorExceptionSpec(SourceLocation Loc,
3382                                            CXXMethodDecl *MD);
3383 
3384   /// \brief Determine what sort of exception specification a defaulted
3385   /// default constructor of a class will have, and whether the parameter
3386   /// will be const.
3387   ImplicitExceptionSpecification
3388   ComputeDefaultedCopyCtorExceptionSpec(CXXMethodDecl *MD);
3389 
3390   /// \brief Determine what sort of exception specification a defautled
3391   /// copy assignment operator of a class will have, and whether the
3392   /// parameter will be const.
3393   ImplicitExceptionSpecification
3394   ComputeDefaultedCopyAssignmentExceptionSpec(CXXMethodDecl *MD);
3395 
3396   /// \brief Determine what sort of exception specification a defaulted move
3397   /// constructor of a class will have.
3398   ImplicitExceptionSpecification
3399   ComputeDefaultedMoveCtorExceptionSpec(CXXMethodDecl *MD);
3400 
3401   /// \brief Determine what sort of exception specification a defaulted move
3402   /// assignment operator of a class will have.
3403   ImplicitExceptionSpecification
3404   ComputeDefaultedMoveAssignmentExceptionSpec(CXXMethodDecl *MD);
3405 
3406   /// \brief Determine what sort of exception specification a defaulted
3407   /// destructor of a class will have.
3408   ImplicitExceptionSpecification
3409   ComputeDefaultedDtorExceptionSpec(CXXMethodDecl *MD);
3410 
3411   /// \brief Evaluate the implicit exception specification for a defaulted
3412   /// special member function.
3413   void EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD);
3414 
3415   /// \brief Check the given exception-specification and update the
3416   /// extended prototype information with the results.
3417   void checkExceptionSpecification(ExceptionSpecificationType EST,
3418                                    ArrayRef<ParsedType> DynamicExceptions,
3419                                    ArrayRef<SourceRange> DynamicExceptionRanges,
3420                                    Expr *NoexceptExpr,
3421                                    llvm::SmallVectorImpl<QualType> &Exceptions,
3422                                    FunctionProtoType::ExtProtoInfo &EPI);
3423 
3424   /// \brief Determine if a special member function should have a deleted
3425   /// definition when it is defaulted.
3426   bool ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
3427                                  bool Diagnose = false);
3428 
3429   /// \brief Declare the implicit default constructor for the given class.
3430   ///
3431   /// \param ClassDecl The class declaration into which the implicit
3432   /// default constructor will be added.
3433   ///
3434   /// \returns The implicitly-declared default constructor.
3435   CXXConstructorDecl *DeclareImplicitDefaultConstructor(
3436                                                      CXXRecordDecl *ClassDecl);
3437 
3438   /// DefineImplicitDefaultConstructor - Checks for feasibility of
3439   /// defining this constructor as the default constructor.
3440   void DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
3441                                         CXXConstructorDecl *Constructor);
3442 
3443   /// \brief Declare the implicit destructor for the given class.
3444   ///
3445   /// \param ClassDecl The class declaration into which the implicit
3446   /// destructor will be added.
3447   ///
3448   /// \returns The implicitly-declared destructor.
3449   CXXDestructorDecl *DeclareImplicitDestructor(CXXRecordDecl *ClassDecl);
3450 
3451   /// DefineImplicitDestructor - Checks for feasibility of
3452   /// defining this destructor as the default destructor.
3453   void DefineImplicitDestructor(SourceLocation CurrentLocation,
3454                                 CXXDestructorDecl *Destructor);
3455 
3456   /// \brief Build an exception spec for destructors that don't have one.
3457   ///
3458   /// C++11 says that user-defined destructors with no exception spec get one
3459   /// that looks as if the destructor was implicitly declared.
3460   void AdjustDestructorExceptionSpec(CXXRecordDecl *ClassDecl,
3461                                      CXXDestructorDecl *Destructor);
3462 
3463   /// \brief Declare all inherited constructors for the given class.
3464   ///
3465   /// \param ClassDecl The class declaration into which the inherited
3466   /// constructors will be added.
3467   void DeclareInheritedConstructors(CXXRecordDecl *ClassDecl);
3468 
3469   /// \brief Declare the implicit copy constructor for the given class.
3470   ///
3471   /// \param ClassDecl The class declaration into which the implicit
3472   /// copy constructor will be added.
3473   ///
3474   /// \returns The implicitly-declared copy constructor.
3475   CXXConstructorDecl *DeclareImplicitCopyConstructor(CXXRecordDecl *ClassDecl);
3476 
3477   /// DefineImplicitCopyConstructor - Checks for feasibility of
3478   /// defining this constructor as the copy constructor.
3479   void DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
3480                                      CXXConstructorDecl *Constructor);
3481 
3482   /// \brief Declare the implicit move constructor for the given class.
3483   ///
3484   /// \param ClassDecl The Class declaration into which the implicit
3485   /// move constructor will be added.
3486   ///
3487   /// \returns The implicitly-declared move constructor, or NULL if it wasn't
3488   /// declared.
3489   CXXConstructorDecl *DeclareImplicitMoveConstructor(CXXRecordDecl *ClassDecl);
3490 
3491   /// DefineImplicitMoveConstructor - Checks for feasibility of
3492   /// defining this constructor as the move constructor.
3493   void DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
3494                                      CXXConstructorDecl *Constructor);
3495 
3496   /// \brief Declare the implicit copy assignment operator for the given class.
3497   ///
3498   /// \param ClassDecl The class declaration into which the implicit
3499   /// copy assignment operator will be added.
3500   ///
3501   /// \returns The implicitly-declared copy assignment operator.
3502   CXXMethodDecl *DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl);
3503 
3504   /// \brief Defines an implicitly-declared copy assignment operator.
3505   void DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
3506                                     CXXMethodDecl *MethodDecl);
3507 
3508   /// \brief Declare the implicit move assignment operator for the given class.
3509   ///
3510   /// \param ClassDecl The Class declaration into which the implicit
3511   /// move assignment operator will be added.
3512   ///
3513   /// \returns The implicitly-declared move assignment operator, or NULL if it
3514   /// wasn't declared.
3515   CXXMethodDecl *DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl);
3516 
3517   /// \brief Defines an implicitly-declared move assignment operator.
3518   void DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
3519                                     CXXMethodDecl *MethodDecl);
3520 
3521   /// \brief Force the declaration of any implicitly-declared members of this
3522   /// class.
3523   void ForceDeclarationOfImplicitMembers(CXXRecordDecl *Class);
3524 
3525   /// \brief Determine whether the given function is an implicitly-deleted
3526   /// special member function.
3527   bool isImplicitlyDeleted(FunctionDecl *FD);
3528 
3529   /// \brief Check whether 'this' shows up in the type of a static member
3530   /// function after the (naturally empty) cv-qualifier-seq would be.
3531   ///
3532   /// \returns true if an error occurred.
3533   bool checkThisInStaticMemberFunctionType(CXXMethodDecl *Method);
3534 
3535   /// \brief Whether this' shows up in the exception specification of a static
3536   /// member function.
3537   bool checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method);
3538 
3539   /// \brief Check whether 'this' shows up in the attributes of the given
3540   /// static member function.
3541   ///
3542   /// \returns true if an error occurred.
3543   bool checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method);
3544 
3545   /// MaybeBindToTemporary - If the passed in expression has a record type with
3546   /// a non-trivial destructor, this will return CXXBindTemporaryExpr. Otherwise
3547   /// it simply returns the passed in expression.
3548   ExprResult MaybeBindToTemporary(Expr *E);
3549 
3550   bool CompleteConstructorCall(CXXConstructorDecl *Constructor,
3551                                MultiExprArg ArgsPtr,
3552                                SourceLocation Loc,
3553                                SmallVectorImpl<Expr*> &ConvertedArgs,
3554                                bool AllowExplicit = false);
3555 
3556   ParsedType getDestructorName(SourceLocation TildeLoc,
3557                                IdentifierInfo &II, SourceLocation NameLoc,
3558                                Scope *S, CXXScopeSpec &SS,
3559                                ParsedType ObjectType,
3560                                bool EnteringContext);
3561 
3562   ParsedType getDestructorType(const DeclSpec& DS, ParsedType ObjectType);
3563 
3564   // Checks that reinterpret casts don't have undefined behavior.
3565   void CheckCompatibleReinterpretCast(QualType SrcType, QualType DestType,
3566                                       bool IsDereference, SourceRange Range);
3567 
3568   /// ActOnCXXNamedCast - Parse {dynamic,static,reinterpret,const}_cast's.
3569   ExprResult ActOnCXXNamedCast(SourceLocation OpLoc,
3570                                tok::TokenKind Kind,
3571                                SourceLocation LAngleBracketLoc,
3572                                Declarator &D,
3573                                SourceLocation RAngleBracketLoc,
3574                                SourceLocation LParenLoc,
3575                                Expr *E,
3576                                SourceLocation RParenLoc);
3577 
3578   ExprResult BuildCXXNamedCast(SourceLocation OpLoc,
3579                                tok::TokenKind Kind,
3580                                TypeSourceInfo *Ty,
3581                                Expr *E,
3582                                SourceRange AngleBrackets,
3583                                SourceRange Parens);
3584 
3585   ExprResult BuildCXXTypeId(QualType TypeInfoType,
3586                             SourceLocation TypeidLoc,
3587                             TypeSourceInfo *Operand,
3588                             SourceLocation RParenLoc);
3589   ExprResult BuildCXXTypeId(QualType TypeInfoType,
3590                             SourceLocation TypeidLoc,
3591                             Expr *Operand,
3592                             SourceLocation RParenLoc);
3593 
3594   /// ActOnCXXTypeid - Parse typeid( something ).
3595   ExprResult ActOnCXXTypeid(SourceLocation OpLoc,
3596                             SourceLocation LParenLoc, bool isType,
3597                             void *TyOrExpr,
3598                             SourceLocation RParenLoc);
3599 
3600   ExprResult BuildCXXUuidof(QualType TypeInfoType,
3601                             SourceLocation TypeidLoc,
3602                             TypeSourceInfo *Operand,
3603                             SourceLocation RParenLoc);
3604   ExprResult BuildCXXUuidof(QualType TypeInfoType,
3605                             SourceLocation TypeidLoc,
3606                             Expr *Operand,
3607                             SourceLocation RParenLoc);
3608 
3609   /// ActOnCXXUuidof - Parse __uuidof( something ).
3610   ExprResult ActOnCXXUuidof(SourceLocation OpLoc,
3611                             SourceLocation LParenLoc, bool isType,
3612                             void *TyOrExpr,
3613                             SourceLocation RParenLoc);
3614 
3615 
3616   //// ActOnCXXThis -  Parse 'this' pointer.
3617   ExprResult ActOnCXXThis(SourceLocation loc);
3618 
3619   /// \brief Try to retrieve the type of the 'this' pointer.
3620   ///
3621   /// \returns The type of 'this', if possible. Otherwise, returns a NULL type.
3622   QualType getCurrentThisType();
3623 
3624   /// \brief When non-NULL, the C++ 'this' expression is allowed despite the
3625   /// current context not being a non-static member function. In such cases,
3626   /// this provides the type used for 'this'.
3627   QualType CXXThisTypeOverride;
3628 
3629   /// \brief RAII object used to temporarily allow the C++ 'this' expression
3630   /// to be used, with the given qualifiers on the current class type.
3631   class CXXThisScopeRAII {
3632     Sema &S;
3633     QualType OldCXXThisTypeOverride;
3634     bool Enabled;
3635 
3636   public:
3637     /// \brief Introduce a new scope where 'this' may be allowed (when enabled),
3638     /// using the given declaration (which is either a class template or a
3639     /// class) along with the given qualifiers.
3640     /// along with the qualifiers placed on '*this'.
3641     CXXThisScopeRAII(Sema &S, Decl *ContextDecl, unsigned CXXThisTypeQuals,
3642                      bool Enabled = true);
3643 
3644     ~CXXThisScopeRAII();
3645   };
3646 
3647   /// \brief Make sure the value of 'this' is actually available in the current
3648   /// context, if it is a potentially evaluated context.
3649   ///
3650   /// \param Loc The location at which the capture of 'this' occurs.
3651   ///
3652   /// \param Explicit Whether 'this' is explicitly captured in a lambda
3653   /// capture list.
3654   void CheckCXXThisCapture(SourceLocation Loc, bool Explicit = false);
3655 
3656   /// \brief Determine whether the given type is the type of *this that is used
3657   /// outside of the body of a member function for a type that is currently
3658   /// being defined.
3659   bool isThisOutsideMemberFunctionBody(QualType BaseType);
3660 
3661   /// ActOnCXXBoolLiteral - Parse {true,false} literals.
3662   ExprResult ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind);
3663 
3664 
3665   /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
3666   ExprResult ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind);
3667 
3668   /// ActOnCXXNullPtrLiteral - Parse 'nullptr'.
3669   ExprResult ActOnCXXNullPtrLiteral(SourceLocation Loc);
3670 
3671   //// ActOnCXXThrow -  Parse throw expressions.
3672   ExprResult ActOnCXXThrow(Scope *S, SourceLocation OpLoc, Expr *expr);
3673   ExprResult BuildCXXThrow(SourceLocation OpLoc, Expr *Ex,
3674                            bool IsThrownVarInScope);
3675   ExprResult CheckCXXThrowOperand(SourceLocation ThrowLoc, Expr *E,
3676                                   bool IsThrownVarInScope);
3677 
3678   /// ActOnCXXTypeConstructExpr - Parse construction of a specified type.
3679   /// Can be interpreted either as function-style casting ("int(x)")
3680   /// or class type construction ("ClassType(x,y,z)")
3681   /// or creation of a value-initialized type ("int()").
3682   ExprResult ActOnCXXTypeConstructExpr(ParsedType TypeRep,
3683                                        SourceLocation LParenLoc,
3684                                        MultiExprArg Exprs,
3685                                        SourceLocation RParenLoc);
3686 
3687   ExprResult BuildCXXTypeConstructExpr(TypeSourceInfo *Type,
3688                                        SourceLocation LParenLoc,
3689                                        MultiExprArg Exprs,
3690                                        SourceLocation RParenLoc);
3691 
3692   /// ActOnCXXNew - Parsed a C++ 'new' expression.
3693   ExprResult ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
3694                          SourceLocation PlacementLParen,
3695                          MultiExprArg PlacementArgs,
3696                          SourceLocation PlacementRParen,
3697                          SourceRange TypeIdParens, Declarator &D,
3698                          Expr *Initializer);
3699   ExprResult BuildCXXNew(SourceLocation StartLoc, bool UseGlobal,
3700                          SourceLocation PlacementLParen,
3701                          MultiExprArg PlacementArgs,
3702                          SourceLocation PlacementRParen,
3703                          SourceRange TypeIdParens,
3704                          QualType AllocType,
3705                          TypeSourceInfo *AllocTypeInfo,
3706                          Expr *ArraySize,
3707                          SourceRange DirectInitRange,
3708                          Expr *Initializer,
3709                          bool TypeMayContainAuto = true);
3710 
3711   bool CheckAllocatedType(QualType AllocType, SourceLocation Loc,
3712                           SourceRange R);
3713   bool FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,
3714                                bool UseGlobal, QualType AllocType, bool IsArray,
3715                                Expr **PlaceArgs, unsigned NumPlaceArgs,
3716                                FunctionDecl *&OperatorNew,
3717                                FunctionDecl *&OperatorDelete);
3718   bool FindAllocationOverload(SourceLocation StartLoc, SourceRange Range,
3719                               DeclarationName Name, Expr** Args,
3720                               unsigned NumArgs, DeclContext *Ctx,
3721                               bool AllowMissing, FunctionDecl *&Operator,
3722                               bool Diagnose = true);
3723   void DeclareGlobalNewDelete();
3724   void DeclareGlobalAllocationFunction(DeclarationName Name, QualType Return,
3725                                        QualType Argument,
3726                                        bool addMallocAttr = false);
3727 
3728   bool FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD,
3729                                 DeclarationName Name, FunctionDecl* &Operator,
3730                                 bool Diagnose = true);
3731 
3732   /// ActOnCXXDelete - Parsed a C++ 'delete' expression
3733   ExprResult ActOnCXXDelete(SourceLocation StartLoc,
3734                             bool UseGlobal, bool ArrayForm,
3735                             Expr *Operand);
3736 
3737   DeclResult ActOnCXXConditionDeclaration(Scope *S, Declarator &D);
3738   ExprResult CheckConditionVariable(VarDecl *ConditionVar,
3739                                     SourceLocation StmtLoc,
3740                                     bool ConvertToBoolean);
3741 
3742   ExprResult ActOnNoexceptExpr(SourceLocation KeyLoc, SourceLocation LParen,
3743                                Expr *Operand, SourceLocation RParen);
3744   ExprResult BuildCXXNoexceptExpr(SourceLocation KeyLoc, Expr *Operand,
3745                                   SourceLocation RParen);
3746 
3747   /// ActOnUnaryTypeTrait - Parsed one of the unary type trait support
3748   /// pseudo-functions.
3749   ExprResult ActOnUnaryTypeTrait(UnaryTypeTrait OTT,
3750                                  SourceLocation KWLoc,
3751                                  ParsedType Ty,
3752                                  SourceLocation RParen);
3753 
3754   ExprResult BuildUnaryTypeTrait(UnaryTypeTrait OTT,
3755                                  SourceLocation KWLoc,
3756                                  TypeSourceInfo *T,
3757                                  SourceLocation RParen);
3758 
3759   /// ActOnBinaryTypeTrait - Parsed one of the bianry type trait support
3760   /// pseudo-functions.
3761   ExprResult ActOnBinaryTypeTrait(BinaryTypeTrait OTT,
3762                                   SourceLocation KWLoc,
3763                                   ParsedType LhsTy,
3764                                   ParsedType RhsTy,
3765                                   SourceLocation RParen);
3766 
3767   ExprResult BuildBinaryTypeTrait(BinaryTypeTrait BTT,
3768                                   SourceLocation KWLoc,
3769                                   TypeSourceInfo *LhsT,
3770                                   TypeSourceInfo *RhsT,
3771                                   SourceLocation RParen);
3772 
3773   /// \brief Parsed one of the type trait support pseudo-functions.
3774   ExprResult ActOnTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
3775                             ArrayRef<ParsedType> Args,
3776                             SourceLocation RParenLoc);
3777   ExprResult BuildTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
3778                             ArrayRef<TypeSourceInfo *> Args,
3779                             SourceLocation RParenLoc);
3780 
3781   /// ActOnArrayTypeTrait - Parsed one of the bianry type trait support
3782   /// pseudo-functions.
3783   ExprResult ActOnArrayTypeTrait(ArrayTypeTrait ATT,
3784                                  SourceLocation KWLoc,
3785                                  ParsedType LhsTy,
3786                                  Expr *DimExpr,
3787                                  SourceLocation RParen);
3788 
3789   ExprResult BuildArrayTypeTrait(ArrayTypeTrait ATT,
3790                                  SourceLocation KWLoc,
3791                                  TypeSourceInfo *TSInfo,
3792                                  Expr *DimExpr,
3793                                  SourceLocation RParen);
3794 
3795   /// ActOnExpressionTrait - Parsed one of the unary type trait support
3796   /// pseudo-functions.
3797   ExprResult ActOnExpressionTrait(ExpressionTrait OET,
3798                                   SourceLocation KWLoc,
3799                                   Expr *Queried,
3800                                   SourceLocation RParen);
3801 
3802   ExprResult BuildExpressionTrait(ExpressionTrait OET,
3803                                   SourceLocation KWLoc,
3804                                   Expr *Queried,
3805                                   SourceLocation RParen);
3806 
3807   ExprResult ActOnStartCXXMemberReference(Scope *S,
3808                                           Expr *Base,
3809                                           SourceLocation OpLoc,
3810                                           tok::TokenKind OpKind,
3811                                           ParsedType &ObjectType,
3812                                           bool &MayBePseudoDestructor);
3813 
3814   ExprResult DiagnoseDtorReference(SourceLocation NameLoc, Expr *MemExpr);
3815 
3816   ExprResult BuildPseudoDestructorExpr(Expr *Base,
3817                                        SourceLocation OpLoc,
3818                                        tok::TokenKind OpKind,
3819                                        const CXXScopeSpec &SS,
3820                                        TypeSourceInfo *ScopeType,
3821                                        SourceLocation CCLoc,
3822                                        SourceLocation TildeLoc,
3823                                      PseudoDestructorTypeStorage DestroyedType,
3824                                        bool HasTrailingLParen);
3825 
3826   ExprResult ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
3827                                        SourceLocation OpLoc,
3828                                        tok::TokenKind OpKind,
3829                                        CXXScopeSpec &SS,
3830                                        UnqualifiedId &FirstTypeName,
3831                                        SourceLocation CCLoc,
3832                                        SourceLocation TildeLoc,
3833                                        UnqualifiedId &SecondTypeName,
3834                                        bool HasTrailingLParen);
3835 
3836   ExprResult ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
3837                                        SourceLocation OpLoc,
3838                                        tok::TokenKind OpKind,
3839                                        SourceLocation TildeLoc,
3840                                        const DeclSpec& DS,
3841                                        bool HasTrailingLParen);
3842 
3843   /// MaybeCreateExprWithCleanups - If the current full-expression
3844   /// requires any cleanups, surround it with a ExprWithCleanups node.
3845   /// Otherwise, just returns the passed-in expression.
3846   Expr *MaybeCreateExprWithCleanups(Expr *SubExpr);
3847   Stmt *MaybeCreateStmtWithCleanups(Stmt *SubStmt);
3848   ExprResult MaybeCreateExprWithCleanups(ExprResult SubExpr);
3849 
ActOnFinishFullExpr(Expr * Expr)3850   ExprResult ActOnFinishFullExpr(Expr *Expr) {
3851     return ActOnFinishFullExpr(Expr, Expr ? Expr->getExprLoc()
3852                                           : SourceLocation());
3853   }
3854   ExprResult ActOnFinishFullExpr(Expr *Expr, SourceLocation CC);
3855   StmtResult ActOnFinishFullStmt(Stmt *Stmt);
3856 
3857   // Marks SS invalid if it represents an incomplete type.
3858   bool RequireCompleteDeclContext(CXXScopeSpec &SS, DeclContext *DC);
3859 
3860   DeclContext *computeDeclContext(QualType T);
3861   DeclContext *computeDeclContext(const CXXScopeSpec &SS,
3862                                   bool EnteringContext = false);
3863   bool isDependentScopeSpecifier(const CXXScopeSpec &SS);
3864   CXXRecordDecl *getCurrentInstantiationOf(NestedNameSpecifier *NNS);
3865   bool isUnknownSpecialization(const CXXScopeSpec &SS);
3866 
3867   /// \brief The parser has parsed a global nested-name-specifier '::'.
3868   ///
3869   /// \param S The scope in which this nested-name-specifier occurs.
3870   ///
3871   /// \param CCLoc The location of the '::'.
3872   ///
3873   /// \param SS The nested-name-specifier, which will be updated in-place
3874   /// to reflect the parsed nested-name-specifier.
3875   ///
3876   /// \returns true if an error occurred, false otherwise.
3877   bool ActOnCXXGlobalScopeSpecifier(Scope *S, SourceLocation CCLoc,
3878                                     CXXScopeSpec &SS);
3879 
3880   bool isAcceptableNestedNameSpecifier(NamedDecl *SD);
3881   NamedDecl *FindFirstQualifierInScope(Scope *S, NestedNameSpecifier *NNS);
3882 
3883   bool isNonTypeNestedNameSpecifier(Scope *S, CXXScopeSpec &SS,
3884                                     SourceLocation IdLoc,
3885                                     IdentifierInfo &II,
3886                                     ParsedType ObjectType);
3887 
3888   bool BuildCXXNestedNameSpecifier(Scope *S,
3889                                    IdentifierInfo &Identifier,
3890                                    SourceLocation IdentifierLoc,
3891                                    SourceLocation CCLoc,
3892                                    QualType ObjectType,
3893                                    bool EnteringContext,
3894                                    CXXScopeSpec &SS,
3895                                    NamedDecl *ScopeLookupResult,
3896                                    bool ErrorRecoveryLookup);
3897 
3898   /// \brief The parser has parsed a nested-name-specifier 'identifier::'.
3899   ///
3900   /// \param S The scope in which this nested-name-specifier occurs.
3901   ///
3902   /// \param Identifier The identifier preceding the '::'.
3903   ///
3904   /// \param IdentifierLoc The location of the identifier.
3905   ///
3906   /// \param CCLoc The location of the '::'.
3907   ///
3908   /// \param ObjectType The type of the object, if we're parsing
3909   /// nested-name-specifier in a member access expression.
3910   ///
3911   /// \param EnteringContext Whether we're entering the context nominated by
3912   /// this nested-name-specifier.
3913   ///
3914   /// \param SS The nested-name-specifier, which is both an input
3915   /// parameter (the nested-name-specifier before this type) and an
3916   /// output parameter (containing the full nested-name-specifier,
3917   /// including this new type).
3918   ///
3919   /// \returns true if an error occurred, false otherwise.
3920   bool ActOnCXXNestedNameSpecifier(Scope *S,
3921                                    IdentifierInfo &Identifier,
3922                                    SourceLocation IdentifierLoc,
3923                                    SourceLocation CCLoc,
3924                                    ParsedType ObjectType,
3925                                    bool EnteringContext,
3926                                    CXXScopeSpec &SS);
3927 
3928   ExprResult ActOnDecltypeExpression(Expr *E);
3929 
3930   bool ActOnCXXNestedNameSpecifierDecltype(CXXScopeSpec &SS,
3931                                            const DeclSpec &DS,
3932                                            SourceLocation ColonColonLoc);
3933 
3934   bool IsInvalidUnlessNestedName(Scope *S, CXXScopeSpec &SS,
3935                                  IdentifierInfo &Identifier,
3936                                  SourceLocation IdentifierLoc,
3937                                  SourceLocation ColonLoc,
3938                                  ParsedType ObjectType,
3939                                  bool EnteringContext);
3940 
3941   /// \brief The parser has parsed a nested-name-specifier
3942   /// 'template[opt] template-name < template-args >::'.
3943   ///
3944   /// \param S The scope in which this nested-name-specifier occurs.
3945   ///
3946   /// \param SS The nested-name-specifier, which is both an input
3947   /// parameter (the nested-name-specifier before this type) and an
3948   /// output parameter (containing the full nested-name-specifier,
3949   /// including this new type).
3950   ///
3951   /// \param TemplateKWLoc the location of the 'template' keyword, if any.
3952   /// \param TemplateName the template name.
3953   /// \param TemplateNameLoc The location of the template name.
3954   /// \param LAngleLoc The location of the opening angle bracket  ('<').
3955   /// \param TemplateArgs The template arguments.
3956   /// \param RAngleLoc The location of the closing angle bracket  ('>').
3957   /// \param CCLoc The location of the '::'.
3958   ///
3959   /// \param EnteringContext Whether we're entering the context of the
3960   /// nested-name-specifier.
3961   ///
3962   ///
3963   /// \returns true if an error occurred, false otherwise.
3964   bool ActOnCXXNestedNameSpecifier(Scope *S,
3965                                    CXXScopeSpec &SS,
3966                                    SourceLocation TemplateKWLoc,
3967                                    TemplateTy TemplateName,
3968                                    SourceLocation TemplateNameLoc,
3969                                    SourceLocation LAngleLoc,
3970                                    ASTTemplateArgsPtr TemplateArgs,
3971                                    SourceLocation RAngleLoc,
3972                                    SourceLocation CCLoc,
3973                                    bool EnteringContext);
3974 
3975   /// \brief Given a C++ nested-name-specifier, produce an annotation value
3976   /// that the parser can use later to reconstruct the given
3977   /// nested-name-specifier.
3978   ///
3979   /// \param SS A nested-name-specifier.
3980   ///
3981   /// \returns A pointer containing all of the information in the
3982   /// nested-name-specifier \p SS.
3983   void *SaveNestedNameSpecifierAnnotation(CXXScopeSpec &SS);
3984 
3985   /// \brief Given an annotation pointer for a nested-name-specifier, restore
3986   /// the nested-name-specifier structure.
3987   ///
3988   /// \param Annotation The annotation pointer, produced by
3989   /// \c SaveNestedNameSpecifierAnnotation().
3990   ///
3991   /// \param AnnotationRange The source range corresponding to the annotation.
3992   ///
3993   /// \param SS The nested-name-specifier that will be updated with the contents
3994   /// of the annotation pointer.
3995   void RestoreNestedNameSpecifierAnnotation(void *Annotation,
3996                                             SourceRange AnnotationRange,
3997                                             CXXScopeSpec &SS);
3998 
3999   bool ShouldEnterDeclaratorScope(Scope *S, const CXXScopeSpec &SS);
4000 
4001   /// ActOnCXXEnterDeclaratorScope - Called when a C++ scope specifier (global
4002   /// scope or nested-name-specifier) is parsed, part of a declarator-id.
4003   /// After this method is called, according to [C++ 3.4.3p3], names should be
4004   /// looked up in the declarator-id's scope, until the declarator is parsed and
4005   /// ActOnCXXExitDeclaratorScope is called.
4006   /// The 'SS' should be a non-empty valid CXXScopeSpec.
4007   bool ActOnCXXEnterDeclaratorScope(Scope *S, CXXScopeSpec &SS);
4008 
4009   /// ActOnCXXExitDeclaratorScope - Called when a declarator that previously
4010   /// invoked ActOnCXXEnterDeclaratorScope(), is finished. 'SS' is the same
4011   /// CXXScopeSpec that was passed to ActOnCXXEnterDeclaratorScope as well.
4012   /// Used to indicate that names should revert to being looked up in the
4013   /// defining scope.
4014   void ActOnCXXExitDeclaratorScope(Scope *S, const CXXScopeSpec &SS);
4015 
4016   /// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse an
4017   /// initializer for the declaration 'Dcl'.
4018   /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
4019   /// static data member of class X, names should be looked up in the scope of
4020   /// class X.
4021   void ActOnCXXEnterDeclInitializer(Scope *S, Decl *Dcl);
4022 
4023   /// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
4024   /// initializer for the declaration 'Dcl'.
4025   void ActOnCXXExitDeclInitializer(Scope *S, Decl *Dcl);
4026 
4027   /// \brief Create a new lambda closure type.
4028   CXXRecordDecl *createLambdaClosureType(SourceRange IntroducerRange,
4029                                          bool KnownDependent = false);
4030 
4031   /// \brief Start the definition of a lambda expression.
4032   CXXMethodDecl *startLambdaDefinition(CXXRecordDecl *Class,
4033                                        SourceRange IntroducerRange,
4034                                        TypeSourceInfo *MethodType,
4035                                        SourceLocation EndLoc,
4036                                        llvm::ArrayRef<ParmVarDecl *> Params);
4037 
4038   /// \brief Introduce the scope for a lambda expression.
4039   sema::LambdaScopeInfo *enterLambdaScope(CXXMethodDecl *CallOperator,
4040                                           SourceRange IntroducerRange,
4041                                           LambdaCaptureDefault CaptureDefault,
4042                                           bool ExplicitParams,
4043                                           bool ExplicitResultType,
4044                                           bool Mutable);
4045 
4046   /// \brief Note that we have finished the explicit captures for the
4047   /// given lambda.
4048   void finishLambdaExplicitCaptures(sema::LambdaScopeInfo *LSI);
4049 
4050   /// \brief Introduce the lambda parameters into scope.
4051   void addLambdaParameters(CXXMethodDecl *CallOperator, Scope *CurScope);
4052 
4053   /// \brief Deduce a block or lambda's return type based on the return
4054   /// statements present in the body.
4055   void deduceClosureReturnType(sema::CapturingScopeInfo &CSI);
4056 
4057   /// ActOnStartOfLambdaDefinition - This is called just before we start
4058   /// parsing the body of a lambda; it analyzes the explicit captures and
4059   /// arguments, and sets up various data-structures for the body of the
4060   /// lambda.
4061   void ActOnStartOfLambdaDefinition(LambdaIntroducer &Intro,
4062                                     Declarator &ParamInfo, Scope *CurScope);
4063 
4064   /// ActOnLambdaError - If there is an error parsing a lambda, this callback
4065   /// is invoked to pop the information about the lambda.
4066   void ActOnLambdaError(SourceLocation StartLoc, Scope *CurScope,
4067                         bool IsInstantiation = false);
4068 
4069   /// ActOnLambdaExpr - This is called when the body of a lambda expression
4070   /// was successfully completed.
4071   ExprResult ActOnLambdaExpr(SourceLocation StartLoc, Stmt *Body,
4072                              Scope *CurScope,
4073                              bool IsInstantiation = false);
4074 
4075   /// \brief Define the "body" of the conversion from a lambda object to a
4076   /// function pointer.
4077   ///
4078   /// This routine doesn't actually define a sensible body; rather, it fills
4079   /// in the initialization expression needed to copy the lambda object into
4080   /// the block, and IR generation actually generates the real body of the
4081   /// block pointer conversion.
4082   void DefineImplicitLambdaToFunctionPointerConversion(
4083          SourceLocation CurrentLoc, CXXConversionDecl *Conv);
4084 
4085   /// \brief Define the "body" of the conversion from a lambda object to a
4086   /// block pointer.
4087   ///
4088   /// This routine doesn't actually define a sensible body; rather, it fills
4089   /// in the initialization expression needed to copy the lambda object into
4090   /// the block, and IR generation actually generates the real body of the
4091   /// block pointer conversion.
4092   void DefineImplicitLambdaToBlockPointerConversion(SourceLocation CurrentLoc,
4093                                                     CXXConversionDecl *Conv);
4094 
4095   ExprResult BuildBlockForLambdaConversion(SourceLocation CurrentLocation,
4096                                            SourceLocation ConvLocation,
4097                                            CXXConversionDecl *Conv,
4098                                            Expr *Src);
4099 
4100   // ParseObjCStringLiteral - Parse Objective-C string literals.
4101   ExprResult ParseObjCStringLiteral(SourceLocation *AtLocs,
4102                                     Expr **Strings,
4103                                     unsigned NumStrings);
4104 
4105   ExprResult BuildObjCStringLiteral(SourceLocation AtLoc, StringLiteral *S);
4106 
4107   /// BuildObjCNumericLiteral - builds an ObjCBoxedExpr AST node for the
4108   /// numeric literal expression. Type of the expression will be "NSNumber *"
4109   /// or "id" if NSNumber is unavailable.
4110   ExprResult BuildObjCNumericLiteral(SourceLocation AtLoc, Expr *Number);
4111   ExprResult ActOnObjCBoolLiteral(SourceLocation AtLoc, SourceLocation ValueLoc,
4112                                   bool Value);
4113   ExprResult BuildObjCArrayLiteral(SourceRange SR, MultiExprArg Elements);
4114 
4115   /// BuildObjCBoxedExpr - builds an ObjCBoxedExpr AST node for the
4116   /// '@' prefixed parenthesized expression. The type of the expression will
4117   /// either be "NSNumber *" or "NSString *" depending on the type of
4118   /// ValueType, which is allowed to be a built-in numeric type or
4119   /// "char *" or "const char *".
4120   ExprResult BuildObjCBoxedExpr(SourceRange SR, Expr *ValueExpr);
4121 
4122   ExprResult BuildObjCSubscriptExpression(SourceLocation RB, Expr *BaseExpr,
4123                                           Expr *IndexExpr,
4124                                           ObjCMethodDecl *getterMethod,
4125                                           ObjCMethodDecl *setterMethod);
4126 
4127   ExprResult BuildObjCDictionaryLiteral(SourceRange SR,
4128                                         ObjCDictionaryElement *Elements,
4129                                         unsigned NumElements);
4130 
4131   ExprResult BuildObjCEncodeExpression(SourceLocation AtLoc,
4132                                   TypeSourceInfo *EncodedTypeInfo,
4133                                   SourceLocation RParenLoc);
4134   ExprResult BuildCXXMemberCallExpr(Expr *Exp, NamedDecl *FoundDecl,
4135                                     CXXConversionDecl *Method,
4136                                     bool HadMultipleCandidates);
4137 
4138   ExprResult ParseObjCEncodeExpression(SourceLocation AtLoc,
4139                                        SourceLocation EncodeLoc,
4140                                        SourceLocation LParenLoc,
4141                                        ParsedType Ty,
4142                                        SourceLocation RParenLoc);
4143 
4144   /// ParseObjCSelectorExpression - Build selector expression for \@selector
4145   ExprResult ParseObjCSelectorExpression(Selector Sel,
4146                                          SourceLocation AtLoc,
4147                                          SourceLocation SelLoc,
4148                                          SourceLocation LParenLoc,
4149                                          SourceLocation RParenLoc);
4150 
4151   /// ParseObjCProtocolExpression - Build protocol expression for \@protocol
4152   ExprResult ParseObjCProtocolExpression(IdentifierInfo * ProtocolName,
4153                                          SourceLocation AtLoc,
4154                                          SourceLocation ProtoLoc,
4155                                          SourceLocation LParenLoc,
4156                                          SourceLocation ProtoIdLoc,
4157                                          SourceLocation RParenLoc);
4158 
4159   //===--------------------------------------------------------------------===//
4160   // C++ Declarations
4161   //
4162   Decl *ActOnStartLinkageSpecification(Scope *S,
4163                                        SourceLocation ExternLoc,
4164                                        SourceLocation LangLoc,
4165                                        StringRef Lang,
4166                                        SourceLocation LBraceLoc);
4167   Decl *ActOnFinishLinkageSpecification(Scope *S,
4168                                         Decl *LinkageSpec,
4169                                         SourceLocation RBraceLoc);
4170 
4171 
4172   //===--------------------------------------------------------------------===//
4173   // C++ Classes
4174   //
4175   bool isCurrentClassName(const IdentifierInfo &II, Scope *S,
4176                           const CXXScopeSpec *SS = 0);
4177 
4178   bool ActOnAccessSpecifier(AccessSpecifier Access,
4179                             SourceLocation ASLoc,
4180                             SourceLocation ColonLoc,
4181                             AttributeList *Attrs = 0);
4182 
4183   Decl *ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS,
4184                                  Declarator &D,
4185                                  MultiTemplateParamsArg TemplateParameterLists,
4186                                  Expr *BitfieldWidth, const VirtSpecifiers &VS,
4187                                  InClassInitStyle InitStyle);
4188   void ActOnCXXInClassMemberInitializer(Decl *VarDecl, SourceLocation EqualLoc,
4189                                         Expr *Init);
4190 
4191   MemInitResult ActOnMemInitializer(Decl *ConstructorD,
4192                                     Scope *S,
4193                                     CXXScopeSpec &SS,
4194                                     IdentifierInfo *MemberOrBase,
4195                                     ParsedType TemplateTypeTy,
4196                                     const DeclSpec &DS,
4197                                     SourceLocation IdLoc,
4198                                     SourceLocation LParenLoc,
4199                                     Expr **Args, unsigned NumArgs,
4200                                     SourceLocation RParenLoc,
4201                                     SourceLocation EllipsisLoc);
4202 
4203   MemInitResult ActOnMemInitializer(Decl *ConstructorD,
4204                                     Scope *S,
4205                                     CXXScopeSpec &SS,
4206                                     IdentifierInfo *MemberOrBase,
4207                                     ParsedType TemplateTypeTy,
4208                                     const DeclSpec &DS,
4209                                     SourceLocation IdLoc,
4210                                     Expr *InitList,
4211                                     SourceLocation EllipsisLoc);
4212 
4213   MemInitResult BuildMemInitializer(Decl *ConstructorD,
4214                                     Scope *S,
4215                                     CXXScopeSpec &SS,
4216                                     IdentifierInfo *MemberOrBase,
4217                                     ParsedType TemplateTypeTy,
4218                                     const DeclSpec &DS,
4219                                     SourceLocation IdLoc,
4220                                     Expr *Init,
4221                                     SourceLocation EllipsisLoc);
4222 
4223   MemInitResult BuildMemberInitializer(ValueDecl *Member,
4224                                        Expr *Init,
4225                                        SourceLocation IdLoc);
4226 
4227   MemInitResult BuildBaseInitializer(QualType BaseType,
4228                                      TypeSourceInfo *BaseTInfo,
4229                                      Expr *Init,
4230                                      CXXRecordDecl *ClassDecl,
4231                                      SourceLocation EllipsisLoc);
4232 
4233   MemInitResult BuildDelegatingInitializer(TypeSourceInfo *TInfo,
4234                                            Expr *Init,
4235                                            CXXRecordDecl *ClassDecl);
4236 
4237   bool SetDelegatingInitializer(CXXConstructorDecl *Constructor,
4238                                 CXXCtorInitializer *Initializer);
4239 
4240   bool SetCtorInitializers(CXXConstructorDecl *Constructor,
4241                            CXXCtorInitializer **Initializers,
4242                            unsigned NumInitializers, bool AnyErrors);
4243 
4244   void SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation);
4245 
4246 
4247   /// MarkBaseAndMemberDestructorsReferenced - Given a record decl,
4248   /// mark all the non-trivial destructors of its members and bases as
4249   /// referenced.
4250   void MarkBaseAndMemberDestructorsReferenced(SourceLocation Loc,
4251                                               CXXRecordDecl *Record);
4252 
4253   /// \brief The list of classes whose vtables have been used within
4254   /// this translation unit, and the source locations at which the
4255   /// first use occurred.
4256   typedef std::pair<CXXRecordDecl*, SourceLocation> VTableUse;
4257 
4258   /// \brief The list of vtables that are required but have not yet been
4259   /// materialized.
4260   SmallVector<VTableUse, 16> VTableUses;
4261 
4262   /// \brief The set of classes whose vtables have been used within
4263   /// this translation unit, and a bit that will be true if the vtable is
4264   /// required to be emitted (otherwise, it should be emitted only if needed
4265   /// by code generation).
4266   llvm::DenseMap<CXXRecordDecl *, bool> VTablesUsed;
4267 
4268   /// \brief Load any externally-stored vtable uses.
4269   void LoadExternalVTableUses();
4270 
4271   typedef LazyVector<CXXRecordDecl *, ExternalSemaSource,
4272                      &ExternalSemaSource::ReadDynamicClasses, 2, 2>
4273     DynamicClassesType;
4274 
4275   /// \brief A list of all of the dynamic classes in this translation
4276   /// unit.
4277   DynamicClassesType DynamicClasses;
4278 
4279   /// \brief Note that the vtable for the given class was used at the
4280   /// given location.
4281   void MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
4282                       bool DefinitionRequired = false);
4283 
4284   /// \brief Mark the exception specifications of all virtual member functions
4285   /// in the given class as needed.
4286   void MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
4287                                              const CXXRecordDecl *RD);
4288 
4289   /// MarkVirtualMembersReferenced - Will mark all members of the given
4290   /// CXXRecordDecl referenced.
4291   void MarkVirtualMembersReferenced(SourceLocation Loc,
4292                                     const CXXRecordDecl *RD);
4293 
4294   /// \brief Define all of the vtables that have been used in this
4295   /// translation unit and reference any virtual members used by those
4296   /// vtables.
4297   ///
4298   /// \returns true if any work was done, false otherwise.
4299   bool DefineUsedVTables();
4300 
4301   void AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl);
4302 
4303   void ActOnMemInitializers(Decl *ConstructorDecl,
4304                             SourceLocation ColonLoc,
4305                             CXXCtorInitializer **MemInits,
4306                             unsigned NumMemInits,
4307                             bool AnyErrors);
4308 
4309   void CheckCompletedCXXClass(CXXRecordDecl *Record);
4310   void ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
4311                                          Decl *TagDecl,
4312                                          SourceLocation LBrac,
4313                                          SourceLocation RBrac,
4314                                          AttributeList *AttrList);
4315   void ActOnFinishCXXMemberDecls();
4316 
4317   void ActOnReenterTemplateScope(Scope *S, Decl *Template);
4318   void ActOnReenterDeclaratorTemplateScope(Scope *S, DeclaratorDecl *D);
4319   void ActOnStartDelayedMemberDeclarations(Scope *S, Decl *Record);
4320   void ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *Method);
4321   void ActOnDelayedCXXMethodParameter(Scope *S, Decl *Param);
4322   void ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *Record);
4323   void ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *Method);
4324   void ActOnFinishDelayedMemberInitializers(Decl *Record);
4325   void MarkAsLateParsedTemplate(FunctionDecl *FD, bool Flag = true);
4326   bool IsInsideALocalClassWithinATemplateFunction();
4327 
4328   Decl *ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
4329                                      Expr *AssertExpr,
4330                                      Expr *AssertMessageExpr,
4331                                      SourceLocation RParenLoc);
4332   Decl *BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
4333                                      Expr *AssertExpr,
4334                                      StringLiteral *AssertMessageExpr,
4335                                      SourceLocation RParenLoc,
4336                                      bool Failed);
4337 
4338   FriendDecl *CheckFriendTypeDecl(SourceLocation Loc,
4339                                   SourceLocation FriendLoc,
4340                                   TypeSourceInfo *TSInfo);
4341   Decl *ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
4342                             MultiTemplateParamsArg TemplateParams);
4343   Decl *ActOnFriendFunctionDecl(Scope *S, Declarator &D,
4344                                 MultiTemplateParamsArg TemplateParams);
4345 
4346   QualType CheckConstructorDeclarator(Declarator &D, QualType R,
4347                                       StorageClass& SC);
4348   void CheckConstructor(CXXConstructorDecl *Constructor);
4349   QualType CheckDestructorDeclarator(Declarator &D, QualType R,
4350                                      StorageClass& SC);
4351   bool CheckDestructor(CXXDestructorDecl *Destructor);
4352   void CheckConversionDeclarator(Declarator &D, QualType &R,
4353                                  StorageClass& SC);
4354   Decl *ActOnConversionDeclarator(CXXConversionDecl *Conversion);
4355 
4356   void CheckExplicitlyDefaultedMethods(CXXRecordDecl *Record);
4357   void CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD);
4358 
4359   //===--------------------------------------------------------------------===//
4360   // C++ Derived Classes
4361   //
4362 
4363   /// ActOnBaseSpecifier - Parsed a base specifier
4364   CXXBaseSpecifier *CheckBaseSpecifier(CXXRecordDecl *Class,
4365                                        SourceRange SpecifierRange,
4366                                        bool Virtual, AccessSpecifier Access,
4367                                        TypeSourceInfo *TInfo,
4368                                        SourceLocation EllipsisLoc);
4369 
4370   BaseResult ActOnBaseSpecifier(Decl *classdecl,
4371                                 SourceRange SpecifierRange,
4372                                 bool Virtual, AccessSpecifier Access,
4373                                 ParsedType basetype,
4374                                 SourceLocation BaseLoc,
4375                                 SourceLocation EllipsisLoc);
4376 
4377   bool AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
4378                             unsigned NumBases);
4379   void ActOnBaseSpecifiers(Decl *ClassDecl, CXXBaseSpecifier **Bases,
4380                            unsigned NumBases);
4381 
4382   bool IsDerivedFrom(QualType Derived, QualType Base);
4383   bool IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths);
4384 
4385   // FIXME: I don't like this name.
4386   void BuildBasePathArray(const CXXBasePaths &Paths, CXXCastPath &BasePath);
4387 
4388   bool BasePathInvolvesVirtualBase(const CXXCastPath &BasePath);
4389 
4390   bool CheckDerivedToBaseConversion(QualType Derived, QualType Base,
4391                                     SourceLocation Loc, SourceRange Range,
4392                                     CXXCastPath *BasePath = 0,
4393                                     bool IgnoreAccess = false);
4394   bool CheckDerivedToBaseConversion(QualType Derived, QualType Base,
4395                                     unsigned InaccessibleBaseID,
4396                                     unsigned AmbigiousBaseConvID,
4397                                     SourceLocation Loc, SourceRange Range,
4398                                     DeclarationName Name,
4399                                     CXXCastPath *BasePath);
4400 
4401   std::string getAmbiguousPathsDisplayString(CXXBasePaths &Paths);
4402 
4403   /// CheckOverridingFunctionReturnType - Checks whether the return types are
4404   /// covariant, according to C++ [class.virtual]p5.
4405   bool CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
4406                                          const CXXMethodDecl *Old);
4407 
4408   /// CheckOverridingFunctionExceptionSpec - Checks whether the exception
4409   /// spec is a subset of base spec.
4410   bool CheckOverridingFunctionExceptionSpec(const CXXMethodDecl *New,
4411                                             const CXXMethodDecl *Old);
4412 
4413   bool CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange);
4414 
4415   /// CheckOverrideControl - Check C++11 override control semantics.
4416   void CheckOverrideControl(Decl *D);
4417 
4418   /// CheckForFunctionMarkedFinal - Checks whether a virtual member function
4419   /// overrides a virtual member function marked 'final', according to
4420   /// C++11 [class.virtual]p4.
4421   bool CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
4422                                               const CXXMethodDecl *Old);
4423 
4424 
4425   //===--------------------------------------------------------------------===//
4426   // C++ Access Control
4427   //
4428 
4429   enum AccessResult {
4430     AR_accessible,
4431     AR_inaccessible,
4432     AR_dependent,
4433     AR_delayed
4434   };
4435 
4436   bool SetMemberAccessSpecifier(NamedDecl *MemberDecl,
4437                                 NamedDecl *PrevMemberDecl,
4438                                 AccessSpecifier LexicalAS);
4439 
4440   AccessResult CheckUnresolvedMemberAccess(UnresolvedMemberExpr *E,
4441                                            DeclAccessPair FoundDecl);
4442   AccessResult CheckUnresolvedLookupAccess(UnresolvedLookupExpr *E,
4443                                            DeclAccessPair FoundDecl);
4444   AccessResult CheckAllocationAccess(SourceLocation OperatorLoc,
4445                                      SourceRange PlacementRange,
4446                                      CXXRecordDecl *NamingClass,
4447                                      DeclAccessPair FoundDecl,
4448                                      bool Diagnose = true);
4449   AccessResult CheckConstructorAccess(SourceLocation Loc,
4450                                       CXXConstructorDecl *D,
4451                                       const InitializedEntity &Entity,
4452                                       AccessSpecifier Access,
4453                                       bool IsCopyBindingRefToTemp = false);
4454   AccessResult CheckConstructorAccess(SourceLocation Loc,
4455                                       CXXConstructorDecl *D,
4456                                       const InitializedEntity &Entity,
4457                                       AccessSpecifier Access,
4458                                       const PartialDiagnostic &PDiag);
4459   AccessResult CheckDestructorAccess(SourceLocation Loc,
4460                                      CXXDestructorDecl *Dtor,
4461                                      const PartialDiagnostic &PDiag,
4462                                      QualType objectType = QualType());
4463   AccessResult CheckFriendAccess(NamedDecl *D);
4464   AccessResult CheckMemberOperatorAccess(SourceLocation Loc,
4465                                          Expr *ObjectExpr,
4466                                          Expr *ArgExpr,
4467                                          DeclAccessPair FoundDecl);
4468   AccessResult CheckAddressOfMemberAccess(Expr *OvlExpr,
4469                                           DeclAccessPair FoundDecl);
4470   AccessResult CheckBaseClassAccess(SourceLocation AccessLoc,
4471                                     QualType Base, QualType Derived,
4472                                     const CXXBasePath &Path,
4473                                     unsigned DiagID,
4474                                     bool ForceCheck = false,
4475                                     bool ForceUnprivileged = false);
4476   void CheckLookupAccess(const LookupResult &R);
4477   bool IsSimplyAccessible(NamedDecl *decl, DeclContext *Ctx);
4478   bool isSpecialMemberAccessibleForDeletion(CXXMethodDecl *decl,
4479                                             AccessSpecifier access,
4480                                             QualType objectType);
4481 
4482   void HandleDependentAccessCheck(const DependentDiagnostic &DD,
4483                          const MultiLevelTemplateArgumentList &TemplateArgs);
4484   void PerformDependentDiagnostics(const DeclContext *Pattern,
4485                         const MultiLevelTemplateArgumentList &TemplateArgs);
4486 
4487   void HandleDelayedAccessCheck(sema::DelayedDiagnostic &DD, Decl *Ctx);
4488 
4489   /// \brief When true, access checking violations are treated as SFINAE
4490   /// failures rather than hard errors.
4491   bool AccessCheckingSFINAE;
4492 
4493   enum AbstractDiagSelID {
4494     AbstractNone = -1,
4495     AbstractReturnType,
4496     AbstractParamType,
4497     AbstractVariableType,
4498     AbstractFieldType,
4499     AbstractIvarType,
4500     AbstractArrayType
4501   };
4502 
4503   bool RequireNonAbstractType(SourceLocation Loc, QualType T,
4504                               TypeDiagnoser &Diagnoser);
4505   template<typename T1>
RequireNonAbstractType(SourceLocation Loc,QualType T,unsigned DiagID,const T1 & Arg1)4506   bool RequireNonAbstractType(SourceLocation Loc, QualType T,
4507                               unsigned DiagID,
4508                               const T1 &Arg1) {
4509     BoundTypeDiagnoser1<T1> Diagnoser(DiagID, Arg1);
4510     return RequireNonAbstractType(Loc, T, Diagnoser);
4511   }
4512 
4513   template<typename T1, typename T2>
RequireNonAbstractType(SourceLocation Loc,QualType T,unsigned DiagID,const T1 & Arg1,const T2 & Arg2)4514   bool RequireNonAbstractType(SourceLocation Loc, QualType T,
4515                               unsigned DiagID,
4516                               const T1 &Arg1, const T2 &Arg2) {
4517     BoundTypeDiagnoser2<T1, T2> Diagnoser(DiagID, Arg1, Arg2);
4518     return RequireNonAbstractType(Loc, T, Diagnoser);
4519   }
4520 
4521   template<typename T1, typename T2, typename T3>
RequireNonAbstractType(SourceLocation Loc,QualType T,unsigned DiagID,const T1 & Arg1,const T2 & Arg2,const T3 & Arg3)4522   bool RequireNonAbstractType(SourceLocation Loc, QualType T,
4523                               unsigned DiagID,
4524                               const T1 &Arg1, const T2 &Arg2, const T3 &Arg3) {
4525     BoundTypeDiagnoser3<T1, T2, T3> Diagnoser(DiagID, Arg1, Arg2, Arg3);
4526     return RequireNonAbstractType(Loc, T, Diagnoser);
4527   }
4528 
4529   void DiagnoseAbstractType(const CXXRecordDecl *RD);
4530 
4531   bool RequireNonAbstractType(SourceLocation Loc, QualType T, unsigned DiagID,
4532                               AbstractDiagSelID SelID = AbstractNone);
4533 
4534   //===--------------------------------------------------------------------===//
4535   // C++ Overloaded Operators [C++ 13.5]
4536   //
4537 
4538   bool CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl);
4539 
4540   bool CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl);
4541 
4542   //===--------------------------------------------------------------------===//
4543   // C++ Templates [C++ 14]
4544   //
4545   void FilterAcceptableTemplateNames(LookupResult &R,
4546                                      bool AllowFunctionTemplates = true);
4547   bool hasAnyAcceptableTemplateNames(LookupResult &R,
4548                                      bool AllowFunctionTemplates = true);
4549 
4550   void LookupTemplateName(LookupResult &R, Scope *S, CXXScopeSpec &SS,
4551                           QualType ObjectType, bool EnteringContext,
4552                           bool &MemberOfUnknownSpecialization);
4553 
4554   TemplateNameKind isTemplateName(Scope *S,
4555                                   CXXScopeSpec &SS,
4556                                   bool hasTemplateKeyword,
4557                                   UnqualifiedId &Name,
4558                                   ParsedType ObjectType,
4559                                   bool EnteringContext,
4560                                   TemplateTy &Template,
4561                                   bool &MemberOfUnknownSpecialization);
4562 
4563   bool DiagnoseUnknownTemplateName(const IdentifierInfo &II,
4564                                    SourceLocation IILoc,
4565                                    Scope *S,
4566                                    const CXXScopeSpec *SS,
4567                                    TemplateTy &SuggestedTemplate,
4568                                    TemplateNameKind &SuggestedKind);
4569 
4570   void DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl);
4571   TemplateDecl *AdjustDeclIfTemplate(Decl *&Decl);
4572 
4573   Decl *ActOnTypeParameter(Scope *S, bool Typename, bool Ellipsis,
4574                            SourceLocation EllipsisLoc,
4575                            SourceLocation KeyLoc,
4576                            IdentifierInfo *ParamName,
4577                            SourceLocation ParamNameLoc,
4578                            unsigned Depth, unsigned Position,
4579                            SourceLocation EqualLoc,
4580                            ParsedType DefaultArg);
4581 
4582   QualType CheckNonTypeTemplateParameterType(QualType T, SourceLocation Loc);
4583   Decl *ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
4584                                       unsigned Depth,
4585                                       unsigned Position,
4586                                       SourceLocation EqualLoc,
4587                                       Expr *DefaultArg);
4588   Decl *ActOnTemplateTemplateParameter(Scope *S,
4589                                        SourceLocation TmpLoc,
4590                                        TemplateParameterList *Params,
4591                                        SourceLocation EllipsisLoc,
4592                                        IdentifierInfo *ParamName,
4593                                        SourceLocation ParamNameLoc,
4594                                        unsigned Depth,
4595                                        unsigned Position,
4596                                        SourceLocation EqualLoc,
4597                                        ParsedTemplateArgument DefaultArg);
4598 
4599   TemplateParameterList *
4600   ActOnTemplateParameterList(unsigned Depth,
4601                              SourceLocation ExportLoc,
4602                              SourceLocation TemplateLoc,
4603                              SourceLocation LAngleLoc,
4604                              Decl **Params, unsigned NumParams,
4605                              SourceLocation RAngleLoc);
4606 
4607   /// \brief The context in which we are checking a template parameter
4608   /// list.
4609   enum TemplateParamListContext {
4610     TPC_ClassTemplate,
4611     TPC_FunctionTemplate,
4612     TPC_ClassTemplateMember,
4613     TPC_FriendFunctionTemplate,
4614     TPC_FriendFunctionTemplateDefinition,
4615     TPC_TypeAliasTemplate
4616   };
4617 
4618   bool CheckTemplateParameterList(TemplateParameterList *NewParams,
4619                                   TemplateParameterList *OldParams,
4620                                   TemplateParamListContext TPC);
4621   TemplateParameterList *
4622   MatchTemplateParametersToScopeSpecifier(SourceLocation DeclStartLoc,
4623                                           SourceLocation DeclLoc,
4624                                           const CXXScopeSpec &SS,
4625                                           TemplateParameterList **ParamLists,
4626                                           unsigned NumParamLists,
4627                                           bool IsFriend,
4628                                           bool &IsExplicitSpecialization,
4629                                           bool &Invalid);
4630 
4631   DeclResult CheckClassTemplate(Scope *S, unsigned TagSpec, TagUseKind TUK,
4632                                 SourceLocation KWLoc, CXXScopeSpec &SS,
4633                                 IdentifierInfo *Name, SourceLocation NameLoc,
4634                                 AttributeList *Attr,
4635                                 TemplateParameterList *TemplateParams,
4636                                 AccessSpecifier AS,
4637                                 SourceLocation ModulePrivateLoc,
4638                                 unsigned NumOuterTemplateParamLists,
4639                             TemplateParameterList **OuterTemplateParamLists);
4640 
4641   void translateTemplateArguments(const ASTTemplateArgsPtr &In,
4642                                   TemplateArgumentListInfo &Out);
4643 
4644   void NoteAllFoundTemplates(TemplateName Name);
4645 
4646   QualType CheckTemplateIdType(TemplateName Template,
4647                                SourceLocation TemplateLoc,
4648                               TemplateArgumentListInfo &TemplateArgs);
4649 
4650   TypeResult
4651   ActOnTemplateIdType(CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
4652                       TemplateTy Template, SourceLocation TemplateLoc,
4653                       SourceLocation LAngleLoc,
4654                       ASTTemplateArgsPtr TemplateArgs,
4655                       SourceLocation RAngleLoc,
4656                       bool IsCtorOrDtorName = false);
4657 
4658   /// \brief Parsed an elaborated-type-specifier that refers to a template-id,
4659   /// such as \c class T::template apply<U>.
4660   TypeResult ActOnTagTemplateIdType(TagUseKind TUK,
4661                                     TypeSpecifierType TagSpec,
4662                                     SourceLocation TagLoc,
4663                                     CXXScopeSpec &SS,
4664                                     SourceLocation TemplateKWLoc,
4665                                     TemplateTy TemplateD,
4666                                     SourceLocation TemplateLoc,
4667                                     SourceLocation LAngleLoc,
4668                                     ASTTemplateArgsPtr TemplateArgsIn,
4669                                     SourceLocation RAngleLoc);
4670 
4671 
4672   ExprResult BuildTemplateIdExpr(const CXXScopeSpec &SS,
4673                                  SourceLocation TemplateKWLoc,
4674                                  LookupResult &R,
4675                                  bool RequiresADL,
4676                                const TemplateArgumentListInfo *TemplateArgs);
4677 
4678   ExprResult BuildQualifiedTemplateIdExpr(CXXScopeSpec &SS,
4679                                           SourceLocation TemplateKWLoc,
4680                                const DeclarationNameInfo &NameInfo,
4681                                const TemplateArgumentListInfo *TemplateArgs);
4682 
4683   TemplateNameKind ActOnDependentTemplateName(Scope *S,
4684                                               CXXScopeSpec &SS,
4685                                               SourceLocation TemplateKWLoc,
4686                                               UnqualifiedId &Name,
4687                                               ParsedType ObjectType,
4688                                               bool EnteringContext,
4689                                               TemplateTy &Template);
4690 
4691   DeclResult
4692   ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec, TagUseKind TUK,
4693                                    SourceLocation KWLoc,
4694                                    SourceLocation ModulePrivateLoc,
4695                                    CXXScopeSpec &SS,
4696                                    TemplateTy Template,
4697                                    SourceLocation TemplateNameLoc,
4698                                    SourceLocation LAngleLoc,
4699                                    ASTTemplateArgsPtr TemplateArgs,
4700                                    SourceLocation RAngleLoc,
4701                                    AttributeList *Attr,
4702                                  MultiTemplateParamsArg TemplateParameterLists);
4703 
4704   Decl *ActOnTemplateDeclarator(Scope *S,
4705                                 MultiTemplateParamsArg TemplateParameterLists,
4706                                 Declarator &D);
4707 
4708   Decl *ActOnStartOfFunctionTemplateDef(Scope *FnBodyScope,
4709                                   MultiTemplateParamsArg TemplateParameterLists,
4710                                         Declarator &D);
4711 
4712   bool
4713   CheckSpecializationInstantiationRedecl(SourceLocation NewLoc,
4714                                          TemplateSpecializationKind NewTSK,
4715                                          NamedDecl *PrevDecl,
4716                                          TemplateSpecializationKind PrevTSK,
4717                                          SourceLocation PrevPtOfInstantiation,
4718                                          bool &SuppressNew);
4719 
4720   bool CheckDependentFunctionTemplateSpecialization(FunctionDecl *FD,
4721                     const TemplateArgumentListInfo &ExplicitTemplateArgs,
4722                                                     LookupResult &Previous);
4723 
4724   bool CheckFunctionTemplateSpecialization(FunctionDecl *FD,
4725                          TemplateArgumentListInfo *ExplicitTemplateArgs,
4726                                            LookupResult &Previous);
4727   bool CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous);
4728 
4729   DeclResult
4730   ActOnExplicitInstantiation(Scope *S,
4731                              SourceLocation ExternLoc,
4732                              SourceLocation TemplateLoc,
4733                              unsigned TagSpec,
4734                              SourceLocation KWLoc,
4735                              const CXXScopeSpec &SS,
4736                              TemplateTy Template,
4737                              SourceLocation TemplateNameLoc,
4738                              SourceLocation LAngleLoc,
4739                              ASTTemplateArgsPtr TemplateArgs,
4740                              SourceLocation RAngleLoc,
4741                              AttributeList *Attr);
4742 
4743   DeclResult
4744   ActOnExplicitInstantiation(Scope *S,
4745                              SourceLocation ExternLoc,
4746                              SourceLocation TemplateLoc,
4747                              unsigned TagSpec,
4748                              SourceLocation KWLoc,
4749                              CXXScopeSpec &SS,
4750                              IdentifierInfo *Name,
4751                              SourceLocation NameLoc,
4752                              AttributeList *Attr);
4753 
4754   DeclResult ActOnExplicitInstantiation(Scope *S,
4755                                         SourceLocation ExternLoc,
4756                                         SourceLocation TemplateLoc,
4757                                         Declarator &D);
4758 
4759   TemplateArgumentLoc
4760   SubstDefaultTemplateArgumentIfAvailable(TemplateDecl *Template,
4761                                           SourceLocation TemplateLoc,
4762                                           SourceLocation RAngleLoc,
4763                                           Decl *Param,
4764                           SmallVectorImpl<TemplateArgument> &Converted);
4765 
4766   /// \brief Specifies the context in which a particular template
4767   /// argument is being checked.
4768   enum CheckTemplateArgumentKind {
4769     /// \brief The template argument was specified in the code or was
4770     /// instantiated with some deduced template arguments.
4771     CTAK_Specified,
4772 
4773     /// \brief The template argument was deduced via template argument
4774     /// deduction.
4775     CTAK_Deduced,
4776 
4777     /// \brief The template argument was deduced from an array bound
4778     /// via template argument deduction.
4779     CTAK_DeducedFromArrayBound
4780   };
4781 
4782   bool CheckTemplateArgument(NamedDecl *Param,
4783                              const TemplateArgumentLoc &Arg,
4784                              NamedDecl *Template,
4785                              SourceLocation TemplateLoc,
4786                              SourceLocation RAngleLoc,
4787                              unsigned ArgumentPackIndex,
4788                            SmallVectorImpl<TemplateArgument> &Converted,
4789                              CheckTemplateArgumentKind CTAK = CTAK_Specified);
4790 
4791   /// \brief Check that the given template arguments can be be provided to
4792   /// the given template, converting the arguments along the way.
4793   ///
4794   /// \param Template The template to which the template arguments are being
4795   /// provided.
4796   ///
4797   /// \param TemplateLoc The location of the template name in the source.
4798   ///
4799   /// \param TemplateArgs The list of template arguments. If the template is
4800   /// a template template parameter, this function may extend the set of
4801   /// template arguments to also include substituted, defaulted template
4802   /// arguments.
4803   ///
4804   /// \param PartialTemplateArgs True if the list of template arguments is
4805   /// intentionally partial, e.g., because we're checking just the initial
4806   /// set of template arguments.
4807   ///
4808   /// \param Converted Will receive the converted, canonicalized template
4809   /// arguments.
4810   ///
4811   ///
4812   /// \param ExpansionIntoFixedList If non-NULL, will be set true to indicate
4813   /// when the template arguments contain a pack expansion that is being
4814   /// expanded into a fixed parameter list.
4815   ///
4816   /// \returns True if an error occurred, false otherwise.
4817   bool CheckTemplateArgumentList(TemplateDecl *Template,
4818                                  SourceLocation TemplateLoc,
4819                                  TemplateArgumentListInfo &TemplateArgs,
4820                                  bool PartialTemplateArgs,
4821                            SmallVectorImpl<TemplateArgument> &Converted,
4822                                  bool *ExpansionIntoFixedList = 0);
4823 
4824   bool CheckTemplateTypeArgument(TemplateTypeParmDecl *Param,
4825                                  const TemplateArgumentLoc &Arg,
4826                            SmallVectorImpl<TemplateArgument> &Converted);
4827 
4828   bool CheckTemplateArgument(TemplateTypeParmDecl *Param,
4829                              TypeSourceInfo *Arg);
4830   ExprResult CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
4831                                    QualType InstantiatedParamType, Expr *Arg,
4832                                    TemplateArgument &Converted,
4833                                CheckTemplateArgumentKind CTAK = CTAK_Specified);
4834   bool CheckTemplateArgument(TemplateTemplateParmDecl *Param,
4835                              const TemplateArgumentLoc &Arg,
4836                              unsigned ArgumentPackIndex);
4837 
4838   ExprResult
4839   BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg,
4840                                           QualType ParamType,
4841                                           SourceLocation Loc);
4842   ExprResult
4843   BuildExpressionFromIntegralTemplateArgument(const TemplateArgument &Arg,
4844                                               SourceLocation Loc);
4845 
4846   /// \brief Enumeration describing how template parameter lists are compared
4847   /// for equality.
4848   enum TemplateParameterListEqualKind {
4849     /// \brief We are matching the template parameter lists of two templates
4850     /// that might be redeclarations.
4851     ///
4852     /// \code
4853     /// template<typename T> struct X;
4854     /// template<typename T> struct X;
4855     /// \endcode
4856     TPL_TemplateMatch,
4857 
4858     /// \brief We are matching the template parameter lists of two template
4859     /// template parameters as part of matching the template parameter lists
4860     /// of two templates that might be redeclarations.
4861     ///
4862     /// \code
4863     /// template<template<int I> class TT> struct X;
4864     /// template<template<int Value> class Other> struct X;
4865     /// \endcode
4866     TPL_TemplateTemplateParmMatch,
4867 
4868     /// \brief We are matching the template parameter lists of a template
4869     /// template argument against the template parameter lists of a template
4870     /// template parameter.
4871     ///
4872     /// \code
4873     /// template<template<int Value> class Metafun> struct X;
4874     /// template<int Value> struct integer_c;
4875     /// X<integer_c> xic;
4876     /// \endcode
4877     TPL_TemplateTemplateArgumentMatch
4878   };
4879 
4880   bool TemplateParameterListsAreEqual(TemplateParameterList *New,
4881                                       TemplateParameterList *Old,
4882                                       bool Complain,
4883                                       TemplateParameterListEqualKind Kind,
4884                                       SourceLocation TemplateArgLoc
4885                                         = SourceLocation());
4886 
4887   bool CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams);
4888 
4889   /// \brief Called when the parser has parsed a C++ typename
4890   /// specifier, e.g., "typename T::type".
4891   ///
4892   /// \param S The scope in which this typename type occurs.
4893   /// \param TypenameLoc the location of the 'typename' keyword
4894   /// \param SS the nested-name-specifier following the typename (e.g., 'T::').
4895   /// \param II the identifier we're retrieving (e.g., 'type' in the example).
4896   /// \param IdLoc the location of the identifier.
4897   TypeResult
4898   ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
4899                     const CXXScopeSpec &SS, const IdentifierInfo &II,
4900                     SourceLocation IdLoc);
4901 
4902   /// \brief Called when the parser has parsed a C++ typename
4903   /// specifier that ends in a template-id, e.g.,
4904   /// "typename MetaFun::template apply<T1, T2>".
4905   ///
4906   /// \param S The scope in which this typename type occurs.
4907   /// \param TypenameLoc the location of the 'typename' keyword
4908   /// \param SS the nested-name-specifier following the typename (e.g., 'T::').
4909   /// \param TemplateLoc the location of the 'template' keyword, if any.
4910   /// \param TemplateName The template name.
4911   /// \param TemplateNameLoc The location of the template name.
4912   /// \param LAngleLoc The location of the opening angle bracket  ('<').
4913   /// \param TemplateArgs The template arguments.
4914   /// \param RAngleLoc The location of the closing angle bracket  ('>').
4915   TypeResult
4916   ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
4917                     const CXXScopeSpec &SS,
4918                     SourceLocation TemplateLoc,
4919                     TemplateTy TemplateName,
4920                     SourceLocation TemplateNameLoc,
4921                     SourceLocation LAngleLoc,
4922                     ASTTemplateArgsPtr TemplateArgs,
4923                     SourceLocation RAngleLoc);
4924 
4925   QualType CheckTypenameType(ElaboratedTypeKeyword Keyword,
4926                              SourceLocation KeywordLoc,
4927                              NestedNameSpecifierLoc QualifierLoc,
4928                              const IdentifierInfo &II,
4929                              SourceLocation IILoc);
4930 
4931   TypeSourceInfo *RebuildTypeInCurrentInstantiation(TypeSourceInfo *T,
4932                                                     SourceLocation Loc,
4933                                                     DeclarationName Name);
4934   bool RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS);
4935 
4936   ExprResult RebuildExprInCurrentInstantiation(Expr *E);
4937   bool RebuildTemplateParamsInCurrentInstantiation(
4938                                                 TemplateParameterList *Params);
4939 
4940   std::string
4941   getTemplateArgumentBindingsText(const TemplateParameterList *Params,
4942                                   const TemplateArgumentList &Args);
4943 
4944   std::string
4945   getTemplateArgumentBindingsText(const TemplateParameterList *Params,
4946                                   const TemplateArgument *Args,
4947                                   unsigned NumArgs);
4948 
4949   //===--------------------------------------------------------------------===//
4950   // C++ Variadic Templates (C++0x [temp.variadic])
4951   //===--------------------------------------------------------------------===//
4952 
4953   /// \brief The context in which an unexpanded parameter pack is
4954   /// being diagnosed.
4955   ///
4956   /// Note that the values of this enumeration line up with the first
4957   /// argument to the \c err_unexpanded_parameter_pack diagnostic.
4958   enum UnexpandedParameterPackContext {
4959     /// \brief An arbitrary expression.
4960     UPPC_Expression = 0,
4961 
4962     /// \brief The base type of a class type.
4963     UPPC_BaseType,
4964 
4965     /// \brief The type of an arbitrary declaration.
4966     UPPC_DeclarationType,
4967 
4968     /// \brief The type of a data member.
4969     UPPC_DataMemberType,
4970 
4971     /// \brief The size of a bit-field.
4972     UPPC_BitFieldWidth,
4973 
4974     /// \brief The expression in a static assertion.
4975     UPPC_StaticAssertExpression,
4976 
4977     /// \brief The fixed underlying type of an enumeration.
4978     UPPC_FixedUnderlyingType,
4979 
4980     /// \brief The enumerator value.
4981     UPPC_EnumeratorValue,
4982 
4983     /// \brief A using declaration.
4984     UPPC_UsingDeclaration,
4985 
4986     /// \brief A friend declaration.
4987     UPPC_FriendDeclaration,
4988 
4989     /// \brief A declaration qualifier.
4990     UPPC_DeclarationQualifier,
4991 
4992     /// \brief An initializer.
4993     UPPC_Initializer,
4994 
4995     /// \brief A default argument.
4996     UPPC_DefaultArgument,
4997 
4998     /// \brief The type of a non-type template parameter.
4999     UPPC_NonTypeTemplateParameterType,
5000 
5001     /// \brief The type of an exception.
5002     UPPC_ExceptionType,
5003 
5004     /// \brief Partial specialization.
5005     UPPC_PartialSpecialization,
5006 
5007     /// \brief Microsoft __if_exists.
5008     UPPC_IfExists,
5009 
5010     /// \brief Microsoft __if_not_exists.
5011     UPPC_IfNotExists,
5012 
5013     /// \brief Lambda expression.
5014     UPPC_Lambda,
5015 
5016     /// \brief Block expression,
5017     UPPC_Block
5018 };
5019 
5020   /// \brief Diagnose unexpanded parameter packs.
5021   ///
5022   /// \param Loc The location at which we should emit the diagnostic.
5023   ///
5024   /// \param UPPC The context in which we are diagnosing unexpanded
5025   /// parameter packs.
5026   ///
5027   /// \param Unexpanded the set of unexpanded parameter packs.
5028   ///
5029   /// \returns true if an error occurred, false otherwise.
5030   bool DiagnoseUnexpandedParameterPacks(SourceLocation Loc,
5031                                         UnexpandedParameterPackContext UPPC,
5032                                   ArrayRef<UnexpandedParameterPack> Unexpanded);
5033 
5034   /// \brief If the given type contains an unexpanded parameter pack,
5035   /// diagnose the error.
5036   ///
5037   /// \param Loc The source location where a diagnostc should be emitted.
5038   ///
5039   /// \param T The type that is being checked for unexpanded parameter
5040   /// packs.
5041   ///
5042   /// \returns true if an error occurred, false otherwise.
5043   bool DiagnoseUnexpandedParameterPack(SourceLocation Loc, TypeSourceInfo *T,
5044                                        UnexpandedParameterPackContext UPPC);
5045 
5046   /// \brief If the given expression contains an unexpanded parameter
5047   /// pack, diagnose the error.
5048   ///
5049   /// \param E The expression that is being checked for unexpanded
5050   /// parameter packs.
5051   ///
5052   /// \returns true if an error occurred, false otherwise.
5053   bool DiagnoseUnexpandedParameterPack(Expr *E,
5054                        UnexpandedParameterPackContext UPPC = UPPC_Expression);
5055 
5056   /// \brief If the given nested-name-specifier contains an unexpanded
5057   /// parameter pack, diagnose the error.
5058   ///
5059   /// \param SS The nested-name-specifier that is being checked for
5060   /// unexpanded parameter packs.
5061   ///
5062   /// \returns true if an error occurred, false otherwise.
5063   bool DiagnoseUnexpandedParameterPack(const CXXScopeSpec &SS,
5064                                        UnexpandedParameterPackContext UPPC);
5065 
5066   /// \brief If the given name contains an unexpanded parameter pack,
5067   /// diagnose the error.
5068   ///
5069   /// \param NameInfo The name (with source location information) that
5070   /// is being checked for unexpanded parameter packs.
5071   ///
5072   /// \returns true if an error occurred, false otherwise.
5073   bool DiagnoseUnexpandedParameterPack(const DeclarationNameInfo &NameInfo,
5074                                        UnexpandedParameterPackContext UPPC);
5075 
5076   /// \brief If the given template name contains an unexpanded parameter pack,
5077   /// diagnose the error.
5078   ///
5079   /// \param Loc The location of the template name.
5080   ///
5081   /// \param Template The template name that is being checked for unexpanded
5082   /// parameter packs.
5083   ///
5084   /// \returns true if an error occurred, false otherwise.
5085   bool DiagnoseUnexpandedParameterPack(SourceLocation Loc,
5086                                        TemplateName Template,
5087                                        UnexpandedParameterPackContext UPPC);
5088 
5089   /// \brief If the given template argument contains an unexpanded parameter
5090   /// pack, diagnose the error.
5091   ///
5092   /// \param Arg The template argument that is being checked for unexpanded
5093   /// parameter packs.
5094   ///
5095   /// \returns true if an error occurred, false otherwise.
5096   bool DiagnoseUnexpandedParameterPack(TemplateArgumentLoc Arg,
5097                                        UnexpandedParameterPackContext UPPC);
5098 
5099   /// \brief Collect the set of unexpanded parameter packs within the given
5100   /// template argument.
5101   ///
5102   /// \param Arg The template argument that will be traversed to find
5103   /// unexpanded parameter packs.
5104   void collectUnexpandedParameterPacks(TemplateArgument Arg,
5105                    SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
5106 
5107   /// \brief Collect the set of unexpanded parameter packs within the given
5108   /// template argument.
5109   ///
5110   /// \param Arg The template argument that will be traversed to find
5111   /// unexpanded parameter packs.
5112   void collectUnexpandedParameterPacks(TemplateArgumentLoc Arg,
5113                     SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
5114 
5115   /// \brief Collect the set of unexpanded parameter packs within the given
5116   /// type.
5117   ///
5118   /// \param T The type that will be traversed to find
5119   /// unexpanded parameter packs.
5120   void collectUnexpandedParameterPacks(QualType T,
5121                    SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
5122 
5123   /// \brief Collect the set of unexpanded parameter packs within the given
5124   /// type.
5125   ///
5126   /// \param TL The type that will be traversed to find
5127   /// unexpanded parameter packs.
5128   void collectUnexpandedParameterPacks(TypeLoc TL,
5129                    SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
5130 
5131   /// \brief Collect the set of unexpanded parameter packs within the given
5132   /// nested-name-specifier.
5133   ///
5134   /// \param SS The nested-name-specifier that will be traversed to find
5135   /// unexpanded parameter packs.
5136   void collectUnexpandedParameterPacks(CXXScopeSpec &SS,
5137                          SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
5138 
5139   /// \brief Collect the set of unexpanded parameter packs within the given
5140   /// name.
5141   ///
5142   /// \param NameInfo The name that will be traversed to find
5143   /// unexpanded parameter packs.
5144   void collectUnexpandedParameterPacks(const DeclarationNameInfo &NameInfo,
5145                          SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
5146 
5147   /// \brief Invoked when parsing a template argument followed by an
5148   /// ellipsis, which creates a pack expansion.
5149   ///
5150   /// \param Arg The template argument preceding the ellipsis, which
5151   /// may already be invalid.
5152   ///
5153   /// \param EllipsisLoc The location of the ellipsis.
5154   ParsedTemplateArgument ActOnPackExpansion(const ParsedTemplateArgument &Arg,
5155                                             SourceLocation EllipsisLoc);
5156 
5157   /// \brief Invoked when parsing a type followed by an ellipsis, which
5158   /// creates a pack expansion.
5159   ///
5160   /// \param Type The type preceding the ellipsis, which will become
5161   /// the pattern of the pack expansion.
5162   ///
5163   /// \param EllipsisLoc The location of the ellipsis.
5164   TypeResult ActOnPackExpansion(ParsedType Type, SourceLocation EllipsisLoc);
5165 
5166   /// \brief Construct a pack expansion type from the pattern of the pack
5167   /// expansion.
5168   TypeSourceInfo *CheckPackExpansion(TypeSourceInfo *Pattern,
5169                                      SourceLocation EllipsisLoc,
5170                                      llvm::Optional<unsigned> NumExpansions);
5171 
5172   /// \brief Construct a pack expansion type from the pattern of the pack
5173   /// expansion.
5174   QualType CheckPackExpansion(QualType Pattern,
5175                               SourceRange PatternRange,
5176                               SourceLocation EllipsisLoc,
5177                               llvm::Optional<unsigned> NumExpansions);
5178 
5179   /// \brief Invoked when parsing an expression followed by an ellipsis, which
5180   /// creates a pack expansion.
5181   ///
5182   /// \param Pattern The expression preceding the ellipsis, which will become
5183   /// the pattern of the pack expansion.
5184   ///
5185   /// \param EllipsisLoc The location of the ellipsis.
5186   ExprResult ActOnPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc);
5187 
5188   /// \brief Invoked when parsing an expression followed by an ellipsis, which
5189   /// creates a pack expansion.
5190   ///
5191   /// \param Pattern The expression preceding the ellipsis, which will become
5192   /// the pattern of the pack expansion.
5193   ///
5194   /// \param EllipsisLoc The location of the ellipsis.
5195   ExprResult CheckPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc,
5196                                 llvm::Optional<unsigned> NumExpansions);
5197 
5198   /// \brief Determine whether we could expand a pack expansion with the
5199   /// given set of parameter packs into separate arguments by repeatedly
5200   /// transforming the pattern.
5201   ///
5202   /// \param EllipsisLoc The location of the ellipsis that identifies the
5203   /// pack expansion.
5204   ///
5205   /// \param PatternRange The source range that covers the entire pattern of
5206   /// the pack expansion.
5207   ///
5208   /// \param Unexpanded The set of unexpanded parameter packs within the
5209   /// pattern.
5210   ///
5211   /// \param ShouldExpand Will be set to \c true if the transformer should
5212   /// expand the corresponding pack expansions into separate arguments. When
5213   /// set, \c NumExpansions must also be set.
5214   ///
5215   /// \param RetainExpansion Whether the caller should add an unexpanded
5216   /// pack expansion after all of the expanded arguments. This is used
5217   /// when extending explicitly-specified template argument packs per
5218   /// C++0x [temp.arg.explicit]p9.
5219   ///
5220   /// \param NumExpansions The number of separate arguments that will be in
5221   /// the expanded form of the corresponding pack expansion. This is both an
5222   /// input and an output parameter, which can be set by the caller if the
5223   /// number of expansions is known a priori (e.g., due to a prior substitution)
5224   /// and will be set by the callee when the number of expansions is known.
5225   /// The callee must set this value when \c ShouldExpand is \c true; it may
5226   /// set this value in other cases.
5227   ///
5228   /// \returns true if an error occurred (e.g., because the parameter packs
5229   /// are to be instantiated with arguments of different lengths), false
5230   /// otherwise. If false, \c ShouldExpand (and possibly \c NumExpansions)
5231   /// must be set.
5232   bool CheckParameterPacksForExpansion(SourceLocation EllipsisLoc,
5233                                        SourceRange PatternRange,
5234                              llvm::ArrayRef<UnexpandedParameterPack> Unexpanded,
5235                              const MultiLevelTemplateArgumentList &TemplateArgs,
5236                                        bool &ShouldExpand,
5237                                        bool &RetainExpansion,
5238                                        llvm::Optional<unsigned> &NumExpansions);
5239 
5240   /// \brief Determine the number of arguments in the given pack expansion
5241   /// type.
5242   ///
5243   /// This routine assumes that the number of arguments in the expansion is
5244   /// consistent across all of the unexpanded parameter packs in its pattern.
5245   ///
5246   /// Returns an empty Optional if the type can't be expanded.
5247   llvm::Optional<unsigned> getNumArgumentsInExpansion(QualType T,
5248                             const MultiLevelTemplateArgumentList &TemplateArgs);
5249 
5250   /// \brief Determine whether the given declarator contains any unexpanded
5251   /// parameter packs.
5252   ///
5253   /// This routine is used by the parser to disambiguate function declarators
5254   /// with an ellipsis prior to the ')', e.g.,
5255   ///
5256   /// \code
5257   ///   void f(T...);
5258   /// \endcode
5259   ///
5260   /// To determine whether we have an (unnamed) function parameter pack or
5261   /// a variadic function.
5262   ///
5263   /// \returns true if the declarator contains any unexpanded parameter packs,
5264   /// false otherwise.
5265   bool containsUnexpandedParameterPacks(Declarator &D);
5266 
5267   //===--------------------------------------------------------------------===//
5268   // C++ Template Argument Deduction (C++ [temp.deduct])
5269   //===--------------------------------------------------------------------===//
5270 
5271   /// \brief Describes the result of template argument deduction.
5272   ///
5273   /// The TemplateDeductionResult enumeration describes the result of
5274   /// template argument deduction, as returned from
5275   /// DeduceTemplateArguments(). The separate TemplateDeductionInfo
5276   /// structure provides additional information about the results of
5277   /// template argument deduction, e.g., the deduced template argument
5278   /// list (if successful) or the specific template parameters or
5279   /// deduced arguments that were involved in the failure.
5280   enum TemplateDeductionResult {
5281     /// \brief Template argument deduction was successful.
5282     TDK_Success = 0,
5283     /// \brief Template argument deduction exceeded the maximum template
5284     /// instantiation depth (which has already been diagnosed).
5285     TDK_InstantiationDepth,
5286     /// \brief Template argument deduction did not deduce a value
5287     /// for every template parameter.
5288     TDK_Incomplete,
5289     /// \brief Template argument deduction produced inconsistent
5290     /// deduced values for the given template parameter.
5291     TDK_Inconsistent,
5292     /// \brief Template argument deduction failed due to inconsistent
5293     /// cv-qualifiers on a template parameter type that would
5294     /// otherwise be deduced, e.g., we tried to deduce T in "const T"
5295     /// but were given a non-const "X".
5296     TDK_Underqualified,
5297     /// \brief Substitution of the deduced template argument values
5298     /// resulted in an error.
5299     TDK_SubstitutionFailure,
5300     /// \brief Substitution of the deduced template argument values
5301     /// into a non-deduced context produced a type or value that
5302     /// produces a type that does not match the original template
5303     /// arguments provided.
5304     TDK_NonDeducedMismatch,
5305     /// \brief When performing template argument deduction for a function
5306     /// template, there were too many call arguments.
5307     TDK_TooManyArguments,
5308     /// \brief When performing template argument deduction for a function
5309     /// template, there were too few call arguments.
5310     TDK_TooFewArguments,
5311     /// \brief The explicitly-specified template arguments were not valid
5312     /// template arguments for the given template.
5313     TDK_InvalidExplicitArguments,
5314     /// \brief The arguments included an overloaded function name that could
5315     /// not be resolved to a suitable function.
5316     TDK_FailedOverloadResolution
5317   };
5318 
5319   TemplateDeductionResult
5320   DeduceTemplateArguments(ClassTemplatePartialSpecializationDecl *Partial,
5321                           const TemplateArgumentList &TemplateArgs,
5322                           sema::TemplateDeductionInfo &Info);
5323 
5324   TemplateDeductionResult
5325   SubstituteExplicitTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
5326                               TemplateArgumentListInfo &ExplicitTemplateArgs,
5327                       SmallVectorImpl<DeducedTemplateArgument> &Deduced,
5328                                  SmallVectorImpl<QualType> &ParamTypes,
5329                                       QualType *FunctionType,
5330                                       sema::TemplateDeductionInfo &Info);
5331 
5332   /// brief A function argument from which we performed template argument
5333   // deduction for a call.
5334   struct OriginalCallArg {
OriginalCallArgOriginalCallArg5335     OriginalCallArg(QualType OriginalParamType,
5336                     unsigned ArgIdx,
5337                     QualType OriginalArgType)
5338       : OriginalParamType(OriginalParamType), ArgIdx(ArgIdx),
5339         OriginalArgType(OriginalArgType) { }
5340 
5341     QualType OriginalParamType;
5342     unsigned ArgIdx;
5343     QualType OriginalArgType;
5344   };
5345 
5346   TemplateDeductionResult
5347   FinishTemplateArgumentDeduction(FunctionTemplateDecl *FunctionTemplate,
5348                       SmallVectorImpl<DeducedTemplateArgument> &Deduced,
5349                                   unsigned NumExplicitlySpecified,
5350                                   FunctionDecl *&Specialization,
5351                                   sema::TemplateDeductionInfo &Info,
5352            SmallVectorImpl<OriginalCallArg> const *OriginalCallArgs = 0);
5353 
5354   TemplateDeductionResult
5355   DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
5356                           TemplateArgumentListInfo *ExplicitTemplateArgs,
5357                           llvm::ArrayRef<Expr *> Args,
5358                           FunctionDecl *&Specialization,
5359                           sema::TemplateDeductionInfo &Info);
5360 
5361   TemplateDeductionResult
5362   DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
5363                           TemplateArgumentListInfo *ExplicitTemplateArgs,
5364                           QualType ArgFunctionType,
5365                           FunctionDecl *&Specialization,
5366                           sema::TemplateDeductionInfo &Info);
5367 
5368   TemplateDeductionResult
5369   DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
5370                           QualType ToType,
5371                           CXXConversionDecl *&Specialization,
5372                           sema::TemplateDeductionInfo &Info);
5373 
5374   TemplateDeductionResult
5375   DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
5376                           TemplateArgumentListInfo *ExplicitTemplateArgs,
5377                           FunctionDecl *&Specialization,
5378                           sema::TemplateDeductionInfo &Info);
5379 
5380   /// \brief Result type of DeduceAutoType.
5381   enum DeduceAutoResult {
5382     DAR_Succeeded,
5383     DAR_Failed,
5384     DAR_FailedAlreadyDiagnosed
5385   };
5386 
5387   DeduceAutoResult DeduceAutoType(TypeSourceInfo *AutoType, Expr *&Initializer,
5388                                   TypeSourceInfo *&Result);
5389   void DiagnoseAutoDeductionFailure(VarDecl *VDecl, Expr *Init);
5390 
5391   FunctionTemplateDecl *getMoreSpecializedTemplate(FunctionTemplateDecl *FT1,
5392                                                    FunctionTemplateDecl *FT2,
5393                                                    SourceLocation Loc,
5394                                            TemplatePartialOrderingContext TPOC,
5395                                                    unsigned NumCallArguments);
5396   UnresolvedSetIterator getMostSpecialized(UnresolvedSetIterator SBegin,
5397                                            UnresolvedSetIterator SEnd,
5398                                            TemplatePartialOrderingContext TPOC,
5399                                            unsigned NumCallArguments,
5400                                            SourceLocation Loc,
5401                                            const PartialDiagnostic &NoneDiag,
5402                                            const PartialDiagnostic &AmbigDiag,
5403                                         const PartialDiagnostic &CandidateDiag,
5404                                         bool Complain = true,
5405                                         QualType TargetType = QualType());
5406 
5407   ClassTemplatePartialSpecializationDecl *
5408   getMoreSpecializedPartialSpecialization(
5409                                   ClassTemplatePartialSpecializationDecl *PS1,
5410                                   ClassTemplatePartialSpecializationDecl *PS2,
5411                                   SourceLocation Loc);
5412 
5413   void MarkUsedTemplateParameters(const TemplateArgumentList &TemplateArgs,
5414                                   bool OnlyDeduced,
5415                                   unsigned Depth,
5416                                   llvm::SmallBitVector &Used);
MarkDeducedTemplateParameters(FunctionTemplateDecl * FunctionTemplate,llvm::SmallBitVector & Deduced)5417   void MarkDeducedTemplateParameters(FunctionTemplateDecl *FunctionTemplate,
5418                                      llvm::SmallBitVector &Deduced) {
5419     return MarkDeducedTemplateParameters(Context, FunctionTemplate, Deduced);
5420   }
5421   static void MarkDeducedTemplateParameters(ASTContext &Ctx,
5422                                          FunctionTemplateDecl *FunctionTemplate,
5423                                          llvm::SmallBitVector &Deduced);
5424 
5425   //===--------------------------------------------------------------------===//
5426   // C++ Template Instantiation
5427   //
5428 
5429   MultiLevelTemplateArgumentList getTemplateInstantiationArgs(NamedDecl *D,
5430                                      const TemplateArgumentList *Innermost = 0,
5431                                                 bool RelativeToPrimary = false,
5432                                                const FunctionDecl *Pattern = 0);
5433 
5434   /// \brief A template instantiation that is currently in progress.
5435   struct ActiveTemplateInstantiation {
5436     /// \brief The kind of template instantiation we are performing
5437     enum InstantiationKind {
5438       /// We are instantiating a template declaration. The entity is
5439       /// the declaration we're instantiating (e.g., a CXXRecordDecl).
5440       TemplateInstantiation,
5441 
5442       /// We are instantiating a default argument for a template
5443       /// parameter. The Entity is the template, and
5444       /// TemplateArgs/NumTemplateArguments provides the template
5445       /// arguments as specified.
5446       /// FIXME: Use a TemplateArgumentList
5447       DefaultTemplateArgumentInstantiation,
5448 
5449       /// We are instantiating a default argument for a function.
5450       /// The Entity is the ParmVarDecl, and TemplateArgs/NumTemplateArgs
5451       /// provides the template arguments as specified.
5452       DefaultFunctionArgumentInstantiation,
5453 
5454       /// We are substituting explicit template arguments provided for
5455       /// a function template. The entity is a FunctionTemplateDecl.
5456       ExplicitTemplateArgumentSubstitution,
5457 
5458       /// We are substituting template argument determined as part of
5459       /// template argument deduction for either a class template
5460       /// partial specialization or a function template. The
5461       /// Entity is either a ClassTemplatePartialSpecializationDecl or
5462       /// a FunctionTemplateDecl.
5463       DeducedTemplateArgumentSubstitution,
5464 
5465       /// We are substituting prior template arguments into a new
5466       /// template parameter. The template parameter itself is either a
5467       /// NonTypeTemplateParmDecl or a TemplateTemplateParmDecl.
5468       PriorTemplateArgumentSubstitution,
5469 
5470       /// We are checking the validity of a default template argument that
5471       /// has been used when naming a template-id.
5472       DefaultTemplateArgumentChecking,
5473 
5474       /// We are instantiating the exception specification for a function
5475       /// template which was deferred until it was needed.
5476       ExceptionSpecInstantiation
5477     } Kind;
5478 
5479     /// \brief The point of instantiation within the source code.
5480     SourceLocation PointOfInstantiation;
5481 
5482     /// \brief The template (or partial specialization) in which we are
5483     /// performing the instantiation, for substitutions of prior template
5484     /// arguments.
5485     NamedDecl *Template;
5486 
5487     /// \brief The entity that is being instantiated.
5488     uintptr_t Entity;
5489 
5490     /// \brief The list of template arguments we are substituting, if they
5491     /// are not part of the entity.
5492     const TemplateArgument *TemplateArgs;
5493 
5494     /// \brief The number of template arguments in TemplateArgs.
5495     unsigned NumTemplateArgs;
5496 
5497     /// \brief The template deduction info object associated with the
5498     /// substitution or checking of explicit or deduced template arguments.
5499     sema::TemplateDeductionInfo *DeductionInfo;
5500 
5501     /// \brief The source range that covers the construct that cause
5502     /// the instantiation, e.g., the template-id that causes a class
5503     /// template instantiation.
5504     SourceRange InstantiationRange;
5505 
ActiveTemplateInstantiationActiveTemplateInstantiation5506     ActiveTemplateInstantiation()
5507       : Kind(TemplateInstantiation), Template(0), Entity(0), TemplateArgs(0),
5508         NumTemplateArgs(0), DeductionInfo(0) {}
5509 
5510     /// \brief Determines whether this template is an actual instantiation
5511     /// that should be counted toward the maximum instantiation depth.
5512     bool isInstantiationRecord() const;
5513 
5514     friend bool operator==(const ActiveTemplateInstantiation &X,
5515                            const ActiveTemplateInstantiation &Y) {
5516       if (X.Kind != Y.Kind)
5517         return false;
5518 
5519       if (X.Entity != Y.Entity)
5520         return false;
5521 
5522       switch (X.Kind) {
5523       case TemplateInstantiation:
5524       case ExceptionSpecInstantiation:
5525         return true;
5526 
5527       case PriorTemplateArgumentSubstitution:
5528       case DefaultTemplateArgumentChecking:
5529         if (X.Template != Y.Template)
5530           return false;
5531 
5532         // Fall through
5533 
5534       case DefaultTemplateArgumentInstantiation:
5535       case ExplicitTemplateArgumentSubstitution:
5536       case DeducedTemplateArgumentSubstitution:
5537       case DefaultFunctionArgumentInstantiation:
5538         return X.TemplateArgs == Y.TemplateArgs;
5539 
5540       }
5541 
5542       llvm_unreachable("Invalid InstantiationKind!");
5543     }
5544 
5545     friend bool operator!=(const ActiveTemplateInstantiation &X,
5546                            const ActiveTemplateInstantiation &Y) {
5547       return !(X == Y);
5548     }
5549   };
5550 
5551   /// \brief List of active template instantiations.
5552   ///
5553   /// This vector is treated as a stack. As one template instantiation
5554   /// requires another template instantiation, additional
5555   /// instantiations are pushed onto the stack up to a
5556   /// user-configurable limit LangOptions::InstantiationDepth.
5557   SmallVector<ActiveTemplateInstantiation, 16>
5558     ActiveTemplateInstantiations;
5559 
5560   /// \brief Whether we are in a SFINAE context that is not associated with
5561   /// template instantiation.
5562   ///
5563   /// This is used when setting up a SFINAE trap (\c see SFINAETrap) outside
5564   /// of a template instantiation or template argument deduction.
5565   bool InNonInstantiationSFINAEContext;
5566 
5567   /// \brief The number of ActiveTemplateInstantiation entries in
5568   /// \c ActiveTemplateInstantiations that are not actual instantiations and,
5569   /// therefore, should not be counted as part of the instantiation depth.
5570   unsigned NonInstantiationEntries;
5571 
5572   /// \brief The last template from which a template instantiation
5573   /// error or warning was produced.
5574   ///
5575   /// This value is used to suppress printing of redundant template
5576   /// instantiation backtraces when there are multiple errors in the
5577   /// same instantiation. FIXME: Does this belong in Sema? It's tough
5578   /// to implement it anywhere else.
5579   ActiveTemplateInstantiation LastTemplateInstantiationErrorContext;
5580 
5581   /// \brief The current index into pack expansion arguments that will be
5582   /// used for substitution of parameter packs.
5583   ///
5584   /// The pack expansion index will be -1 to indicate that parameter packs
5585   /// should be instantiated as themselves. Otherwise, the index specifies
5586   /// which argument within the parameter pack will be used for substitution.
5587   int ArgumentPackSubstitutionIndex;
5588 
5589   /// \brief RAII object used to change the argument pack substitution index
5590   /// within a \c Sema object.
5591   ///
5592   /// See \c ArgumentPackSubstitutionIndex for more information.
5593   class ArgumentPackSubstitutionIndexRAII {
5594     Sema &Self;
5595     int OldSubstitutionIndex;
5596 
5597   public:
ArgumentPackSubstitutionIndexRAII(Sema & Self,int NewSubstitutionIndex)5598     ArgumentPackSubstitutionIndexRAII(Sema &Self, int NewSubstitutionIndex)
5599       : Self(Self), OldSubstitutionIndex(Self.ArgumentPackSubstitutionIndex) {
5600       Self.ArgumentPackSubstitutionIndex = NewSubstitutionIndex;
5601     }
5602 
~ArgumentPackSubstitutionIndexRAII()5603     ~ArgumentPackSubstitutionIndexRAII() {
5604       Self.ArgumentPackSubstitutionIndex = OldSubstitutionIndex;
5605     }
5606   };
5607 
5608   friend class ArgumentPackSubstitutionRAII;
5609 
5610   /// \brief The stack of calls expression undergoing template instantiation.
5611   ///
5612   /// The top of this stack is used by a fixit instantiating unresolved
5613   /// function calls to fix the AST to match the textual change it prints.
5614   SmallVector<CallExpr *, 8> CallsUndergoingInstantiation;
5615 
5616   /// \brief For each declaration that involved template argument deduction, the
5617   /// set of diagnostics that were suppressed during that template argument
5618   /// deduction.
5619   ///
5620   /// FIXME: Serialize this structure to the AST file.
5621   llvm::DenseMap<Decl *, SmallVector<PartialDiagnosticAt, 1> >
5622     SuppressedDiagnostics;
5623 
5624   /// \brief A stack object to be created when performing template
5625   /// instantiation.
5626   ///
5627   /// Construction of an object of type \c InstantiatingTemplate
5628   /// pushes the current instantiation onto the stack of active
5629   /// instantiations. If the size of this stack exceeds the maximum
5630   /// number of recursive template instantiations, construction
5631   /// produces an error and evaluates true.
5632   ///
5633   /// Destruction of this object will pop the named instantiation off
5634   /// the stack.
5635   struct InstantiatingTemplate {
5636     /// \brief Note that we are instantiating a class template,
5637     /// function template, or a member thereof.
5638     InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
5639                           Decl *Entity,
5640                           SourceRange InstantiationRange = SourceRange());
5641 
5642     struct ExceptionSpecification {};
5643     /// \brief Note that we are instantiating an exception specification
5644     /// of a function template.
5645     InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
5646                           FunctionDecl *Entity, ExceptionSpecification,
5647                           SourceRange InstantiationRange = SourceRange());
5648 
5649     /// \brief Note that we are instantiating a default argument in a
5650     /// template-id.
5651     InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
5652                           TemplateDecl *Template,
5653                           ArrayRef<TemplateArgument> TemplateArgs,
5654                           SourceRange InstantiationRange = SourceRange());
5655 
5656     /// \brief Note that we are instantiating a default argument in a
5657     /// template-id.
5658     InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
5659                           FunctionTemplateDecl *FunctionTemplate,
5660                           ArrayRef<TemplateArgument> TemplateArgs,
5661                           ActiveTemplateInstantiation::InstantiationKind Kind,
5662                           sema::TemplateDeductionInfo &DeductionInfo,
5663                           SourceRange InstantiationRange = SourceRange());
5664 
5665     /// \brief Note that we are instantiating as part of template
5666     /// argument deduction for a class template partial
5667     /// specialization.
5668     InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
5669                           ClassTemplatePartialSpecializationDecl *PartialSpec,
5670                           ArrayRef<TemplateArgument> TemplateArgs,
5671                           sema::TemplateDeductionInfo &DeductionInfo,
5672                           SourceRange InstantiationRange = SourceRange());
5673 
5674     InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
5675                           ParmVarDecl *Param,
5676                           ArrayRef<TemplateArgument> TemplateArgs,
5677                           SourceRange InstantiationRange = SourceRange());
5678 
5679     /// \brief Note that we are substituting prior template arguments into a
5680     /// non-type or template template parameter.
5681     InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
5682                           NamedDecl *Template,
5683                           NonTypeTemplateParmDecl *Param,
5684                           ArrayRef<TemplateArgument> TemplateArgs,
5685                           SourceRange InstantiationRange);
5686 
5687     InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
5688                           NamedDecl *Template,
5689                           TemplateTemplateParmDecl *Param,
5690                           ArrayRef<TemplateArgument> TemplateArgs,
5691                           SourceRange InstantiationRange);
5692 
5693     /// \brief Note that we are checking the default template argument
5694     /// against the template parameter for a given template-id.
5695     InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
5696                           TemplateDecl *Template,
5697                           NamedDecl *Param,
5698                           ArrayRef<TemplateArgument> TemplateArgs,
5699                           SourceRange InstantiationRange);
5700 
5701 
5702     /// \brief Note that we have finished instantiating this template.
5703     void Clear();
5704 
~InstantiatingTemplateInstantiatingTemplate5705     ~InstantiatingTemplate() { Clear(); }
5706 
5707     /// \brief Determines whether we have exceeded the maximum
5708     /// recursive template instantiations.
5709     operator bool() const { return Invalid; }
5710 
5711   private:
5712     Sema &SemaRef;
5713     bool Invalid;
5714     bool SavedInNonInstantiationSFINAEContext;
5715     bool CheckInstantiationDepth(SourceLocation PointOfInstantiation,
5716                                  SourceRange InstantiationRange);
5717 
5718     InstantiatingTemplate(const InstantiatingTemplate&); // not implemented
5719 
5720     InstantiatingTemplate&
5721     operator=(const InstantiatingTemplate&); // not implemented
5722   };
5723 
5724   void PrintInstantiationStack();
5725 
5726   /// \brief Determines whether we are currently in a context where
5727   /// template argument substitution failures are not considered
5728   /// errors.
5729   ///
5730   /// \returns An empty \c llvm::Optional if we're not in a SFINAE context.
5731   /// Otherwise, contains a pointer that, if non-NULL, contains the nearest
5732   /// template-deduction context object, which can be used to capture
5733   /// diagnostics that will be suppressed.
5734   llvm::Optional<sema::TemplateDeductionInfo *> isSFINAEContext() const;
5735 
5736   /// \brief Determines whether we are currently in a context that
5737   /// is not evaluated as per C++ [expr] p5.
isUnevaluatedContext()5738   bool isUnevaluatedContext() const {
5739     assert(!ExprEvalContexts.empty() &&
5740            "Must be in an expression evaluation context");
5741     return ExprEvalContexts.back().Context == Sema::Unevaluated;
5742   }
5743 
5744   /// \brief RAII class used to determine whether SFINAE has
5745   /// trapped any errors that occur during template argument
5746   /// deduction.`
5747   class SFINAETrap {
5748     Sema &SemaRef;
5749     unsigned PrevSFINAEErrors;
5750     bool PrevInNonInstantiationSFINAEContext;
5751     bool PrevAccessCheckingSFINAE;
5752 
5753   public:
5754     explicit SFINAETrap(Sema &SemaRef, bool AccessCheckingSFINAE = false)
SemaRef(SemaRef)5755       : SemaRef(SemaRef), PrevSFINAEErrors(SemaRef.NumSFINAEErrors),
5756         PrevInNonInstantiationSFINAEContext(
5757                                       SemaRef.InNonInstantiationSFINAEContext),
5758         PrevAccessCheckingSFINAE(SemaRef.AccessCheckingSFINAE)
5759     {
5760       if (!SemaRef.isSFINAEContext())
5761         SemaRef.InNonInstantiationSFINAEContext = true;
5762       SemaRef.AccessCheckingSFINAE = AccessCheckingSFINAE;
5763     }
5764 
~SFINAETrap()5765     ~SFINAETrap() {
5766       SemaRef.NumSFINAEErrors = PrevSFINAEErrors;
5767       SemaRef.InNonInstantiationSFINAEContext
5768         = PrevInNonInstantiationSFINAEContext;
5769       SemaRef.AccessCheckingSFINAE = PrevAccessCheckingSFINAE;
5770     }
5771 
5772     /// \brief Determine whether any SFINAE errors have been trapped.
hasErrorOccurred()5773     bool hasErrorOccurred() const {
5774       return SemaRef.NumSFINAEErrors > PrevSFINAEErrors;
5775     }
5776   };
5777 
5778   /// \brief The current instantiation scope used to store local
5779   /// variables.
5780   LocalInstantiationScope *CurrentInstantiationScope;
5781 
5782   /// \brief The number of typos corrected by CorrectTypo.
5783   unsigned TyposCorrected;
5784 
5785   typedef llvm::DenseMap<IdentifierInfo *, TypoCorrection>
5786     UnqualifiedTyposCorrectedMap;
5787 
5788   /// \brief A cache containing the results of typo correction for unqualified
5789   /// name lookup.
5790   ///
5791   /// The string is the string that we corrected to (which may be empty, if
5792   /// there was no correction), while the boolean will be true when the
5793   /// string represents a keyword.
5794   UnqualifiedTyposCorrectedMap UnqualifiedTyposCorrected;
5795 
5796   /// \brief Worker object for performing CFG-based warnings.
5797   sema::AnalysisBasedWarnings AnalysisWarnings;
5798 
5799   /// \brief An entity for which implicit template instantiation is required.
5800   ///
5801   /// The source location associated with the declaration is the first place in
5802   /// the source code where the declaration was "used". It is not necessarily
5803   /// the point of instantiation (which will be either before or after the
5804   /// namespace-scope declaration that triggered this implicit instantiation),
5805   /// However, it is the location that diagnostics should generally refer to,
5806   /// because users will need to know what code triggered the instantiation.
5807   typedef std::pair<ValueDecl *, SourceLocation> PendingImplicitInstantiation;
5808 
5809   /// \brief The queue of implicit template instantiations that are required
5810   /// but have not yet been performed.
5811   std::deque<PendingImplicitInstantiation> PendingInstantiations;
5812 
5813   /// \brief The queue of implicit template instantiations that are required
5814   /// and must be performed within the current local scope.
5815   ///
5816   /// This queue is only used for member functions of local classes in
5817   /// templates, which must be instantiated in the same scope as their
5818   /// enclosing function, so that they can reference function-local
5819   /// types, static variables, enumerators, etc.
5820   std::deque<PendingImplicitInstantiation> PendingLocalImplicitInstantiations;
5821 
5822   void PerformPendingInstantiations(bool LocalOnly = false);
5823 
5824   TypeSourceInfo *SubstType(TypeSourceInfo *T,
5825                             const MultiLevelTemplateArgumentList &TemplateArgs,
5826                             SourceLocation Loc, DeclarationName Entity);
5827 
5828   QualType SubstType(QualType T,
5829                      const MultiLevelTemplateArgumentList &TemplateArgs,
5830                      SourceLocation Loc, DeclarationName Entity);
5831 
5832   TypeSourceInfo *SubstType(TypeLoc TL,
5833                             const MultiLevelTemplateArgumentList &TemplateArgs,
5834                             SourceLocation Loc, DeclarationName Entity);
5835 
5836   TypeSourceInfo *SubstFunctionDeclType(TypeSourceInfo *T,
5837                             const MultiLevelTemplateArgumentList &TemplateArgs,
5838                                         SourceLocation Loc,
5839                                         DeclarationName Entity,
5840                                         CXXRecordDecl *ThisContext,
5841                                         unsigned ThisTypeQuals);
5842   ParmVarDecl *SubstParmVarDecl(ParmVarDecl *D,
5843                             const MultiLevelTemplateArgumentList &TemplateArgs,
5844                                 int indexAdjustment,
5845                                 llvm::Optional<unsigned> NumExpansions,
5846                                 bool ExpectParameterPack);
5847   bool SubstParmTypes(SourceLocation Loc,
5848                       ParmVarDecl **Params, unsigned NumParams,
5849                       const MultiLevelTemplateArgumentList &TemplateArgs,
5850                       SmallVectorImpl<QualType> &ParamTypes,
5851                       SmallVectorImpl<ParmVarDecl *> *OutParams = 0);
5852   ExprResult SubstExpr(Expr *E,
5853                        const MultiLevelTemplateArgumentList &TemplateArgs);
5854 
5855   /// \brief Substitute the given template arguments into a list of
5856   /// expressions, expanding pack expansions if required.
5857   ///
5858   /// \param Exprs The list of expressions to substitute into.
5859   ///
5860   /// \param NumExprs The number of expressions in \p Exprs.
5861   ///
5862   /// \param IsCall Whether this is some form of call, in which case
5863   /// default arguments will be dropped.
5864   ///
5865   /// \param TemplateArgs The set of template arguments to substitute.
5866   ///
5867   /// \param Outputs Will receive all of the substituted arguments.
5868   ///
5869   /// \returns true if an error occurred, false otherwise.
5870   bool SubstExprs(Expr **Exprs, unsigned NumExprs, bool IsCall,
5871                   const MultiLevelTemplateArgumentList &TemplateArgs,
5872                   SmallVectorImpl<Expr *> &Outputs);
5873 
5874   StmtResult SubstStmt(Stmt *S,
5875                        const MultiLevelTemplateArgumentList &TemplateArgs);
5876 
5877   Decl *SubstDecl(Decl *D, DeclContext *Owner,
5878                   const MultiLevelTemplateArgumentList &TemplateArgs);
5879 
5880   ExprResult SubstInitializer(Expr *E,
5881                        const MultiLevelTemplateArgumentList &TemplateArgs,
5882                        bool CXXDirectInit);
5883 
5884   bool
5885   SubstBaseSpecifiers(CXXRecordDecl *Instantiation,
5886                       CXXRecordDecl *Pattern,
5887                       const MultiLevelTemplateArgumentList &TemplateArgs);
5888 
5889   bool
5890   InstantiateClass(SourceLocation PointOfInstantiation,
5891                    CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern,
5892                    const MultiLevelTemplateArgumentList &TemplateArgs,
5893                    TemplateSpecializationKind TSK,
5894                    bool Complain = true);
5895 
5896   bool InstantiateEnum(SourceLocation PointOfInstantiation,
5897                        EnumDecl *Instantiation, EnumDecl *Pattern,
5898                        const MultiLevelTemplateArgumentList &TemplateArgs,
5899                        TemplateSpecializationKind TSK);
5900 
5901   struct LateInstantiatedAttribute {
5902     const Attr *TmplAttr;
5903     LocalInstantiationScope *Scope;
5904     Decl *NewDecl;
5905 
LateInstantiatedAttributeLateInstantiatedAttribute5906     LateInstantiatedAttribute(const Attr *A, LocalInstantiationScope *S,
5907                               Decl *D)
5908       : TmplAttr(A), Scope(S), NewDecl(D)
5909     { }
5910   };
5911   typedef SmallVector<LateInstantiatedAttribute, 16> LateInstantiatedAttrVec;
5912 
5913   void InstantiateAttrs(const MultiLevelTemplateArgumentList &TemplateArgs,
5914                         const Decl *Pattern, Decl *Inst,
5915                         LateInstantiatedAttrVec *LateAttrs = 0,
5916                         LocalInstantiationScope *OuterMostScope = 0);
5917 
5918   bool
5919   InstantiateClassTemplateSpecialization(SourceLocation PointOfInstantiation,
5920                            ClassTemplateSpecializationDecl *ClassTemplateSpec,
5921                            TemplateSpecializationKind TSK,
5922                            bool Complain = true);
5923 
5924   void InstantiateClassMembers(SourceLocation PointOfInstantiation,
5925                                CXXRecordDecl *Instantiation,
5926                             const MultiLevelTemplateArgumentList &TemplateArgs,
5927                                TemplateSpecializationKind TSK);
5928 
5929   void InstantiateClassTemplateSpecializationMembers(
5930                                           SourceLocation PointOfInstantiation,
5931                            ClassTemplateSpecializationDecl *ClassTemplateSpec,
5932                                                 TemplateSpecializationKind TSK);
5933 
5934   NestedNameSpecifierLoc
5935   SubstNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS,
5936                            const MultiLevelTemplateArgumentList &TemplateArgs);
5937 
5938   DeclarationNameInfo
5939   SubstDeclarationNameInfo(const DeclarationNameInfo &NameInfo,
5940                            const MultiLevelTemplateArgumentList &TemplateArgs);
5941   TemplateName
5942   SubstTemplateName(NestedNameSpecifierLoc QualifierLoc, TemplateName Name,
5943                     SourceLocation Loc,
5944                     const MultiLevelTemplateArgumentList &TemplateArgs);
5945   bool Subst(const TemplateArgumentLoc *Args, unsigned NumArgs,
5946              TemplateArgumentListInfo &Result,
5947              const MultiLevelTemplateArgumentList &TemplateArgs);
5948 
5949   void InstantiateExceptionSpec(SourceLocation PointOfInstantiation,
5950                                 FunctionDecl *Function);
5951   void InstantiateFunctionDefinition(SourceLocation PointOfInstantiation,
5952                                      FunctionDecl *Function,
5953                                      bool Recursive = false,
5954                                      bool DefinitionRequired = false);
5955   void InstantiateStaticDataMemberDefinition(
5956                                      SourceLocation PointOfInstantiation,
5957                                      VarDecl *Var,
5958                                      bool Recursive = false,
5959                                      bool DefinitionRequired = false);
5960 
5961   void InstantiateMemInitializers(CXXConstructorDecl *New,
5962                                   const CXXConstructorDecl *Tmpl,
5963                             const MultiLevelTemplateArgumentList &TemplateArgs);
5964 
5965   NamedDecl *FindInstantiatedDecl(SourceLocation Loc, NamedDecl *D,
5966                           const MultiLevelTemplateArgumentList &TemplateArgs);
5967   DeclContext *FindInstantiatedContext(SourceLocation Loc, DeclContext *DC,
5968                           const MultiLevelTemplateArgumentList &TemplateArgs);
5969 
5970   // Objective-C declarations.
5971   enum ObjCContainerKind {
5972     OCK_None = -1,
5973     OCK_Interface = 0,
5974     OCK_Protocol,
5975     OCK_Category,
5976     OCK_ClassExtension,
5977     OCK_Implementation,
5978     OCK_CategoryImplementation
5979   };
5980   ObjCContainerKind getObjCContainerKind() const;
5981 
5982   Decl *ActOnStartClassInterface(SourceLocation AtInterfaceLoc,
5983                                  IdentifierInfo *ClassName,
5984                                  SourceLocation ClassLoc,
5985                                  IdentifierInfo *SuperName,
5986                                  SourceLocation SuperLoc,
5987                                  Decl * const *ProtoRefs,
5988                                  unsigned NumProtoRefs,
5989                                  const SourceLocation *ProtoLocs,
5990                                  SourceLocation EndProtoLoc,
5991                                  AttributeList *AttrList);
5992 
5993   Decl *ActOnCompatibilityAlias(
5994                     SourceLocation AtCompatibilityAliasLoc,
5995                     IdentifierInfo *AliasName,  SourceLocation AliasLocation,
5996                     IdentifierInfo *ClassName, SourceLocation ClassLocation);
5997 
5998   bool CheckForwardProtocolDeclarationForCircularDependency(
5999     IdentifierInfo *PName,
6000     SourceLocation &PLoc, SourceLocation PrevLoc,
6001     const ObjCList<ObjCProtocolDecl> &PList);
6002 
6003   Decl *ActOnStartProtocolInterface(
6004                     SourceLocation AtProtoInterfaceLoc,
6005                     IdentifierInfo *ProtocolName, SourceLocation ProtocolLoc,
6006                     Decl * const *ProtoRefNames, unsigned NumProtoRefs,
6007                     const SourceLocation *ProtoLocs,
6008                     SourceLocation EndProtoLoc,
6009                     AttributeList *AttrList);
6010 
6011   Decl *ActOnStartCategoryInterface(SourceLocation AtInterfaceLoc,
6012                                     IdentifierInfo *ClassName,
6013                                     SourceLocation ClassLoc,
6014                                     IdentifierInfo *CategoryName,
6015                                     SourceLocation CategoryLoc,
6016                                     Decl * const *ProtoRefs,
6017                                     unsigned NumProtoRefs,
6018                                     const SourceLocation *ProtoLocs,
6019                                     SourceLocation EndProtoLoc);
6020 
6021   Decl *ActOnStartClassImplementation(
6022                     SourceLocation AtClassImplLoc,
6023                     IdentifierInfo *ClassName, SourceLocation ClassLoc,
6024                     IdentifierInfo *SuperClassname,
6025                     SourceLocation SuperClassLoc);
6026 
6027   Decl *ActOnStartCategoryImplementation(SourceLocation AtCatImplLoc,
6028                                          IdentifierInfo *ClassName,
6029                                          SourceLocation ClassLoc,
6030                                          IdentifierInfo *CatName,
6031                                          SourceLocation CatLoc);
6032 
6033   DeclGroupPtrTy ActOnFinishObjCImplementation(Decl *ObjCImpDecl,
6034                                                ArrayRef<Decl *> Decls);
6035 
6036   DeclGroupPtrTy ActOnForwardClassDeclaration(SourceLocation Loc,
6037                                      IdentifierInfo **IdentList,
6038                                      SourceLocation *IdentLocs,
6039                                      unsigned NumElts);
6040 
6041   DeclGroupPtrTy ActOnForwardProtocolDeclaration(SourceLocation AtProtoclLoc,
6042                                         const IdentifierLocPair *IdentList,
6043                                         unsigned NumElts,
6044                                         AttributeList *attrList);
6045 
6046   void FindProtocolDeclaration(bool WarnOnDeclarations,
6047                                const IdentifierLocPair *ProtocolId,
6048                                unsigned NumProtocols,
6049                                SmallVectorImpl<Decl *> &Protocols);
6050 
6051   /// Ensure attributes are consistent with type.
6052   /// \param [in, out] Attributes The attributes to check; they will
6053   /// be modified to be consistent with \arg PropertyTy.
6054   void CheckObjCPropertyAttributes(Decl *PropertyPtrTy,
6055                                    SourceLocation Loc,
6056                                    unsigned &Attributes,
6057                                    bool propertyInPrimaryClass);
6058 
6059   /// Process the specified property declaration and create decls for the
6060   /// setters and getters as needed.
6061   /// \param property The property declaration being processed
6062   /// \param CD The semantic container for the property
6063   /// \param redeclaredProperty Declaration for property if redeclared
6064   ///        in class extension.
6065   /// \param lexicalDC Container for redeclaredProperty.
6066   void ProcessPropertyDecl(ObjCPropertyDecl *property,
6067                            ObjCContainerDecl *CD,
6068                            ObjCPropertyDecl *redeclaredProperty = 0,
6069                            ObjCContainerDecl *lexicalDC = 0);
6070 
6071 
6072   void DiagnosePropertyMismatch(ObjCPropertyDecl *Property,
6073                                 ObjCPropertyDecl *SuperProperty,
6074                                 const IdentifierInfo *Name);
6075   void ComparePropertiesInBaseAndSuper(ObjCInterfaceDecl *IDecl);
6076 
6077 
6078   void CompareProperties(Decl *CDecl, Decl *MergeProtocols);
6079 
6080   void DiagnoseClassExtensionDupMethods(ObjCCategoryDecl *CAT,
6081                                         ObjCInterfaceDecl *ID);
6082 
6083   void MatchOneProtocolPropertiesInClass(Decl *CDecl,
6084                                          ObjCProtocolDecl *PDecl);
6085 
6086   Decl *ActOnAtEnd(Scope *S, SourceRange AtEnd,
6087                    Decl **allMethods = 0, unsigned allNum = 0,
6088                    Decl **allProperties = 0, unsigned pNum = 0,
6089                    DeclGroupPtrTy *allTUVars = 0, unsigned tuvNum = 0);
6090 
6091   Decl *ActOnProperty(Scope *S, SourceLocation AtLoc,
6092                       SourceLocation LParenLoc,
6093                       FieldDeclarator &FD, ObjCDeclSpec &ODS,
6094                       Selector GetterSel, Selector SetterSel,
6095                       bool *OverridingProperty,
6096                       tok::ObjCKeywordKind MethodImplKind,
6097                       DeclContext *lexicalDC = 0);
6098 
6099   Decl *ActOnPropertyImplDecl(Scope *S,
6100                               SourceLocation AtLoc,
6101                               SourceLocation PropertyLoc,
6102                               bool ImplKind,
6103                               IdentifierInfo *PropertyId,
6104                               IdentifierInfo *PropertyIvar,
6105                               SourceLocation PropertyIvarLoc);
6106 
6107   enum ObjCSpecialMethodKind {
6108     OSMK_None,
6109     OSMK_Alloc,
6110     OSMK_New,
6111     OSMK_Copy,
6112     OSMK_RetainingInit,
6113     OSMK_NonRetainingInit
6114   };
6115 
6116   struct ObjCArgInfo {
6117     IdentifierInfo *Name;
6118     SourceLocation NameLoc;
6119     // The Type is null if no type was specified, and the DeclSpec is invalid
6120     // in this case.
6121     ParsedType Type;
6122     ObjCDeclSpec DeclSpec;
6123 
6124     /// ArgAttrs - Attribute list for this argument.
6125     AttributeList *ArgAttrs;
6126   };
6127 
6128   Decl *ActOnMethodDeclaration(
6129     Scope *S,
6130     SourceLocation BeginLoc, // location of the + or -.
6131     SourceLocation EndLoc,   // location of the ; or {.
6132     tok::TokenKind MethodType,
6133     ObjCDeclSpec &ReturnQT, ParsedType ReturnType,
6134     ArrayRef<SourceLocation> SelectorLocs, Selector Sel,
6135     // optional arguments. The number of types/arguments is obtained
6136     // from the Sel.getNumArgs().
6137     ObjCArgInfo *ArgInfo,
6138     DeclaratorChunk::ParamInfo *CParamInfo, unsigned CNumArgs, // c-style args
6139     AttributeList *AttrList, tok::ObjCKeywordKind MethodImplKind,
6140     bool isVariadic, bool MethodDefinition);
6141 
6142   ObjCMethodDecl *LookupMethodInQualifiedType(Selector Sel,
6143                                               const ObjCObjectPointerType *OPT,
6144                                               bool IsInstance);
6145   ObjCMethodDecl *LookupMethodInObjectType(Selector Sel, QualType Ty,
6146                                            bool IsInstance);
6147 
6148   bool inferObjCARCLifetime(ValueDecl *decl);
6149 
6150   ExprResult
6151   HandleExprPropertyRefExpr(const ObjCObjectPointerType *OPT,
6152                             Expr *BaseExpr,
6153                             SourceLocation OpLoc,
6154                             DeclarationName MemberName,
6155                             SourceLocation MemberLoc,
6156                             SourceLocation SuperLoc, QualType SuperType,
6157                             bool Super);
6158 
6159   ExprResult
6160   ActOnClassPropertyRefExpr(IdentifierInfo &receiverName,
6161                             IdentifierInfo &propertyName,
6162                             SourceLocation receiverNameLoc,
6163                             SourceLocation propertyNameLoc);
6164 
6165   ObjCMethodDecl *tryCaptureObjCSelf(SourceLocation Loc);
6166 
6167   /// \brief Describes the kind of message expression indicated by a message
6168   /// send that starts with an identifier.
6169   enum ObjCMessageKind {
6170     /// \brief The message is sent to 'super'.
6171     ObjCSuperMessage,
6172     /// \brief The message is an instance message.
6173     ObjCInstanceMessage,
6174     /// \brief The message is a class message, and the identifier is a type
6175     /// name.
6176     ObjCClassMessage
6177   };
6178 
6179   ObjCMessageKind getObjCMessageKind(Scope *S,
6180                                      IdentifierInfo *Name,
6181                                      SourceLocation NameLoc,
6182                                      bool IsSuper,
6183                                      bool HasTrailingDot,
6184                                      ParsedType &ReceiverType);
6185 
6186   ExprResult ActOnSuperMessage(Scope *S, SourceLocation SuperLoc,
6187                                Selector Sel,
6188                                SourceLocation LBracLoc,
6189                                ArrayRef<SourceLocation> SelectorLocs,
6190                                SourceLocation RBracLoc,
6191                                MultiExprArg Args);
6192 
6193   ExprResult BuildClassMessage(TypeSourceInfo *ReceiverTypeInfo,
6194                                QualType ReceiverType,
6195                                SourceLocation SuperLoc,
6196                                Selector Sel,
6197                                ObjCMethodDecl *Method,
6198                                SourceLocation LBracLoc,
6199                                ArrayRef<SourceLocation> SelectorLocs,
6200                                SourceLocation RBracLoc,
6201                                MultiExprArg Args,
6202                                bool isImplicit = false);
6203 
6204   ExprResult BuildClassMessageImplicit(QualType ReceiverType,
6205                                        bool isSuperReceiver,
6206                                        SourceLocation Loc,
6207                                        Selector Sel,
6208                                        ObjCMethodDecl *Method,
6209                                        MultiExprArg Args);
6210 
6211   ExprResult ActOnClassMessage(Scope *S,
6212                                ParsedType Receiver,
6213                                Selector Sel,
6214                                SourceLocation LBracLoc,
6215                                ArrayRef<SourceLocation> SelectorLocs,
6216                                SourceLocation RBracLoc,
6217                                MultiExprArg Args);
6218 
6219   ExprResult BuildInstanceMessage(Expr *Receiver,
6220                                   QualType ReceiverType,
6221                                   SourceLocation SuperLoc,
6222                                   Selector Sel,
6223                                   ObjCMethodDecl *Method,
6224                                   SourceLocation LBracLoc,
6225                                   ArrayRef<SourceLocation> SelectorLocs,
6226                                   SourceLocation RBracLoc,
6227                                   MultiExprArg Args,
6228                                   bool isImplicit = false);
6229 
6230   ExprResult BuildInstanceMessageImplicit(Expr *Receiver,
6231                                           QualType ReceiverType,
6232                                           SourceLocation Loc,
6233                                           Selector Sel,
6234                                           ObjCMethodDecl *Method,
6235                                           MultiExprArg Args);
6236 
6237   ExprResult ActOnInstanceMessage(Scope *S,
6238                                   Expr *Receiver,
6239                                   Selector Sel,
6240                                   SourceLocation LBracLoc,
6241                                   ArrayRef<SourceLocation> SelectorLocs,
6242                                   SourceLocation RBracLoc,
6243                                   MultiExprArg Args);
6244 
6245   ExprResult BuildObjCBridgedCast(SourceLocation LParenLoc,
6246                                   ObjCBridgeCastKind Kind,
6247                                   SourceLocation BridgeKeywordLoc,
6248                                   TypeSourceInfo *TSInfo,
6249                                   Expr *SubExpr);
6250 
6251   ExprResult ActOnObjCBridgedCast(Scope *S,
6252                                   SourceLocation LParenLoc,
6253                                   ObjCBridgeCastKind Kind,
6254                                   SourceLocation BridgeKeywordLoc,
6255                                   ParsedType Type,
6256                                   SourceLocation RParenLoc,
6257                                   Expr *SubExpr);
6258 
6259   bool checkInitMethod(ObjCMethodDecl *method, QualType receiverTypeIfCall);
6260 
6261   /// \brief Check whether the given new method is a valid override of the
6262   /// given overridden method, and set any properties that should be inherited.
6263   void CheckObjCMethodOverride(ObjCMethodDecl *NewMethod,
6264                                const ObjCMethodDecl *Overridden,
6265                                bool IsImplementation);
6266 
6267   /// \brief Describes the compatibility of a result type with its method.
6268   enum ResultTypeCompatibilityKind {
6269     RTC_Compatible,
6270     RTC_Incompatible,
6271     RTC_Unknown
6272   };
6273 
6274   void CheckObjCMethodOverrides(ObjCMethodDecl *ObjCMethod,
6275                                 ObjCInterfaceDecl *CurrentClass,
6276                                 ResultTypeCompatibilityKind RTC);
6277 
6278   enum PragmaOptionsAlignKind {
6279     POAK_Native,  // #pragma options align=native
6280     POAK_Natural, // #pragma options align=natural
6281     POAK_Packed,  // #pragma options align=packed
6282     POAK_Power,   // #pragma options align=power
6283     POAK_Mac68k,  // #pragma options align=mac68k
6284     POAK_Reset    // #pragma options align=reset
6285   };
6286 
6287   /// ActOnPragmaOptionsAlign - Called on well formed \#pragma options align.
6288   void ActOnPragmaOptionsAlign(PragmaOptionsAlignKind Kind,
6289                                SourceLocation PragmaLoc,
6290                                SourceLocation KindLoc);
6291 
6292   enum PragmaPackKind {
6293     PPK_Default, // #pragma pack([n])
6294     PPK_Show,    // #pragma pack(show), only supported by MSVC.
6295     PPK_Push,    // #pragma pack(push, [identifier], [n])
6296     PPK_Pop      // #pragma pack(pop, [identifier], [n])
6297   };
6298 
6299   enum PragmaMSStructKind {
6300     PMSST_OFF,  // #pragms ms_struct off
6301     PMSST_ON    // #pragms ms_struct on
6302   };
6303 
6304   /// ActOnPragmaPack - Called on well formed \#pragma pack(...).
6305   void ActOnPragmaPack(PragmaPackKind Kind,
6306                        IdentifierInfo *Name,
6307                        Expr *Alignment,
6308                        SourceLocation PragmaLoc,
6309                        SourceLocation LParenLoc,
6310                        SourceLocation RParenLoc);
6311 
6312   /// ActOnPragmaMSStruct - Called on well formed \#pragma ms_struct [on|off].
6313   void ActOnPragmaMSStruct(PragmaMSStructKind Kind);
6314 
6315   /// ActOnPragmaUnused - Called on well-formed '\#pragma unused'.
6316   void ActOnPragmaUnused(const Token &Identifier,
6317                          Scope *curScope,
6318                          SourceLocation PragmaLoc);
6319 
6320   /// ActOnPragmaVisibility - Called on well formed \#pragma GCC visibility... .
6321   void ActOnPragmaVisibility(const IdentifierInfo* VisType,
6322                              SourceLocation PragmaLoc);
6323 
6324   NamedDecl *DeclClonePragmaWeak(NamedDecl *ND, IdentifierInfo *II,
6325                                  SourceLocation Loc);
6326   void DeclApplyPragmaWeak(Scope *S, NamedDecl *ND, WeakInfo &W);
6327 
6328   /// ActOnPragmaWeakID - Called on well formed \#pragma weak ident.
6329   void ActOnPragmaWeakID(IdentifierInfo* WeakName,
6330                          SourceLocation PragmaLoc,
6331                          SourceLocation WeakNameLoc);
6332 
6333   /// ActOnPragmaRedefineExtname - Called on well formed
6334   /// \#pragma redefine_extname oldname newname.
6335   void ActOnPragmaRedefineExtname(IdentifierInfo* WeakName,
6336                                   IdentifierInfo* AliasName,
6337                                   SourceLocation PragmaLoc,
6338                                   SourceLocation WeakNameLoc,
6339                                   SourceLocation AliasNameLoc);
6340 
6341   /// ActOnPragmaWeakAlias - Called on well formed \#pragma weak ident = ident.
6342   void ActOnPragmaWeakAlias(IdentifierInfo* WeakName,
6343                             IdentifierInfo* AliasName,
6344                             SourceLocation PragmaLoc,
6345                             SourceLocation WeakNameLoc,
6346                             SourceLocation AliasNameLoc);
6347 
6348   /// ActOnPragmaFPContract - Called on well formed
6349   /// \#pragma {STDC,OPENCL} FP_CONTRACT
6350   void ActOnPragmaFPContract(tok::OnOffSwitch OOS);
6351 
6352   /// AddAlignmentAttributesForRecord - Adds any needed alignment attributes to
6353   /// a the record decl, to handle '\#pragma pack' and '\#pragma options align'.
6354   void AddAlignmentAttributesForRecord(RecordDecl *RD);
6355 
6356   /// AddMsStructLayoutForRecord - Adds ms_struct layout attribute to record.
6357   void AddMsStructLayoutForRecord(RecordDecl *RD);
6358 
6359   /// FreePackedContext - Deallocate and null out PackContext.
6360   void FreePackedContext();
6361 
6362   /// PushNamespaceVisibilityAttr - Note that we've entered a
6363   /// namespace with a visibility attribute.
6364   void PushNamespaceVisibilityAttr(const VisibilityAttr *Attr,
6365                                    SourceLocation Loc);
6366 
6367   /// AddPushedVisibilityAttribute - If '\#pragma GCC visibility' was used,
6368   /// add an appropriate visibility attribute.
6369   void AddPushedVisibilityAttribute(Decl *RD);
6370 
6371   /// PopPragmaVisibility - Pop the top element of the visibility stack; used
6372   /// for '\#pragma GCC visibility' and visibility attributes on namespaces.
6373   void PopPragmaVisibility(bool IsNamespaceEnd, SourceLocation EndLoc);
6374 
6375   /// FreeVisContext - Deallocate and null out VisContext.
6376   void FreeVisContext();
6377 
6378   /// AddCFAuditedAttribute - Check whether we're currently within
6379   /// '\#pragma clang arc_cf_code_audited' and, if so, consider adding
6380   /// the appropriate attribute.
6381   void AddCFAuditedAttribute(Decl *D);
6382 
6383   /// AddAlignedAttr - Adds an aligned attribute to a particular declaration.
6384   void AddAlignedAttr(SourceRange AttrRange, Decl *D, Expr *E,
6385                       bool isDeclSpec);
6386   void AddAlignedAttr(SourceRange AttrRange, Decl *D, TypeSourceInfo *T,
6387                       bool isDeclSpec);
6388 
6389   /// \brief The kind of conversion being performed.
6390   enum CheckedConversionKind {
6391     /// \brief An implicit conversion.
6392     CCK_ImplicitConversion,
6393     /// \brief A C-style cast.
6394     CCK_CStyleCast,
6395     /// \brief A functional-style cast.
6396     CCK_FunctionalCast,
6397     /// \brief A cast other than a C-style cast.
6398     CCK_OtherCast
6399   };
6400 
6401   /// ImpCastExprToType - If Expr is not of type 'Type', insert an implicit
6402   /// cast.  If there is already an implicit cast, merge into the existing one.
6403   /// If isLvalue, the result of the cast is an lvalue.
6404   ExprResult ImpCastExprToType(Expr *E, QualType Type, CastKind CK,
6405                                ExprValueKind VK = VK_RValue,
6406                                const CXXCastPath *BasePath = 0,
6407                                CheckedConversionKind CCK
6408                                   = CCK_ImplicitConversion);
6409 
6410   /// ScalarTypeToBooleanCastKind - Returns the cast kind corresponding
6411   /// to the conversion from scalar type ScalarTy to the Boolean type.
6412   static CastKind ScalarTypeToBooleanCastKind(QualType ScalarTy);
6413 
6414   /// IgnoredValueConversions - Given that an expression's result is
6415   /// syntactically ignored, perform any conversions that are
6416   /// required.
6417   ExprResult IgnoredValueConversions(Expr *E);
6418 
6419   // UsualUnaryConversions - promotes integers (C99 6.3.1.1p2) and converts
6420   // functions and arrays to their respective pointers (C99 6.3.2.1).
6421   ExprResult UsualUnaryConversions(Expr *E);
6422 
6423   // DefaultFunctionArrayConversion - converts functions and arrays
6424   // to their respective pointers (C99 6.3.2.1).
6425   ExprResult DefaultFunctionArrayConversion(Expr *E);
6426 
6427   // DefaultFunctionArrayLvalueConversion - converts functions and
6428   // arrays to their respective pointers and performs the
6429   // lvalue-to-rvalue conversion.
6430   ExprResult DefaultFunctionArrayLvalueConversion(Expr *E);
6431 
6432   // DefaultLvalueConversion - performs lvalue-to-rvalue conversion on
6433   // the operand.  This is DefaultFunctionArrayLvalueConversion,
6434   // except that it assumes the operand isn't of function or array
6435   // type.
6436   ExprResult DefaultLvalueConversion(Expr *E);
6437 
6438   // DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
6439   // do not have a prototype. Integer promotions are performed on each
6440   // argument, and arguments that have type float are promoted to double.
6441   ExprResult DefaultArgumentPromotion(Expr *E);
6442 
6443   // Used for emitting the right warning by DefaultVariadicArgumentPromotion
6444   enum VariadicCallType {
6445     VariadicFunction,
6446     VariadicBlock,
6447     VariadicMethod,
6448     VariadicConstructor,
6449     VariadicDoesNotApply
6450   };
6451 
6452   VariadicCallType getVariadicCallType(FunctionDecl *FDecl,
6453                                        const FunctionProtoType *Proto,
6454                                        Expr *Fn);
6455 
6456   // Used for determining in which context a type is allowed to be passed to a
6457   // vararg function.
6458   enum VarArgKind {
6459     VAK_Valid,
6460     VAK_ValidInCXX11,
6461     VAK_Invalid
6462   };
6463 
6464   // Determines which VarArgKind fits an expression.
6465   VarArgKind isValidVarArgType(const QualType &Ty);
6466 
6467   /// GatherArgumentsForCall - Collector argument expressions for various
6468   /// form of call prototypes.
6469   bool GatherArgumentsForCall(SourceLocation CallLoc,
6470                               FunctionDecl *FDecl,
6471                               const FunctionProtoType *Proto,
6472                               unsigned FirstProtoArg,
6473                               Expr **Args, unsigned NumArgs,
6474                               SmallVector<Expr *, 8> &AllArgs,
6475                               VariadicCallType CallType = VariadicDoesNotApply,
6476                               bool AllowExplicit = false);
6477 
6478   // DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
6479   // will create a runtime trap if the resulting type is not a POD type.
6480   ExprResult DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
6481                                               FunctionDecl *FDecl);
6482 
6483   /// Checks to see if the given expression is a valid argument to a variadic
6484   /// function, issuing a diagnostic and returning NULL if not.
6485   bool variadicArgumentPODCheck(const Expr *E, VariadicCallType CT);
6486 
6487   // UsualArithmeticConversions - performs the UsualUnaryConversions on it's
6488   // operands and then handles various conversions that are common to binary
6489   // operators (C99 6.3.1.8). If both operands aren't arithmetic, this
6490   // routine returns the first non-arithmetic type found. The client is
6491   // responsible for emitting appropriate error diagnostics.
6492   QualType UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
6493                                       bool IsCompAssign = false);
6494 
6495   /// AssignConvertType - All of the 'assignment' semantic checks return this
6496   /// enum to indicate whether the assignment was allowed.  These checks are
6497   /// done for simple assignments, as well as initialization, return from
6498   /// function, argument passing, etc.  The query is phrased in terms of a
6499   /// source and destination type.
6500   enum AssignConvertType {
6501     /// Compatible - the types are compatible according to the standard.
6502     Compatible,
6503 
6504     /// PointerToInt - The assignment converts a pointer to an int, which we
6505     /// accept as an extension.
6506     PointerToInt,
6507 
6508     /// IntToPointer - The assignment converts an int to a pointer, which we
6509     /// accept as an extension.
6510     IntToPointer,
6511 
6512     /// FunctionVoidPointer - The assignment is between a function pointer and
6513     /// void*, which the standard doesn't allow, but we accept as an extension.
6514     FunctionVoidPointer,
6515 
6516     /// IncompatiblePointer - The assignment is between two pointers types that
6517     /// are not compatible, but we accept them as an extension.
6518     IncompatiblePointer,
6519 
6520     /// IncompatiblePointer - The assignment is between two pointers types which
6521     /// point to integers which have a different sign, but are otherwise
6522     /// identical. This is a subset of the above, but broken out because it's by
6523     /// far the most common case of incompatible pointers.
6524     IncompatiblePointerSign,
6525 
6526     /// CompatiblePointerDiscardsQualifiers - The assignment discards
6527     /// c/v/r qualifiers, which we accept as an extension.
6528     CompatiblePointerDiscardsQualifiers,
6529 
6530     /// IncompatiblePointerDiscardsQualifiers - The assignment
6531     /// discards qualifiers that we don't permit to be discarded,
6532     /// like address spaces.
6533     IncompatiblePointerDiscardsQualifiers,
6534 
6535     /// IncompatibleNestedPointerQualifiers - The assignment is between two
6536     /// nested pointer types, and the qualifiers other than the first two
6537     /// levels differ e.g. char ** -> const char **, but we accept them as an
6538     /// extension.
6539     IncompatibleNestedPointerQualifiers,
6540 
6541     /// IncompatibleVectors - The assignment is between two vector types that
6542     /// have the same size, which we accept as an extension.
6543     IncompatibleVectors,
6544 
6545     /// IntToBlockPointer - The assignment converts an int to a block
6546     /// pointer. We disallow this.
6547     IntToBlockPointer,
6548 
6549     /// IncompatibleBlockPointer - The assignment is between two block
6550     /// pointers types that are not compatible.
6551     IncompatibleBlockPointer,
6552 
6553     /// IncompatibleObjCQualifiedId - The assignment is between a qualified
6554     /// id type and something else (that is incompatible with it). For example,
6555     /// "id <XXX>" = "Foo *", where "Foo *" doesn't implement the XXX protocol.
6556     IncompatibleObjCQualifiedId,
6557 
6558     /// IncompatibleObjCWeakRef - Assigning a weak-unavailable object to an
6559     /// object with __weak qualifier.
6560     IncompatibleObjCWeakRef,
6561 
6562     /// Incompatible - We reject this conversion outright, it is invalid to
6563     /// represent it in the AST.
6564     Incompatible
6565   };
6566 
6567   /// DiagnoseAssignmentResult - Emit a diagnostic, if required, for the
6568   /// assignment conversion type specified by ConvTy.  This returns true if the
6569   /// conversion was invalid or false if the conversion was accepted.
6570   bool DiagnoseAssignmentResult(AssignConvertType ConvTy,
6571                                 SourceLocation Loc,
6572                                 QualType DstType, QualType SrcType,
6573                                 Expr *SrcExpr, AssignmentAction Action,
6574                                 bool *Complained = 0);
6575 
6576   /// DiagnoseAssignmentEnum - Warn if assignment to enum is a constant
6577   /// integer not in the range of enum values.
6578   void DiagnoseAssignmentEnum(QualType DstType, QualType SrcType,
6579                               Expr *SrcExpr);
6580 
6581   /// CheckAssignmentConstraints - Perform type checking for assignment,
6582   /// argument passing, variable initialization, and function return values.
6583   /// C99 6.5.16.
6584   AssignConvertType CheckAssignmentConstraints(SourceLocation Loc,
6585                                                QualType LHSType,
6586                                                QualType RHSType);
6587 
6588   /// Check assignment constraints and prepare for a conversion of the
6589   /// RHS to the LHS type.
6590   AssignConvertType CheckAssignmentConstraints(QualType LHSType,
6591                                                ExprResult &RHS,
6592                                                CastKind &Kind);
6593 
6594   // CheckSingleAssignmentConstraints - Currently used by
6595   // CheckAssignmentOperands, and ActOnReturnStmt. Prior to type checking,
6596   // this routine performs the default function/array converions.
6597   AssignConvertType CheckSingleAssignmentConstraints(QualType LHSType,
6598                                                      ExprResult &RHS,
6599                                                      bool Diagnose = true);
6600 
6601   // \brief If the lhs type is a transparent union, check whether we
6602   // can initialize the transparent union with the given expression.
6603   AssignConvertType CheckTransparentUnionArgumentConstraints(QualType ArgType,
6604                                                              ExprResult &RHS);
6605 
6606   bool IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType);
6607 
6608   bool CheckExceptionSpecCompatibility(Expr *From, QualType ToType);
6609 
6610   ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
6611                                        AssignmentAction Action,
6612                                        bool AllowExplicit = false);
6613   ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
6614                                        AssignmentAction Action,
6615                                        bool AllowExplicit,
6616                                        ImplicitConversionSequence& ICS);
6617   ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
6618                                        const ImplicitConversionSequence& ICS,
6619                                        AssignmentAction Action,
6620                                        CheckedConversionKind CCK
6621                                           = CCK_ImplicitConversion);
6622   ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
6623                                        const StandardConversionSequence& SCS,
6624                                        AssignmentAction Action,
6625                                        CheckedConversionKind CCK);
6626 
6627   /// the following "Check" methods will return a valid/converted QualType
6628   /// or a null QualType (indicating an error diagnostic was issued).
6629 
6630   /// type checking binary operators (subroutines of CreateBuiltinBinOp).
6631   QualType InvalidOperands(SourceLocation Loc, ExprResult &LHS,
6632                            ExprResult &RHS);
6633   QualType CheckPointerToMemberOperands( // C++ 5.5
6634     ExprResult &LHS, ExprResult &RHS, ExprValueKind &VK,
6635     SourceLocation OpLoc, bool isIndirect);
6636   QualType CheckMultiplyDivideOperands( // C99 6.5.5
6637     ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign,
6638     bool IsDivide);
6639   QualType CheckRemainderOperands( // C99 6.5.5
6640     ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
6641     bool IsCompAssign = false);
6642   QualType CheckAdditionOperands( // C99 6.5.6
6643     ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc,
6644     QualType* CompLHSTy = 0);
6645   QualType CheckSubtractionOperands( // C99 6.5.6
6646     ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
6647     QualType* CompLHSTy = 0);
6648   QualType CheckShiftOperands( // C99 6.5.7
6649     ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc,
6650     bool IsCompAssign = false);
6651   QualType CheckCompareOperands( // C99 6.5.8/9
6652     ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned OpaqueOpc,
6653                                 bool isRelational);
6654   QualType CheckBitwiseOperands( // C99 6.5.[10...12]
6655     ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
6656     bool IsCompAssign = false);
6657   QualType CheckLogicalOperands( // C99 6.5.[13,14]
6658     ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc);
6659   // CheckAssignmentOperands is used for both simple and compound assignment.
6660   // For simple assignment, pass both expressions and a null converted type.
6661   // For compound assignment, pass both expressions and the converted type.
6662   QualType CheckAssignmentOperands( // C99 6.5.16.[1,2]
6663     Expr *LHSExpr, ExprResult &RHS, SourceLocation Loc, QualType CompoundType);
6664 
6665   ExprResult checkPseudoObjectIncDec(Scope *S, SourceLocation OpLoc,
6666                                      UnaryOperatorKind Opcode, Expr *Op);
6667   ExprResult checkPseudoObjectAssignment(Scope *S, SourceLocation OpLoc,
6668                                          BinaryOperatorKind Opcode,
6669                                          Expr *LHS, Expr *RHS);
6670   ExprResult checkPseudoObjectRValue(Expr *E);
6671   Expr *recreateSyntacticForm(PseudoObjectExpr *E);
6672 
6673   QualType CheckConditionalOperands( // C99 6.5.15
6674     ExprResult &Cond, ExprResult &LHS, ExprResult &RHS,
6675     ExprValueKind &VK, ExprObjectKind &OK, SourceLocation QuestionLoc);
6676   QualType CXXCheckConditionalOperands( // C++ 5.16
6677     ExprResult &cond, ExprResult &lhs, ExprResult &rhs,
6678     ExprValueKind &VK, ExprObjectKind &OK, SourceLocation questionLoc);
6679   QualType FindCompositePointerType(SourceLocation Loc, Expr *&E1, Expr *&E2,
6680                                     bool *NonStandardCompositeType = 0);
6681   QualType FindCompositePointerType(SourceLocation Loc,
6682                                     ExprResult &E1, ExprResult &E2,
6683                                     bool *NonStandardCompositeType = 0) {
6684     Expr *E1Tmp = E1.take(), *E2Tmp = E2.take();
6685     QualType Composite = FindCompositePointerType(Loc, E1Tmp, E2Tmp,
6686                                                   NonStandardCompositeType);
6687     E1 = Owned(E1Tmp);
6688     E2 = Owned(E2Tmp);
6689     return Composite;
6690   }
6691 
6692   QualType FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
6693                                         SourceLocation QuestionLoc);
6694 
6695   bool DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
6696                                   SourceLocation QuestionLoc);
6697 
6698   /// type checking for vector binary operators.
6699   QualType CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
6700                                SourceLocation Loc, bool IsCompAssign);
6701   QualType GetSignedVectorType(QualType V);
6702   QualType CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
6703                                       SourceLocation Loc, bool isRelational);
6704   QualType CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
6705                                       SourceLocation Loc);
6706 
6707   /// type checking declaration initializers (C99 6.7.8)
6708   bool CheckForConstantInitializer(Expr *e, QualType t);
6709 
6710   // type checking C++ declaration initializers (C++ [dcl.init]).
6711 
6712   /// ReferenceCompareResult - Expresses the result of comparing two
6713   /// types (cv1 T1 and cv2 T2) to determine their compatibility for the
6714   /// purposes of initialization by reference (C++ [dcl.init.ref]p4).
6715   enum ReferenceCompareResult {
6716     /// Ref_Incompatible - The two types are incompatible, so direct
6717     /// reference binding is not possible.
6718     Ref_Incompatible = 0,
6719     /// Ref_Related - The two types are reference-related, which means
6720     /// that their unqualified forms (T1 and T2) are either the same
6721     /// or T1 is a base class of T2.
6722     Ref_Related,
6723     /// Ref_Compatible_With_Added_Qualification - The two types are
6724     /// reference-compatible with added qualification, meaning that
6725     /// they are reference-compatible and the qualifiers on T1 (cv1)
6726     /// are greater than the qualifiers on T2 (cv2).
6727     Ref_Compatible_With_Added_Qualification,
6728     /// Ref_Compatible - The two types are reference-compatible and
6729     /// have equivalent qualifiers (cv1 == cv2).
6730     Ref_Compatible
6731   };
6732 
6733   ReferenceCompareResult CompareReferenceRelationship(SourceLocation Loc,
6734                                                       QualType T1, QualType T2,
6735                                                       bool &DerivedToBase,
6736                                                       bool &ObjCConversion,
6737                                                 bool &ObjCLifetimeConversion);
6738 
6739   ExprResult checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
6740                                  Expr *CastExpr, CastKind &CastKind,
6741                                  ExprValueKind &VK, CXXCastPath &Path);
6742 
6743   /// \brief Force an expression with unknown-type to an expression of the
6744   /// given type.
6745   ExprResult forceUnknownAnyToType(Expr *E, QualType ToType);
6746 
6747   // CheckVectorCast - check type constraints for vectors.
6748   // Since vectors are an extension, there are no C standard reference for this.
6749   // We allow casting between vectors and integer datatypes of the same size.
6750   // returns true if the cast is invalid
6751   bool CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
6752                        CastKind &Kind);
6753 
6754   // CheckExtVectorCast - check type constraints for extended vectors.
6755   // Since vectors are an extension, there are no C standard reference for this.
6756   // We allow casting between vectors and integer datatypes of the same size,
6757   // or vectors and the element type of that vector.
6758   // returns the cast expr
6759   ExprResult CheckExtVectorCast(SourceRange R, QualType DestTy, Expr *CastExpr,
6760                                 CastKind &Kind);
6761 
6762   ExprResult BuildCXXFunctionalCastExpr(TypeSourceInfo *TInfo,
6763                                         SourceLocation LParenLoc,
6764                                         Expr *CastExpr,
6765                                         SourceLocation RParenLoc);
6766 
6767   enum ARCConversionResult { ACR_okay, ACR_unbridged };
6768 
6769   /// \brief Checks for invalid conversions and casts between
6770   /// retainable pointers and other pointer kinds.
6771   ARCConversionResult CheckObjCARCConversion(SourceRange castRange,
6772                                              QualType castType, Expr *&op,
6773                                              CheckedConversionKind CCK);
6774 
6775   Expr *stripARCUnbridgedCast(Expr *e);
6776   void diagnoseARCUnbridgedCast(Expr *e);
6777 
6778   bool CheckObjCARCUnavailableWeakConversion(QualType castType,
6779                                              QualType ExprType);
6780 
6781   /// checkRetainCycles - Check whether an Objective-C message send
6782   /// might create an obvious retain cycle.
6783   void checkRetainCycles(ObjCMessageExpr *msg);
6784   void checkRetainCycles(Expr *receiver, Expr *argument);
6785 
6786   /// checkUnsafeAssigns - Check whether +1 expr is being assigned
6787   /// to weak/__unsafe_unretained type.
6788   bool checkUnsafeAssigns(SourceLocation Loc, QualType LHS, Expr *RHS);
6789 
6790   /// checkUnsafeExprAssigns - Check whether +1 expr is being assigned
6791   /// to weak/__unsafe_unretained expression.
6792   void checkUnsafeExprAssigns(SourceLocation Loc, Expr *LHS, Expr *RHS);
6793 
6794   /// CheckMessageArgumentTypes - Check types in an Obj-C message send.
6795   /// \param Method - May be null.
6796   /// \param [out] ReturnType - The return type of the send.
6797   /// \return true iff there were any incompatible types.
6798   bool CheckMessageArgumentTypes(QualType ReceiverType,
6799                                  Expr **Args, unsigned NumArgs, Selector Sel,
6800                                  ArrayRef<SourceLocation> SelectorLocs,
6801                                  ObjCMethodDecl *Method, bool isClassMessage,
6802                                  bool isSuperMessage,
6803                                  SourceLocation lbrac, SourceLocation rbrac,
6804                                  QualType &ReturnType, ExprValueKind &VK);
6805 
6806   /// \brief Determine the result of a message send expression based on
6807   /// the type of the receiver, the method expected to receive the message,
6808   /// and the form of the message send.
6809   QualType getMessageSendResultType(QualType ReceiverType,
6810                                     ObjCMethodDecl *Method,
6811                                     bool isClassMessage, bool isSuperMessage);
6812 
6813   /// \brief If the given expression involves a message send to a method
6814   /// with a related result type, emit a note describing what happened.
6815   void EmitRelatedResultTypeNote(const Expr *E);
6816 
6817   /// CheckBooleanCondition - Diagnose problems involving the use of
6818   /// the given expression as a boolean condition (e.g. in an if
6819   /// statement).  Also performs the standard function and array
6820   /// decays, possibly changing the input variable.
6821   ///
6822   /// \param Loc - A location associated with the condition, e.g. the
6823   /// 'if' keyword.
6824   /// \return true iff there were any errors
6825   ExprResult CheckBooleanCondition(Expr *E, SourceLocation Loc);
6826 
6827   ExprResult ActOnBooleanCondition(Scope *S, SourceLocation Loc,
6828                                    Expr *SubExpr);
6829 
6830   /// DiagnoseAssignmentAsCondition - Given that an expression is
6831   /// being used as a boolean condition, warn if it's an assignment.
6832   void DiagnoseAssignmentAsCondition(Expr *E);
6833 
6834   /// \brief Redundant parentheses over an equality comparison can indicate
6835   /// that the user intended an assignment used as condition.
6836   void DiagnoseEqualityWithExtraParens(ParenExpr *ParenE);
6837 
6838   /// CheckCXXBooleanCondition - Returns true if conversion to bool is invalid.
6839   ExprResult CheckCXXBooleanCondition(Expr *CondExpr);
6840 
6841   /// ConvertIntegerToTypeWarnOnOverflow - Convert the specified APInt to have
6842   /// the specified width and sign.  If an overflow occurs, detect it and emit
6843   /// the specified diagnostic.
6844   void ConvertIntegerToTypeWarnOnOverflow(llvm::APSInt &OldVal,
6845                                           unsigned NewWidth, bool NewSign,
6846                                           SourceLocation Loc, unsigned DiagID);
6847 
6848   /// Checks that the Objective-C declaration is declared in the global scope.
6849   /// Emits an error and marks the declaration as invalid if it's not declared
6850   /// in the global scope.
6851   bool CheckObjCDeclScope(Decl *D);
6852 
6853   /// \brief Abstract base class used for diagnosing integer constant
6854   /// expression violations.
6855   class VerifyICEDiagnoser {
6856   public:
6857     bool Suppress;
6858 
Suppress(Suppress)6859     VerifyICEDiagnoser(bool Suppress = false) : Suppress(Suppress) { }
6860 
6861     virtual void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) =0;
6862     virtual void diagnoseFold(Sema &S, SourceLocation Loc, SourceRange SR);
~VerifyICEDiagnoser()6863     virtual ~VerifyICEDiagnoser() { }
6864   };
6865 
6866   /// VerifyIntegerConstantExpression - Verifies that an expression is an ICE,
6867   /// and reports the appropriate diagnostics. Returns false on success.
6868   /// Can optionally return the value of the expression.
6869   ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
6870                                              VerifyICEDiagnoser &Diagnoser,
6871                                              bool AllowFold = true);
6872   ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
6873                                              unsigned DiagID,
6874                                              bool AllowFold = true);
6875   ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result=0);
6876 
6877   /// VerifyBitField - verifies that a bit field expression is an ICE and has
6878   /// the correct width, and that the field type is valid.
6879   /// Returns false on success.
6880   /// Can optionally return whether the bit-field is of width 0
6881   ExprResult VerifyBitField(SourceLocation FieldLoc, IdentifierInfo *FieldName,
6882                             QualType FieldTy, Expr *BitWidth,
6883                             bool *ZeroWidth = 0);
6884 
6885   enum CUDAFunctionTarget {
6886     CFT_Device,
6887     CFT_Global,
6888     CFT_Host,
6889     CFT_HostDevice
6890   };
6891 
6892   CUDAFunctionTarget IdentifyCUDATarget(const FunctionDecl *D);
6893 
6894   bool CheckCUDATarget(CUDAFunctionTarget CallerTarget,
6895                        CUDAFunctionTarget CalleeTarget);
6896 
CheckCUDATarget(const FunctionDecl * Caller,const FunctionDecl * Callee)6897   bool CheckCUDATarget(const FunctionDecl *Caller, const FunctionDecl *Callee) {
6898     return CheckCUDATarget(IdentifyCUDATarget(Caller),
6899                            IdentifyCUDATarget(Callee));
6900   }
6901 
6902   /// \name Code completion
6903   //@{
6904   /// \brief Describes the context in which code completion occurs.
6905   enum ParserCompletionContext {
6906     /// \brief Code completion occurs at top-level or namespace context.
6907     PCC_Namespace,
6908     /// \brief Code completion occurs within a class, struct, or union.
6909     PCC_Class,
6910     /// \brief Code completion occurs within an Objective-C interface, protocol,
6911     /// or category.
6912     PCC_ObjCInterface,
6913     /// \brief Code completion occurs within an Objective-C implementation or
6914     /// category implementation
6915     PCC_ObjCImplementation,
6916     /// \brief Code completion occurs within the list of instance variables
6917     /// in an Objective-C interface, protocol, category, or implementation.
6918     PCC_ObjCInstanceVariableList,
6919     /// \brief Code completion occurs following one or more template
6920     /// headers.
6921     PCC_Template,
6922     /// \brief Code completion occurs following one or more template
6923     /// headers within a class.
6924     PCC_MemberTemplate,
6925     /// \brief Code completion occurs within an expression.
6926     PCC_Expression,
6927     /// \brief Code completion occurs within a statement, which may
6928     /// also be an expression or a declaration.
6929     PCC_Statement,
6930     /// \brief Code completion occurs at the beginning of the
6931     /// initialization statement (or expression) in a for loop.
6932     PCC_ForInit,
6933     /// \brief Code completion occurs within the condition of an if,
6934     /// while, switch, or for statement.
6935     PCC_Condition,
6936     /// \brief Code completion occurs within the body of a function on a
6937     /// recovery path, where we do not have a specific handle on our position
6938     /// in the grammar.
6939     PCC_RecoveryInFunction,
6940     /// \brief Code completion occurs where only a type is permitted.
6941     PCC_Type,
6942     /// \brief Code completion occurs in a parenthesized expression, which
6943     /// might also be a type cast.
6944     PCC_ParenthesizedExpression,
6945     /// \brief Code completion occurs within a sequence of declaration
6946     /// specifiers within a function, method, or block.
6947     PCC_LocalDeclarationSpecifiers
6948   };
6949 
6950   void CodeCompleteModuleImport(SourceLocation ImportLoc, ModuleIdPath Path);
6951   void CodeCompleteOrdinaryName(Scope *S,
6952                                 ParserCompletionContext CompletionContext);
6953   void CodeCompleteDeclSpec(Scope *S, DeclSpec &DS,
6954                             bool AllowNonIdentifiers,
6955                             bool AllowNestedNameSpecifiers);
6956 
6957   struct CodeCompleteExpressionData;
6958   void CodeCompleteExpression(Scope *S,
6959                               const CodeCompleteExpressionData &Data);
6960   void CodeCompleteMemberReferenceExpr(Scope *S, Expr *Base,
6961                                        SourceLocation OpLoc,
6962                                        bool IsArrow);
6963   void CodeCompletePostfixExpression(Scope *S, ExprResult LHS);
6964   void CodeCompleteTag(Scope *S, unsigned TagSpec);
6965   void CodeCompleteTypeQualifiers(DeclSpec &DS);
6966   void CodeCompleteCase(Scope *S);
6967   void CodeCompleteCall(Scope *S, Expr *Fn, llvm::ArrayRef<Expr *> Args);
6968   void CodeCompleteInitializer(Scope *S, Decl *D);
6969   void CodeCompleteReturn(Scope *S);
6970   void CodeCompleteAfterIf(Scope *S);
6971   void CodeCompleteAssignmentRHS(Scope *S, Expr *LHS);
6972 
6973   void CodeCompleteQualifiedId(Scope *S, CXXScopeSpec &SS,
6974                                bool EnteringContext);
6975   void CodeCompleteUsing(Scope *S);
6976   void CodeCompleteUsingDirective(Scope *S);
6977   void CodeCompleteNamespaceDecl(Scope *S);
6978   void CodeCompleteNamespaceAliasDecl(Scope *S);
6979   void CodeCompleteOperatorName(Scope *S);
6980   void CodeCompleteConstructorInitializer(Decl *Constructor,
6981                                           CXXCtorInitializer** Initializers,
6982                                           unsigned NumInitializers);
6983   void CodeCompleteLambdaIntroducer(Scope *S, LambdaIntroducer &Intro,
6984                                     bool AfterAmpersand);
6985 
6986   void CodeCompleteObjCAtDirective(Scope *S);
6987   void CodeCompleteObjCAtVisibility(Scope *S);
6988   void CodeCompleteObjCAtStatement(Scope *S);
6989   void CodeCompleteObjCAtExpression(Scope *S);
6990   void CodeCompleteObjCPropertyFlags(Scope *S, ObjCDeclSpec &ODS);
6991   void CodeCompleteObjCPropertyGetter(Scope *S);
6992   void CodeCompleteObjCPropertySetter(Scope *S);
6993   void CodeCompleteObjCPassingType(Scope *S, ObjCDeclSpec &DS,
6994                                    bool IsParameter);
6995   void CodeCompleteObjCMessageReceiver(Scope *S);
6996   void CodeCompleteObjCSuperMessage(Scope *S, SourceLocation SuperLoc,
6997                                     IdentifierInfo **SelIdents,
6998                                     unsigned NumSelIdents,
6999                                     bool AtArgumentExpression);
7000   void CodeCompleteObjCClassMessage(Scope *S, ParsedType Receiver,
7001                                     IdentifierInfo **SelIdents,
7002                                     unsigned NumSelIdents,
7003                                     bool AtArgumentExpression,
7004                                     bool IsSuper = false);
7005   void CodeCompleteObjCInstanceMessage(Scope *S, Expr *Receiver,
7006                                        IdentifierInfo **SelIdents,
7007                                        unsigned NumSelIdents,
7008                                        bool AtArgumentExpression,
7009                                        ObjCInterfaceDecl *Super = 0);
7010   void CodeCompleteObjCForCollection(Scope *S,
7011                                      DeclGroupPtrTy IterationVar);
7012   void CodeCompleteObjCSelector(Scope *S,
7013                                 IdentifierInfo **SelIdents,
7014                                 unsigned NumSelIdents);
7015   void CodeCompleteObjCProtocolReferences(IdentifierLocPair *Protocols,
7016                                           unsigned NumProtocols);
7017   void CodeCompleteObjCProtocolDecl(Scope *S);
7018   void CodeCompleteObjCInterfaceDecl(Scope *S);
7019   void CodeCompleteObjCSuperclass(Scope *S,
7020                                   IdentifierInfo *ClassName,
7021                                   SourceLocation ClassNameLoc);
7022   void CodeCompleteObjCImplementationDecl(Scope *S);
7023   void CodeCompleteObjCInterfaceCategory(Scope *S,
7024                                          IdentifierInfo *ClassName,
7025                                          SourceLocation ClassNameLoc);
7026   void CodeCompleteObjCImplementationCategory(Scope *S,
7027                                               IdentifierInfo *ClassName,
7028                                               SourceLocation ClassNameLoc);
7029   void CodeCompleteObjCPropertyDefinition(Scope *S);
7030   void CodeCompleteObjCPropertySynthesizeIvar(Scope *S,
7031                                               IdentifierInfo *PropertyName);
7032   void CodeCompleteObjCMethodDecl(Scope *S,
7033                                   bool IsInstanceMethod,
7034                                   ParsedType ReturnType);
7035   void CodeCompleteObjCMethodDeclSelector(Scope *S,
7036                                           bool IsInstanceMethod,
7037                                           bool AtParameterName,
7038                                           ParsedType ReturnType,
7039                                           IdentifierInfo **SelIdents,
7040                                           unsigned NumSelIdents);
7041   void CodeCompletePreprocessorDirective(bool InConditional);
7042   void CodeCompleteInPreprocessorConditionalExclusion(Scope *S);
7043   void CodeCompletePreprocessorMacroName(bool IsDefinition);
7044   void CodeCompletePreprocessorExpression();
7045   void CodeCompletePreprocessorMacroArgument(Scope *S,
7046                                              IdentifierInfo *Macro,
7047                                              MacroInfo *MacroInfo,
7048                                              unsigned Argument);
7049   void CodeCompleteNaturalLanguage();
7050   void GatherGlobalCodeCompletions(CodeCompletionAllocator &Allocator,
7051                                    CodeCompletionTUInfo &CCTUInfo,
7052                   SmallVectorImpl<CodeCompletionResult> &Results);
7053   //@}
7054 
7055   //===--------------------------------------------------------------------===//
7056   // Extra semantic analysis beyond the C type system
7057 
7058 public:
7059   SourceLocation getLocationOfStringLiteralByte(const StringLiteral *SL,
7060                                                 unsigned ByteNo) const;
7061 
7062 private:
7063   void CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
7064                         const ArraySubscriptExpr *ASE=0,
7065                         bool AllowOnePastEnd=true, bool IndexNegated=false);
7066   void CheckArrayAccess(const Expr *E);
7067   // Used to grab the relevant information from a FormatAttr and a
7068   // FunctionDeclaration.
7069   struct FormatStringInfo {
7070     unsigned FormatIdx;
7071     unsigned FirstDataArg;
7072     bool HasVAListArg;
7073   };
7074 
7075   bool getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
7076                            FormatStringInfo *FSI);
7077   bool CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
7078                          const FunctionProtoType *Proto);
7079   bool CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation loc,
7080                            Expr **Args, unsigned NumArgs);
7081   bool CheckBlockCall(NamedDecl *NDecl, CallExpr *TheCall,
7082                       const FunctionProtoType *Proto);
7083   void CheckConstructorCall(FunctionDecl *FDecl,
7084                             Expr **Args,
7085                             unsigned NumArgs,
7086                             const FunctionProtoType *Proto,
7087                             SourceLocation Loc);
7088 
7089   void checkCall(NamedDecl *FDecl, Expr **Args, unsigned NumArgs,
7090                  unsigned NumProtoArgs, bool IsMemberFunction,
7091                  SourceLocation Loc, SourceRange Range,
7092                  VariadicCallType CallType);
7093 
7094 
7095   bool CheckObjCString(Expr *Arg);
7096 
7097   ExprResult CheckBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
7098   bool CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
7099   bool CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
7100 
7101   bool SemaBuiltinVAStart(CallExpr *TheCall);
7102   bool SemaBuiltinUnorderedCompare(CallExpr *TheCall);
7103   bool SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs);
7104 
7105 public:
7106   // Used by C++ template instantiation.
7107   ExprResult SemaBuiltinShuffleVector(CallExpr *TheCall);
7108 
7109 private:
7110   bool SemaBuiltinPrefetch(CallExpr *TheCall);
7111   bool SemaBuiltinObjectSize(CallExpr *TheCall);
7112   bool SemaBuiltinLongjmp(CallExpr *TheCall);
7113   ExprResult SemaBuiltinAtomicOverloaded(ExprResult TheCallResult);
7114   ExprResult SemaAtomicOpsOverloaded(ExprResult TheCallResult,
7115                                      AtomicExpr::AtomicOp Op);
7116   bool SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
7117                               llvm::APSInt &Result);
7118 
7119   enum FormatStringType {
7120     FST_Scanf,
7121     FST_Printf,
7122     FST_NSString,
7123     FST_Strftime,
7124     FST_Strfmon,
7125     FST_Kprintf,
7126     FST_Unknown
7127   };
7128   static FormatStringType GetFormatStringType(const FormatAttr *Format);
7129 
7130   enum StringLiteralCheckType {
7131     SLCT_NotALiteral,
7132     SLCT_UncheckedLiteral,
7133     SLCT_CheckedLiteral
7134   };
7135 
7136   StringLiteralCheckType checkFormatStringExpr(const Expr *E,
7137                                                Expr **Args, unsigned NumArgs,
7138                                                bool HasVAListArg,
7139                                                unsigned format_idx,
7140                                                unsigned firstDataArg,
7141                                                FormatStringType Type,
7142                                                VariadicCallType CallType,
7143                                                bool inFunctionCall = true);
7144 
7145   void CheckFormatString(const StringLiteral *FExpr, const Expr *OrigFormatExpr,
7146                          Expr **Args, unsigned NumArgs, bool HasVAListArg,
7147                          unsigned format_idx, unsigned firstDataArg,
7148                          FormatStringType Type, bool inFunctionCall,
7149                          VariadicCallType CallType);
7150 
7151   bool CheckFormatArguments(const FormatAttr *Format, Expr **Args,
7152                             unsigned NumArgs, bool IsCXXMember,
7153                             VariadicCallType CallType,
7154                             SourceLocation Loc, SourceRange Range);
7155   bool CheckFormatArguments(Expr **Args, unsigned NumArgs,
7156                             bool HasVAListArg, unsigned format_idx,
7157                             unsigned firstDataArg, FormatStringType Type,
7158                             VariadicCallType CallType,
7159                             SourceLocation Loc, SourceRange range);
7160 
7161   void CheckNonNullArguments(const NonNullAttr *NonNull,
7162                              const Expr * const *ExprArgs,
7163                              SourceLocation CallSiteLoc);
7164 
7165   void CheckMemaccessArguments(const CallExpr *Call,
7166                                unsigned BId,
7167                                IdentifierInfo *FnName);
7168 
7169   void CheckStrlcpycatArguments(const CallExpr *Call,
7170                                 IdentifierInfo *FnName);
7171 
7172   void CheckStrncatArguments(const CallExpr *Call,
7173                              IdentifierInfo *FnName);
7174 
7175   void CheckReturnStackAddr(Expr *RetValExp, QualType lhsType,
7176                             SourceLocation ReturnLoc);
7177   void CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr* RHS);
7178   void CheckImplicitConversions(Expr *E, SourceLocation CC = SourceLocation());
7179 
7180   void CheckBitFieldInitialization(SourceLocation InitLoc, FieldDecl *Field,
7181                                    Expr *Init);
7182 
7183 public:
7184   /// \brief Register a magic integral constant to be used as a type tag.
7185   void RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
7186                                   uint64_t MagicValue, QualType Type,
7187                                   bool LayoutCompatible, bool MustBeNull);
7188 
7189   struct TypeTagData {
TypeTagDataTypeTagData7190     TypeTagData() {}
7191 
TypeTagDataTypeTagData7192     TypeTagData(QualType Type, bool LayoutCompatible, bool MustBeNull) :
7193         Type(Type), LayoutCompatible(LayoutCompatible),
7194         MustBeNull(MustBeNull)
7195     {}
7196 
7197     QualType Type;
7198 
7199     /// If true, \c Type should be compared with other expression's types for
7200     /// layout-compatibility.
7201     unsigned LayoutCompatible : 1;
7202     unsigned MustBeNull : 1;
7203   };
7204 
7205   /// A pair of ArgumentKind identifier and magic value.  This uniquely
7206   /// identifies the magic value.
7207   typedef std::pair<const IdentifierInfo *, uint64_t> TypeTagMagicValue;
7208 
7209 private:
7210   /// \brief A map from magic value to type information.
7211   OwningPtr<llvm::DenseMap<TypeTagMagicValue, TypeTagData> >
7212       TypeTagForDatatypeMagicValues;
7213 
7214   /// \brief Peform checks on a call of a function with argument_with_type_tag
7215   /// or pointer_with_type_tag attributes.
7216   void CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
7217                                 const Expr * const *ExprArgs);
7218 
7219   /// \brief The parser's current scope.
7220   ///
7221   /// The parser maintains this state here.
7222   Scope *CurScope;
7223 
7224 protected:
7225   friend class Parser;
7226   friend class InitializationSequence;
7227   friend class ASTReader;
7228   friend class ASTWriter;
7229 
7230 public:
7231   /// \brief Retrieve the parser's current scope.
7232   ///
7233   /// This routine must only be used when it is certain that semantic analysis
7234   /// and the parser are in precisely the same context, which is not the case
7235   /// when, e.g., we are performing any kind of template instantiation.
7236   /// Therefore, the only safe places to use this scope are in the parser
7237   /// itself and in routines directly invoked from the parser and *never* from
7238   /// template substitution or instantiation.
getCurScope()7239   Scope *getCurScope() const { return CurScope; }
7240 
7241   Decl *getObjCDeclContext() const;
7242 
getCurLexicalContext()7243   DeclContext *getCurLexicalContext() const {
7244     return OriginalLexicalContext ? OriginalLexicalContext : CurContext;
7245   }
7246 
7247   AvailabilityResult getCurContextAvailability() const;
7248 
getCurObjCLexicalContext()7249   const DeclContext *getCurObjCLexicalContext() const {
7250     const DeclContext *DC = getCurLexicalContext();
7251     // A category implicitly has the attribute of the interface.
7252     if (const ObjCCategoryDecl *CatD = dyn_cast<ObjCCategoryDecl>(DC))
7253       DC = CatD->getClassInterface();
7254     return DC;
7255   }
7256 };
7257 
7258 /// \brief RAII object that enters a new expression evaluation context.
7259 class EnterExpressionEvaluationContext {
7260   Sema &Actions;
7261 
7262 public:
7263   EnterExpressionEvaluationContext(Sema &Actions,
7264                                    Sema::ExpressionEvaluationContext NewContext,
7265                                    Decl *LambdaContextDecl = 0,
7266                                    bool IsDecltype = false)
Actions(Actions)7267     : Actions(Actions) {
7268     Actions.PushExpressionEvaluationContext(NewContext, LambdaContextDecl,
7269                                             IsDecltype);
7270   }
7271 
~EnterExpressionEvaluationContext()7272   ~EnterExpressionEvaluationContext() {
7273     Actions.PopExpressionEvaluationContext();
7274   }
7275 };
7276 
7277 }  // end namespace clang
7278 
7279 #endif
7280