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