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