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