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