Sema.h revision b9abd87283ac6e929b7e12a577663bc99e61d020
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();
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  void ActOnStartStmtExpr();
2806  ExprResult ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
2807                           SourceLocation RPLoc); // "({..})"
2808  void ActOnStmtExprError();
2809
2810  // __builtin_offsetof(type, identifier(.identifier|[expr])*)
2811  struct OffsetOfComponent {
2812    SourceLocation LocStart, LocEnd;
2813    bool isBrackets;  // true if [expr], false if .ident
2814    union {
2815      IdentifierInfo *IdentInfo;
2816      Expr *E;
2817    } U;
2818  };
2819
2820  /// __builtin_offsetof(type, a.b[123][456].c)
2821  ExprResult BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
2822                                  TypeSourceInfo *TInfo,
2823                                  OffsetOfComponent *CompPtr,
2824                                  unsigned NumComponents,
2825                                  SourceLocation RParenLoc);
2826  ExprResult ActOnBuiltinOffsetOf(Scope *S,
2827                                  SourceLocation BuiltinLoc,
2828                                  SourceLocation TypeLoc,
2829                                  ParsedType ParsedArgTy,
2830                                  OffsetOfComponent *CompPtr,
2831                                  unsigned NumComponents,
2832                                  SourceLocation RParenLoc);
2833
2834  // __builtin_choose_expr(constExpr, expr1, expr2)
2835  ExprResult ActOnChooseExpr(SourceLocation BuiltinLoc,
2836                             Expr *CondExpr, Expr *LHSExpr,
2837                             Expr *RHSExpr, SourceLocation RPLoc);
2838
2839  // __builtin_va_arg(expr, type)
2840  ExprResult ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty,
2841                        SourceLocation RPLoc);
2842  ExprResult BuildVAArgExpr(SourceLocation BuiltinLoc, Expr *E,
2843                            TypeSourceInfo *TInfo, SourceLocation RPLoc);
2844
2845  // __null
2846  ExprResult ActOnGNUNullExpr(SourceLocation TokenLoc);
2847
2848  bool CheckCaseExpression(Expr *E);
2849
2850  /// \brief Describes the result of an "if-exists" condition check.
2851  enum IfExistsResult {
2852    /// \brief The symbol exists.
2853    IER_Exists,
2854
2855    /// \brief The symbol does not exist.
2856    IER_DoesNotExist,
2857
2858    /// \brief The name is a dependent name, so the results will differ
2859    /// from one instantiation to the next.
2860    IER_Dependent,
2861
2862    /// \brief An error occurred.
2863    IER_Error
2864  };
2865
2866  IfExistsResult
2867  CheckMicrosoftIfExistsSymbol(Scope *S, CXXScopeSpec &SS,
2868                               const DeclarationNameInfo &TargetNameInfo);
2869
2870  IfExistsResult
2871  CheckMicrosoftIfExistsSymbol(Scope *S, SourceLocation KeywordLoc,
2872                               bool IsIfExists, CXXScopeSpec &SS,
2873                               UnqualifiedId &Name);
2874
2875  StmtResult BuildMSDependentExistsStmt(SourceLocation KeywordLoc,
2876                                        bool IsIfExists,
2877                                        NestedNameSpecifierLoc QualifierLoc,
2878                                        DeclarationNameInfo NameInfo,
2879                                        Stmt *Nested);
2880  StmtResult ActOnMSDependentExistsStmt(SourceLocation KeywordLoc,
2881                                        bool IsIfExists,
2882                                        CXXScopeSpec &SS, UnqualifiedId &Name,
2883                                        Stmt *Nested);
2884
2885  //===------------------------- "Block" Extension ------------------------===//
2886
2887  /// ActOnBlockStart - This callback is invoked when a block literal is
2888  /// started.
2889  void ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope);
2890
2891  /// ActOnBlockArguments - This callback allows processing of block arguments.
2892  /// If there are no arguments, this is still invoked.
2893  void ActOnBlockArguments(Declarator &ParamInfo, Scope *CurScope);
2894
2895  /// ActOnBlockError - If there is an error parsing a block, this callback
2896  /// is invoked to pop the information about the block from the action impl.
2897  void ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope);
2898
2899  /// ActOnBlockStmtExpr - This is called when the body of a block statement
2900  /// literal was successfully completed.  ^(int x){...}
2901  ExprResult ActOnBlockStmtExpr(SourceLocation CaretLoc, Stmt *Body,
2902                                Scope *CurScope);
2903
2904  //===---------------------------- OpenCL Features -----------------------===//
2905
2906  /// __builtin_astype(...)
2907  ExprResult ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
2908                             SourceLocation BuiltinLoc,
2909                             SourceLocation RParenLoc);
2910
2911  //===---------------------------- C++ Features --------------------------===//
2912
2913  // Act on C++ namespaces
2914  Decl *ActOnStartNamespaceDef(Scope *S, SourceLocation InlineLoc,
2915                               SourceLocation NamespaceLoc,
2916                               SourceLocation IdentLoc,
2917                               IdentifierInfo *Ident,
2918                               SourceLocation LBrace,
2919                               AttributeList *AttrList);
2920  void ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace);
2921
2922  NamespaceDecl *getStdNamespace() const;
2923  NamespaceDecl *getOrCreateStdNamespace();
2924
2925  CXXRecordDecl *getStdBadAlloc() const;
2926
2927  /// \brief Tests whether Ty is an instance of std::initializer_list and, if
2928  /// it is and Element is not NULL, assigns the element type to Element.
2929  bool isStdInitializerList(QualType Ty, QualType *Element);
2930
2931  /// \brief Looks for the std::initializer_list template and instantiates it
2932  /// with Element, or emits an error if it's not found.
2933  ///
2934  /// \returns The instantiated template, or null on error.
2935  QualType BuildStdInitializerList(QualType Element, SourceLocation Loc);
2936
2937  /// \brief Determine whether Ctor is an initializer-list constructor, as
2938  /// defined in [dcl.init.list]p2.
2939  bool isInitListConstructor(const CXXConstructorDecl *Ctor);
2940
2941  Decl *ActOnUsingDirective(Scope *CurScope,
2942                            SourceLocation UsingLoc,
2943                            SourceLocation NamespcLoc,
2944                            CXXScopeSpec &SS,
2945                            SourceLocation IdentLoc,
2946                            IdentifierInfo *NamespcName,
2947                            AttributeList *AttrList);
2948
2949  void PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir);
2950
2951  Decl *ActOnNamespaceAliasDef(Scope *CurScope,
2952                               SourceLocation NamespaceLoc,
2953                               SourceLocation AliasLoc,
2954                               IdentifierInfo *Alias,
2955                               CXXScopeSpec &SS,
2956                               SourceLocation IdentLoc,
2957                               IdentifierInfo *Ident);
2958
2959  void HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow);
2960  bool CheckUsingShadowDecl(UsingDecl *UD, NamedDecl *Target,
2961                            const LookupResult &PreviousDecls);
2962  UsingShadowDecl *BuildUsingShadowDecl(Scope *S, UsingDecl *UD,
2963                                        NamedDecl *Target);
2964
2965  bool CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
2966                                   bool isTypeName,
2967                                   const CXXScopeSpec &SS,
2968                                   SourceLocation NameLoc,
2969                                   const LookupResult &Previous);
2970  bool CheckUsingDeclQualifier(SourceLocation UsingLoc,
2971                               const CXXScopeSpec &SS,
2972                               SourceLocation NameLoc);
2973
2974  NamedDecl *BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
2975                                   SourceLocation UsingLoc,
2976                                   CXXScopeSpec &SS,
2977                                   const DeclarationNameInfo &NameInfo,
2978                                   AttributeList *AttrList,
2979                                   bool IsInstantiation,
2980                                   bool IsTypeName,
2981                                   SourceLocation TypenameLoc);
2982
2983  bool CheckInheritingConstructorUsingDecl(UsingDecl *UD);
2984
2985  Decl *ActOnUsingDeclaration(Scope *CurScope,
2986                              AccessSpecifier AS,
2987                              bool HasUsingKeyword,
2988                              SourceLocation UsingLoc,
2989                              CXXScopeSpec &SS,
2990                              UnqualifiedId &Name,
2991                              AttributeList *AttrList,
2992                              bool IsTypeName,
2993                              SourceLocation TypenameLoc);
2994  Decl *ActOnAliasDeclaration(Scope *CurScope,
2995                              AccessSpecifier AS,
2996                              MultiTemplateParamsArg TemplateParams,
2997                              SourceLocation UsingLoc,
2998                              UnqualifiedId &Name,
2999                              TypeResult Type);
3000
3001  /// InitializeVarWithConstructor - Creates an CXXConstructExpr
3002  /// and sets it as the initializer for the the passed in VarDecl.
3003  bool InitializeVarWithConstructor(VarDecl *VD,
3004                                    CXXConstructorDecl *Constructor,
3005                                    MultiExprArg Exprs,
3006                                    bool HadMultipleCandidates);
3007
3008  /// BuildCXXConstructExpr - Creates a complete call to a constructor,
3009  /// including handling of its default argument expressions.
3010  ///
3011  /// \param ConstructKind - a CXXConstructExpr::ConstructionKind
3012  ExprResult
3013  BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
3014                        CXXConstructorDecl *Constructor, MultiExprArg Exprs,
3015                        bool HadMultipleCandidates, bool RequiresZeroInit,
3016                        unsigned ConstructKind, SourceRange ParenRange);
3017
3018  // FIXME: Can re remove this and have the above BuildCXXConstructExpr check if
3019  // the constructor can be elidable?
3020  ExprResult
3021  BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
3022                        CXXConstructorDecl *Constructor, bool Elidable,
3023                        MultiExprArg Exprs, bool HadMultipleCandidates,
3024                        bool RequiresZeroInit, unsigned ConstructKind,
3025                        SourceRange ParenRange);
3026
3027  /// BuildCXXDefaultArgExpr - Creates a CXXDefaultArgExpr, instantiating
3028  /// the default expr if needed.
3029  ExprResult BuildCXXDefaultArgExpr(SourceLocation CallLoc,
3030                                    FunctionDecl *FD,
3031                                    ParmVarDecl *Param);
3032
3033  /// FinalizeVarWithDestructor - Prepare for calling destructor on the
3034  /// constructed variable.
3035  void FinalizeVarWithDestructor(VarDecl *VD, const RecordType *DeclInitType);
3036
3037  /// \brief Helper class that collects exception specifications for
3038  /// implicitly-declared special member functions.
3039  class ImplicitExceptionSpecification {
3040    // Pointer to allow copying
3041    ASTContext *Context;
3042    // We order exception specifications thus:
3043    // noexcept is the most restrictive, but is only used in C++0x.
3044    // throw() comes next.
3045    // Then a throw(collected exceptions)
3046    // Finally no specification.
3047    // throw(...) is used instead if any called function uses it.
3048    //
3049    // If this exception specification cannot be known yet (for instance,
3050    // because this is the exception specification for a defaulted default
3051    // constructor and we haven't finished parsing the deferred parts of the
3052    // class yet), the C++0x standard does not specify how to behave. We
3053    // record this as an 'unknown' exception specification, which overrules
3054    // any other specification (even 'none', to keep this rule simple).
3055    ExceptionSpecificationType ComputedEST;
3056    llvm::SmallPtrSet<CanQualType, 4> ExceptionsSeen;
3057    SmallVector<QualType, 4> Exceptions;
3058
3059    void ClearExceptions() {
3060      ExceptionsSeen.clear();
3061      Exceptions.clear();
3062    }
3063
3064  public:
3065    explicit ImplicitExceptionSpecification(ASTContext &Context)
3066      : Context(&Context), ComputedEST(EST_BasicNoexcept) {
3067      if (!Context.getLangOpts().CPlusPlus0x)
3068        ComputedEST = EST_DynamicNone;
3069    }
3070
3071    /// \brief Get the computed exception specification type.
3072    ExceptionSpecificationType getExceptionSpecType() const {
3073      assert(ComputedEST != EST_ComputedNoexcept &&
3074             "noexcept(expr) should not be a possible result");
3075      return ComputedEST;
3076    }
3077
3078    /// \brief The number of exceptions in the exception specification.
3079    unsigned size() const { return Exceptions.size(); }
3080
3081    /// \brief The set of exceptions in the exception specification.
3082    const QualType *data() const { return Exceptions.data(); }
3083
3084    /// \brief Integrate another called method into the collected data.
3085    void CalledDecl(CXXMethodDecl *Method);
3086
3087    /// \brief Integrate an invoked expression into the collected data.
3088    void CalledExpr(Expr *E);
3089
3090    /// \brief Specify that the exception specification can't be detemined yet.
3091    void SetDelayed() {
3092      ClearExceptions();
3093      ComputedEST = EST_Delayed;
3094    }
3095
3096    FunctionProtoType::ExtProtoInfo getEPI() const {
3097      FunctionProtoType::ExtProtoInfo EPI;
3098      EPI.ExceptionSpecType = getExceptionSpecType();
3099      EPI.NumExceptions = size();
3100      EPI.Exceptions = data();
3101      return EPI;
3102    }
3103  };
3104
3105  /// \brief Determine what sort of exception specification a defaulted
3106  /// copy constructor of a class will have.
3107  ImplicitExceptionSpecification
3108  ComputeDefaultedDefaultCtorExceptionSpec(CXXRecordDecl *ClassDecl);
3109
3110  /// \brief Determine what sort of exception specification a defaulted
3111  /// default constructor of a class will have, and whether the parameter
3112  /// will be const.
3113  std::pair<ImplicitExceptionSpecification, bool>
3114  ComputeDefaultedCopyCtorExceptionSpecAndConst(CXXRecordDecl *ClassDecl);
3115
3116  /// \brief Determine what sort of exception specification a defautled
3117  /// copy assignment operator of a class will have, and whether the
3118  /// parameter will be const.
3119  std::pair<ImplicitExceptionSpecification, bool>
3120  ComputeDefaultedCopyAssignmentExceptionSpecAndConst(CXXRecordDecl *ClassDecl);
3121
3122  /// \brief Determine what sort of exception specification a defaulted move
3123  /// constructor of a class will have.
3124  ImplicitExceptionSpecification
3125  ComputeDefaultedMoveCtorExceptionSpec(CXXRecordDecl *ClassDecl);
3126
3127  /// \brief Determine what sort of exception specification a defaulted move
3128  /// assignment operator of a class will have.
3129  ImplicitExceptionSpecification
3130  ComputeDefaultedMoveAssignmentExceptionSpec(CXXRecordDecl *ClassDecl);
3131
3132  /// \brief Determine what sort of exception specification a defaulted
3133  /// destructor of a class will have.
3134  ImplicitExceptionSpecification
3135  ComputeDefaultedDtorExceptionSpec(CXXRecordDecl *ClassDecl);
3136
3137  /// \brief Determine if a special member function should have a deleted
3138  /// definition when it is defaulted.
3139  bool ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
3140                                 bool Diagnose = false);
3141
3142  /// \brief Declare the implicit default constructor for the given class.
3143  ///
3144  /// \param ClassDecl The class declaration into which the implicit
3145  /// default constructor will be added.
3146  ///
3147  /// \returns The implicitly-declared default constructor.
3148  CXXConstructorDecl *DeclareImplicitDefaultConstructor(
3149                                                     CXXRecordDecl *ClassDecl);
3150
3151  /// DefineImplicitDefaultConstructor - Checks for feasibility of
3152  /// defining this constructor as the default constructor.
3153  void DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
3154                                        CXXConstructorDecl *Constructor);
3155
3156  /// \brief Declare the implicit destructor for the given class.
3157  ///
3158  /// \param ClassDecl The class declaration into which the implicit
3159  /// destructor will be added.
3160  ///
3161  /// \returns The implicitly-declared destructor.
3162  CXXDestructorDecl *DeclareImplicitDestructor(CXXRecordDecl *ClassDecl);
3163
3164  /// DefineImplicitDestructor - Checks for feasibility of
3165  /// defining this destructor as the default destructor.
3166  void DefineImplicitDestructor(SourceLocation CurrentLocation,
3167                                CXXDestructorDecl *Destructor);
3168
3169  /// \brief Build an exception spec for destructors that don't have one.
3170  ///
3171  /// C++11 says that user-defined destructors with no exception spec get one
3172  /// that looks as if the destructor was implicitly declared.
3173  void AdjustDestructorExceptionSpec(CXXRecordDecl *ClassDecl,
3174                                     CXXDestructorDecl *Destructor);
3175
3176  /// \brief Declare all inherited constructors for the given class.
3177  ///
3178  /// \param ClassDecl The class declaration into which the inherited
3179  /// constructors will be added.
3180  void DeclareInheritedConstructors(CXXRecordDecl *ClassDecl);
3181
3182  /// \brief Declare the implicit copy constructor for the given class.
3183  ///
3184  /// \param ClassDecl The class declaration into which the implicit
3185  /// copy constructor will be added.
3186  ///
3187  /// \returns The implicitly-declared copy constructor.
3188  CXXConstructorDecl *DeclareImplicitCopyConstructor(CXXRecordDecl *ClassDecl);
3189
3190  /// DefineImplicitCopyConstructor - Checks for feasibility of
3191  /// defining this constructor as the copy constructor.
3192  void DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
3193                                     CXXConstructorDecl *Constructor);
3194
3195  /// \brief Declare the implicit move constructor for the given class.
3196  ///
3197  /// \param ClassDecl The Class declaration into which the implicit
3198  /// move constructor will be added.
3199  ///
3200  /// \returns The implicitly-declared move constructor, or NULL if it wasn't
3201  /// declared.
3202  CXXConstructorDecl *DeclareImplicitMoveConstructor(CXXRecordDecl *ClassDecl);
3203
3204  /// DefineImplicitMoveConstructor - Checks for feasibility of
3205  /// defining this constructor as the move constructor.
3206  void DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
3207                                     CXXConstructorDecl *Constructor);
3208
3209  /// \brief Declare the implicit copy assignment operator for the given class.
3210  ///
3211  /// \param ClassDecl The class declaration into which the implicit
3212  /// copy assignment operator will be added.
3213  ///
3214  /// \returns The implicitly-declared copy assignment operator.
3215  CXXMethodDecl *DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl);
3216
3217  /// \brief Defines an implicitly-declared copy assignment operator.
3218  void DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
3219                                    CXXMethodDecl *MethodDecl);
3220
3221  /// \brief Declare the implicit move assignment operator for the given class.
3222  ///
3223  /// \param ClassDecl The Class declaration into which the implicit
3224  /// move assignment operator will be added.
3225  ///
3226  /// \returns The implicitly-declared move assignment operator, or NULL if it
3227  /// wasn't declared.
3228  CXXMethodDecl *DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl);
3229
3230  /// \brief Defines an implicitly-declared move assignment operator.
3231  void DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
3232                                    CXXMethodDecl *MethodDecl);
3233
3234  /// \brief Force the declaration of any implicitly-declared members of this
3235  /// class.
3236  void ForceDeclarationOfImplicitMembers(CXXRecordDecl *Class);
3237
3238  /// \brief Determine whether the given function is an implicitly-deleted
3239  /// special member function.
3240  bool isImplicitlyDeleted(FunctionDecl *FD);
3241
3242  /// MaybeBindToTemporary - If the passed in expression has a record type with
3243  /// a non-trivial destructor, this will return CXXBindTemporaryExpr. Otherwise
3244  /// it simply returns the passed in expression.
3245  ExprResult MaybeBindToTemporary(Expr *E);
3246
3247  bool CompleteConstructorCall(CXXConstructorDecl *Constructor,
3248                               MultiExprArg ArgsPtr,
3249                               SourceLocation Loc,
3250                               ASTOwningVector<Expr*> &ConvertedArgs,
3251                               bool AllowExplicit = false);
3252
3253  ParsedType getDestructorName(SourceLocation TildeLoc,
3254                               IdentifierInfo &II, SourceLocation NameLoc,
3255                               Scope *S, CXXScopeSpec &SS,
3256                               ParsedType ObjectType,
3257                               bool EnteringContext);
3258
3259  ParsedType getDestructorType(const DeclSpec& DS, ParsedType ObjectType);
3260
3261  // Checks that reinterpret casts don't have undefined behavior.
3262  void CheckCompatibleReinterpretCast(QualType SrcType, QualType DestType,
3263                                      bool IsDereference, SourceRange Range);
3264
3265  /// ActOnCXXNamedCast - Parse {dynamic,static,reinterpret,const}_cast's.
3266  ExprResult ActOnCXXNamedCast(SourceLocation OpLoc,
3267                               tok::TokenKind Kind,
3268                               SourceLocation LAngleBracketLoc,
3269                               Declarator &D,
3270                               SourceLocation RAngleBracketLoc,
3271                               SourceLocation LParenLoc,
3272                               Expr *E,
3273                               SourceLocation RParenLoc);
3274
3275  ExprResult BuildCXXNamedCast(SourceLocation OpLoc,
3276                               tok::TokenKind Kind,
3277                               TypeSourceInfo *Ty,
3278                               Expr *E,
3279                               SourceRange AngleBrackets,
3280                               SourceRange Parens);
3281
3282  ExprResult BuildCXXTypeId(QualType TypeInfoType,
3283                            SourceLocation TypeidLoc,
3284                            TypeSourceInfo *Operand,
3285                            SourceLocation RParenLoc);
3286  ExprResult BuildCXXTypeId(QualType TypeInfoType,
3287                            SourceLocation TypeidLoc,
3288                            Expr *Operand,
3289                            SourceLocation RParenLoc);
3290
3291  /// ActOnCXXTypeid - Parse typeid( something ).
3292  ExprResult ActOnCXXTypeid(SourceLocation OpLoc,
3293                            SourceLocation LParenLoc, bool isType,
3294                            void *TyOrExpr,
3295                            SourceLocation RParenLoc);
3296
3297  ExprResult BuildCXXUuidof(QualType TypeInfoType,
3298                            SourceLocation TypeidLoc,
3299                            TypeSourceInfo *Operand,
3300                            SourceLocation RParenLoc);
3301  ExprResult BuildCXXUuidof(QualType TypeInfoType,
3302                            SourceLocation TypeidLoc,
3303                            Expr *Operand,
3304                            SourceLocation RParenLoc);
3305
3306  /// ActOnCXXUuidof - Parse __uuidof( something ).
3307  ExprResult ActOnCXXUuidof(SourceLocation OpLoc,
3308                            SourceLocation LParenLoc, bool isType,
3309                            void *TyOrExpr,
3310                            SourceLocation RParenLoc);
3311
3312
3313  //// ActOnCXXThis -  Parse 'this' pointer.
3314  ExprResult ActOnCXXThis(SourceLocation loc);
3315
3316  /// \brief Try to retrieve the type of the 'this' pointer.
3317  ///
3318  /// \param Capture If true, capture 'this' in this context.
3319  ///
3320  /// \returns The type of 'this', if possible. Otherwise, returns a NULL type.
3321  QualType getCurrentThisType();
3322
3323  /// \brief Make sure the value of 'this' is actually available in the current
3324  /// context, if it is a potentially evaluated context.
3325  ///
3326  /// \param Loc The location at which the capture of 'this' occurs.
3327  ///
3328  /// \param Explicit Whether 'this' is explicitly captured in a lambda
3329  /// capture list.
3330  void CheckCXXThisCapture(SourceLocation Loc, bool Explicit = false);
3331
3332  /// ActOnCXXBoolLiteral - Parse {true,false} literals.
3333  ExprResult ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind);
3334
3335
3336  /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
3337  ExprResult ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind);
3338
3339  /// ActOnCXXNullPtrLiteral - Parse 'nullptr'.
3340  ExprResult ActOnCXXNullPtrLiteral(SourceLocation Loc);
3341
3342  //// ActOnCXXThrow -  Parse throw expressions.
3343  ExprResult ActOnCXXThrow(Scope *S, SourceLocation OpLoc, Expr *expr);
3344  ExprResult BuildCXXThrow(SourceLocation OpLoc, Expr *Ex,
3345                           bool IsThrownVarInScope);
3346  ExprResult CheckCXXThrowOperand(SourceLocation ThrowLoc, Expr *E,
3347                                  bool IsThrownVarInScope);
3348
3349  /// ActOnCXXTypeConstructExpr - Parse construction of a specified type.
3350  /// Can be interpreted either as function-style casting ("int(x)")
3351  /// or class type construction ("ClassType(x,y,z)")
3352  /// or creation of a value-initialized type ("int()").
3353  ExprResult ActOnCXXTypeConstructExpr(ParsedType TypeRep,
3354                                       SourceLocation LParenLoc,
3355                                       MultiExprArg Exprs,
3356                                       SourceLocation RParenLoc);
3357
3358  ExprResult BuildCXXTypeConstructExpr(TypeSourceInfo *Type,
3359                                       SourceLocation LParenLoc,
3360                                       MultiExprArg Exprs,
3361                                       SourceLocation RParenLoc);
3362
3363  /// ActOnCXXNew - Parsed a C++ 'new' expression.
3364  ExprResult ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
3365                         SourceLocation PlacementLParen,
3366                         MultiExprArg PlacementArgs,
3367                         SourceLocation PlacementRParen,
3368                         SourceRange TypeIdParens, Declarator &D,
3369                         Expr *Initializer);
3370  ExprResult BuildCXXNew(SourceLocation StartLoc, bool UseGlobal,
3371                         SourceLocation PlacementLParen,
3372                         MultiExprArg PlacementArgs,
3373                         SourceLocation PlacementRParen,
3374                         SourceRange TypeIdParens,
3375                         QualType AllocType,
3376                         TypeSourceInfo *AllocTypeInfo,
3377                         Expr *ArraySize,
3378                         SourceRange DirectInitRange,
3379                         Expr *Initializer,
3380                         bool TypeMayContainAuto = true);
3381
3382  bool CheckAllocatedType(QualType AllocType, SourceLocation Loc,
3383                          SourceRange R);
3384  bool FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,
3385                               bool UseGlobal, QualType AllocType, bool IsArray,
3386                               Expr **PlaceArgs, unsigned NumPlaceArgs,
3387                               FunctionDecl *&OperatorNew,
3388                               FunctionDecl *&OperatorDelete);
3389  bool FindAllocationOverload(SourceLocation StartLoc, SourceRange Range,
3390                              DeclarationName Name, Expr** Args,
3391                              unsigned NumArgs, DeclContext *Ctx,
3392                              bool AllowMissing, FunctionDecl *&Operator,
3393                              bool Diagnose = true);
3394  void DeclareGlobalNewDelete();
3395  void DeclareGlobalAllocationFunction(DeclarationName Name, QualType Return,
3396                                       QualType Argument,
3397                                       bool addMallocAttr = false);
3398
3399  bool FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD,
3400                                DeclarationName Name, FunctionDecl* &Operator,
3401                                bool Diagnose = true);
3402
3403  /// ActOnCXXDelete - Parsed a C++ 'delete' expression
3404  ExprResult ActOnCXXDelete(SourceLocation StartLoc,
3405                            bool UseGlobal, bool ArrayForm,
3406                            Expr *Operand);
3407
3408  DeclResult ActOnCXXConditionDeclaration(Scope *S, Declarator &D);
3409  ExprResult CheckConditionVariable(VarDecl *ConditionVar,
3410                                    SourceLocation StmtLoc,
3411                                    bool ConvertToBoolean);
3412
3413  ExprResult ActOnNoexceptExpr(SourceLocation KeyLoc, SourceLocation LParen,
3414                               Expr *Operand, SourceLocation RParen);
3415  ExprResult BuildCXXNoexceptExpr(SourceLocation KeyLoc, Expr *Operand,
3416                                  SourceLocation RParen);
3417
3418  /// ActOnUnaryTypeTrait - Parsed one of the unary type trait support
3419  /// pseudo-functions.
3420  ExprResult ActOnUnaryTypeTrait(UnaryTypeTrait OTT,
3421                                 SourceLocation KWLoc,
3422                                 ParsedType Ty,
3423                                 SourceLocation RParen);
3424
3425  ExprResult BuildUnaryTypeTrait(UnaryTypeTrait OTT,
3426                                 SourceLocation KWLoc,
3427                                 TypeSourceInfo *T,
3428                                 SourceLocation RParen);
3429
3430  /// ActOnBinaryTypeTrait - Parsed one of the bianry type trait support
3431  /// pseudo-functions.
3432  ExprResult ActOnBinaryTypeTrait(BinaryTypeTrait OTT,
3433                                  SourceLocation KWLoc,
3434                                  ParsedType LhsTy,
3435                                  ParsedType RhsTy,
3436                                  SourceLocation RParen);
3437
3438  ExprResult BuildBinaryTypeTrait(BinaryTypeTrait BTT,
3439                                  SourceLocation KWLoc,
3440                                  TypeSourceInfo *LhsT,
3441                                  TypeSourceInfo *RhsT,
3442                                  SourceLocation RParen);
3443
3444  /// \brief Parsed one of the type trait support pseudo-functions.
3445  ExprResult ActOnTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
3446                            ArrayRef<ParsedType> Args,
3447                            SourceLocation RParenLoc);
3448  ExprResult BuildTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
3449                            ArrayRef<TypeSourceInfo *> Args,
3450                            SourceLocation RParenLoc);
3451
3452  /// ActOnArrayTypeTrait - Parsed one of the bianry type trait support
3453  /// pseudo-functions.
3454  ExprResult ActOnArrayTypeTrait(ArrayTypeTrait ATT,
3455                                 SourceLocation KWLoc,
3456                                 ParsedType LhsTy,
3457                                 Expr *DimExpr,
3458                                 SourceLocation RParen);
3459
3460  ExprResult BuildArrayTypeTrait(ArrayTypeTrait ATT,
3461                                 SourceLocation KWLoc,
3462                                 TypeSourceInfo *TSInfo,
3463                                 Expr *DimExpr,
3464                                 SourceLocation RParen);
3465
3466  /// ActOnExpressionTrait - Parsed one of the unary type trait support
3467  /// pseudo-functions.
3468  ExprResult ActOnExpressionTrait(ExpressionTrait OET,
3469                                  SourceLocation KWLoc,
3470                                  Expr *Queried,
3471                                  SourceLocation RParen);
3472
3473  ExprResult BuildExpressionTrait(ExpressionTrait OET,
3474                                  SourceLocation KWLoc,
3475                                  Expr *Queried,
3476                                  SourceLocation RParen);
3477
3478  ExprResult ActOnStartCXXMemberReference(Scope *S,
3479                                          Expr *Base,
3480                                          SourceLocation OpLoc,
3481                                          tok::TokenKind OpKind,
3482                                          ParsedType &ObjectType,
3483                                          bool &MayBePseudoDestructor);
3484
3485  ExprResult DiagnoseDtorReference(SourceLocation NameLoc, Expr *MemExpr);
3486
3487  ExprResult BuildPseudoDestructorExpr(Expr *Base,
3488                                       SourceLocation OpLoc,
3489                                       tok::TokenKind OpKind,
3490                                       const CXXScopeSpec &SS,
3491                                       TypeSourceInfo *ScopeType,
3492                                       SourceLocation CCLoc,
3493                                       SourceLocation TildeLoc,
3494                                     PseudoDestructorTypeStorage DestroyedType,
3495                                       bool HasTrailingLParen);
3496
3497  ExprResult ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
3498                                       SourceLocation OpLoc,
3499                                       tok::TokenKind OpKind,
3500                                       CXXScopeSpec &SS,
3501                                       UnqualifiedId &FirstTypeName,
3502                                       SourceLocation CCLoc,
3503                                       SourceLocation TildeLoc,
3504                                       UnqualifiedId &SecondTypeName,
3505                                       bool HasTrailingLParen);
3506
3507  ExprResult ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
3508                                       SourceLocation OpLoc,
3509                                       tok::TokenKind OpKind,
3510                                       SourceLocation TildeLoc,
3511                                       const DeclSpec& DS,
3512                                       bool HasTrailingLParen);
3513
3514  /// MaybeCreateExprWithCleanups - If the current full-expression
3515  /// requires any cleanups, surround it with a ExprWithCleanups node.
3516  /// Otherwise, just returns the passed-in expression.
3517  Expr *MaybeCreateExprWithCleanups(Expr *SubExpr);
3518  Stmt *MaybeCreateStmtWithCleanups(Stmt *SubStmt);
3519  ExprResult MaybeCreateExprWithCleanups(ExprResult SubExpr);
3520
3521  ExprResult ActOnFinishFullExpr(Expr *Expr);
3522  StmtResult ActOnFinishFullStmt(Stmt *Stmt);
3523
3524  // Marks SS invalid if it represents an incomplete type.
3525  bool RequireCompleteDeclContext(CXXScopeSpec &SS, DeclContext *DC);
3526
3527  DeclContext *computeDeclContext(QualType T);
3528  DeclContext *computeDeclContext(const CXXScopeSpec &SS,
3529                                  bool EnteringContext = false);
3530  bool isDependentScopeSpecifier(const CXXScopeSpec &SS);
3531  CXXRecordDecl *getCurrentInstantiationOf(NestedNameSpecifier *NNS);
3532  bool isUnknownSpecialization(const CXXScopeSpec &SS);
3533
3534  /// \brief The parser has parsed a global nested-name-specifier '::'.
3535  ///
3536  /// \param S The scope in which this nested-name-specifier occurs.
3537  ///
3538  /// \param CCLoc The location of the '::'.
3539  ///
3540  /// \param SS The nested-name-specifier, which will be updated in-place
3541  /// to reflect the parsed nested-name-specifier.
3542  ///
3543  /// \returns true if an error occurred, false otherwise.
3544  bool ActOnCXXGlobalScopeSpecifier(Scope *S, SourceLocation CCLoc,
3545                                    CXXScopeSpec &SS);
3546
3547  bool isAcceptableNestedNameSpecifier(NamedDecl *SD);
3548  NamedDecl *FindFirstQualifierInScope(Scope *S, NestedNameSpecifier *NNS);
3549
3550  bool isNonTypeNestedNameSpecifier(Scope *S, CXXScopeSpec &SS,
3551                                    SourceLocation IdLoc,
3552                                    IdentifierInfo &II,
3553                                    ParsedType ObjectType);
3554
3555  bool BuildCXXNestedNameSpecifier(Scope *S,
3556                                   IdentifierInfo &Identifier,
3557                                   SourceLocation IdentifierLoc,
3558                                   SourceLocation CCLoc,
3559                                   QualType ObjectType,
3560                                   bool EnteringContext,
3561                                   CXXScopeSpec &SS,
3562                                   NamedDecl *ScopeLookupResult,
3563                                   bool ErrorRecoveryLookup);
3564
3565  /// \brief The parser has parsed a nested-name-specifier 'identifier::'.
3566  ///
3567  /// \param S The scope in which this nested-name-specifier occurs.
3568  ///
3569  /// \param Identifier The identifier preceding the '::'.
3570  ///
3571  /// \param IdentifierLoc The location of the identifier.
3572  ///
3573  /// \param CCLoc The location of the '::'.
3574  ///
3575  /// \param ObjectType The type of the object, if we're parsing
3576  /// nested-name-specifier in a member access expression.
3577  ///
3578  /// \param EnteringContext Whether we're entering the context nominated by
3579  /// this nested-name-specifier.
3580  ///
3581  /// \param SS The nested-name-specifier, which is both an input
3582  /// parameter (the nested-name-specifier before this type) and an
3583  /// output parameter (containing the full nested-name-specifier,
3584  /// including this new type).
3585  ///
3586  /// \returns true if an error occurred, false otherwise.
3587  bool ActOnCXXNestedNameSpecifier(Scope *S,
3588                                   IdentifierInfo &Identifier,
3589                                   SourceLocation IdentifierLoc,
3590                                   SourceLocation CCLoc,
3591                                   ParsedType ObjectType,
3592                                   bool EnteringContext,
3593                                   CXXScopeSpec &SS);
3594
3595  ExprResult ActOnDecltypeExpression(Expr *E);
3596
3597  bool ActOnCXXNestedNameSpecifierDecltype(CXXScopeSpec &SS,
3598                                           const DeclSpec &DS,
3599                                           SourceLocation ColonColonLoc);
3600
3601  bool IsInvalidUnlessNestedName(Scope *S, CXXScopeSpec &SS,
3602                                 IdentifierInfo &Identifier,
3603                                 SourceLocation IdentifierLoc,
3604                                 SourceLocation ColonLoc,
3605                                 ParsedType ObjectType,
3606                                 bool EnteringContext);
3607
3608  /// \brief The parser has parsed a nested-name-specifier
3609  /// 'template[opt] template-name < template-args >::'.
3610  ///
3611  /// \param S The scope in which this nested-name-specifier occurs.
3612  ///
3613  /// \param SS The nested-name-specifier, which is both an input
3614  /// parameter (the nested-name-specifier before this type) and an
3615  /// output parameter (containing the full nested-name-specifier,
3616  /// including this new type).
3617  ///
3618  /// \param TemplateKWLoc the location of the 'template' keyword, if any.
3619  /// \param TemplateName The template name.
3620  /// \param TemplateNameLoc The location of the template name.
3621  /// \param LAngleLoc The location of the opening angle bracket  ('<').
3622  /// \param TemplateArgs The template arguments.
3623  /// \param RAngleLoc The location of the closing angle bracket  ('>').
3624  /// \param CCLoc The location of the '::'.
3625  ///
3626  /// \param EnteringContext Whether we're entering the context of the
3627  /// nested-name-specifier.
3628  ///
3629  ///
3630  /// \returns true if an error occurred, false otherwise.
3631  bool ActOnCXXNestedNameSpecifier(Scope *S,
3632                                   CXXScopeSpec &SS,
3633                                   SourceLocation TemplateKWLoc,
3634                                   TemplateTy Template,
3635                                   SourceLocation TemplateNameLoc,
3636                                   SourceLocation LAngleLoc,
3637                                   ASTTemplateArgsPtr TemplateArgs,
3638                                   SourceLocation RAngleLoc,
3639                                   SourceLocation CCLoc,
3640                                   bool EnteringContext);
3641
3642  /// \brief Given a C++ nested-name-specifier, produce an annotation value
3643  /// that the parser can use later to reconstruct the given
3644  /// nested-name-specifier.
3645  ///
3646  /// \param SS A nested-name-specifier.
3647  ///
3648  /// \returns A pointer containing all of the information in the
3649  /// nested-name-specifier \p SS.
3650  void *SaveNestedNameSpecifierAnnotation(CXXScopeSpec &SS);
3651
3652  /// \brief Given an annotation pointer for a nested-name-specifier, restore
3653  /// the nested-name-specifier structure.
3654  ///
3655  /// \param Annotation The annotation pointer, produced by
3656  /// \c SaveNestedNameSpecifierAnnotation().
3657  ///
3658  /// \param AnnotationRange The source range corresponding to the annotation.
3659  ///
3660  /// \param SS The nested-name-specifier that will be updated with the contents
3661  /// of the annotation pointer.
3662  void RestoreNestedNameSpecifierAnnotation(void *Annotation,
3663                                            SourceRange AnnotationRange,
3664                                            CXXScopeSpec &SS);
3665
3666  bool ShouldEnterDeclaratorScope(Scope *S, const CXXScopeSpec &SS);
3667
3668  /// ActOnCXXEnterDeclaratorScope - Called when a C++ scope specifier (global
3669  /// scope or nested-name-specifier) is parsed, part of a declarator-id.
3670  /// After this method is called, according to [C++ 3.4.3p3], names should be
3671  /// looked up in the declarator-id's scope, until the declarator is parsed and
3672  /// ActOnCXXExitDeclaratorScope is called.
3673  /// The 'SS' should be a non-empty valid CXXScopeSpec.
3674  bool ActOnCXXEnterDeclaratorScope(Scope *S, CXXScopeSpec &SS);
3675
3676  /// ActOnCXXExitDeclaratorScope - Called when a declarator that previously
3677  /// invoked ActOnCXXEnterDeclaratorScope(), is finished. 'SS' is the same
3678  /// CXXScopeSpec that was passed to ActOnCXXEnterDeclaratorScope as well.
3679  /// Used to indicate that names should revert to being looked up in the
3680  /// defining scope.
3681  void ActOnCXXExitDeclaratorScope(Scope *S, const CXXScopeSpec &SS);
3682
3683  /// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse an
3684  /// initializer for the declaration 'Dcl'.
3685  /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
3686  /// static data member of class X, names should be looked up in the scope of
3687  /// class X.
3688  void ActOnCXXEnterDeclInitializer(Scope *S, Decl *Dcl);
3689
3690  /// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
3691  /// initializer for the declaration 'Dcl'.
3692  void ActOnCXXExitDeclInitializer(Scope *S, Decl *Dcl);
3693
3694  /// \brief Create a new lambda closure type.
3695  CXXRecordDecl *createLambdaClosureType(SourceRange IntroducerRange,
3696                                         bool KnownDependent = false);
3697
3698  /// \brief Start the definition of a lambda expression.
3699  CXXMethodDecl *startLambdaDefinition(CXXRecordDecl *Class,
3700                                       SourceRange IntroducerRange,
3701                                       TypeSourceInfo *MethodType,
3702                                       SourceLocation EndLoc,
3703                                       llvm::ArrayRef<ParmVarDecl *> Params,
3704                                       llvm::Optional<unsigned> ManglingNumber
3705                                         = llvm::Optional<unsigned>(),
3706                                       Decl *ContextDecl = 0);
3707
3708  /// \brief Introduce the scope for a lambda expression.
3709  sema::LambdaScopeInfo *enterLambdaScope(CXXMethodDecl *CallOperator,
3710                                          SourceRange IntroducerRange,
3711                                          LambdaCaptureDefault CaptureDefault,
3712                                          bool ExplicitParams,
3713                                          bool ExplicitResultType,
3714                                          bool Mutable);
3715
3716  /// \brief Note that we have finished the explicit captures for the
3717  /// given lambda.
3718  void finishLambdaExplicitCaptures(sema::LambdaScopeInfo *LSI);
3719
3720  /// \brief Introduce the lambda parameters into scope.
3721  void addLambdaParameters(CXXMethodDecl *CallOperator, Scope *CurScope);
3722
3723  /// ActOnStartOfLambdaDefinition - This is called just before we start
3724  /// parsing the body of a lambda; it analyzes the explicit captures and
3725  /// arguments, and sets up various data-structures for the body of the
3726  /// lambda.
3727  void ActOnStartOfLambdaDefinition(LambdaIntroducer &Intro,
3728                                    Declarator &ParamInfo, Scope *CurScope);
3729
3730  /// ActOnLambdaError - If there is an error parsing a lambda, this callback
3731  /// is invoked to pop the information about the lambda.
3732  void ActOnLambdaError(SourceLocation StartLoc, Scope *CurScope,
3733                        bool IsInstantiation = false);
3734
3735  /// ActOnLambdaExpr - This is called when the body of a lambda expression
3736  /// was successfully completed.
3737  ExprResult ActOnLambdaExpr(SourceLocation StartLoc, Stmt *Body,
3738                             Scope *CurScope,
3739                             bool IsInstantiation = false);
3740
3741  /// \brief Define the "body" of the conversion from a lambda object to a
3742  /// function pointer.
3743  ///
3744  /// This routine doesn't actually define a sensible body; rather, it fills
3745  /// in the initialization expression needed to copy the lambda object into
3746  /// the block, and IR generation actually generates the real body of the
3747  /// block pointer conversion.
3748  void DefineImplicitLambdaToFunctionPointerConversion(
3749         SourceLocation CurrentLoc, CXXConversionDecl *Conv);
3750
3751  /// \brief Define the "body" of the conversion from a lambda object to a
3752  /// block pointer.
3753  ///
3754  /// This routine doesn't actually define a sensible body; rather, it fills
3755  /// in the initialization expression needed to copy the lambda object into
3756  /// the block, and IR generation actually generates the real body of the
3757  /// block pointer conversion.
3758  void DefineImplicitLambdaToBlockPointerConversion(SourceLocation CurrentLoc,
3759                                                    CXXConversionDecl *Conv);
3760
3761  ExprResult BuildBlockForLambdaConversion(SourceLocation CurrentLocation,
3762                                           SourceLocation ConvLocation,
3763                                           CXXConversionDecl *Conv,
3764                                           Expr *Src);
3765
3766  // ParseObjCStringLiteral - Parse Objective-C string literals.
3767  ExprResult ParseObjCStringLiteral(SourceLocation *AtLocs,
3768                                    Expr **Strings,
3769                                    unsigned NumStrings);
3770
3771  ExprResult BuildObjCStringLiteral(SourceLocation AtLoc, StringLiteral *S);
3772
3773  /// BuildObjCNumericLiteral - builds an ObjCNumericLiteral AST node for the
3774  /// numeric literal expression. Type of the expression will be "NSNumber *"
3775  /// or "id" if NSNumber is unavailable.
3776  ExprResult BuildObjCNumericLiteral(SourceLocation AtLoc, Expr *Number);
3777  ExprResult ActOnObjCBoolLiteral(SourceLocation AtLoc, SourceLocation ValueLoc,
3778                                  bool Value);
3779  ExprResult BuildObjCArrayLiteral(SourceRange SR, MultiExprArg Elements);
3780
3781  ExprResult BuildObjCSubscriptExpression(SourceLocation RB, Expr *BaseExpr,
3782                                          Expr *IndexExpr,
3783                                          ObjCMethodDecl *getterMethod,
3784                                          ObjCMethodDecl *setterMethod);
3785
3786  ExprResult BuildObjCDictionaryLiteral(SourceRange SR,
3787                                        ObjCDictionaryElement *Elements,
3788                                        unsigned NumElements);
3789
3790  ExprResult BuildObjCEncodeExpression(SourceLocation AtLoc,
3791                                  TypeSourceInfo *EncodedTypeInfo,
3792                                  SourceLocation RParenLoc);
3793  ExprResult BuildCXXMemberCallExpr(Expr *Exp, NamedDecl *FoundDecl,
3794                                    CXXConversionDecl *Method,
3795                                    bool HadMultipleCandidates);
3796
3797  ExprResult ParseObjCEncodeExpression(SourceLocation AtLoc,
3798                                       SourceLocation EncodeLoc,
3799                                       SourceLocation LParenLoc,
3800                                       ParsedType Ty,
3801                                       SourceLocation RParenLoc);
3802
3803  // ParseObjCSelectorExpression - Build selector expression for @selector
3804  ExprResult ParseObjCSelectorExpression(Selector Sel,
3805                                         SourceLocation AtLoc,
3806                                         SourceLocation SelLoc,
3807                                         SourceLocation LParenLoc,
3808                                         SourceLocation RParenLoc);
3809
3810  // ParseObjCProtocolExpression - Build protocol expression for @protocol
3811  ExprResult ParseObjCProtocolExpression(IdentifierInfo * ProtocolName,
3812                                         SourceLocation AtLoc,
3813                                         SourceLocation ProtoLoc,
3814                                         SourceLocation LParenLoc,
3815                                         SourceLocation RParenLoc);
3816
3817  //===--------------------------------------------------------------------===//
3818  // C++ Declarations
3819  //
3820  Decl *ActOnStartLinkageSpecification(Scope *S,
3821                                       SourceLocation ExternLoc,
3822                                       SourceLocation LangLoc,
3823                                       StringRef Lang,
3824                                       SourceLocation LBraceLoc);
3825  Decl *ActOnFinishLinkageSpecification(Scope *S,
3826                                        Decl *LinkageSpec,
3827                                        SourceLocation RBraceLoc);
3828
3829
3830  //===--------------------------------------------------------------------===//
3831  // C++ Classes
3832  //
3833  bool isCurrentClassName(const IdentifierInfo &II, Scope *S,
3834                          const CXXScopeSpec *SS = 0);
3835
3836  bool ActOnAccessSpecifier(AccessSpecifier Access,
3837                            SourceLocation ASLoc,
3838                            SourceLocation ColonLoc,
3839                            AttributeList *Attrs = 0);
3840
3841  Decl *ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS,
3842                                 Declarator &D,
3843                                 MultiTemplateParamsArg TemplateParameterLists,
3844                                 Expr *BitfieldWidth, const VirtSpecifiers &VS,
3845                                 bool HasDeferredInit);
3846  void ActOnCXXInClassMemberInitializer(Decl *VarDecl, SourceLocation EqualLoc,
3847                                        Expr *Init);
3848
3849  MemInitResult ActOnMemInitializer(Decl *ConstructorD,
3850                                    Scope *S,
3851                                    CXXScopeSpec &SS,
3852                                    IdentifierInfo *MemberOrBase,
3853                                    ParsedType TemplateTypeTy,
3854                                    const DeclSpec &DS,
3855                                    SourceLocation IdLoc,
3856                                    SourceLocation LParenLoc,
3857                                    Expr **Args, unsigned NumArgs,
3858                                    SourceLocation RParenLoc,
3859                                    SourceLocation EllipsisLoc);
3860
3861  MemInitResult ActOnMemInitializer(Decl *ConstructorD,
3862                                    Scope *S,
3863                                    CXXScopeSpec &SS,
3864                                    IdentifierInfo *MemberOrBase,
3865                                    ParsedType TemplateTypeTy,
3866                                    const DeclSpec &DS,
3867                                    SourceLocation IdLoc,
3868                                    Expr *InitList,
3869                                    SourceLocation EllipsisLoc);
3870
3871  MemInitResult BuildMemInitializer(Decl *ConstructorD,
3872                                    Scope *S,
3873                                    CXXScopeSpec &SS,
3874                                    IdentifierInfo *MemberOrBase,
3875                                    ParsedType TemplateTypeTy,
3876                                    const DeclSpec &DS,
3877                                    SourceLocation IdLoc,
3878                                    Expr *Init,
3879                                    SourceLocation EllipsisLoc);
3880
3881  MemInitResult BuildMemberInitializer(ValueDecl *Member,
3882                                       Expr *Init,
3883                                       SourceLocation IdLoc);
3884
3885  MemInitResult BuildBaseInitializer(QualType BaseType,
3886                                     TypeSourceInfo *BaseTInfo,
3887                                     Expr *Init,
3888                                     CXXRecordDecl *ClassDecl,
3889                                     SourceLocation EllipsisLoc);
3890
3891  MemInitResult BuildDelegatingInitializer(TypeSourceInfo *TInfo,
3892                                           Expr *Init,
3893                                           CXXRecordDecl *ClassDecl);
3894
3895  bool SetDelegatingInitializer(CXXConstructorDecl *Constructor,
3896                                CXXCtorInitializer *Initializer);
3897
3898  bool SetCtorInitializers(CXXConstructorDecl *Constructor,
3899                           CXXCtorInitializer **Initializers,
3900                           unsigned NumInitializers, bool AnyErrors);
3901
3902  void SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation);
3903
3904
3905  /// MarkBaseAndMemberDestructorsReferenced - Given a record decl,
3906  /// mark all the non-trivial destructors of its members and bases as
3907  /// referenced.
3908  void MarkBaseAndMemberDestructorsReferenced(SourceLocation Loc,
3909                                              CXXRecordDecl *Record);
3910
3911  /// \brief The list of classes whose vtables have been used within
3912  /// this translation unit, and the source locations at which the
3913  /// first use occurred.
3914  typedef std::pair<CXXRecordDecl*, SourceLocation> VTableUse;
3915
3916  /// \brief The list of vtables that are required but have not yet been
3917  /// materialized.
3918  SmallVector<VTableUse, 16> VTableUses;
3919
3920  /// \brief The set of classes whose vtables have been used within
3921  /// this translation unit, and a bit that will be true if the vtable is
3922  /// required to be emitted (otherwise, it should be emitted only if needed
3923  /// by code generation).
3924  llvm::DenseMap<CXXRecordDecl *, bool> VTablesUsed;
3925
3926  /// \brief Load any externally-stored vtable uses.
3927  void LoadExternalVTableUses();
3928
3929  typedef LazyVector<CXXRecordDecl *, ExternalSemaSource,
3930                     &ExternalSemaSource::ReadDynamicClasses, 2, 2>
3931    DynamicClassesType;
3932
3933  /// \brief A list of all of the dynamic classes in this translation
3934  /// unit.
3935  DynamicClassesType DynamicClasses;
3936
3937  /// \brief Note that the vtable for the given class was used at the
3938  /// given location.
3939  void MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
3940                      bool DefinitionRequired = false);
3941
3942  /// MarkVirtualMembersReferenced - Will mark all members of the given
3943  /// CXXRecordDecl referenced.
3944  void MarkVirtualMembersReferenced(SourceLocation Loc,
3945                                    const CXXRecordDecl *RD);
3946
3947  /// \brief Define all of the vtables that have been used in this
3948  /// translation unit and reference any virtual members used by those
3949  /// vtables.
3950  ///
3951  /// \returns true if any work was done, false otherwise.
3952  bool DefineUsedVTables();
3953
3954  void AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl);
3955
3956  void ActOnMemInitializers(Decl *ConstructorDecl,
3957                            SourceLocation ColonLoc,
3958                            CXXCtorInitializer **MemInits,
3959                            unsigned NumMemInits,
3960                            bool AnyErrors);
3961
3962  void CheckCompletedCXXClass(CXXRecordDecl *Record);
3963  void ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
3964                                         Decl *TagDecl,
3965                                         SourceLocation LBrac,
3966                                         SourceLocation RBrac,
3967                                         AttributeList *AttrList);
3968
3969  void ActOnReenterTemplateScope(Scope *S, Decl *Template);
3970  void ActOnReenterDeclaratorTemplateScope(Scope *S, DeclaratorDecl *D);
3971  void ActOnStartDelayedMemberDeclarations(Scope *S, Decl *Record);
3972  void ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *Method);
3973  void ActOnDelayedCXXMethodParameter(Scope *S, Decl *Param);
3974  void ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *Record);
3975  void ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *Method);
3976  void ActOnFinishDelayedMemberInitializers(Decl *Record);
3977  void MarkAsLateParsedTemplate(FunctionDecl *FD, bool Flag = true);
3978  bool IsInsideALocalClassWithinATemplateFunction();
3979
3980  Decl *ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
3981                                     Expr *AssertExpr,
3982                                     Expr *AssertMessageExpr,
3983                                     SourceLocation RParenLoc);
3984
3985  FriendDecl *CheckFriendTypeDecl(SourceLocation Loc,
3986                                  SourceLocation FriendLoc,
3987                                  TypeSourceInfo *TSInfo);
3988  Decl *ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
3989                            MultiTemplateParamsArg TemplateParams);
3990  Decl *ActOnFriendFunctionDecl(Scope *S, Declarator &D,
3991                                MultiTemplateParamsArg TemplateParams);
3992
3993  QualType CheckConstructorDeclarator(Declarator &D, QualType R,
3994                                      StorageClass& SC);
3995  void CheckConstructor(CXXConstructorDecl *Constructor);
3996  QualType CheckDestructorDeclarator(Declarator &D, QualType R,
3997                                     StorageClass& SC);
3998  bool CheckDestructor(CXXDestructorDecl *Destructor);
3999  void CheckConversionDeclarator(Declarator &D, QualType &R,
4000                                 StorageClass& SC);
4001  Decl *ActOnConversionDeclarator(CXXConversionDecl *Conversion);
4002
4003  void CheckExplicitlyDefaultedMethods(CXXRecordDecl *Record);
4004  void CheckExplicitlyDefaultedDefaultConstructor(CXXConstructorDecl *Ctor);
4005  void CheckExplicitlyDefaultedCopyConstructor(CXXConstructorDecl *Ctor);
4006  void CheckExplicitlyDefaultedCopyAssignment(CXXMethodDecl *Method);
4007  void CheckExplicitlyDefaultedMoveConstructor(CXXConstructorDecl *Ctor);
4008  void CheckExplicitlyDefaultedMoveAssignment(CXXMethodDecl *Method);
4009  void CheckExplicitlyDefaultedDestructor(CXXDestructorDecl *Dtor);
4010
4011  //===--------------------------------------------------------------------===//
4012  // C++ Derived Classes
4013  //
4014
4015  /// ActOnBaseSpecifier - Parsed a base specifier
4016  CXXBaseSpecifier *CheckBaseSpecifier(CXXRecordDecl *Class,
4017                                       SourceRange SpecifierRange,
4018                                       bool Virtual, AccessSpecifier Access,
4019                                       TypeSourceInfo *TInfo,
4020                                       SourceLocation EllipsisLoc);
4021
4022  BaseResult ActOnBaseSpecifier(Decl *classdecl,
4023                                SourceRange SpecifierRange,
4024                                bool Virtual, AccessSpecifier Access,
4025                                ParsedType basetype,
4026                                SourceLocation BaseLoc,
4027                                SourceLocation EllipsisLoc);
4028
4029  bool AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
4030                            unsigned NumBases);
4031  void ActOnBaseSpecifiers(Decl *ClassDecl, CXXBaseSpecifier **Bases,
4032                           unsigned NumBases);
4033
4034  bool IsDerivedFrom(QualType Derived, QualType Base);
4035  bool IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths);
4036
4037  // FIXME: I don't like this name.
4038  void BuildBasePathArray(const CXXBasePaths &Paths, CXXCastPath &BasePath);
4039
4040  bool BasePathInvolvesVirtualBase(const CXXCastPath &BasePath);
4041
4042  bool CheckDerivedToBaseConversion(QualType Derived, QualType Base,
4043                                    SourceLocation Loc, SourceRange Range,
4044                                    CXXCastPath *BasePath = 0,
4045                                    bool IgnoreAccess = false);
4046  bool CheckDerivedToBaseConversion(QualType Derived, QualType Base,
4047                                    unsigned InaccessibleBaseID,
4048                                    unsigned AmbigiousBaseConvID,
4049                                    SourceLocation Loc, SourceRange Range,
4050                                    DeclarationName Name,
4051                                    CXXCastPath *BasePath);
4052
4053  std::string getAmbiguousPathsDisplayString(CXXBasePaths &Paths);
4054
4055  /// CheckOverridingFunctionReturnType - Checks whether the return types are
4056  /// covariant, according to C++ [class.virtual]p5.
4057  bool CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
4058                                         const CXXMethodDecl *Old);
4059
4060  /// CheckOverridingFunctionExceptionSpec - Checks whether the exception
4061  /// spec is a subset of base spec.
4062  bool CheckOverridingFunctionExceptionSpec(const CXXMethodDecl *New,
4063                                            const CXXMethodDecl *Old);
4064
4065  bool CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange);
4066
4067  /// CheckOverrideControl - Check C++0x override control semantics.
4068  void CheckOverrideControl(const Decl *D);
4069
4070  /// CheckForFunctionMarkedFinal - Checks whether a virtual member function
4071  /// overrides a virtual member function marked 'final', according to
4072  /// C++0x [class.virtual]p3.
4073  bool CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
4074                                              const CXXMethodDecl *Old);
4075
4076
4077  //===--------------------------------------------------------------------===//
4078  // C++ Access Control
4079  //
4080
4081  enum AccessResult {
4082    AR_accessible,
4083    AR_inaccessible,
4084    AR_dependent,
4085    AR_delayed
4086  };
4087
4088  bool SetMemberAccessSpecifier(NamedDecl *MemberDecl,
4089                                NamedDecl *PrevMemberDecl,
4090                                AccessSpecifier LexicalAS);
4091
4092  AccessResult CheckUnresolvedMemberAccess(UnresolvedMemberExpr *E,
4093                                           DeclAccessPair FoundDecl);
4094  AccessResult CheckUnresolvedLookupAccess(UnresolvedLookupExpr *E,
4095                                           DeclAccessPair FoundDecl);
4096  AccessResult CheckAllocationAccess(SourceLocation OperatorLoc,
4097                                     SourceRange PlacementRange,
4098                                     CXXRecordDecl *NamingClass,
4099                                     DeclAccessPair FoundDecl,
4100                                     bool Diagnose = true);
4101  AccessResult CheckConstructorAccess(SourceLocation Loc,
4102                                      CXXConstructorDecl *D,
4103                                      const InitializedEntity &Entity,
4104                                      AccessSpecifier Access,
4105                                      bool IsCopyBindingRefToTemp = false);
4106  AccessResult CheckConstructorAccess(SourceLocation Loc,
4107                                      CXXConstructorDecl *D,
4108                                      const InitializedEntity &Entity,
4109                                      AccessSpecifier Access,
4110                                      const PartialDiagnostic &PDiag);
4111  AccessResult CheckDestructorAccess(SourceLocation Loc,
4112                                     CXXDestructorDecl *Dtor,
4113                                     const PartialDiagnostic &PDiag,
4114                                     QualType objectType = QualType());
4115  AccessResult CheckDirectMemberAccess(SourceLocation Loc,
4116                                       NamedDecl *D,
4117                                       const PartialDiagnostic &PDiag);
4118  AccessResult CheckMemberOperatorAccess(SourceLocation Loc,
4119                                         Expr *ObjectExpr,
4120                                         Expr *ArgExpr,
4121                                         DeclAccessPair FoundDecl);
4122  AccessResult CheckAddressOfMemberAccess(Expr *OvlExpr,
4123                                          DeclAccessPair FoundDecl);
4124  AccessResult CheckBaseClassAccess(SourceLocation AccessLoc,
4125                                    QualType Base, QualType Derived,
4126                                    const CXXBasePath &Path,
4127                                    unsigned DiagID,
4128                                    bool ForceCheck = false,
4129                                    bool ForceUnprivileged = false);
4130  void CheckLookupAccess(const LookupResult &R);
4131  bool IsSimplyAccessible(NamedDecl *decl, DeclContext *Ctx);
4132
4133  void HandleDependentAccessCheck(const DependentDiagnostic &DD,
4134                         const MultiLevelTemplateArgumentList &TemplateArgs);
4135  void PerformDependentDiagnostics(const DeclContext *Pattern,
4136                        const MultiLevelTemplateArgumentList &TemplateArgs);
4137
4138  void HandleDelayedAccessCheck(sema::DelayedDiagnostic &DD, Decl *Ctx);
4139
4140  /// A flag to suppress access checking.
4141  bool SuppressAccessChecking;
4142
4143  /// \brief When true, access checking violations are treated as SFINAE
4144  /// failures rather than hard errors.
4145  bool AccessCheckingSFINAE;
4146
4147  /// \brief RAII object used to temporarily suppress access checking.
4148  class SuppressAccessChecksRAII {
4149    Sema &S;
4150    bool SuppressingAccess;
4151
4152  public:
4153    SuppressAccessChecksRAII(Sema &S, bool Suppress)
4154      : S(S), SuppressingAccess(Suppress) {
4155      if (Suppress) S.ActOnStartSuppressingAccessChecks();
4156    }
4157    ~SuppressAccessChecksRAII() {
4158      done();
4159    }
4160    void done() {
4161      if (!SuppressingAccess) return;
4162      S.ActOnStopSuppressingAccessChecks();
4163      SuppressingAccess = false;
4164    }
4165  };
4166
4167  void ActOnStartSuppressingAccessChecks();
4168  void ActOnStopSuppressingAccessChecks();
4169
4170  enum AbstractDiagSelID {
4171    AbstractNone = -1,
4172    AbstractReturnType,
4173    AbstractParamType,
4174    AbstractVariableType,
4175    AbstractFieldType,
4176    AbstractArrayType
4177  };
4178
4179  bool RequireNonAbstractType(SourceLocation Loc, QualType T,
4180                              const PartialDiagnostic &PD);
4181  void DiagnoseAbstractType(const CXXRecordDecl *RD);
4182
4183  bool RequireNonAbstractType(SourceLocation Loc, QualType T, unsigned DiagID,
4184                              AbstractDiagSelID SelID = AbstractNone);
4185
4186  //===--------------------------------------------------------------------===//
4187  // C++ Overloaded Operators [C++ 13.5]
4188  //
4189
4190  bool CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl);
4191
4192  bool CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl);
4193
4194  //===--------------------------------------------------------------------===//
4195  // C++ Templates [C++ 14]
4196  //
4197  void FilterAcceptableTemplateNames(LookupResult &R,
4198                                     bool AllowFunctionTemplates = true);
4199  bool hasAnyAcceptableTemplateNames(LookupResult &R,
4200                                     bool AllowFunctionTemplates = true);
4201
4202  void LookupTemplateName(LookupResult &R, Scope *S, CXXScopeSpec &SS,
4203                          QualType ObjectType, bool EnteringContext,
4204                          bool &MemberOfUnknownSpecialization);
4205
4206  TemplateNameKind isTemplateName(Scope *S,
4207                                  CXXScopeSpec &SS,
4208                                  bool hasTemplateKeyword,
4209                                  UnqualifiedId &Name,
4210                                  ParsedType ObjectType,
4211                                  bool EnteringContext,
4212                                  TemplateTy &Template,
4213                                  bool &MemberOfUnknownSpecialization);
4214
4215  bool DiagnoseUnknownTemplateName(const IdentifierInfo &II,
4216                                   SourceLocation IILoc,
4217                                   Scope *S,
4218                                   const CXXScopeSpec *SS,
4219                                   TemplateTy &SuggestedTemplate,
4220                                   TemplateNameKind &SuggestedKind);
4221
4222  void DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl);
4223  TemplateDecl *AdjustDeclIfTemplate(Decl *&Decl);
4224
4225  Decl *ActOnTypeParameter(Scope *S, bool Typename, bool Ellipsis,
4226                           SourceLocation EllipsisLoc,
4227                           SourceLocation KeyLoc,
4228                           IdentifierInfo *ParamName,
4229                           SourceLocation ParamNameLoc,
4230                           unsigned Depth, unsigned Position,
4231                           SourceLocation EqualLoc,
4232                           ParsedType DefaultArg);
4233
4234  QualType CheckNonTypeTemplateParameterType(QualType T, SourceLocation Loc);
4235  Decl *ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
4236                                      unsigned Depth,
4237                                      unsigned Position,
4238                                      SourceLocation EqualLoc,
4239                                      Expr *DefaultArg);
4240  Decl *ActOnTemplateTemplateParameter(Scope *S,
4241                                       SourceLocation TmpLoc,
4242                                       TemplateParameterList *Params,
4243                                       SourceLocation EllipsisLoc,
4244                                       IdentifierInfo *ParamName,
4245                                       SourceLocation ParamNameLoc,
4246                                       unsigned Depth,
4247                                       unsigned Position,
4248                                       SourceLocation EqualLoc,
4249                                       ParsedTemplateArgument DefaultArg);
4250
4251  TemplateParameterList *
4252  ActOnTemplateParameterList(unsigned Depth,
4253                             SourceLocation ExportLoc,
4254                             SourceLocation TemplateLoc,
4255                             SourceLocation LAngleLoc,
4256                             Decl **Params, unsigned NumParams,
4257                             SourceLocation RAngleLoc);
4258
4259  /// \brief The context in which we are checking a template parameter
4260  /// list.
4261  enum TemplateParamListContext {
4262    TPC_ClassTemplate,
4263    TPC_FunctionTemplate,
4264    TPC_ClassTemplateMember,
4265    TPC_FriendFunctionTemplate,
4266    TPC_FriendFunctionTemplateDefinition,
4267    TPC_TypeAliasTemplate
4268  };
4269
4270  bool CheckTemplateParameterList(TemplateParameterList *NewParams,
4271                                  TemplateParameterList *OldParams,
4272                                  TemplateParamListContext TPC);
4273  TemplateParameterList *
4274  MatchTemplateParametersToScopeSpecifier(SourceLocation DeclStartLoc,
4275                                          SourceLocation DeclLoc,
4276                                          const CXXScopeSpec &SS,
4277                                          TemplateParameterList **ParamLists,
4278                                          unsigned NumParamLists,
4279                                          bool IsFriend,
4280                                          bool &IsExplicitSpecialization,
4281                                          bool &Invalid);
4282
4283  DeclResult CheckClassTemplate(Scope *S, unsigned TagSpec, TagUseKind TUK,
4284                                SourceLocation KWLoc, CXXScopeSpec &SS,
4285                                IdentifierInfo *Name, SourceLocation NameLoc,
4286                                AttributeList *Attr,
4287                                TemplateParameterList *TemplateParams,
4288                                AccessSpecifier AS,
4289                                SourceLocation ModulePrivateLoc,
4290                                unsigned NumOuterTemplateParamLists,
4291                            TemplateParameterList **OuterTemplateParamLists);
4292
4293  void translateTemplateArguments(const ASTTemplateArgsPtr &In,
4294                                  TemplateArgumentListInfo &Out);
4295
4296  void NoteAllFoundTemplates(TemplateName Name);
4297
4298  QualType CheckTemplateIdType(TemplateName Template,
4299                               SourceLocation TemplateLoc,
4300                              TemplateArgumentListInfo &TemplateArgs);
4301
4302  TypeResult
4303  ActOnTemplateIdType(CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
4304                      TemplateTy Template, SourceLocation TemplateLoc,
4305                      SourceLocation LAngleLoc,
4306                      ASTTemplateArgsPtr TemplateArgs,
4307                      SourceLocation RAngleLoc,
4308                      bool IsCtorOrDtorName = false);
4309
4310  /// \brief Parsed an elaborated-type-specifier that refers to a template-id,
4311  /// such as \c class T::template apply<U>.
4312  ///
4313  /// \param TUK
4314  TypeResult ActOnTagTemplateIdType(TagUseKind TUK,
4315                                    TypeSpecifierType TagSpec,
4316                                    SourceLocation TagLoc,
4317                                    CXXScopeSpec &SS,
4318                                    SourceLocation TemplateKWLoc,
4319                                    TemplateTy TemplateD,
4320                                    SourceLocation TemplateLoc,
4321                                    SourceLocation LAngleLoc,
4322                                    ASTTemplateArgsPtr TemplateArgsIn,
4323                                    SourceLocation RAngleLoc);
4324
4325
4326  ExprResult BuildTemplateIdExpr(const CXXScopeSpec &SS,
4327                                 SourceLocation TemplateKWLoc,
4328                                 LookupResult &R,
4329                                 bool RequiresADL,
4330                               const TemplateArgumentListInfo *TemplateArgs);
4331
4332  ExprResult BuildQualifiedTemplateIdExpr(CXXScopeSpec &SS,
4333                                          SourceLocation TemplateKWLoc,
4334                               const DeclarationNameInfo &NameInfo,
4335                               const TemplateArgumentListInfo *TemplateArgs);
4336
4337  TemplateNameKind ActOnDependentTemplateName(Scope *S,
4338                                              CXXScopeSpec &SS,
4339                                              SourceLocation TemplateKWLoc,
4340                                              UnqualifiedId &Name,
4341                                              ParsedType ObjectType,
4342                                              bool EnteringContext,
4343                                              TemplateTy &Template);
4344
4345  DeclResult
4346  ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec, TagUseKind TUK,
4347                                   SourceLocation KWLoc,
4348                                   SourceLocation ModulePrivateLoc,
4349                                   CXXScopeSpec &SS,
4350                                   TemplateTy Template,
4351                                   SourceLocation TemplateNameLoc,
4352                                   SourceLocation LAngleLoc,
4353                                   ASTTemplateArgsPtr TemplateArgs,
4354                                   SourceLocation RAngleLoc,
4355                                   AttributeList *Attr,
4356                                 MultiTemplateParamsArg TemplateParameterLists);
4357
4358  Decl *ActOnTemplateDeclarator(Scope *S,
4359                                MultiTemplateParamsArg TemplateParameterLists,
4360                                Declarator &D);
4361
4362  Decl *ActOnStartOfFunctionTemplateDef(Scope *FnBodyScope,
4363                                  MultiTemplateParamsArg TemplateParameterLists,
4364                                        Declarator &D);
4365
4366  bool
4367  CheckSpecializationInstantiationRedecl(SourceLocation NewLoc,
4368                                         TemplateSpecializationKind NewTSK,
4369                                         NamedDecl *PrevDecl,
4370                                         TemplateSpecializationKind PrevTSK,
4371                                         SourceLocation PrevPtOfInstantiation,
4372                                         bool &SuppressNew);
4373
4374  bool CheckDependentFunctionTemplateSpecialization(FunctionDecl *FD,
4375                    const TemplateArgumentListInfo &ExplicitTemplateArgs,
4376                                                    LookupResult &Previous);
4377
4378  bool CheckFunctionTemplateSpecialization(FunctionDecl *FD,
4379                         TemplateArgumentListInfo *ExplicitTemplateArgs,
4380                                           LookupResult &Previous);
4381  bool CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous);
4382
4383  DeclResult
4384  ActOnExplicitInstantiation(Scope *S,
4385                             SourceLocation ExternLoc,
4386                             SourceLocation TemplateLoc,
4387                             unsigned TagSpec,
4388                             SourceLocation KWLoc,
4389                             const CXXScopeSpec &SS,
4390                             TemplateTy Template,
4391                             SourceLocation TemplateNameLoc,
4392                             SourceLocation LAngleLoc,
4393                             ASTTemplateArgsPtr TemplateArgs,
4394                             SourceLocation RAngleLoc,
4395                             AttributeList *Attr);
4396
4397  DeclResult
4398  ActOnExplicitInstantiation(Scope *S,
4399                             SourceLocation ExternLoc,
4400                             SourceLocation TemplateLoc,
4401                             unsigned TagSpec,
4402                             SourceLocation KWLoc,
4403                             CXXScopeSpec &SS,
4404                             IdentifierInfo *Name,
4405                             SourceLocation NameLoc,
4406                             AttributeList *Attr);
4407
4408  DeclResult ActOnExplicitInstantiation(Scope *S,
4409                                        SourceLocation ExternLoc,
4410                                        SourceLocation TemplateLoc,
4411                                        Declarator &D);
4412
4413  TemplateArgumentLoc
4414  SubstDefaultTemplateArgumentIfAvailable(TemplateDecl *Template,
4415                                          SourceLocation TemplateLoc,
4416                                          SourceLocation RAngleLoc,
4417                                          Decl *Param,
4418                          SmallVectorImpl<TemplateArgument> &Converted);
4419
4420  /// \brief Specifies the context in which a particular template
4421  /// argument is being checked.
4422  enum CheckTemplateArgumentKind {
4423    /// \brief The template argument was specified in the code or was
4424    /// instantiated with some deduced template arguments.
4425    CTAK_Specified,
4426
4427    /// \brief The template argument was deduced via template argument
4428    /// deduction.
4429    CTAK_Deduced,
4430
4431    /// \brief The template argument was deduced from an array bound
4432    /// via template argument deduction.
4433    CTAK_DeducedFromArrayBound
4434  };
4435
4436  bool CheckTemplateArgument(NamedDecl *Param,
4437                             const TemplateArgumentLoc &Arg,
4438                             NamedDecl *Template,
4439                             SourceLocation TemplateLoc,
4440                             SourceLocation RAngleLoc,
4441                             unsigned ArgumentPackIndex,
4442                           SmallVectorImpl<TemplateArgument> &Converted,
4443                             CheckTemplateArgumentKind CTAK = CTAK_Specified);
4444
4445  /// \brief Check that the given template arguments can be be provided to
4446  /// the given template, converting the arguments along the way.
4447  ///
4448  /// \param Template The template to which the template arguments are being
4449  /// provided.
4450  ///
4451  /// \param TemplateLoc The location of the template name in the source.
4452  ///
4453  /// \param TemplateArgs The list of template arguments. If the template is
4454  /// a template template parameter, this function may extend the set of
4455  /// template arguments to also include substituted, defaulted template
4456  /// arguments.
4457  ///
4458  /// \param PartialTemplateArgs True if the list of template arguments is
4459  /// intentionally partial, e.g., because we're checking just the initial
4460  /// set of template arguments.
4461  ///
4462  /// \param Converted Will receive the converted, canonicalized template
4463  /// arguments.
4464  ///
4465  ///
4466  /// \param ExpansionIntoFixedList If non-NULL, will be set true to indicate
4467  /// when the template arguments contain a pack expansion that is being
4468  /// expanded into a fixed parameter list.
4469  ///
4470  /// \returns True if an error occurred, false otherwise.
4471  bool CheckTemplateArgumentList(TemplateDecl *Template,
4472                                 SourceLocation TemplateLoc,
4473                                 TemplateArgumentListInfo &TemplateArgs,
4474                                 bool PartialTemplateArgs,
4475                           SmallVectorImpl<TemplateArgument> &Converted,
4476                                 bool *ExpansionIntoFixedList = 0);
4477
4478  bool CheckTemplateTypeArgument(TemplateTypeParmDecl *Param,
4479                                 const TemplateArgumentLoc &Arg,
4480                           SmallVectorImpl<TemplateArgument> &Converted);
4481
4482  bool CheckTemplateArgument(TemplateTypeParmDecl *Param,
4483                             TypeSourceInfo *Arg);
4484  bool CheckTemplateArgumentPointerToMember(Expr *Arg,
4485                                            TemplateArgument &Converted);
4486  ExprResult CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
4487                                   QualType InstantiatedParamType, Expr *Arg,
4488                                   TemplateArgument &Converted,
4489                               CheckTemplateArgumentKind CTAK = CTAK_Specified);
4490  bool CheckTemplateArgument(TemplateTemplateParmDecl *Param,
4491                             const TemplateArgumentLoc &Arg);
4492
4493  ExprResult
4494  BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg,
4495                                          QualType ParamType,
4496                                          SourceLocation Loc);
4497  ExprResult
4498  BuildExpressionFromIntegralTemplateArgument(const TemplateArgument &Arg,
4499                                              SourceLocation Loc);
4500
4501  /// \brief Enumeration describing how template parameter lists are compared
4502  /// for equality.
4503  enum TemplateParameterListEqualKind {
4504    /// \brief We are matching the template parameter lists of two templates
4505    /// that might be redeclarations.
4506    ///
4507    /// \code
4508    /// template<typename T> struct X;
4509    /// template<typename T> struct X;
4510    /// \endcode
4511    TPL_TemplateMatch,
4512
4513    /// \brief We are matching the template parameter lists of two template
4514    /// template parameters as part of matching the template parameter lists
4515    /// of two templates that might be redeclarations.
4516    ///
4517    /// \code
4518    /// template<template<int I> class TT> struct X;
4519    /// template<template<int Value> class Other> struct X;
4520    /// \endcode
4521    TPL_TemplateTemplateParmMatch,
4522
4523    /// \brief We are matching the template parameter lists of a template
4524    /// template argument against the template parameter lists of a template
4525    /// template parameter.
4526    ///
4527    /// \code
4528    /// template<template<int Value> class Metafun> struct X;
4529    /// template<int Value> struct integer_c;
4530    /// X<integer_c> xic;
4531    /// \endcode
4532    TPL_TemplateTemplateArgumentMatch
4533  };
4534
4535  bool TemplateParameterListsAreEqual(TemplateParameterList *New,
4536                                      TemplateParameterList *Old,
4537                                      bool Complain,
4538                                      TemplateParameterListEqualKind Kind,
4539                                      SourceLocation TemplateArgLoc
4540                                        = SourceLocation());
4541
4542  bool CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams);
4543
4544  /// \brief Called when the parser has parsed a C++ typename
4545  /// specifier, e.g., "typename T::type".
4546  ///
4547  /// \param S The scope in which this typename type occurs.
4548  /// \param TypenameLoc the location of the 'typename' keyword
4549  /// \param SS the nested-name-specifier following the typename (e.g., 'T::').
4550  /// \param II the identifier we're retrieving (e.g., 'type' in the example).
4551  /// \param IdLoc the location of the identifier.
4552  TypeResult
4553  ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
4554                    const CXXScopeSpec &SS, const IdentifierInfo &II,
4555                    SourceLocation IdLoc);
4556
4557  /// \brief Called when the parser has parsed a C++ typename
4558  /// specifier that ends in a template-id, e.g.,
4559  /// "typename MetaFun::template apply<T1, T2>".
4560  ///
4561  /// \param S The scope in which this typename type occurs.
4562  /// \param TypenameLoc the location of the 'typename' keyword
4563  /// \param SS the nested-name-specifier following the typename (e.g., 'T::').
4564  /// \param TemplateLoc the location of the 'template' keyword, if any.
4565  /// \param TemplateName The template name.
4566  /// \param TemplateNameLoc The location of the template name.
4567  /// \param LAngleLoc The location of the opening angle bracket  ('<').
4568  /// \param TemplateArgs The template arguments.
4569  /// \param RAngleLoc The location of the closing angle bracket  ('>').
4570  TypeResult
4571  ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
4572                    const CXXScopeSpec &SS,
4573                    SourceLocation TemplateLoc,
4574                    TemplateTy Template,
4575                    SourceLocation TemplateNameLoc,
4576                    SourceLocation LAngleLoc,
4577                    ASTTemplateArgsPtr TemplateArgs,
4578                    SourceLocation RAngleLoc);
4579
4580  QualType CheckTypenameType(ElaboratedTypeKeyword Keyword,
4581                             SourceLocation KeywordLoc,
4582                             NestedNameSpecifierLoc QualifierLoc,
4583                             const IdentifierInfo &II,
4584                             SourceLocation IILoc);
4585
4586  TypeSourceInfo *RebuildTypeInCurrentInstantiation(TypeSourceInfo *T,
4587                                                    SourceLocation Loc,
4588                                                    DeclarationName Name);
4589  bool RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS);
4590
4591  ExprResult RebuildExprInCurrentInstantiation(Expr *E);
4592  bool RebuildTemplateParamsInCurrentInstantiation(
4593                                                TemplateParameterList *Params);
4594
4595  std::string
4596  getTemplateArgumentBindingsText(const TemplateParameterList *Params,
4597                                  const TemplateArgumentList &Args);
4598
4599  std::string
4600  getTemplateArgumentBindingsText(const TemplateParameterList *Params,
4601                                  const TemplateArgument *Args,
4602                                  unsigned NumArgs);
4603
4604  //===--------------------------------------------------------------------===//
4605  // C++ Variadic Templates (C++0x [temp.variadic])
4606  //===--------------------------------------------------------------------===//
4607
4608  /// \brief The context in which an unexpanded parameter pack is
4609  /// being diagnosed.
4610  ///
4611  /// Note that the values of this enumeration line up with the first
4612  /// argument to the \c err_unexpanded_parameter_pack diagnostic.
4613  enum UnexpandedParameterPackContext {
4614    /// \brief An arbitrary expression.
4615    UPPC_Expression = 0,
4616
4617    /// \brief The base type of a class type.
4618    UPPC_BaseType,
4619
4620    /// \brief The type of an arbitrary declaration.
4621    UPPC_DeclarationType,
4622
4623    /// \brief The type of a data member.
4624    UPPC_DataMemberType,
4625
4626    /// \brief The size of a bit-field.
4627    UPPC_BitFieldWidth,
4628
4629    /// \brief The expression in a static assertion.
4630    UPPC_StaticAssertExpression,
4631
4632    /// \brief The fixed underlying type of an enumeration.
4633    UPPC_FixedUnderlyingType,
4634
4635    /// \brief The enumerator value.
4636    UPPC_EnumeratorValue,
4637
4638    /// \brief A using declaration.
4639    UPPC_UsingDeclaration,
4640
4641    /// \brief A friend declaration.
4642    UPPC_FriendDeclaration,
4643
4644    /// \brief A declaration qualifier.
4645    UPPC_DeclarationQualifier,
4646
4647    /// \brief An initializer.
4648    UPPC_Initializer,
4649
4650    /// \brief A default argument.
4651    UPPC_DefaultArgument,
4652
4653    /// \brief The type of a non-type template parameter.
4654    UPPC_NonTypeTemplateParameterType,
4655
4656    /// \brief The type of an exception.
4657    UPPC_ExceptionType,
4658
4659    /// \brief Partial specialization.
4660    UPPC_PartialSpecialization,
4661
4662    /// \brief Microsoft __if_exists.
4663    UPPC_IfExists,
4664
4665    /// \brief Microsoft __if_not_exists.
4666    UPPC_IfNotExists
4667};
4668
4669  /// \brief Diagnose unexpanded parameter packs.
4670  ///
4671  /// \param Loc The location at which we should emit the diagnostic.
4672  ///
4673  /// \param UPPC The context in which we are diagnosing unexpanded
4674  /// parameter packs.
4675  ///
4676  /// \param Unexpanded the set of unexpanded parameter packs.
4677  void DiagnoseUnexpandedParameterPacks(SourceLocation Loc,
4678                                        UnexpandedParameterPackContext UPPC,
4679                                  ArrayRef<UnexpandedParameterPack> Unexpanded);
4680
4681  /// \brief If the given type contains an unexpanded parameter pack,
4682  /// diagnose the error.
4683  ///
4684  /// \param Loc The source location where a diagnostc should be emitted.
4685  ///
4686  /// \param T The type that is being checked for unexpanded parameter
4687  /// packs.
4688  ///
4689  /// \returns true if an error occurred, false otherwise.
4690  bool DiagnoseUnexpandedParameterPack(SourceLocation Loc, TypeSourceInfo *T,
4691                                       UnexpandedParameterPackContext UPPC);
4692
4693  /// \brief If the given expression contains an unexpanded parameter
4694  /// pack, diagnose the error.
4695  ///
4696  /// \param E The expression that is being checked for unexpanded
4697  /// parameter packs.
4698  ///
4699  /// \returns true if an error occurred, false otherwise.
4700  bool DiagnoseUnexpandedParameterPack(Expr *E,
4701                       UnexpandedParameterPackContext UPPC = UPPC_Expression);
4702
4703  /// \brief If the given nested-name-specifier contains an unexpanded
4704  /// parameter pack, diagnose the error.
4705  ///
4706  /// \param SS The nested-name-specifier that is being checked for
4707  /// unexpanded parameter packs.
4708  ///
4709  /// \returns true if an error occurred, false otherwise.
4710  bool DiagnoseUnexpandedParameterPack(const CXXScopeSpec &SS,
4711                                       UnexpandedParameterPackContext UPPC);
4712
4713  /// \brief If the given name contains an unexpanded parameter pack,
4714  /// diagnose the error.
4715  ///
4716  /// \param NameInfo The name (with source location information) that
4717  /// is being checked for unexpanded parameter packs.
4718  ///
4719  /// \returns true if an error occurred, false otherwise.
4720  bool DiagnoseUnexpandedParameterPack(const DeclarationNameInfo &NameInfo,
4721                                       UnexpandedParameterPackContext UPPC);
4722
4723  /// \brief If the given template name contains an unexpanded parameter pack,
4724  /// diagnose the error.
4725  ///
4726  /// \param Loc The location of the template name.
4727  ///
4728  /// \param Template The template name that is being checked for unexpanded
4729  /// parameter packs.
4730  ///
4731  /// \returns true if an error occurred, false otherwise.
4732  bool DiagnoseUnexpandedParameterPack(SourceLocation Loc,
4733                                       TemplateName Template,
4734                                       UnexpandedParameterPackContext UPPC);
4735
4736  /// \brief If the given template argument contains an unexpanded parameter
4737  /// pack, diagnose the error.
4738  ///
4739  /// \param Arg The template argument that is being checked for unexpanded
4740  /// parameter packs.
4741  ///
4742  /// \returns true if an error occurred, false otherwise.
4743  bool DiagnoseUnexpandedParameterPack(TemplateArgumentLoc Arg,
4744                                       UnexpandedParameterPackContext UPPC);
4745
4746  /// \brief Collect the set of unexpanded parameter packs within the given
4747  /// template argument.
4748  ///
4749  /// \param Arg The template argument that will be traversed to find
4750  /// unexpanded parameter packs.
4751  void collectUnexpandedParameterPacks(TemplateArgument Arg,
4752                   SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
4753
4754  /// \brief Collect the set of unexpanded parameter packs within the given
4755  /// template argument.
4756  ///
4757  /// \param Arg The template argument that will be traversed to find
4758  /// unexpanded parameter packs.
4759  void collectUnexpandedParameterPacks(TemplateArgumentLoc Arg,
4760                    SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
4761
4762  /// \brief Collect the set of unexpanded parameter packs within the given
4763  /// type.
4764  ///
4765  /// \param T The type that will be traversed to find
4766  /// unexpanded parameter packs.
4767  void collectUnexpandedParameterPacks(QualType T,
4768                   SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
4769
4770  /// \brief Collect the set of unexpanded parameter packs within the given
4771  /// type.
4772  ///
4773  /// \param TL The type that will be traversed to find
4774  /// unexpanded parameter packs.
4775  void collectUnexpandedParameterPacks(TypeLoc TL,
4776                   SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
4777
4778  /// \brief Collect the set of unexpanded parameter packs within the given
4779  /// nested-name-specifier.
4780  ///
4781  /// \param SS The nested-name-specifier that will be traversed to find
4782  /// unexpanded parameter packs.
4783  void collectUnexpandedParameterPacks(CXXScopeSpec &SS,
4784                         SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
4785
4786  /// \brief Collect the set of unexpanded parameter packs within the given
4787  /// name.
4788  ///
4789  /// \param NameInfo The name that will be traversed to find
4790  /// unexpanded parameter packs.
4791  void collectUnexpandedParameterPacks(const DeclarationNameInfo &NameInfo,
4792                         SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
4793
4794  /// \brief Invoked when parsing a template argument followed by an
4795  /// ellipsis, which creates a pack expansion.
4796  ///
4797  /// \param Arg The template argument preceding the ellipsis, which
4798  /// may already be invalid.
4799  ///
4800  /// \param EllipsisLoc The location of the ellipsis.
4801  ParsedTemplateArgument ActOnPackExpansion(const ParsedTemplateArgument &Arg,
4802                                            SourceLocation EllipsisLoc);
4803
4804  /// \brief Invoked when parsing a type followed by an ellipsis, which
4805  /// creates a pack expansion.
4806  ///
4807  /// \param Type The type preceding the ellipsis, which will become
4808  /// the pattern of the pack expansion.
4809  ///
4810  /// \param EllipsisLoc The location of the ellipsis.
4811  TypeResult ActOnPackExpansion(ParsedType Type, SourceLocation EllipsisLoc);
4812
4813  /// \brief Construct a pack expansion type from the pattern of the pack
4814  /// expansion.
4815  TypeSourceInfo *CheckPackExpansion(TypeSourceInfo *Pattern,
4816                                     SourceLocation EllipsisLoc,
4817                                     llvm::Optional<unsigned> NumExpansions);
4818
4819  /// \brief Construct a pack expansion type from the pattern of the pack
4820  /// expansion.
4821  QualType CheckPackExpansion(QualType Pattern,
4822                              SourceRange PatternRange,
4823                              SourceLocation EllipsisLoc,
4824                              llvm::Optional<unsigned> NumExpansions);
4825
4826  /// \brief Invoked when parsing an expression followed by an ellipsis, which
4827  /// creates a pack expansion.
4828  ///
4829  /// \param Pattern The expression preceding the ellipsis, which will become
4830  /// the pattern of the pack expansion.
4831  ///
4832  /// \param EllipsisLoc The location of the ellipsis.
4833  ExprResult ActOnPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc);
4834
4835  /// \brief Invoked when parsing an expression followed by an ellipsis, which
4836  /// creates a pack expansion.
4837  ///
4838  /// \param Pattern The expression preceding the ellipsis, which will become
4839  /// the pattern of the pack expansion.
4840  ///
4841  /// \param EllipsisLoc The location of the ellipsis.
4842  ExprResult CheckPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc,
4843                                llvm::Optional<unsigned> NumExpansions);
4844
4845  /// \brief Determine whether we could expand a pack expansion with the
4846  /// given set of parameter packs into separate arguments by repeatedly
4847  /// transforming the pattern.
4848  ///
4849  /// \param EllipsisLoc The location of the ellipsis that identifies the
4850  /// pack expansion.
4851  ///
4852  /// \param PatternRange The source range that covers the entire pattern of
4853  /// the pack expansion.
4854  ///
4855  /// \param Unexpanded The set of unexpanded parameter packs within the
4856  /// pattern.
4857  ///
4858  /// \param NumUnexpanded The number of unexpanded parameter packs in
4859  /// \p Unexpanded.
4860  ///
4861  /// \param ShouldExpand Will be set to \c true if the transformer should
4862  /// expand the corresponding pack expansions into separate arguments. When
4863  /// set, \c NumExpansions must also be set.
4864  ///
4865  /// \param RetainExpansion Whether the caller should add an unexpanded
4866  /// pack expansion after all of the expanded arguments. This is used
4867  /// when extending explicitly-specified template argument packs per
4868  /// C++0x [temp.arg.explicit]p9.
4869  ///
4870  /// \param NumExpansions The number of separate arguments that will be in
4871  /// the expanded form of the corresponding pack expansion. This is both an
4872  /// input and an output parameter, which can be set by the caller if the
4873  /// number of expansions is known a priori (e.g., due to a prior substitution)
4874  /// and will be set by the callee when the number of expansions is known.
4875  /// The callee must set this value when \c ShouldExpand is \c true; it may
4876  /// set this value in other cases.
4877  ///
4878  /// \returns true if an error occurred (e.g., because the parameter packs
4879  /// are to be instantiated with arguments of different lengths), false
4880  /// otherwise. If false, \c ShouldExpand (and possibly \c NumExpansions)
4881  /// must be set.
4882  bool CheckParameterPacksForExpansion(SourceLocation EllipsisLoc,
4883                                       SourceRange PatternRange,
4884                             llvm::ArrayRef<UnexpandedParameterPack> Unexpanded,
4885                             const MultiLevelTemplateArgumentList &TemplateArgs,
4886                                       bool &ShouldExpand,
4887                                       bool &RetainExpansion,
4888                                       llvm::Optional<unsigned> &NumExpansions);
4889
4890  /// \brief Determine the number of arguments in the given pack expansion
4891  /// type.
4892  ///
4893  /// This routine already assumes that the pack expansion type can be
4894  /// expanded and that the number of arguments in the expansion is
4895  /// consistent across all of the unexpanded parameter packs in its pattern.
4896  unsigned getNumArgumentsInExpansion(QualType T,
4897                            const MultiLevelTemplateArgumentList &TemplateArgs);
4898
4899  /// \brief Determine whether the given declarator contains any unexpanded
4900  /// parameter packs.
4901  ///
4902  /// This routine is used by the parser to disambiguate function declarators
4903  /// with an ellipsis prior to the ')', e.g.,
4904  ///
4905  /// \code
4906  ///   void f(T...);
4907  /// \endcode
4908  ///
4909  /// To determine whether we have an (unnamed) function parameter pack or
4910  /// a variadic function.
4911  ///
4912  /// \returns true if the declarator contains any unexpanded parameter packs,
4913  /// false otherwise.
4914  bool containsUnexpandedParameterPacks(Declarator &D);
4915
4916  //===--------------------------------------------------------------------===//
4917  // C++ Template Argument Deduction (C++ [temp.deduct])
4918  //===--------------------------------------------------------------------===//
4919
4920  /// \brief Describes the result of template argument deduction.
4921  ///
4922  /// The TemplateDeductionResult enumeration describes the result of
4923  /// template argument deduction, as returned from
4924  /// DeduceTemplateArguments(). The separate TemplateDeductionInfo
4925  /// structure provides additional information about the results of
4926  /// template argument deduction, e.g., the deduced template argument
4927  /// list (if successful) or the specific template parameters or
4928  /// deduced arguments that were involved in the failure.
4929  enum TemplateDeductionResult {
4930    /// \brief Template argument deduction was successful.
4931    TDK_Success = 0,
4932    /// \brief Template argument deduction exceeded the maximum template
4933    /// instantiation depth (which has already been diagnosed).
4934    TDK_InstantiationDepth,
4935    /// \brief Template argument deduction did not deduce a value
4936    /// for every template parameter.
4937    TDK_Incomplete,
4938    /// \brief Template argument deduction produced inconsistent
4939    /// deduced values for the given template parameter.
4940    TDK_Inconsistent,
4941    /// \brief Template argument deduction failed due to inconsistent
4942    /// cv-qualifiers on a template parameter type that would
4943    /// otherwise be deduced, e.g., we tried to deduce T in "const T"
4944    /// but were given a non-const "X".
4945    TDK_Underqualified,
4946    /// \brief Substitution of the deduced template argument values
4947    /// resulted in an error.
4948    TDK_SubstitutionFailure,
4949    /// \brief Substitution of the deduced template argument values
4950    /// into a non-deduced context produced a type or value that
4951    /// produces a type that does not match the original template
4952    /// arguments provided.
4953    TDK_NonDeducedMismatch,
4954    /// \brief When performing template argument deduction for a function
4955    /// template, there were too many call arguments.
4956    TDK_TooManyArguments,
4957    /// \brief When performing template argument deduction for a function
4958    /// template, there were too few call arguments.
4959    TDK_TooFewArguments,
4960    /// \brief The explicitly-specified template arguments were not valid
4961    /// template arguments for the given template.
4962    TDK_InvalidExplicitArguments,
4963    /// \brief The arguments included an overloaded function name that could
4964    /// not be resolved to a suitable function.
4965    TDK_FailedOverloadResolution
4966  };
4967
4968  TemplateDeductionResult
4969  DeduceTemplateArguments(ClassTemplatePartialSpecializationDecl *Partial,
4970                          const TemplateArgumentList &TemplateArgs,
4971                          sema::TemplateDeductionInfo &Info);
4972
4973  TemplateDeductionResult
4974  SubstituteExplicitTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
4975                              TemplateArgumentListInfo &ExplicitTemplateArgs,
4976                      SmallVectorImpl<DeducedTemplateArgument> &Deduced,
4977                                 SmallVectorImpl<QualType> &ParamTypes,
4978                                      QualType *FunctionType,
4979                                      sema::TemplateDeductionInfo &Info);
4980
4981  /// brief A function argument from which we performed template argument
4982  // deduction for a call.
4983  struct OriginalCallArg {
4984    OriginalCallArg(QualType OriginalParamType,
4985                    unsigned ArgIdx,
4986                    QualType OriginalArgType)
4987      : OriginalParamType(OriginalParamType), ArgIdx(ArgIdx),
4988        OriginalArgType(OriginalArgType) { }
4989
4990    QualType OriginalParamType;
4991    unsigned ArgIdx;
4992    QualType OriginalArgType;
4993  };
4994
4995  TemplateDeductionResult
4996  FinishTemplateArgumentDeduction(FunctionTemplateDecl *FunctionTemplate,
4997                      SmallVectorImpl<DeducedTemplateArgument> &Deduced,
4998                                  unsigned NumExplicitlySpecified,
4999                                  FunctionDecl *&Specialization,
5000                                  sema::TemplateDeductionInfo &Info,
5001           SmallVectorImpl<OriginalCallArg> const *OriginalCallArgs = 0);
5002
5003  TemplateDeductionResult
5004  DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
5005                          TemplateArgumentListInfo *ExplicitTemplateArgs,
5006                          llvm::ArrayRef<Expr *> Args,
5007                          FunctionDecl *&Specialization,
5008                          sema::TemplateDeductionInfo &Info);
5009
5010  TemplateDeductionResult
5011  DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
5012                          TemplateArgumentListInfo *ExplicitTemplateArgs,
5013                          QualType ArgFunctionType,
5014                          FunctionDecl *&Specialization,
5015                          sema::TemplateDeductionInfo &Info);
5016
5017  TemplateDeductionResult
5018  DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
5019                          QualType ToType,
5020                          CXXConversionDecl *&Specialization,
5021                          sema::TemplateDeductionInfo &Info);
5022
5023  TemplateDeductionResult
5024  DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
5025                          TemplateArgumentListInfo *ExplicitTemplateArgs,
5026                          FunctionDecl *&Specialization,
5027                          sema::TemplateDeductionInfo &Info);
5028
5029  /// \brief Result type of DeduceAutoType.
5030  enum DeduceAutoResult {
5031    DAR_Succeeded,
5032    DAR_Failed,
5033    DAR_FailedAlreadyDiagnosed
5034  };
5035
5036  DeduceAutoResult DeduceAutoType(TypeSourceInfo *AutoType, Expr *&Initializer,
5037                                  TypeSourceInfo *&Result);
5038  void DiagnoseAutoDeductionFailure(VarDecl *VDecl, Expr *Init);
5039
5040  FunctionTemplateDecl *getMoreSpecializedTemplate(FunctionTemplateDecl *FT1,
5041                                                   FunctionTemplateDecl *FT2,
5042                                                   SourceLocation Loc,
5043                                           TemplatePartialOrderingContext TPOC,
5044                                                   unsigned NumCallArguments);
5045  UnresolvedSetIterator getMostSpecialized(UnresolvedSetIterator SBegin,
5046                                           UnresolvedSetIterator SEnd,
5047                                           TemplatePartialOrderingContext TPOC,
5048                                           unsigned NumCallArguments,
5049                                           SourceLocation Loc,
5050                                           const PartialDiagnostic &NoneDiag,
5051                                           const PartialDiagnostic &AmbigDiag,
5052                                        const PartialDiagnostic &CandidateDiag,
5053                                        bool Complain = true,
5054                                        QualType TargetType = QualType());
5055
5056  ClassTemplatePartialSpecializationDecl *
5057  getMoreSpecializedPartialSpecialization(
5058                                  ClassTemplatePartialSpecializationDecl *PS1,
5059                                  ClassTemplatePartialSpecializationDecl *PS2,
5060                                  SourceLocation Loc);
5061
5062  void MarkUsedTemplateParameters(const TemplateArgumentList &TemplateArgs,
5063                                  bool OnlyDeduced,
5064                                  unsigned Depth,
5065                                  llvm::SmallBitVector &Used);
5066  void MarkDeducedTemplateParameters(FunctionTemplateDecl *FunctionTemplate,
5067                                     llvm::SmallBitVector &Deduced) {
5068    return MarkDeducedTemplateParameters(Context, FunctionTemplate, Deduced);
5069  }
5070  static void MarkDeducedTemplateParameters(ASTContext &Ctx,
5071                                         FunctionTemplateDecl *FunctionTemplate,
5072                                         llvm::SmallBitVector &Deduced);
5073
5074  //===--------------------------------------------------------------------===//
5075  // C++ Template Instantiation
5076  //
5077
5078  MultiLevelTemplateArgumentList getTemplateInstantiationArgs(NamedDecl *D,
5079                                     const TemplateArgumentList *Innermost = 0,
5080                                                bool RelativeToPrimary = false,
5081                                               const FunctionDecl *Pattern = 0);
5082
5083  /// \brief A template instantiation that is currently in progress.
5084  struct ActiveTemplateInstantiation {
5085    /// \brief The kind of template instantiation we are performing
5086    enum InstantiationKind {
5087      /// We are instantiating a template declaration. The entity is
5088      /// the declaration we're instantiating (e.g., a CXXRecordDecl).
5089      TemplateInstantiation,
5090
5091      /// We are instantiating a default argument for a template
5092      /// parameter. The Entity is the template, and
5093      /// TemplateArgs/NumTemplateArguments provides the template
5094      /// arguments as specified.
5095      /// FIXME: Use a TemplateArgumentList
5096      DefaultTemplateArgumentInstantiation,
5097
5098      /// We are instantiating a default argument for a function.
5099      /// The Entity is the ParmVarDecl, and TemplateArgs/NumTemplateArgs
5100      /// provides the template arguments as specified.
5101      DefaultFunctionArgumentInstantiation,
5102
5103      /// We are substituting explicit template arguments provided for
5104      /// a function template. The entity is a FunctionTemplateDecl.
5105      ExplicitTemplateArgumentSubstitution,
5106
5107      /// We are substituting template argument determined as part of
5108      /// template argument deduction for either a class template
5109      /// partial specialization or a function template. The
5110      /// Entity is either a ClassTemplatePartialSpecializationDecl or
5111      /// a FunctionTemplateDecl.
5112      DeducedTemplateArgumentSubstitution,
5113
5114      /// We are substituting prior template arguments into a new
5115      /// template parameter. The template parameter itself is either a
5116      /// NonTypeTemplateParmDecl or a TemplateTemplateParmDecl.
5117      PriorTemplateArgumentSubstitution,
5118
5119      /// We are checking the validity of a default template argument that
5120      /// has been used when naming a template-id.
5121      DefaultTemplateArgumentChecking
5122    } Kind;
5123
5124    /// \brief The point of instantiation within the source code.
5125    SourceLocation PointOfInstantiation;
5126
5127    /// \brief The template (or partial specialization) in which we are
5128    /// performing the instantiation, for substitutions of prior template
5129    /// arguments.
5130    NamedDecl *Template;
5131
5132    /// \brief The entity that is being instantiated.
5133    uintptr_t Entity;
5134
5135    /// \brief The list of template arguments we are substituting, if they
5136    /// are not part of the entity.
5137    const TemplateArgument *TemplateArgs;
5138
5139    /// \brief The number of template arguments in TemplateArgs.
5140    unsigned NumTemplateArgs;
5141
5142    /// \brief The template deduction info object associated with the
5143    /// substitution or checking of explicit or deduced template arguments.
5144    sema::TemplateDeductionInfo *DeductionInfo;
5145
5146    /// \brief The source range that covers the construct that cause
5147    /// the instantiation, e.g., the template-id that causes a class
5148    /// template instantiation.
5149    SourceRange InstantiationRange;
5150
5151    ActiveTemplateInstantiation()
5152      : Kind(TemplateInstantiation), Template(0), Entity(0), TemplateArgs(0),
5153        NumTemplateArgs(0), DeductionInfo(0) {}
5154
5155    /// \brief Determines whether this template is an actual instantiation
5156    /// that should be counted toward the maximum instantiation depth.
5157    bool isInstantiationRecord() const;
5158
5159    friend bool operator==(const ActiveTemplateInstantiation &X,
5160                           const ActiveTemplateInstantiation &Y) {
5161      if (X.Kind != Y.Kind)
5162        return false;
5163
5164      if (X.Entity != Y.Entity)
5165        return false;
5166
5167      switch (X.Kind) {
5168      case TemplateInstantiation:
5169        return true;
5170
5171      case PriorTemplateArgumentSubstitution:
5172      case DefaultTemplateArgumentChecking:
5173        if (X.Template != Y.Template)
5174          return false;
5175
5176        // Fall through
5177
5178      case DefaultTemplateArgumentInstantiation:
5179      case ExplicitTemplateArgumentSubstitution:
5180      case DeducedTemplateArgumentSubstitution:
5181      case DefaultFunctionArgumentInstantiation:
5182        return X.TemplateArgs == Y.TemplateArgs;
5183
5184      }
5185
5186      llvm_unreachable("Invalid InstantiationKind!");
5187    }
5188
5189    friend bool operator!=(const ActiveTemplateInstantiation &X,
5190                           const ActiveTemplateInstantiation &Y) {
5191      return !(X == Y);
5192    }
5193  };
5194
5195  /// \brief List of active template instantiations.
5196  ///
5197  /// This vector is treated as a stack. As one template instantiation
5198  /// requires another template instantiation, additional
5199  /// instantiations are pushed onto the stack up to a
5200  /// user-configurable limit LangOptions::InstantiationDepth.
5201  SmallVector<ActiveTemplateInstantiation, 16>
5202    ActiveTemplateInstantiations;
5203
5204  /// \brief Whether we are in a SFINAE context that is not associated with
5205  /// template instantiation.
5206  ///
5207  /// This is used when setting up a SFINAE trap (\c see SFINAETrap) outside
5208  /// of a template instantiation or template argument deduction.
5209  bool InNonInstantiationSFINAEContext;
5210
5211  /// \brief The number of ActiveTemplateInstantiation entries in
5212  /// \c ActiveTemplateInstantiations that are not actual instantiations and,
5213  /// therefore, should not be counted as part of the instantiation depth.
5214  unsigned NonInstantiationEntries;
5215
5216  /// \brief The last template from which a template instantiation
5217  /// error or warning was produced.
5218  ///
5219  /// This value is used to suppress printing of redundant template
5220  /// instantiation backtraces when there are multiple errors in the
5221  /// same instantiation. FIXME: Does this belong in Sema? It's tough
5222  /// to implement it anywhere else.
5223  ActiveTemplateInstantiation LastTemplateInstantiationErrorContext;
5224
5225  /// \brief The current index into pack expansion arguments that will be
5226  /// used for substitution of parameter packs.
5227  ///
5228  /// The pack expansion index will be -1 to indicate that parameter packs
5229  /// should be instantiated as themselves. Otherwise, the index specifies
5230  /// which argument within the parameter pack will be used for substitution.
5231  int ArgumentPackSubstitutionIndex;
5232
5233  /// \brief RAII object used to change the argument pack substitution index
5234  /// within a \c Sema object.
5235  ///
5236  /// See \c ArgumentPackSubstitutionIndex for more information.
5237  class ArgumentPackSubstitutionIndexRAII {
5238    Sema &Self;
5239    int OldSubstitutionIndex;
5240
5241  public:
5242    ArgumentPackSubstitutionIndexRAII(Sema &Self, int NewSubstitutionIndex)
5243      : Self(Self), OldSubstitutionIndex(Self.ArgumentPackSubstitutionIndex) {
5244      Self.ArgumentPackSubstitutionIndex = NewSubstitutionIndex;
5245    }
5246
5247    ~ArgumentPackSubstitutionIndexRAII() {
5248      Self.ArgumentPackSubstitutionIndex = OldSubstitutionIndex;
5249    }
5250  };
5251
5252  friend class ArgumentPackSubstitutionRAII;
5253
5254  /// \brief The stack of calls expression undergoing template instantiation.
5255  ///
5256  /// The top of this stack is used by a fixit instantiating unresolved
5257  /// function calls to fix the AST to match the textual change it prints.
5258  SmallVector<CallExpr *, 8> CallsUndergoingInstantiation;
5259
5260  /// \brief For each declaration that involved template argument deduction, the
5261  /// set of diagnostics that were suppressed during that template argument
5262  /// deduction.
5263  ///
5264  /// FIXME: Serialize this structure to the AST file.
5265  llvm::DenseMap<Decl *, SmallVector<PartialDiagnosticAt, 1> >
5266    SuppressedDiagnostics;
5267
5268  /// \brief A stack object to be created when performing template
5269  /// instantiation.
5270  ///
5271  /// Construction of an object of type \c InstantiatingTemplate
5272  /// pushes the current instantiation onto the stack of active
5273  /// instantiations. If the size of this stack exceeds the maximum
5274  /// number of recursive template instantiations, construction
5275  /// produces an error and evaluates true.
5276  ///
5277  /// Destruction of this object will pop the named instantiation off
5278  /// the stack.
5279  struct InstantiatingTemplate {
5280    /// \brief Note that we are instantiating a class template,
5281    /// function template, or a member thereof.
5282    InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
5283                          Decl *Entity,
5284                          SourceRange InstantiationRange = SourceRange());
5285
5286    /// \brief Note that we are instantiating a default argument in a
5287    /// template-id.
5288    InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
5289                          TemplateDecl *Template,
5290                          const TemplateArgument *TemplateArgs,
5291                          unsigned NumTemplateArgs,
5292                          SourceRange InstantiationRange = SourceRange());
5293
5294    /// \brief Note that we are instantiating a default argument in a
5295    /// template-id.
5296    InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
5297                          FunctionTemplateDecl *FunctionTemplate,
5298                          const TemplateArgument *TemplateArgs,
5299                          unsigned NumTemplateArgs,
5300                          ActiveTemplateInstantiation::InstantiationKind Kind,
5301                          sema::TemplateDeductionInfo &DeductionInfo,
5302                          SourceRange InstantiationRange = SourceRange());
5303
5304    /// \brief Note that we are instantiating as part of template
5305    /// argument deduction for a class template partial
5306    /// specialization.
5307    InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
5308                          ClassTemplatePartialSpecializationDecl *PartialSpec,
5309                          const TemplateArgument *TemplateArgs,
5310                          unsigned NumTemplateArgs,
5311                          sema::TemplateDeductionInfo &DeductionInfo,
5312                          SourceRange InstantiationRange = SourceRange());
5313
5314    InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
5315                          ParmVarDecl *Param,
5316                          const TemplateArgument *TemplateArgs,
5317                          unsigned NumTemplateArgs,
5318                          SourceRange InstantiationRange = SourceRange());
5319
5320    /// \brief Note that we are substituting prior template arguments into a
5321    /// non-type or template template parameter.
5322    InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
5323                          NamedDecl *Template,
5324                          NonTypeTemplateParmDecl *Param,
5325                          const TemplateArgument *TemplateArgs,
5326                          unsigned NumTemplateArgs,
5327                          SourceRange InstantiationRange);
5328
5329    InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
5330                          NamedDecl *Template,
5331                          TemplateTemplateParmDecl *Param,
5332                          const TemplateArgument *TemplateArgs,
5333                          unsigned NumTemplateArgs,
5334                          SourceRange InstantiationRange);
5335
5336    /// \brief Note that we are checking the default template argument
5337    /// against the template parameter for a given template-id.
5338    InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
5339                          TemplateDecl *Template,
5340                          NamedDecl *Param,
5341                          const TemplateArgument *TemplateArgs,
5342                          unsigned NumTemplateArgs,
5343                          SourceRange InstantiationRange);
5344
5345
5346    /// \brief Note that we have finished instantiating this template.
5347    void Clear();
5348
5349    ~InstantiatingTemplate() { Clear(); }
5350
5351    /// \brief Determines whether we have exceeded the maximum
5352    /// recursive template instantiations.
5353    operator bool() const { return Invalid; }
5354
5355  private:
5356    Sema &SemaRef;
5357    bool Invalid;
5358    bool SavedInNonInstantiationSFINAEContext;
5359    bool CheckInstantiationDepth(SourceLocation PointOfInstantiation,
5360                                 SourceRange InstantiationRange);
5361
5362    InstantiatingTemplate(const InstantiatingTemplate&); // not implemented
5363
5364    InstantiatingTemplate&
5365    operator=(const InstantiatingTemplate&); // not implemented
5366  };
5367
5368  void PrintInstantiationStack();
5369
5370  /// \brief Determines whether we are currently in a context where
5371  /// template argument substitution failures are not considered
5372  /// errors.
5373  ///
5374  /// \returns An empty \c llvm::Optional if we're not in a SFINAE context.
5375  /// Otherwise, contains a pointer that, if non-NULL, contains the nearest
5376  /// template-deduction context object, which can be used to capture
5377  /// diagnostics that will be suppressed.
5378  llvm::Optional<sema::TemplateDeductionInfo *> isSFINAEContext() const;
5379
5380  /// \brief RAII class used to determine whether SFINAE has
5381  /// trapped any errors that occur during template argument
5382  /// deduction.`
5383  class SFINAETrap {
5384    Sema &SemaRef;
5385    unsigned PrevSFINAEErrors;
5386    bool PrevInNonInstantiationSFINAEContext;
5387    bool PrevAccessCheckingSFINAE;
5388
5389  public:
5390    explicit SFINAETrap(Sema &SemaRef, bool AccessCheckingSFINAE = false)
5391      : SemaRef(SemaRef), PrevSFINAEErrors(SemaRef.NumSFINAEErrors),
5392        PrevInNonInstantiationSFINAEContext(
5393                                      SemaRef.InNonInstantiationSFINAEContext),
5394        PrevAccessCheckingSFINAE(SemaRef.AccessCheckingSFINAE)
5395    {
5396      if (!SemaRef.isSFINAEContext())
5397        SemaRef.InNonInstantiationSFINAEContext = true;
5398      SemaRef.AccessCheckingSFINAE = AccessCheckingSFINAE;
5399    }
5400
5401    ~SFINAETrap() {
5402      SemaRef.NumSFINAEErrors = PrevSFINAEErrors;
5403      SemaRef.InNonInstantiationSFINAEContext
5404        = PrevInNonInstantiationSFINAEContext;
5405      SemaRef.AccessCheckingSFINAE = PrevAccessCheckingSFINAE;
5406    }
5407
5408    /// \brief Determine whether any SFINAE errors have been trapped.
5409    bool hasErrorOccurred() const {
5410      return SemaRef.NumSFINAEErrors > PrevSFINAEErrors;
5411    }
5412  };
5413
5414  /// \brief The current instantiation scope used to store local
5415  /// variables.
5416  LocalInstantiationScope *CurrentInstantiationScope;
5417
5418  /// \brief The number of typos corrected by CorrectTypo.
5419  unsigned TyposCorrected;
5420
5421  typedef llvm::DenseMap<IdentifierInfo *, TypoCorrection>
5422    UnqualifiedTyposCorrectedMap;
5423
5424  /// \brief A cache containing the results of typo correction for unqualified
5425  /// name lookup.
5426  ///
5427  /// The string is the string that we corrected to (which may be empty, if
5428  /// there was no correction), while the boolean will be true when the
5429  /// string represents a keyword.
5430  UnqualifiedTyposCorrectedMap UnqualifiedTyposCorrected;
5431
5432  /// \brief Worker object for performing CFG-based warnings.
5433  sema::AnalysisBasedWarnings AnalysisWarnings;
5434
5435  /// \brief An entity for which implicit template instantiation is required.
5436  ///
5437  /// The source location associated with the declaration is the first place in
5438  /// the source code where the declaration was "used". It is not necessarily
5439  /// the point of instantiation (which will be either before or after the
5440  /// namespace-scope declaration that triggered this implicit instantiation),
5441  /// However, it is the location that diagnostics should generally refer to,
5442  /// because users will need to know what code triggered the instantiation.
5443  typedef std::pair<ValueDecl *, SourceLocation> PendingImplicitInstantiation;
5444
5445  /// \brief The queue of implicit template instantiations that are required
5446  /// but have not yet been performed.
5447  std::deque<PendingImplicitInstantiation> PendingInstantiations;
5448
5449  /// \brief The queue of implicit template instantiations that are required
5450  /// and must be performed within the current local scope.
5451  ///
5452  /// This queue is only used for member functions of local classes in
5453  /// templates, which must be instantiated in the same scope as their
5454  /// enclosing function, so that they can reference function-local
5455  /// types, static variables, enumerators, etc.
5456  std::deque<PendingImplicitInstantiation> PendingLocalImplicitInstantiations;
5457
5458  void PerformPendingInstantiations(bool LocalOnly = false);
5459
5460  TypeSourceInfo *SubstType(TypeSourceInfo *T,
5461                            const MultiLevelTemplateArgumentList &TemplateArgs,
5462                            SourceLocation Loc, DeclarationName Entity);
5463
5464  QualType SubstType(QualType T,
5465                     const MultiLevelTemplateArgumentList &TemplateArgs,
5466                     SourceLocation Loc, DeclarationName Entity);
5467
5468  TypeSourceInfo *SubstType(TypeLoc TL,
5469                            const MultiLevelTemplateArgumentList &TemplateArgs,
5470                            SourceLocation Loc, DeclarationName Entity);
5471
5472  TypeSourceInfo *SubstFunctionDeclType(TypeSourceInfo *T,
5473                            const MultiLevelTemplateArgumentList &TemplateArgs,
5474                                        SourceLocation Loc,
5475                                        DeclarationName Entity);
5476  ParmVarDecl *SubstParmVarDecl(ParmVarDecl *D,
5477                            const MultiLevelTemplateArgumentList &TemplateArgs,
5478                                int indexAdjustment,
5479                                llvm::Optional<unsigned> NumExpansions,
5480                                bool ExpectParameterPack);
5481  bool SubstParmTypes(SourceLocation Loc,
5482                      ParmVarDecl **Params, unsigned NumParams,
5483                      const MultiLevelTemplateArgumentList &TemplateArgs,
5484                      SmallVectorImpl<QualType> &ParamTypes,
5485                      SmallVectorImpl<ParmVarDecl *> *OutParams = 0);
5486  ExprResult SubstExpr(Expr *E,
5487                       const MultiLevelTemplateArgumentList &TemplateArgs);
5488
5489  /// \brief Substitute the given template arguments into a list of
5490  /// expressions, expanding pack expansions if required.
5491  ///
5492  /// \param Exprs The list of expressions to substitute into.
5493  ///
5494  /// \param NumExprs The number of expressions in \p Exprs.
5495  ///
5496  /// \param IsCall Whether this is some form of call, in which case
5497  /// default arguments will be dropped.
5498  ///
5499  /// \param TemplateArgs The set of template arguments to substitute.
5500  ///
5501  /// \param Outputs Will receive all of the substituted arguments.
5502  ///
5503  /// \returns true if an error occurred, false otherwise.
5504  bool SubstExprs(Expr **Exprs, unsigned NumExprs, bool IsCall,
5505                  const MultiLevelTemplateArgumentList &TemplateArgs,
5506                  SmallVectorImpl<Expr *> &Outputs);
5507
5508  StmtResult SubstStmt(Stmt *S,
5509                       const MultiLevelTemplateArgumentList &TemplateArgs);
5510
5511  Decl *SubstDecl(Decl *D, DeclContext *Owner,
5512                  const MultiLevelTemplateArgumentList &TemplateArgs);
5513
5514  ExprResult SubstInitializer(Expr *E,
5515                       const MultiLevelTemplateArgumentList &TemplateArgs,
5516                       bool CXXDirectInit);
5517
5518  bool
5519  SubstBaseSpecifiers(CXXRecordDecl *Instantiation,
5520                      CXXRecordDecl *Pattern,
5521                      const MultiLevelTemplateArgumentList &TemplateArgs);
5522
5523  bool
5524  InstantiateClass(SourceLocation PointOfInstantiation,
5525                   CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern,
5526                   const MultiLevelTemplateArgumentList &TemplateArgs,
5527                   TemplateSpecializationKind TSK,
5528                   bool Complain = true);
5529
5530  bool InstantiateEnum(SourceLocation PointOfInstantiation,
5531                       EnumDecl *Instantiation, EnumDecl *Pattern,
5532                       const MultiLevelTemplateArgumentList &TemplateArgs,
5533                       TemplateSpecializationKind TSK);
5534
5535  struct LateInstantiatedAttribute {
5536    const Attr *TmplAttr;
5537    LocalInstantiationScope *Scope;
5538    Decl *NewDecl;
5539
5540    LateInstantiatedAttribute(const Attr *A, LocalInstantiationScope *S,
5541                              Decl *D)
5542      : TmplAttr(A), Scope(S), NewDecl(D)
5543    { }
5544  };
5545  typedef SmallVector<LateInstantiatedAttribute, 16> LateInstantiatedAttrVec;
5546
5547  void InstantiateAttrs(const MultiLevelTemplateArgumentList &TemplateArgs,
5548                        const Decl *Pattern, Decl *Inst,
5549                        LateInstantiatedAttrVec *LateAttrs = 0,
5550                        LocalInstantiationScope *OuterMostScope = 0);
5551
5552  bool
5553  InstantiateClassTemplateSpecialization(SourceLocation PointOfInstantiation,
5554                           ClassTemplateSpecializationDecl *ClassTemplateSpec,
5555                           TemplateSpecializationKind TSK,
5556                           bool Complain = true);
5557
5558  void InstantiateClassMembers(SourceLocation PointOfInstantiation,
5559                               CXXRecordDecl *Instantiation,
5560                            const MultiLevelTemplateArgumentList &TemplateArgs,
5561                               TemplateSpecializationKind TSK);
5562
5563  void InstantiateClassTemplateSpecializationMembers(
5564                                          SourceLocation PointOfInstantiation,
5565                           ClassTemplateSpecializationDecl *ClassTemplateSpec,
5566                                                TemplateSpecializationKind TSK);
5567
5568  NestedNameSpecifierLoc
5569  SubstNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS,
5570                           const MultiLevelTemplateArgumentList &TemplateArgs);
5571
5572  DeclarationNameInfo
5573  SubstDeclarationNameInfo(const DeclarationNameInfo &NameInfo,
5574                           const MultiLevelTemplateArgumentList &TemplateArgs);
5575  TemplateName
5576  SubstTemplateName(NestedNameSpecifierLoc QualifierLoc, TemplateName Name,
5577                    SourceLocation Loc,
5578                    const MultiLevelTemplateArgumentList &TemplateArgs);
5579  bool Subst(const TemplateArgumentLoc *Args, unsigned NumArgs,
5580             TemplateArgumentListInfo &Result,
5581             const MultiLevelTemplateArgumentList &TemplateArgs);
5582
5583  void InstantiateFunctionDefinition(SourceLocation PointOfInstantiation,
5584                                     FunctionDecl *Function,
5585                                     bool Recursive = false,
5586                                     bool DefinitionRequired = false);
5587  void InstantiateStaticDataMemberDefinition(
5588                                     SourceLocation PointOfInstantiation,
5589                                     VarDecl *Var,
5590                                     bool Recursive = false,
5591                                     bool DefinitionRequired = false);
5592
5593  void InstantiateMemInitializers(CXXConstructorDecl *New,
5594                                  const CXXConstructorDecl *Tmpl,
5595                            const MultiLevelTemplateArgumentList &TemplateArgs);
5596
5597  NamedDecl *FindInstantiatedDecl(SourceLocation Loc, NamedDecl *D,
5598                          const MultiLevelTemplateArgumentList &TemplateArgs);
5599  DeclContext *FindInstantiatedContext(SourceLocation Loc, DeclContext *DC,
5600                          const MultiLevelTemplateArgumentList &TemplateArgs);
5601
5602  // Objective-C declarations.
5603  enum ObjCContainerKind {
5604    OCK_None = -1,
5605    OCK_Interface = 0,
5606    OCK_Protocol,
5607    OCK_Category,
5608    OCK_ClassExtension,
5609    OCK_Implementation,
5610    OCK_CategoryImplementation
5611  };
5612  ObjCContainerKind getObjCContainerKind() const;
5613
5614  Decl *ActOnStartClassInterface(SourceLocation AtInterfaceLoc,
5615                                 IdentifierInfo *ClassName,
5616                                 SourceLocation ClassLoc,
5617                                 IdentifierInfo *SuperName,
5618                                 SourceLocation SuperLoc,
5619                                 Decl * const *ProtoRefs,
5620                                 unsigned NumProtoRefs,
5621                                 const SourceLocation *ProtoLocs,
5622                                 SourceLocation EndProtoLoc,
5623                                 AttributeList *AttrList);
5624
5625  Decl *ActOnCompatiblityAlias(
5626                    SourceLocation AtCompatibilityAliasLoc,
5627                    IdentifierInfo *AliasName,  SourceLocation AliasLocation,
5628                    IdentifierInfo *ClassName, SourceLocation ClassLocation);
5629
5630  bool CheckForwardProtocolDeclarationForCircularDependency(
5631    IdentifierInfo *PName,
5632    SourceLocation &PLoc, SourceLocation PrevLoc,
5633    const ObjCList<ObjCProtocolDecl> &PList);
5634
5635  Decl *ActOnStartProtocolInterface(
5636                    SourceLocation AtProtoInterfaceLoc,
5637                    IdentifierInfo *ProtocolName, SourceLocation ProtocolLoc,
5638                    Decl * const *ProtoRefNames, unsigned NumProtoRefs,
5639                    const SourceLocation *ProtoLocs,
5640                    SourceLocation EndProtoLoc,
5641                    AttributeList *AttrList);
5642
5643  Decl *ActOnStartCategoryInterface(SourceLocation AtInterfaceLoc,
5644                                    IdentifierInfo *ClassName,
5645                                    SourceLocation ClassLoc,
5646                                    IdentifierInfo *CategoryName,
5647                                    SourceLocation CategoryLoc,
5648                                    Decl * const *ProtoRefs,
5649                                    unsigned NumProtoRefs,
5650                                    const SourceLocation *ProtoLocs,
5651                                    SourceLocation EndProtoLoc);
5652
5653  Decl *ActOnStartClassImplementation(
5654                    SourceLocation AtClassImplLoc,
5655                    IdentifierInfo *ClassName, SourceLocation ClassLoc,
5656                    IdentifierInfo *SuperClassname,
5657                    SourceLocation SuperClassLoc);
5658
5659  Decl *ActOnStartCategoryImplementation(SourceLocation AtCatImplLoc,
5660                                         IdentifierInfo *ClassName,
5661                                         SourceLocation ClassLoc,
5662                                         IdentifierInfo *CatName,
5663                                         SourceLocation CatLoc);
5664
5665  DeclGroupPtrTy ActOnFinishObjCImplementation(Decl *ObjCImpDecl,
5666                                               ArrayRef<Decl *> Decls);
5667
5668  DeclGroupPtrTy ActOnForwardClassDeclaration(SourceLocation Loc,
5669                                     IdentifierInfo **IdentList,
5670                                     SourceLocation *IdentLocs,
5671                                     unsigned NumElts);
5672
5673  DeclGroupPtrTy ActOnForwardProtocolDeclaration(SourceLocation AtProtoclLoc,
5674                                        const IdentifierLocPair *IdentList,
5675                                        unsigned NumElts,
5676                                        AttributeList *attrList);
5677
5678  void FindProtocolDeclaration(bool WarnOnDeclarations,
5679                               const IdentifierLocPair *ProtocolId,
5680                               unsigned NumProtocols,
5681                               SmallVectorImpl<Decl *> &Protocols);
5682
5683  /// Ensure attributes are consistent with type.
5684  /// \param [in, out] Attributes The attributes to check; they will
5685  /// be modified to be consistent with \arg PropertyTy.
5686  void CheckObjCPropertyAttributes(Decl *PropertyPtrTy,
5687                                   SourceLocation Loc,
5688                                   unsigned &Attributes);
5689
5690  /// Process the specified property declaration and create decls for the
5691  /// setters and getters as needed.
5692  /// \param property The property declaration being processed
5693  /// \param DC The semantic container for the property
5694  /// \param redeclaredProperty Declaration for property if redeclared
5695  ///        in class extension.
5696  /// \param lexicalDC Container for redeclaredProperty.
5697  void ProcessPropertyDecl(ObjCPropertyDecl *property,
5698                           ObjCContainerDecl *DC,
5699                           ObjCPropertyDecl *redeclaredProperty = 0,
5700                           ObjCContainerDecl *lexicalDC = 0);
5701
5702  void DiagnosePropertyMismatch(ObjCPropertyDecl *Property,
5703                                ObjCPropertyDecl *SuperProperty,
5704                                const IdentifierInfo *Name);
5705  void ComparePropertiesInBaseAndSuper(ObjCInterfaceDecl *IDecl);
5706
5707  void CompareMethodParamsInBaseAndSuper(Decl *IDecl,
5708                                         ObjCMethodDecl *MethodDecl,
5709                                         bool IsInstance);
5710
5711  void CompareProperties(Decl *CDecl, Decl *MergeProtocols);
5712
5713  void DiagnoseClassExtensionDupMethods(ObjCCategoryDecl *CAT,
5714                                        ObjCInterfaceDecl *ID);
5715
5716  void MatchOneProtocolPropertiesInClass(Decl *CDecl,
5717                                         ObjCProtocolDecl *PDecl);
5718
5719  Decl *ActOnAtEnd(Scope *S, SourceRange AtEnd,
5720                   Decl **allMethods = 0, unsigned allNum = 0,
5721                   Decl **allProperties = 0, unsigned pNum = 0,
5722                   DeclGroupPtrTy *allTUVars = 0, unsigned tuvNum = 0);
5723
5724  Decl *ActOnProperty(Scope *S, SourceLocation AtLoc,
5725                      SourceLocation LParenLoc,
5726                      FieldDeclarator &FD, ObjCDeclSpec &ODS,
5727                      Selector GetterSel, Selector SetterSel,
5728                      bool *OverridingProperty,
5729                      tok::ObjCKeywordKind MethodImplKind,
5730                      DeclContext *lexicalDC = 0);
5731
5732  Decl *ActOnPropertyImplDecl(Scope *S,
5733                              SourceLocation AtLoc,
5734                              SourceLocation PropertyLoc,
5735                              bool ImplKind,
5736                              IdentifierInfo *PropertyId,
5737                              IdentifierInfo *PropertyIvar,
5738                              SourceLocation PropertyIvarLoc);
5739
5740  enum ObjCSpecialMethodKind {
5741    OSMK_None,
5742    OSMK_Alloc,
5743    OSMK_New,
5744    OSMK_Copy,
5745    OSMK_RetainingInit,
5746    OSMK_NonRetainingInit
5747  };
5748
5749  struct ObjCArgInfo {
5750    IdentifierInfo *Name;
5751    SourceLocation NameLoc;
5752    // The Type is null if no type was specified, and the DeclSpec is invalid
5753    // in this case.
5754    ParsedType Type;
5755    ObjCDeclSpec DeclSpec;
5756
5757    /// ArgAttrs - Attribute list for this argument.
5758    AttributeList *ArgAttrs;
5759  };
5760
5761  Decl *ActOnMethodDeclaration(
5762    Scope *S,
5763    SourceLocation BeginLoc, // location of the + or -.
5764    SourceLocation EndLoc,   // location of the ; or {.
5765    tok::TokenKind MethodType,
5766    ObjCDeclSpec &ReturnQT, ParsedType ReturnType,
5767    ArrayRef<SourceLocation> SelectorLocs, Selector Sel,
5768    // optional arguments. The number of types/arguments is obtained
5769    // from the Sel.getNumArgs().
5770    ObjCArgInfo *ArgInfo,
5771    DeclaratorChunk::ParamInfo *CParamInfo, unsigned CNumArgs, // c-style args
5772    AttributeList *AttrList, tok::ObjCKeywordKind MethodImplKind,
5773    bool isVariadic, bool MethodDefinition);
5774
5775  // Helper method for ActOnClassMethod/ActOnInstanceMethod.
5776  // Will search "local" class/category implementations for a method decl.
5777  // Will also search in class's root looking for instance method.
5778  // Returns 0 if no method is found.
5779  ObjCMethodDecl *LookupPrivateClassMethod(Selector Sel,
5780                                           ObjCInterfaceDecl *CDecl);
5781  ObjCMethodDecl *LookupPrivateInstanceMethod(Selector Sel,
5782                                              ObjCInterfaceDecl *ClassDecl);
5783  ObjCMethodDecl *LookupMethodInQualifiedType(Selector Sel,
5784                                              const ObjCObjectPointerType *OPT,
5785                                              bool IsInstance);
5786  ObjCMethodDecl *LookupMethodInObjectType(Selector Sel, QualType Ty,
5787                                           bool IsInstance);
5788
5789  bool inferObjCARCLifetime(ValueDecl *decl);
5790
5791  ExprResult
5792  HandleExprPropertyRefExpr(const ObjCObjectPointerType *OPT,
5793                            Expr *BaseExpr,
5794                            SourceLocation OpLoc,
5795                            DeclarationName MemberName,
5796                            SourceLocation MemberLoc,
5797                            SourceLocation SuperLoc, QualType SuperType,
5798                            bool Super);
5799
5800  ExprResult
5801  ActOnClassPropertyRefExpr(IdentifierInfo &receiverName,
5802                            IdentifierInfo &propertyName,
5803                            SourceLocation receiverNameLoc,
5804                            SourceLocation propertyNameLoc);
5805
5806  ObjCMethodDecl *tryCaptureObjCSelf(SourceLocation Loc);
5807
5808  /// \brief Describes the kind of message expression indicated by a message
5809  /// send that starts with an identifier.
5810  enum ObjCMessageKind {
5811    /// \brief The message is sent to 'super'.
5812    ObjCSuperMessage,
5813    /// \brief The message is an instance message.
5814    ObjCInstanceMessage,
5815    /// \brief The message is a class message, and the identifier is a type
5816    /// name.
5817    ObjCClassMessage
5818  };
5819
5820  ObjCMessageKind getObjCMessageKind(Scope *S,
5821                                     IdentifierInfo *Name,
5822                                     SourceLocation NameLoc,
5823                                     bool IsSuper,
5824                                     bool HasTrailingDot,
5825                                     ParsedType &ReceiverType);
5826
5827  ExprResult ActOnSuperMessage(Scope *S, SourceLocation SuperLoc,
5828                               Selector Sel,
5829                               SourceLocation LBracLoc,
5830                               ArrayRef<SourceLocation> SelectorLocs,
5831                               SourceLocation RBracLoc,
5832                               MultiExprArg Args);
5833
5834  ExprResult BuildClassMessage(TypeSourceInfo *ReceiverTypeInfo,
5835                               QualType ReceiverType,
5836                               SourceLocation SuperLoc,
5837                               Selector Sel,
5838                               ObjCMethodDecl *Method,
5839                               SourceLocation LBracLoc,
5840                               ArrayRef<SourceLocation> SelectorLocs,
5841                               SourceLocation RBracLoc,
5842                               MultiExprArg Args,
5843                               bool isImplicit = false);
5844
5845  ExprResult BuildClassMessageImplicit(QualType ReceiverType,
5846                                       bool isSuperReceiver,
5847                                       SourceLocation Loc,
5848                                       Selector Sel,
5849                                       ObjCMethodDecl *Method,
5850                                       MultiExprArg Args);
5851
5852  ExprResult ActOnClassMessage(Scope *S,
5853                               ParsedType Receiver,
5854                               Selector Sel,
5855                               SourceLocation LBracLoc,
5856                               ArrayRef<SourceLocation> SelectorLocs,
5857                               SourceLocation RBracLoc,
5858                               MultiExprArg Args);
5859
5860  ExprResult BuildInstanceMessage(Expr *Receiver,
5861                                  QualType ReceiverType,
5862                                  SourceLocation SuperLoc,
5863                                  Selector Sel,
5864                                  ObjCMethodDecl *Method,
5865                                  SourceLocation LBracLoc,
5866                                  ArrayRef<SourceLocation> SelectorLocs,
5867                                  SourceLocation RBracLoc,
5868                                  MultiExprArg Args,
5869                                  bool isImplicit = false);
5870
5871  ExprResult BuildInstanceMessageImplicit(Expr *Receiver,
5872                                          QualType ReceiverType,
5873                                          SourceLocation Loc,
5874                                          Selector Sel,
5875                                          ObjCMethodDecl *Method,
5876                                          MultiExprArg Args);
5877
5878  ExprResult ActOnInstanceMessage(Scope *S,
5879                                  Expr *Receiver,
5880                                  Selector Sel,
5881                                  SourceLocation LBracLoc,
5882                                  ArrayRef<SourceLocation> SelectorLocs,
5883                                  SourceLocation RBracLoc,
5884                                  MultiExprArg Args);
5885
5886  ExprResult BuildObjCBridgedCast(SourceLocation LParenLoc,
5887                                  ObjCBridgeCastKind Kind,
5888                                  SourceLocation BridgeKeywordLoc,
5889                                  TypeSourceInfo *TSInfo,
5890                                  Expr *SubExpr);
5891
5892  ExprResult ActOnObjCBridgedCast(Scope *S,
5893                                  SourceLocation LParenLoc,
5894                                  ObjCBridgeCastKind Kind,
5895                                  SourceLocation BridgeKeywordLoc,
5896                                  ParsedType Type,
5897                                  SourceLocation RParenLoc,
5898                                  Expr *SubExpr);
5899
5900  bool checkInitMethod(ObjCMethodDecl *method, QualType receiverTypeIfCall);
5901
5902  /// \brief Check whether the given new method is a valid override of the
5903  /// given overridden method, and set any properties that should be inherited.
5904  void CheckObjCMethodOverride(ObjCMethodDecl *NewMethod,
5905                               const ObjCMethodDecl *Overridden,
5906                               bool IsImplementation);
5907
5908  /// \brief Check whether the given method overrides any methods in its class,
5909  /// calling \c CheckObjCMethodOverride for each overridden method.
5910  bool CheckObjCMethodOverrides(ObjCMethodDecl *NewMethod, DeclContext *DC);
5911
5912  enum PragmaOptionsAlignKind {
5913    POAK_Native,  // #pragma options align=native
5914    POAK_Natural, // #pragma options align=natural
5915    POAK_Packed,  // #pragma options align=packed
5916    POAK_Power,   // #pragma options align=power
5917    POAK_Mac68k,  // #pragma options align=mac68k
5918    POAK_Reset    // #pragma options align=reset
5919  };
5920
5921  /// ActOnPragmaOptionsAlign - Called on well formed #pragma options align.
5922  void ActOnPragmaOptionsAlign(PragmaOptionsAlignKind Kind,
5923                               SourceLocation PragmaLoc,
5924                               SourceLocation KindLoc);
5925
5926  enum PragmaPackKind {
5927    PPK_Default, // #pragma pack([n])
5928    PPK_Show,    // #pragma pack(show), only supported by MSVC.
5929    PPK_Push,    // #pragma pack(push, [identifier], [n])
5930    PPK_Pop      // #pragma pack(pop, [identifier], [n])
5931  };
5932
5933  enum PragmaMSStructKind {
5934    PMSST_OFF,  // #pragms ms_struct off
5935    PMSST_ON    // #pragms ms_struct on
5936  };
5937
5938  /// ActOnPragmaPack - Called on well formed #pragma pack(...).
5939  void ActOnPragmaPack(PragmaPackKind Kind,
5940                       IdentifierInfo *Name,
5941                       Expr *Alignment,
5942                       SourceLocation PragmaLoc,
5943                       SourceLocation LParenLoc,
5944                       SourceLocation RParenLoc);
5945
5946  /// ActOnPragmaMSStruct - Called on well formed #pragms ms_struct [on|off].
5947  void ActOnPragmaMSStruct(PragmaMSStructKind Kind);
5948
5949  /// ActOnPragmaUnused - Called on well-formed '#pragma unused'.
5950  void ActOnPragmaUnused(const Token &Identifier,
5951                         Scope *curScope,
5952                         SourceLocation PragmaLoc);
5953
5954  /// ActOnPragmaVisibility - Called on well formed #pragma GCC visibility... .
5955  void ActOnPragmaVisibility(const IdentifierInfo* VisType,
5956                             SourceLocation PragmaLoc);
5957
5958  NamedDecl *DeclClonePragmaWeak(NamedDecl *ND, IdentifierInfo *II,
5959                                 SourceLocation Loc);
5960  void DeclApplyPragmaWeak(Scope *S, NamedDecl *ND, WeakInfo &W);
5961
5962  /// ActOnPragmaWeakID - Called on well formed #pragma weak ident.
5963  void ActOnPragmaWeakID(IdentifierInfo* WeakName,
5964                         SourceLocation PragmaLoc,
5965                         SourceLocation WeakNameLoc);
5966
5967  /// ActOnPragmaRedefineExtname - Called on well formed
5968  /// #pragma redefine_extname oldname newname.
5969  void ActOnPragmaRedefineExtname(IdentifierInfo* WeakName,
5970                                  IdentifierInfo* AliasName,
5971                                  SourceLocation PragmaLoc,
5972                                  SourceLocation WeakNameLoc,
5973                                  SourceLocation AliasNameLoc);
5974
5975  /// ActOnPragmaWeakAlias - Called on well formed #pragma weak ident = ident.
5976  void ActOnPragmaWeakAlias(IdentifierInfo* WeakName,
5977                            IdentifierInfo* AliasName,
5978                            SourceLocation PragmaLoc,
5979                            SourceLocation WeakNameLoc,
5980                            SourceLocation AliasNameLoc);
5981
5982  /// ActOnPragmaFPContract - Called on well formed
5983  /// #pragma {STDC,OPENCL} FP_CONTRACT
5984  void ActOnPragmaFPContract(tok::OnOffSwitch OOS);
5985
5986  /// AddAlignmentAttributesForRecord - Adds any needed alignment attributes to
5987  /// a the record decl, to handle '#pragma pack' and '#pragma options align'.
5988  void AddAlignmentAttributesForRecord(RecordDecl *RD);
5989
5990  /// AddMsStructLayoutForRecord - Adds ms_struct layout attribute to record.
5991  void AddMsStructLayoutForRecord(RecordDecl *RD);
5992
5993  /// FreePackedContext - Deallocate and null out PackContext.
5994  void FreePackedContext();
5995
5996  /// PushNamespaceVisibilityAttr - Note that we've entered a
5997  /// namespace with a visibility attribute.
5998  void PushNamespaceVisibilityAttr(const VisibilityAttr *Attr,
5999                                   SourceLocation Loc);
6000
6001  /// AddPushedVisibilityAttribute - If '#pragma GCC visibility' was used,
6002  /// add an appropriate visibility attribute.
6003  void AddPushedVisibilityAttribute(Decl *RD);
6004
6005  /// PopPragmaVisibility - Pop the top element of the visibility stack; used
6006  /// for '#pragma GCC visibility' and visibility attributes on namespaces.
6007  void PopPragmaVisibility(bool IsNamespaceEnd, SourceLocation EndLoc);
6008
6009  /// FreeVisContext - Deallocate and null out VisContext.
6010  void FreeVisContext();
6011
6012  /// AddCFAuditedAttribute - Check whether we're currently within
6013  /// '#pragma clang arc_cf_code_audited' and, if so, consider adding
6014  /// the appropriate attribute.
6015  void AddCFAuditedAttribute(Decl *D);
6016
6017  /// AddAlignedAttr - Adds an aligned attribute to a particular declaration.
6018  void AddAlignedAttr(SourceRange AttrRange, Decl *D, Expr *E);
6019  void AddAlignedAttr(SourceRange AttrRange, Decl *D, TypeSourceInfo *T);
6020
6021  /// \brief The kind of conversion being performed.
6022  enum CheckedConversionKind {
6023    /// \brief An implicit conversion.
6024    CCK_ImplicitConversion,
6025    /// \brief A C-style cast.
6026    CCK_CStyleCast,
6027    /// \brief A functional-style cast.
6028    CCK_FunctionalCast,
6029    /// \brief A cast other than a C-style cast.
6030    CCK_OtherCast
6031  };
6032
6033  /// ImpCastExprToType - If Expr is not of type 'Type', insert an implicit
6034  /// cast.  If there is already an implicit cast, merge into the existing one.
6035  /// If isLvalue, the result of the cast is an lvalue.
6036  ExprResult ImpCastExprToType(Expr *E, QualType Type, CastKind CK,
6037                               ExprValueKind VK = VK_RValue,
6038                               const CXXCastPath *BasePath = 0,
6039                               CheckedConversionKind CCK
6040                                  = CCK_ImplicitConversion);
6041
6042  /// ScalarTypeToBooleanCastKind - Returns the cast kind corresponding
6043  /// to the conversion from scalar type ScalarTy to the Boolean type.
6044  static CastKind ScalarTypeToBooleanCastKind(QualType ScalarTy);
6045
6046  /// IgnoredValueConversions - Given that an expression's result is
6047  /// syntactically ignored, perform any conversions that are
6048  /// required.
6049  ExprResult IgnoredValueConversions(Expr *E);
6050
6051  // UsualUnaryConversions - promotes integers (C99 6.3.1.1p2) and converts
6052  // functions and arrays to their respective pointers (C99 6.3.2.1).
6053  ExprResult UsualUnaryConversions(Expr *E);
6054
6055  // DefaultFunctionArrayConversion - converts functions and arrays
6056  // to their respective pointers (C99 6.3.2.1).
6057  ExprResult DefaultFunctionArrayConversion(Expr *E);
6058
6059  // DefaultFunctionArrayLvalueConversion - converts functions and
6060  // arrays to their respective pointers and performs the
6061  // lvalue-to-rvalue conversion.
6062  ExprResult DefaultFunctionArrayLvalueConversion(Expr *E);
6063
6064  // DefaultLvalueConversion - performs lvalue-to-rvalue conversion on
6065  // the operand.  This is DefaultFunctionArrayLvalueConversion,
6066  // except that it assumes the operand isn't of function or array
6067  // type.
6068  ExprResult DefaultLvalueConversion(Expr *E);
6069
6070  // DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
6071  // do not have a prototype. Integer promotions are performed on each
6072  // argument, and arguments that have type float are promoted to double.
6073  ExprResult DefaultArgumentPromotion(Expr *E);
6074
6075  // Used for emitting the right warning by DefaultVariadicArgumentPromotion
6076  enum VariadicCallType {
6077    VariadicFunction,
6078    VariadicBlock,
6079    VariadicMethod,
6080    VariadicConstructor,
6081    VariadicDoesNotApply
6082  };
6083
6084  /// GatherArgumentsForCall - Collector argument expressions for various
6085  /// form of call prototypes.
6086  bool GatherArgumentsForCall(SourceLocation CallLoc,
6087                              FunctionDecl *FDecl,
6088                              const FunctionProtoType *Proto,
6089                              unsigned FirstProtoArg,
6090                              Expr **Args, unsigned NumArgs,
6091                              SmallVector<Expr *, 8> &AllArgs,
6092                              VariadicCallType CallType = VariadicDoesNotApply,
6093                              bool AllowExplicit = false);
6094
6095  // DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
6096  // will warn if the resulting type is not a POD type.
6097  ExprResult DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
6098                                              FunctionDecl *FDecl);
6099
6100  // UsualArithmeticConversions - performs the UsualUnaryConversions on it's
6101  // operands and then handles various conversions that are common to binary
6102  // operators (C99 6.3.1.8). If both operands aren't arithmetic, this
6103  // routine returns the first non-arithmetic type found. The client is
6104  // responsible for emitting appropriate error diagnostics.
6105  QualType UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
6106                                      bool IsCompAssign = false);
6107
6108  /// AssignConvertType - All of the 'assignment' semantic checks return this
6109  /// enum to indicate whether the assignment was allowed.  These checks are
6110  /// done for simple assignments, as well as initialization, return from
6111  /// function, argument passing, etc.  The query is phrased in terms of a
6112  /// source and destination type.
6113  enum AssignConvertType {
6114    /// Compatible - the types are compatible according to the standard.
6115    Compatible,
6116
6117    /// PointerToInt - The assignment converts a pointer to an int, which we
6118    /// accept as an extension.
6119    PointerToInt,
6120
6121    /// IntToPointer - The assignment converts an int to a pointer, which we
6122    /// accept as an extension.
6123    IntToPointer,
6124
6125    /// FunctionVoidPointer - The assignment is between a function pointer and
6126    /// void*, which the standard doesn't allow, but we accept as an extension.
6127    FunctionVoidPointer,
6128
6129    /// IncompatiblePointer - The assignment is between two pointers types that
6130    /// are not compatible, but we accept them as an extension.
6131    IncompatiblePointer,
6132
6133    /// IncompatiblePointer - The assignment is between two pointers types which
6134    /// point to integers which have a different sign, but are otherwise
6135    /// identical. This is a subset of the above, but broken out because it's by
6136    /// far the most common case of incompatible pointers.
6137    IncompatiblePointerSign,
6138
6139    /// CompatiblePointerDiscardsQualifiers - The assignment discards
6140    /// c/v/r qualifiers, which we accept as an extension.
6141    CompatiblePointerDiscardsQualifiers,
6142
6143    /// IncompatiblePointerDiscardsQualifiers - The assignment
6144    /// discards qualifiers that we don't permit to be discarded,
6145    /// like address spaces.
6146    IncompatiblePointerDiscardsQualifiers,
6147
6148    /// IncompatibleNestedPointerQualifiers - The assignment is between two
6149    /// nested pointer types, and the qualifiers other than the first two
6150    /// levels differ e.g. char ** -> const char **, but we accept them as an
6151    /// extension.
6152    IncompatibleNestedPointerQualifiers,
6153
6154    /// IncompatibleVectors - The assignment is between two vector types that
6155    /// have the same size, which we accept as an extension.
6156    IncompatibleVectors,
6157
6158    /// IntToBlockPointer - The assignment converts an int to a block
6159    /// pointer. We disallow this.
6160    IntToBlockPointer,
6161
6162    /// IncompatibleBlockPointer - The assignment is between two block
6163    /// pointers types that are not compatible.
6164    IncompatibleBlockPointer,
6165
6166    /// IncompatibleObjCQualifiedId - The assignment is between a qualified
6167    /// id type and something else (that is incompatible with it). For example,
6168    /// "id <XXX>" = "Foo *", where "Foo *" doesn't implement the XXX protocol.
6169    IncompatibleObjCQualifiedId,
6170
6171    /// IncompatibleObjCWeakRef - Assigning a weak-unavailable object to an
6172    /// object with __weak qualifier.
6173    IncompatibleObjCWeakRef,
6174
6175    /// Incompatible - We reject this conversion outright, it is invalid to
6176    /// represent it in the AST.
6177    Incompatible
6178  };
6179
6180  /// DiagnoseAssignmentResult - Emit a diagnostic, if required, for the
6181  /// assignment conversion type specified by ConvTy.  This returns true if the
6182  /// conversion was invalid or false if the conversion was accepted.
6183  bool DiagnoseAssignmentResult(AssignConvertType ConvTy,
6184                                SourceLocation Loc,
6185                                QualType DstType, QualType SrcType,
6186                                Expr *SrcExpr, AssignmentAction Action,
6187                                bool *Complained = 0);
6188
6189  /// CheckAssignmentConstraints - Perform type checking for assignment,
6190  /// argument passing, variable initialization, and function return values.
6191  /// C99 6.5.16.
6192  AssignConvertType CheckAssignmentConstraints(SourceLocation Loc,
6193                                               QualType LHSType,
6194                                               QualType RHSType);
6195
6196  /// Check assignment constraints and prepare for a conversion of the
6197  /// RHS to the LHS type.
6198  AssignConvertType CheckAssignmentConstraints(QualType LHSType,
6199                                               ExprResult &RHS,
6200                                               CastKind &Kind);
6201
6202  // CheckSingleAssignmentConstraints - Currently used by
6203  // CheckAssignmentOperands, and ActOnReturnStmt. Prior to type checking,
6204  // this routine performs the default function/array converions.
6205  AssignConvertType CheckSingleAssignmentConstraints(QualType LHSType,
6206                                                     ExprResult &RHS,
6207                                                     bool Diagnose = true);
6208
6209  // \brief If the lhs type is a transparent union, check whether we
6210  // can initialize the transparent union with the given expression.
6211  AssignConvertType CheckTransparentUnionArgumentConstraints(QualType ArgType,
6212                                                             ExprResult &RHS);
6213
6214  bool IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType);
6215
6216  bool CheckExceptionSpecCompatibility(Expr *From, QualType ToType);
6217
6218  ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
6219                                       AssignmentAction Action,
6220                                       bool AllowExplicit = false);
6221  ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
6222                                       AssignmentAction Action,
6223                                       bool AllowExplicit,
6224                                       ImplicitConversionSequence& ICS);
6225  ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
6226                                       const ImplicitConversionSequence& ICS,
6227                                       AssignmentAction Action,
6228                                       CheckedConversionKind CCK
6229                                          = CCK_ImplicitConversion);
6230  ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
6231                                       const StandardConversionSequence& SCS,
6232                                       AssignmentAction Action,
6233                                       CheckedConversionKind CCK);
6234
6235  /// the following "Check" methods will return a valid/converted QualType
6236  /// or a null QualType (indicating an error diagnostic was issued).
6237
6238  /// type checking binary operators (subroutines of CreateBuiltinBinOp).
6239  QualType InvalidOperands(SourceLocation Loc, ExprResult &LHS,
6240                           ExprResult &RHS);
6241  QualType CheckPointerToMemberOperands( // C++ 5.5
6242    ExprResult &LHS, ExprResult &RHS, ExprValueKind &VK,
6243    SourceLocation OpLoc, bool isIndirect);
6244  QualType CheckMultiplyDivideOperands( // C99 6.5.5
6245    ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign,
6246    bool IsDivide);
6247  QualType CheckRemainderOperands( // C99 6.5.5
6248    ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
6249    bool IsCompAssign = false);
6250  QualType CheckAdditionOperands( // C99 6.5.6
6251    ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc,
6252    QualType* CompLHSTy = 0);
6253  QualType CheckSubtractionOperands( // C99 6.5.6
6254    ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
6255    QualType* CompLHSTy = 0);
6256  QualType CheckShiftOperands( // C99 6.5.7
6257    ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc,
6258    bool IsCompAssign = false);
6259  QualType CheckCompareOperands( // C99 6.5.8/9
6260    ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned OpaqueOpc,
6261                                bool isRelational);
6262  QualType CheckBitwiseOperands( // C99 6.5.[10...12]
6263    ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
6264    bool IsCompAssign = false);
6265  QualType CheckLogicalOperands( // C99 6.5.[13,14]
6266    ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc);
6267  // CheckAssignmentOperands is used for both simple and compound assignment.
6268  // For simple assignment, pass both expressions and a null converted type.
6269  // For compound assignment, pass both expressions and the converted type.
6270  QualType CheckAssignmentOperands( // C99 6.5.16.[1,2]
6271    Expr *LHSExpr, ExprResult &RHS, SourceLocation Loc, QualType CompoundType);
6272
6273  ExprResult checkPseudoObjectIncDec(Scope *S, SourceLocation OpLoc,
6274                                     UnaryOperatorKind Opcode, Expr *Op);
6275  ExprResult checkPseudoObjectAssignment(Scope *S, SourceLocation OpLoc,
6276                                         BinaryOperatorKind Opcode,
6277                                         Expr *LHS, Expr *RHS);
6278  ExprResult checkPseudoObjectRValue(Expr *E);
6279  Expr *recreateSyntacticForm(PseudoObjectExpr *E);
6280
6281  QualType CheckConditionalOperands( // C99 6.5.15
6282    ExprResult &Cond, ExprResult &LHS, ExprResult &RHS,
6283    ExprValueKind &VK, ExprObjectKind &OK, SourceLocation QuestionLoc);
6284  QualType CXXCheckConditionalOperands( // C++ 5.16
6285    ExprResult &cond, ExprResult &lhs, ExprResult &rhs,
6286    ExprValueKind &VK, ExprObjectKind &OK, SourceLocation questionLoc);
6287  QualType FindCompositePointerType(SourceLocation Loc, Expr *&E1, Expr *&E2,
6288                                    bool *NonStandardCompositeType = 0);
6289  QualType FindCompositePointerType(SourceLocation Loc,
6290                                    ExprResult &E1, ExprResult &E2,
6291                                    bool *NonStandardCompositeType = 0) {
6292    Expr *E1Tmp = E1.take(), *E2Tmp = E2.take();
6293    QualType Composite = FindCompositePointerType(Loc, E1Tmp, E2Tmp,
6294                                                  NonStandardCompositeType);
6295    E1 = Owned(E1Tmp);
6296    E2 = Owned(E2Tmp);
6297    return Composite;
6298  }
6299
6300  QualType FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
6301                                        SourceLocation QuestionLoc);
6302
6303  bool DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
6304                                  SourceLocation QuestionLoc);
6305
6306  /// type checking for vector binary operators.
6307  QualType CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
6308                               SourceLocation Loc, bool IsCompAssign);
6309  QualType GetSignedVectorType(QualType V);
6310  QualType CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
6311                                      SourceLocation Loc, bool isRelational);
6312  QualType CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
6313                                      SourceLocation Loc);
6314
6315  /// type checking declaration initializers (C99 6.7.8)
6316  bool CheckForConstantInitializer(Expr *e, QualType t);
6317
6318  // type checking C++ declaration initializers (C++ [dcl.init]).
6319
6320  /// ReferenceCompareResult - Expresses the result of comparing two
6321  /// types (cv1 T1 and cv2 T2) to determine their compatibility for the
6322  /// purposes of initialization by reference (C++ [dcl.init.ref]p4).
6323  enum ReferenceCompareResult {
6324    /// Ref_Incompatible - The two types are incompatible, so direct
6325    /// reference binding is not possible.
6326    Ref_Incompatible = 0,
6327    /// Ref_Related - The two types are reference-related, which means
6328    /// that their unqualified forms (T1 and T2) are either the same
6329    /// or T1 is a base class of T2.
6330    Ref_Related,
6331    /// Ref_Compatible_With_Added_Qualification - The two types are
6332    /// reference-compatible with added qualification, meaning that
6333    /// they are reference-compatible and the qualifiers on T1 (cv1)
6334    /// are greater than the qualifiers on T2 (cv2).
6335    Ref_Compatible_With_Added_Qualification,
6336    /// Ref_Compatible - The two types are reference-compatible and
6337    /// have equivalent qualifiers (cv1 == cv2).
6338    Ref_Compatible
6339  };
6340
6341  ReferenceCompareResult CompareReferenceRelationship(SourceLocation Loc,
6342                                                      QualType T1, QualType T2,
6343                                                      bool &DerivedToBase,
6344                                                      bool &ObjCConversion,
6345                                                bool &ObjCLifetimeConversion);
6346
6347  ExprResult checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
6348                                 Expr *CastExpr, CastKind &CastKind,
6349                                 ExprValueKind &VK, CXXCastPath &Path);
6350
6351  /// \brief Force an expression with unknown-type to an expression of the
6352  /// given type.
6353  ExprResult forceUnknownAnyToType(Expr *E, QualType ToType);
6354
6355  // CheckVectorCast - check type constraints for vectors.
6356  // Since vectors are an extension, there are no C standard reference for this.
6357  // We allow casting between vectors and integer datatypes of the same size.
6358  // returns true if the cast is invalid
6359  bool CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
6360                       CastKind &Kind);
6361
6362  // CheckExtVectorCast - check type constraints for extended vectors.
6363  // Since vectors are an extension, there are no C standard reference for this.
6364  // We allow casting between vectors and integer datatypes of the same size,
6365  // or vectors and the element type of that vector.
6366  // returns the cast expr
6367  ExprResult CheckExtVectorCast(SourceRange R, QualType DestTy, Expr *CastExpr,
6368                                CastKind &Kind);
6369
6370  ExprResult BuildCXXFunctionalCastExpr(TypeSourceInfo *TInfo,
6371                                        SourceLocation LParenLoc,
6372                                        Expr *CastExpr,
6373                                        SourceLocation RParenLoc);
6374
6375  enum ARCConversionResult { ACR_okay, ACR_unbridged };
6376
6377  /// \brief Checks for invalid conversions and casts between
6378  /// retainable pointers and other pointer kinds.
6379  ARCConversionResult CheckObjCARCConversion(SourceRange castRange,
6380                                             QualType castType, Expr *&op,
6381                                             CheckedConversionKind CCK);
6382
6383  Expr *stripARCUnbridgedCast(Expr *e);
6384  void diagnoseARCUnbridgedCast(Expr *e);
6385
6386  bool CheckObjCARCUnavailableWeakConversion(QualType castType,
6387                                             QualType ExprType);
6388
6389  /// checkRetainCycles - Check whether an Objective-C message send
6390  /// might create an obvious retain cycle.
6391  void checkRetainCycles(ObjCMessageExpr *msg);
6392  void checkRetainCycles(Expr *receiver, Expr *argument);
6393
6394  /// checkUnsafeAssigns - Check whether +1 expr is being assigned
6395  /// to weak/__unsafe_unretained type.
6396  bool checkUnsafeAssigns(SourceLocation Loc, QualType LHS, Expr *RHS);
6397
6398  /// checkUnsafeExprAssigns - Check whether +1 expr is being assigned
6399  /// to weak/__unsafe_unretained expression.
6400  void checkUnsafeExprAssigns(SourceLocation Loc, Expr *LHS, Expr *RHS);
6401
6402  /// CheckMessageArgumentTypes - Check types in an Obj-C message send.
6403  /// \param Method - May be null.
6404  /// \param [out] ReturnType - The return type of the send.
6405  /// \return true iff there were any incompatible types.
6406  bool CheckMessageArgumentTypes(QualType ReceiverType,
6407                                 Expr **Args, unsigned NumArgs, Selector Sel,
6408                                 ObjCMethodDecl *Method, bool isClassMessage,
6409                                 bool isSuperMessage,
6410                                 SourceLocation lbrac, SourceLocation rbrac,
6411                                 QualType &ReturnType, ExprValueKind &VK);
6412
6413  /// \brief Determine the result of a message send expression based on
6414  /// the type of the receiver, the method expected to receive the message,
6415  /// and the form of the message send.
6416  QualType getMessageSendResultType(QualType ReceiverType,
6417                                    ObjCMethodDecl *Method,
6418                                    bool isClassMessage, bool isSuperMessage);
6419
6420  /// \brief If the given expression involves a message send to a method
6421  /// with a related result type, emit a note describing what happened.
6422  void EmitRelatedResultTypeNote(const Expr *E);
6423
6424  /// CheckBooleanCondition - Diagnose problems involving the use of
6425  /// the given expression as a boolean condition (e.g. in an if
6426  /// statement).  Also performs the standard function and array
6427  /// decays, possibly changing the input variable.
6428  ///
6429  /// \param Loc - A location associated with the condition, e.g. the
6430  /// 'if' keyword.
6431  /// \return true iff there were any errors
6432  ExprResult CheckBooleanCondition(Expr *E, SourceLocation Loc);
6433
6434  ExprResult ActOnBooleanCondition(Scope *S, SourceLocation Loc,
6435                                   Expr *SubExpr);
6436
6437  /// DiagnoseAssignmentAsCondition - Given that an expression is
6438  /// being used as a boolean condition, warn if it's an assignment.
6439  void DiagnoseAssignmentAsCondition(Expr *E);
6440
6441  /// \brief Redundant parentheses over an equality comparison can indicate
6442  /// that the user intended an assignment used as condition.
6443  void DiagnoseEqualityWithExtraParens(ParenExpr *ParenE);
6444
6445  /// CheckCXXBooleanCondition - Returns true if conversion to bool is invalid.
6446  ExprResult CheckCXXBooleanCondition(Expr *CondExpr);
6447
6448  /// ConvertIntegerToTypeWarnOnOverflow - Convert the specified APInt to have
6449  /// the specified width and sign.  If an overflow occurs, detect it and emit
6450  /// the specified diagnostic.
6451  void ConvertIntegerToTypeWarnOnOverflow(llvm::APSInt &OldVal,
6452                                          unsigned NewWidth, bool NewSign,
6453                                          SourceLocation Loc, unsigned DiagID);
6454
6455  /// Checks that the Objective-C declaration is declared in the global scope.
6456  /// Emits an error and marks the declaration as invalid if it's not declared
6457  /// in the global scope.
6458  bool CheckObjCDeclScope(Decl *D);
6459
6460  /// VerifyIntegerConstantExpression - Verifies that an expression is an ICE,
6461  /// and reports the appropriate diagnostics. Returns false on success.
6462  /// Can optionally return the value of the expression.
6463  ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
6464                                             PartialDiagnostic Diag,
6465                                             bool AllowFold,
6466                                             PartialDiagnostic FoldDiag);
6467  ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
6468                                             PartialDiagnostic Diag,
6469                                             bool AllowFold = true) {
6470    return VerifyIntegerConstantExpression(E, Result, Diag, AllowFold,
6471                                           PDiag(0));
6472  }
6473  ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result = 0);
6474
6475  /// VerifyBitField - verifies that a bit field expression is an ICE and has
6476  /// the correct width, and that the field type is valid.
6477  /// Returns false on success.
6478  /// Can optionally return whether the bit-field is of width 0
6479  ExprResult VerifyBitField(SourceLocation FieldLoc, IdentifierInfo *FieldName,
6480                            QualType FieldTy, Expr *BitWidth,
6481                            bool *ZeroWidth = 0);
6482
6483  enum CUDAFunctionTarget {
6484    CFT_Device,
6485    CFT_Global,
6486    CFT_Host,
6487    CFT_HostDevice
6488  };
6489
6490  CUDAFunctionTarget IdentifyCUDATarget(const FunctionDecl *D);
6491
6492  bool CheckCUDATarget(CUDAFunctionTarget CallerTarget,
6493                       CUDAFunctionTarget CalleeTarget);
6494
6495  bool CheckCUDATarget(const FunctionDecl *Caller, const FunctionDecl *Callee) {
6496    return CheckCUDATarget(IdentifyCUDATarget(Caller),
6497                           IdentifyCUDATarget(Callee));
6498  }
6499
6500  /// \name Code completion
6501  //@{
6502  /// \brief Describes the context in which code completion occurs.
6503  enum ParserCompletionContext {
6504    /// \brief Code completion occurs at top-level or namespace context.
6505    PCC_Namespace,
6506    /// \brief Code completion occurs within a class, struct, or union.
6507    PCC_Class,
6508    /// \brief Code completion occurs within an Objective-C interface, protocol,
6509    /// or category.
6510    PCC_ObjCInterface,
6511    /// \brief Code completion occurs within an Objective-C implementation or
6512    /// category implementation
6513    PCC_ObjCImplementation,
6514    /// \brief Code completion occurs within the list of instance variables
6515    /// in an Objective-C interface, protocol, category, or implementation.
6516    PCC_ObjCInstanceVariableList,
6517    /// \brief Code completion occurs following one or more template
6518    /// headers.
6519    PCC_Template,
6520    /// \brief Code completion occurs following one or more template
6521    /// headers within a class.
6522    PCC_MemberTemplate,
6523    /// \brief Code completion occurs within an expression.
6524    PCC_Expression,
6525    /// \brief Code completion occurs within a statement, which may
6526    /// also be an expression or a declaration.
6527    PCC_Statement,
6528    /// \brief Code completion occurs at the beginning of the
6529    /// initialization statement (or expression) in a for loop.
6530    PCC_ForInit,
6531    /// \brief Code completion occurs within the condition of an if,
6532    /// while, switch, or for statement.
6533    PCC_Condition,
6534    /// \brief Code completion occurs within the body of a function on a
6535    /// recovery path, where we do not have a specific handle on our position
6536    /// in the grammar.
6537    PCC_RecoveryInFunction,
6538    /// \brief Code completion occurs where only a type is permitted.
6539    PCC_Type,
6540    /// \brief Code completion occurs in a parenthesized expression, which
6541    /// might also be a type cast.
6542    PCC_ParenthesizedExpression,
6543    /// \brief Code completion occurs within a sequence of declaration
6544    /// specifiers within a function, method, or block.
6545    PCC_LocalDeclarationSpecifiers
6546  };
6547
6548  void CodeCompleteModuleImport(SourceLocation ImportLoc, ModuleIdPath Path);
6549  void CodeCompleteOrdinaryName(Scope *S,
6550                                ParserCompletionContext CompletionContext);
6551  void CodeCompleteDeclSpec(Scope *S, DeclSpec &DS,
6552                            bool AllowNonIdentifiers,
6553                            bool AllowNestedNameSpecifiers);
6554
6555  struct CodeCompleteExpressionData;
6556  void CodeCompleteExpression(Scope *S,
6557                              const CodeCompleteExpressionData &Data);
6558  void CodeCompleteMemberReferenceExpr(Scope *S, Expr *Base,
6559                                       SourceLocation OpLoc,
6560                                       bool IsArrow);
6561  void CodeCompletePostfixExpression(Scope *S, ExprResult LHS);
6562  void CodeCompleteTag(Scope *S, unsigned TagSpec);
6563  void CodeCompleteTypeQualifiers(DeclSpec &DS);
6564  void CodeCompleteCase(Scope *S);
6565  void CodeCompleteCall(Scope *S, Expr *Fn, llvm::ArrayRef<Expr *> Args);
6566  void CodeCompleteInitializer(Scope *S, Decl *D);
6567  void CodeCompleteReturn(Scope *S);
6568  void CodeCompleteAfterIf(Scope *S);
6569  void CodeCompleteAssignmentRHS(Scope *S, Expr *LHS);
6570
6571  void CodeCompleteQualifiedId(Scope *S, CXXScopeSpec &SS,
6572                               bool EnteringContext);
6573  void CodeCompleteUsing(Scope *S);
6574  void CodeCompleteUsingDirective(Scope *S);
6575  void CodeCompleteNamespaceDecl(Scope *S);
6576  void CodeCompleteNamespaceAliasDecl(Scope *S);
6577  void CodeCompleteOperatorName(Scope *S);
6578  void CodeCompleteConstructorInitializer(Decl *Constructor,
6579                                          CXXCtorInitializer** Initializers,
6580                                          unsigned NumInitializers);
6581  void CodeCompleteLambdaIntroducer(Scope *S, LambdaIntroducer &Intro,
6582                                    bool AfterAmpersand);
6583
6584  void CodeCompleteObjCAtDirective(Scope *S);
6585  void CodeCompleteObjCAtVisibility(Scope *S);
6586  void CodeCompleteObjCAtStatement(Scope *S);
6587  void CodeCompleteObjCAtExpression(Scope *S);
6588  void CodeCompleteObjCPropertyFlags(Scope *S, ObjCDeclSpec &ODS);
6589  void CodeCompleteObjCPropertyGetter(Scope *S);
6590  void CodeCompleteObjCPropertySetter(Scope *S);
6591  void CodeCompleteObjCPassingType(Scope *S, ObjCDeclSpec &DS,
6592                                   bool IsParameter);
6593  void CodeCompleteObjCMessageReceiver(Scope *S);
6594  void CodeCompleteObjCSuperMessage(Scope *S, SourceLocation SuperLoc,
6595                                    IdentifierInfo **SelIdents,
6596                                    unsigned NumSelIdents,
6597                                    bool AtArgumentExpression);
6598  void CodeCompleteObjCClassMessage(Scope *S, ParsedType Receiver,
6599                                    IdentifierInfo **SelIdents,
6600                                    unsigned NumSelIdents,
6601                                    bool AtArgumentExpression,
6602                                    bool IsSuper = false);
6603  void CodeCompleteObjCInstanceMessage(Scope *S, Expr *Receiver,
6604                                       IdentifierInfo **SelIdents,
6605                                       unsigned NumSelIdents,
6606                                       bool AtArgumentExpression,
6607                                       ObjCInterfaceDecl *Super = 0);
6608  void CodeCompleteObjCForCollection(Scope *S,
6609                                     DeclGroupPtrTy IterationVar);
6610  void CodeCompleteObjCSelector(Scope *S,
6611                                IdentifierInfo **SelIdents,
6612                                unsigned NumSelIdents);
6613  void CodeCompleteObjCProtocolReferences(IdentifierLocPair *Protocols,
6614                                          unsigned NumProtocols);
6615  void CodeCompleteObjCProtocolDecl(Scope *S);
6616  void CodeCompleteObjCInterfaceDecl(Scope *S);
6617  void CodeCompleteObjCSuperclass(Scope *S,
6618                                  IdentifierInfo *ClassName,
6619                                  SourceLocation ClassNameLoc);
6620  void CodeCompleteObjCImplementationDecl(Scope *S);
6621  void CodeCompleteObjCInterfaceCategory(Scope *S,
6622                                         IdentifierInfo *ClassName,
6623                                         SourceLocation ClassNameLoc);
6624  void CodeCompleteObjCImplementationCategory(Scope *S,
6625                                              IdentifierInfo *ClassName,
6626                                              SourceLocation ClassNameLoc);
6627  void CodeCompleteObjCPropertyDefinition(Scope *S);
6628  void CodeCompleteObjCPropertySynthesizeIvar(Scope *S,
6629                                              IdentifierInfo *PropertyName);
6630  void CodeCompleteObjCMethodDecl(Scope *S,
6631                                  bool IsInstanceMethod,
6632                                  ParsedType ReturnType);
6633  void CodeCompleteObjCMethodDeclSelector(Scope *S,
6634                                          bool IsInstanceMethod,
6635                                          bool AtParameterName,
6636                                          ParsedType ReturnType,
6637                                          IdentifierInfo **SelIdents,
6638                                          unsigned NumSelIdents);
6639  void CodeCompletePreprocessorDirective(bool InConditional);
6640  void CodeCompleteInPreprocessorConditionalExclusion(Scope *S);
6641  void CodeCompletePreprocessorMacroName(bool IsDefinition);
6642  void CodeCompletePreprocessorExpression();
6643  void CodeCompletePreprocessorMacroArgument(Scope *S,
6644                                             IdentifierInfo *Macro,
6645                                             MacroInfo *MacroInfo,
6646                                             unsigned Argument);
6647  void CodeCompleteNaturalLanguage();
6648  void GatherGlobalCodeCompletions(CodeCompletionAllocator &Allocator,
6649                  SmallVectorImpl<CodeCompletionResult> &Results);
6650  //@}
6651
6652  //===--------------------------------------------------------------------===//
6653  // Extra semantic analysis beyond the C type system
6654
6655public:
6656  SourceLocation getLocationOfStringLiteralByte(const StringLiteral *SL,
6657                                                unsigned ByteNo) const;
6658
6659private:
6660  void CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
6661                        const ArraySubscriptExpr *ASE=0,
6662                        bool AllowOnePastEnd=true, bool IndexNegated=false);
6663  void CheckArrayAccess(const Expr *E);
6664  bool CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall);
6665  bool CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation loc,
6666                           Expr **Args, unsigned NumArgs);
6667  bool CheckBlockCall(NamedDecl *NDecl, CallExpr *TheCall);
6668
6669  bool CheckObjCString(Expr *Arg);
6670
6671  ExprResult CheckBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
6672  bool CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
6673
6674  bool SemaBuiltinVAStart(CallExpr *TheCall);
6675  bool SemaBuiltinUnorderedCompare(CallExpr *TheCall);
6676  bool SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs);
6677
6678public:
6679  // Used by C++ template instantiation.
6680  ExprResult SemaBuiltinShuffleVector(CallExpr *TheCall);
6681
6682private:
6683  bool SemaBuiltinPrefetch(CallExpr *TheCall);
6684  bool SemaBuiltinObjectSize(CallExpr *TheCall);
6685  bool SemaBuiltinLongjmp(CallExpr *TheCall);
6686  ExprResult SemaBuiltinAtomicOverloaded(ExprResult TheCallResult);
6687  ExprResult SemaAtomicOpsOverloaded(ExprResult TheCallResult,
6688                                     AtomicExpr::AtomicOp Op);
6689  bool SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
6690                              llvm::APSInt &Result);
6691
6692  enum FormatStringType {
6693    FST_Scanf,
6694    FST_Printf,
6695    FST_NSString,
6696    FST_Strftime,
6697    FST_Strfmon,
6698    FST_Kprintf,
6699    FST_Unknown
6700  };
6701  static FormatStringType GetFormatStringType(const FormatAttr *Format);
6702  bool SemaCheckStringLiteral(const Expr *E, Expr **Args, unsigned NumArgs,
6703                              bool HasVAListArg, unsigned format_idx,
6704                              unsigned firstDataArg, FormatStringType Type,
6705                              bool inFunctionCall = true);
6706
6707  void CheckFormatString(const StringLiteral *FExpr, const Expr *OrigFormatExpr,
6708                         Expr **Args, unsigned NumArgs, bool HasVAListArg,
6709                         unsigned format_idx, unsigned firstDataArg,
6710                         FormatStringType Type, bool inFunctionCall);
6711
6712  void CheckFormatArguments(const FormatAttr *Format, CallExpr *TheCall);
6713  void CheckFormatArguments(const FormatAttr *Format, Expr **Args,
6714                            unsigned NumArgs, bool IsCXXMember,
6715                            SourceLocation Loc, SourceRange Range);
6716  void CheckFormatArguments(Expr **Args, unsigned NumArgs,
6717                            bool HasVAListArg, unsigned format_idx,
6718                            unsigned firstDataArg, FormatStringType Type,
6719                            SourceLocation Loc, SourceRange range);
6720
6721  void CheckNonNullArguments(const NonNullAttr *NonNull,
6722                             const Expr * const *ExprArgs,
6723                             SourceLocation CallSiteLoc);
6724
6725  void CheckMemaccessArguments(const CallExpr *Call,
6726                               unsigned BId,
6727                               IdentifierInfo *FnName);
6728
6729  void CheckStrlcpycatArguments(const CallExpr *Call,
6730                                IdentifierInfo *FnName);
6731
6732  void CheckStrncatArguments(const CallExpr *Call,
6733                             IdentifierInfo *FnName);
6734
6735  void CheckReturnStackAddr(Expr *RetValExp, QualType lhsType,
6736                            SourceLocation ReturnLoc);
6737  void CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr* RHS);
6738  void CheckImplicitConversions(Expr *E, SourceLocation CC = SourceLocation());
6739
6740  void CheckBitFieldInitialization(SourceLocation InitLoc, FieldDecl *Field,
6741                                   Expr *Init);
6742
6743  /// \brief The parser's current scope.
6744  ///
6745  /// The parser maintains this state here.
6746  Scope *CurScope;
6747
6748protected:
6749  friend class Parser;
6750  friend class InitializationSequence;
6751  friend class ASTReader;
6752  friend class ASTWriter;
6753
6754public:
6755  /// \brief Retrieve the parser's current scope.
6756  ///
6757  /// This routine must only be used when it is certain that semantic analysis
6758  /// and the parser are in precisely the same context, which is not the case
6759  /// when, e.g., we are performing any kind of template instantiation.
6760  /// Therefore, the only safe places to use this scope are in the parser
6761  /// itself and in routines directly invoked from the parser and *never* from
6762  /// template substitution or instantiation.
6763  Scope *getCurScope() const { return CurScope; }
6764
6765  Decl *getObjCDeclContext() const;
6766
6767  DeclContext *getCurLexicalContext() const {
6768    return OriginalLexicalContext ? OriginalLexicalContext : CurContext;
6769  }
6770
6771  AvailabilityResult getCurContextAvailability() const;
6772};
6773
6774/// \brief RAII object that enters a new expression evaluation context.
6775class EnterExpressionEvaluationContext {
6776  Sema &Actions;
6777
6778public:
6779  EnterExpressionEvaluationContext(Sema &Actions,
6780                                   Sema::ExpressionEvaluationContext NewContext,
6781                                   Decl *LambdaContextDecl = 0,
6782                                   bool IsDecltype = false)
6783    : Actions(Actions) {
6784    Actions.PushExpressionEvaluationContext(NewContext, LambdaContextDecl,
6785                                            IsDecltype);
6786  }
6787
6788  ~EnterExpressionEvaluationContext() {
6789    Actions.PopExpressionEvaluationContext();
6790  }
6791};
6792
6793}  // end namespace clang
6794
6795#endif
6796