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