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