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