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