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