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