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