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