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