Sema.h revision 0320a1d7b3305d1aef36ee68b77bebe170e1d30a
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/AST/Expr.h"
24#include "clang/AST/DeclarationName.h"
25#include "clang/AST/ExternalASTSource.h"
26#include "clang/AST/TypeLoc.h"
27#include "clang/Basic/Specifiers.h"
28#include "clang/Basic/TemplateKinds.h"
29#include "clang/Basic/TypeTraits.h"
30#include "clang/Basic/ExpressionTraits.h"
31#include "llvm/ADT/OwningPtr.h"
32#include "llvm/ADT/SmallPtrSet.h"
33#include "llvm/ADT/SmallVector.h"
34#include <deque>
35#include <string>
36
37namespace llvm {
38  class APSInt;
39  template <typename ValueT> struct DenseMapInfo;
40  template <typename ValueT, typename ValueInfoT> class DenseSet;
41}
42
43namespace clang {
44  class ADLResult;
45  class ASTConsumer;
46  class ASTContext;
47  class ASTMutationListener;
48  class ArrayType;
49  class AttributeList;
50  class BlockDecl;
51  class CXXBasePath;
52  class CXXBasePaths;
53  typedef llvm::SmallVector<CXXBaseSpecifier*, 4> CXXCastPath;
54  class CXXConstructorDecl;
55  class CXXConversionDecl;
56  class CXXDestructorDecl;
57  class CXXFieldCollector;
58  class CXXMemberCallExpr;
59  class CXXMethodDecl;
60  class CXXScopeSpec;
61  class CXXTemporary;
62  class CXXTryStmt;
63  class CallExpr;
64  class ClassTemplateDecl;
65  class ClassTemplatePartialSpecializationDecl;
66  class ClassTemplateSpecializationDecl;
67  class CodeCompleteConsumer;
68  class CodeCompletionAllocator;
69  class CodeCompletionResult;
70  class Decl;
71  class DeclAccessPair;
72  class DeclContext;
73  class DeclRefExpr;
74  class DeclaratorDecl;
75  class DeducedTemplateArgument;
76  class DependentDiagnostic;
77  class DesignatedInitExpr;
78  class Designation;
79  class EnumConstantDecl;
80  class Expr;
81  class ExtVectorType;
82  class ExternalSemaSource;
83  class FormatAttr;
84  class FriendDecl;
85  class FunctionDecl;
86  class FunctionProtoType;
87  class FunctionTemplateDecl;
88  class ImplicitConversionSequence;
89  class InitListExpr;
90  class InitializationKind;
91  class InitializationSequence;
92  class InitializedEntity;
93  class IntegerLiteral;
94  class LabelStmt;
95  class LangOptions;
96  class LocalInstantiationScope;
97  class LookupResult;
98  class MacroInfo;
99  class MultiLevelTemplateArgumentList;
100  class NamedDecl;
101  class NonNullAttr;
102  class ObjCCategoryDecl;
103  class ObjCCategoryImplDecl;
104  class ObjCCompatibleAliasDecl;
105  class ObjCContainerDecl;
106  class ObjCImplDecl;
107  class ObjCImplementationDecl;
108  class ObjCInterfaceDecl;
109  class ObjCIvarDecl;
110  template <class T> class ObjCList;
111  class ObjCMethodDecl;
112  class ObjCPropertyDecl;
113  class ObjCProtocolDecl;
114  class OverloadCandidateSet;
115  class OverloadExpr;
116  class ParenListExpr;
117  class ParmVarDecl;
118  class Preprocessor;
119  class PseudoDestructorTypeStorage;
120  class QualType;
121  class StandardConversionSequence;
122  class Stmt;
123  class StringLiteral;
124  class SwitchStmt;
125  class TargetAttributesSema;
126  class TemplateArgument;
127  class TemplateArgumentList;
128  class TemplateArgumentLoc;
129  class TemplateDecl;
130  class TemplateParameterList;
131  class TemplatePartialOrderingContext;
132  class TemplateTemplateParmDecl;
133  class Token;
134  class TypeAliasDecl;
135  class TypedefDecl;
136  class TypedefNameDecl;
137  class TypeLoc;
138  class UnqualifiedId;
139  class UnresolvedLookupExpr;
140  class UnresolvedMemberExpr;
141  class UnresolvedSetImpl;
142  class UnresolvedSetIterator;
143  class UsingDecl;
144  class UsingShadowDecl;
145  class ValueDecl;
146  class VarDecl;
147  class VisibilityAttr;
148  class VisibleDeclConsumer;
149  class IndirectFieldDecl;
150
151namespace sema {
152  class AccessedEntity;
153  class BlockScopeInfo;
154  class DelayedDiagnostic;
155  class FunctionScopeInfo;
156  class TemplateDeductionInfo;
157}
158
159/// \brief Holds a QualType and a TypeSourceInfo* that came out of a declarator
160/// parsing.
161///
162/// LocInfoType is a "transient" type, only needed for passing to/from Parser
163/// and Sema, when we want to preserve type source info for a parsed type.
164/// It will not participate in the type system semantics in any way.
165class LocInfoType : public Type {
166  enum {
167    // The last number that can fit in Type's TC.
168    // Avoids conflict with an existing Type class.
169    LocInfo = Type::TypeLast + 1
170  };
171
172  TypeSourceInfo *DeclInfo;
173
174  LocInfoType(QualType ty, TypeSourceInfo *TInfo)
175    : Type((TypeClass)LocInfo, ty, ty->isDependentType(),
176           ty->isVariablyModifiedType(),
177           ty->containsUnexpandedParameterPack()),
178      DeclInfo(TInfo) {
179    assert(getTypeClass() == (TypeClass)LocInfo && "LocInfo didn't fit in TC?");
180  }
181  friend class Sema;
182
183public:
184  QualType getType() const { return getCanonicalTypeInternal(); }
185  TypeSourceInfo *getTypeSourceInfo() const { return DeclInfo; }
186
187  void getAsStringInternal(std::string &Str,
188                                   const PrintingPolicy &Policy) const;
189
190  static bool classof(const Type *T) {
191    return T->getTypeClass() == (TypeClass)LocInfo;
192  }
193  static bool classof(const LocInfoType *) { return true; }
194};
195
196// FIXME: No way to easily map from TemplateTypeParmTypes to
197// TemplateTypeParmDecls, so we have this horrible PointerUnion.
198typedef std::pair<llvm::PointerUnion<const TemplateTypeParmType*, NamedDecl*>,
199                  SourceLocation> UnexpandedParameterPack;
200
201/// Sema - This implements semantic analysis and AST building for C.
202class Sema {
203  Sema(const Sema&);           // DO NOT IMPLEMENT
204  void operator=(const Sema&); // DO NOT IMPLEMENT
205  mutable const TargetAttributesSema* TheTargetAttributesSema;
206public:
207  typedef OpaquePtr<DeclGroupRef> DeclGroupPtrTy;
208  typedef OpaquePtr<TemplateName> TemplateTy;
209  typedef OpaquePtr<QualType> TypeTy;
210  typedef Attr AttrTy;
211  typedef CXXBaseSpecifier BaseTy;
212  typedef CXXCtorInitializer MemInitTy;
213  typedef Expr ExprTy;
214  typedef Stmt StmtTy;
215  typedef TemplateParameterList TemplateParamsTy;
216  typedef NestedNameSpecifier CXXScopeTy;
217
218  OpenCLOptions OpenCLFeatures;
219  FPOptions FPFeatures;
220
221  const LangOptions &LangOpts;
222  Preprocessor &PP;
223  ASTContext &Context;
224  ASTConsumer &Consumer;
225  Diagnostic &Diags;
226  SourceManager &SourceMgr;
227
228  /// \brief Source of additional semantic information.
229  ExternalSemaSource *ExternalSource;
230
231  /// \brief Code-completion consumer.
232  CodeCompleteConsumer *CodeCompleter;
233
234  /// CurContext - This is the current declaration context of parsing.
235  DeclContext *CurContext;
236
237  /// VAListTagName - The declaration name corresponding to __va_list_tag.
238  /// This is used as part of a hack to omit that class from ADL results.
239  DeclarationName VAListTagName;
240
241  /// PackContext - Manages the stack for #pragma pack. An alignment
242  /// of 0 indicates default alignment.
243  void *PackContext; // Really a "PragmaPackStack*"
244
245  bool MSStructPragmaOn; // True when #pragma ms_struct on
246
247  /// VisContext - Manages the stack for #pragma GCC visibility.
248  void *VisContext; // Really a "PragmaVisStack*"
249
250  /// \brief Stack containing information about each of the nested
251  /// function, block, and method scopes that are currently active.
252  ///
253  /// This array is never empty.  Clients should ignore the first
254  /// element, which is used to cache a single FunctionScopeInfo
255  /// that's used to parse every top-level function.
256  llvm::SmallVector<sema::FunctionScopeInfo *, 4> FunctionScopes;
257
258  /// ExprTemporaries - This is the stack of temporaries that are created by
259  /// the current full expression.
260  llvm::SmallVector<CXXTemporary*, 8> ExprTemporaries;
261
262  /// ExtVectorDecls - This is a list all the extended vector types. This allows
263  /// us to associate a raw vector type with one of the ext_vector type names.
264  /// This is only necessary for issuing pretty diagnostics.
265  llvm::SmallVector<TypedefNameDecl*, 24> ExtVectorDecls;
266
267  /// FieldCollector - Collects CXXFieldDecls during parsing of C++ classes.
268  llvm::OwningPtr<CXXFieldCollector> FieldCollector;
269
270  typedef llvm::SmallPtrSet<const CXXRecordDecl*, 8> RecordDeclSetTy;
271
272  /// PureVirtualClassDiagSet - a set of class declarations which we have
273  /// emitted a list of pure virtual functions. Used to prevent emitting the
274  /// same list more than once.
275  llvm::OwningPtr<RecordDeclSetTy> PureVirtualClassDiagSet;
276
277  /// ParsingInitForAutoVars - a set of declarations with auto types for which
278  /// we are currently parsing the initializer.
279  llvm::SmallPtrSet<const Decl*, 4> ParsingInitForAutoVars;
280
281  /// \brief A mapping from external names to the most recent
282  /// locally-scoped external declaration with that name.
283  ///
284  /// This map contains external declarations introduced in local
285  /// scoped, e.g.,
286  ///
287  /// \code
288  /// void f() {
289  ///   void foo(int, int);
290  /// }
291  /// \endcode
292  ///
293  /// Here, the name "foo" will be associated with the declaration on
294  /// "foo" within f. This name is not visible outside of
295  /// "f". However, we still find it in two cases:
296  ///
297  ///   - If we are declaring another external with the name "foo", we
298  ///     can find "foo" as a previous declaration, so that the types
299  ///     of this external declaration can be checked for
300  ///     compatibility.
301  ///
302  ///   - If we would implicitly declare "foo" (e.g., due to a call to
303  ///     "foo" in C when no prototype or definition is visible), then
304  ///     we find this declaration of "foo" and complain that it is
305  ///     not visible.
306  llvm::DenseMap<DeclarationName, NamedDecl *> LocallyScopedExternalDecls;
307
308  /// \brief All the tentative definitions encountered in the TU.
309  llvm::SmallVector<VarDecl *, 2> TentativeDefinitions;
310
311  /// \brief The set of file scoped decls seen so far that have not been used
312  /// and must warn if not used. Only contains the first declaration.
313  llvm::SmallVector<const DeclaratorDecl*, 4> UnusedFileScopedDecls;
314
315  /// \brief All the delegating constructors seen so far in the file, used for
316  /// cycle detection at the end of the TU.
317  llvm::SmallVector<CXXConstructorDecl*, 4> DelegatingCtorDecls;
318
319  /// \brief Callback to the parser to parse templated functions when needed.
320  typedef void LateTemplateParserCB(void *P, const FunctionDecl *FD);
321  LateTemplateParserCB *LateTemplateParser;
322  void *OpaqueParser;
323
324  void SetLateTemplateParser(LateTemplateParserCB *LTP, void *P) {
325    LateTemplateParser = LTP;
326    OpaqueParser = P;
327  }
328
329  class DelayedDiagnostics;
330
331  class ParsingDeclState {
332    unsigned SavedStackSize;
333    friend class Sema::DelayedDiagnostics;
334  };
335
336  class ProcessingContextState {
337    unsigned SavedParsingDepth;
338    unsigned SavedActiveStackBase;
339    friend class Sema::DelayedDiagnostics;
340  };
341
342  /// A class which encapsulates the logic for delaying diagnostics
343  /// during parsing and other processing.
344  class DelayedDiagnostics {
345    /// \brief The stack of diagnostics that were delayed due to being
346    /// produced during the parsing of a declaration.
347    sema::DelayedDiagnostic *Stack;
348
349    /// \brief The number of objects on the delayed-diagnostics stack.
350    unsigned StackSize;
351
352    /// \brief The current capacity of the delayed-diagnostics stack.
353    unsigned StackCapacity;
354
355    /// \brief The index of the first "active" delayed diagnostic in
356    /// the stack.  When parsing class definitions, we ignore active
357    /// delayed diagnostics from the surrounding context.
358    unsigned ActiveStackBase;
359
360    /// \brief The depth of the declarations we're currently parsing.
361    /// This gets saved and reset whenever we enter a class definition.
362    unsigned ParsingDepth;
363
364  public:
365    DelayedDiagnostics() : Stack(0), StackSize(0), StackCapacity(0),
366      ActiveStackBase(0), ParsingDepth(0) {}
367
368    ~DelayedDiagnostics() {
369      delete[] reinterpret_cast<char*>(Stack);
370    }
371
372    /// Adds a delayed diagnostic.
373    void add(const sema::DelayedDiagnostic &diag);
374
375    /// Determines whether diagnostics should be delayed.
376    bool shouldDelayDiagnostics() { return ParsingDepth > 0; }
377
378    /// Observe that we've started parsing a declaration.  Access and
379    /// deprecation diagnostics will be delayed; when the declaration
380    /// is completed, all active delayed diagnostics will be evaluated
381    /// in its context, and then active diagnostics stack will be
382    /// popped down to the saved depth.
383    ParsingDeclState pushParsingDecl() {
384      ParsingDepth++;
385
386      ParsingDeclState state;
387      state.SavedStackSize = StackSize;
388      return state;
389    }
390
391    /// Observe that we're completed parsing a declaration.
392    static void popParsingDecl(Sema &S, ParsingDeclState state, Decl *decl);
393
394    /// Observe that we've started processing a different context, the
395    /// contents of which are semantically separate from the
396    /// declarations it may lexically appear in.  This sets aside the
397    /// current stack of active diagnostics and starts afresh.
398    ProcessingContextState pushContext() {
399      assert(StackSize >= ActiveStackBase);
400
401      ProcessingContextState state;
402      state.SavedParsingDepth = ParsingDepth;
403      state.SavedActiveStackBase = ActiveStackBase;
404
405      ActiveStackBase = StackSize;
406      ParsingDepth = 0;
407
408      return state;
409    }
410
411    /// Observe that we've stopped processing a context.  This
412    /// restores the previous stack of active diagnostics.
413    void popContext(ProcessingContextState state) {
414      assert(ActiveStackBase == StackSize);
415      assert(ParsingDepth == 0);
416      ActiveStackBase = state.SavedActiveStackBase;
417      ParsingDepth = state.SavedParsingDepth;
418    }
419  } DelayedDiagnostics;
420
421  /// A RAII object to temporarily push a declaration context.
422  class ContextRAII {
423  private:
424    Sema &S;
425    DeclContext *SavedContext;
426    ProcessingContextState SavedContextState;
427
428  public:
429    ContextRAII(Sema &S, DeclContext *ContextToPush)
430      : S(S), SavedContext(S.CurContext),
431        SavedContextState(S.DelayedDiagnostics.pushContext())
432    {
433      assert(ContextToPush && "pushing null context");
434      S.CurContext = ContextToPush;
435    }
436
437    void pop() {
438      if (!SavedContext) return;
439      S.CurContext = SavedContext;
440      S.DelayedDiagnostics.popContext(SavedContextState);
441      SavedContext = 0;
442    }
443
444    ~ContextRAII() {
445      pop();
446    }
447  };
448
449  /// WeakUndeclaredIdentifiers - Identifiers contained in
450  /// #pragma weak before declared. rare. may alias another
451  /// identifier, declared or undeclared
452  class WeakInfo {
453    IdentifierInfo *alias;  // alias (optional)
454    SourceLocation loc;     // for diagnostics
455    bool used;              // identifier later declared?
456  public:
457    WeakInfo()
458      : alias(0), loc(SourceLocation()), used(false) {}
459    WeakInfo(IdentifierInfo *Alias, SourceLocation Loc)
460      : alias(Alias), loc(Loc), used(false) {}
461    inline IdentifierInfo * getAlias() const { return alias; }
462    inline SourceLocation getLocation() const { return loc; }
463    void setUsed(bool Used=true) { used = Used; }
464    inline bool getUsed() { return used; }
465    bool operator==(WeakInfo RHS) const {
466      return alias == RHS.getAlias() && loc == RHS.getLocation();
467    }
468    bool operator!=(WeakInfo RHS) const { return !(*this == RHS); }
469  };
470  llvm::DenseMap<IdentifierInfo*,WeakInfo> WeakUndeclaredIdentifiers;
471
472  /// WeakTopLevelDecl - Translation-unit scoped declarations generated by
473  /// #pragma weak during processing of other Decls.
474  /// I couldn't figure out a clean way to generate these in-line, so
475  /// we store them here and handle separately -- which is a hack.
476  /// It would be best to refactor this.
477  llvm::SmallVector<Decl*,2> WeakTopLevelDecl;
478
479  IdentifierResolver IdResolver;
480
481  /// Translation Unit Scope - useful to Objective-C actions that need
482  /// to lookup file scope declarations in the "ordinary" C decl namespace.
483  /// For example, user-defined classes, built-in "id" type, etc.
484  Scope *TUScope;
485
486  /// \brief The C++ "std" namespace, where the standard library resides.
487  LazyDeclPtr StdNamespace;
488
489  /// \brief The C++ "std::bad_alloc" class, which is defined by the C++
490  /// standard library.
491  LazyDeclPtr StdBadAlloc;
492
493  /// \brief The C++ "type_info" declaration, which is defined in <typeinfo>.
494  RecordDecl *CXXTypeInfoDecl;
495
496  /// \brief The MSVC "_GUID" struct, which is defined in MSVC header files.
497  RecordDecl *MSVCGuidDecl;
498
499  /// A flag to remember whether the implicit forms of operator new and delete
500  /// have been declared.
501  bool GlobalNewDeleteDeclared;
502
503  /// \brief The set of declarations that have been referenced within
504  /// a potentially evaluated expression.
505  typedef llvm::SmallVector<std::pair<SourceLocation, Decl *>, 10>
506    PotentiallyReferencedDecls;
507
508  /// \brief A set of diagnostics that may be emitted.
509  typedef llvm::SmallVector<std::pair<SourceLocation, PartialDiagnostic>, 10>
510    PotentiallyEmittedDiagnostics;
511
512  /// \brief Describes how the expressions currently being parsed are
513  /// evaluated at run-time, if at all.
514  enum ExpressionEvaluationContext {
515    /// \brief The current expression and its subexpressions occur within an
516    /// unevaluated operand (C++0x [expr]p8), such as a constant expression
517    /// or the subexpression of \c sizeof, where the type or the value of the
518    /// expression may be significant but no code will be generated to evaluate
519    /// the value of the expression at run time.
520    Unevaluated,
521
522    /// \brief The current expression is potentially evaluated at run time,
523    /// which means that code may be generated to evaluate the value of the
524    /// expression at run time.
525    PotentiallyEvaluated,
526
527    /// \brief The current expression may be potentially evaluated or it may
528    /// be unevaluated, but it is impossible to tell from the lexical context.
529    /// This evaluation context is used primary for the operand of the C++
530    /// \c typeid expression, whose argument is potentially evaluated only when
531    /// it is an lvalue of polymorphic class type (C++ [basic.def.odr]p2).
532    PotentiallyPotentiallyEvaluated,
533
534    /// \brief The current expression is potentially evaluated, but any
535    /// declarations referenced inside that expression are only used if
536    /// in fact the current expression is used.
537    ///
538    /// This value is used when parsing default function arguments, for which
539    /// we would like to provide diagnostics (e.g., passing non-POD arguments
540    /// through varargs) but do not want to mark declarations as "referenced"
541    /// until the default argument is used.
542    PotentiallyEvaluatedIfUsed
543  };
544
545  /// \brief Data structure used to record current or nested
546  /// expression evaluation contexts.
547  struct ExpressionEvaluationContextRecord {
548    /// \brief The expression evaluation context.
549    ExpressionEvaluationContext Context;
550
551    /// \brief The number of temporaries that were active when we
552    /// entered this expression evaluation context.
553    unsigned NumTemporaries;
554
555    /// \brief The set of declarations referenced within a
556    /// potentially potentially-evaluated context.
557    ///
558    /// When leaving a potentially potentially-evaluated context, each
559    /// of these elements will be as referenced if the corresponding
560    /// potentially potentially evaluated expression is potentially
561    /// evaluated.
562    PotentiallyReferencedDecls *PotentiallyReferenced;
563
564    /// \brief The set of diagnostics to emit should this potentially
565    /// potentially-evaluated context become evaluated.
566    PotentiallyEmittedDiagnostics *PotentiallyDiagnosed;
567
568    ExpressionEvaluationContextRecord(ExpressionEvaluationContext Context,
569                                      unsigned NumTemporaries)
570      : Context(Context), NumTemporaries(NumTemporaries),
571        PotentiallyReferenced(0), PotentiallyDiagnosed(0) { }
572
573    void addReferencedDecl(SourceLocation Loc, Decl *Decl) {
574      if (!PotentiallyReferenced)
575        PotentiallyReferenced = new PotentiallyReferencedDecls;
576      PotentiallyReferenced->push_back(std::make_pair(Loc, Decl));
577    }
578
579    void addDiagnostic(SourceLocation Loc, const PartialDiagnostic &PD) {
580      if (!PotentiallyDiagnosed)
581        PotentiallyDiagnosed = new PotentiallyEmittedDiagnostics;
582      PotentiallyDiagnosed->push_back(std::make_pair(Loc, PD));
583    }
584
585    void Destroy() {
586      delete PotentiallyReferenced;
587      delete PotentiallyDiagnosed;
588      PotentiallyReferenced = 0;
589      PotentiallyDiagnosed = 0;
590    }
591  };
592
593  /// A stack of expression evaluation contexts.
594  llvm::SmallVector<ExpressionEvaluationContextRecord, 8> ExprEvalContexts;
595
596  /// \brief Whether the code handled by Sema should be considered a
597  /// complete translation unit or not.
598  ///
599  /// When true (which is generally the case), Sema will perform
600  /// end-of-translation-unit semantic tasks (such as creating
601  /// initializers for tentative definitions in C) once parsing has
602  /// completed. This flag will be false when building PCH files,
603  /// since a PCH file is by definition not a complete translation
604  /// unit.
605  bool CompleteTranslationUnit;
606
607  llvm::BumpPtrAllocator BumpAlloc;
608
609  /// \brief The number of SFINAE diagnostics that have been trapped.
610  unsigned NumSFINAEErrors;
611
612  typedef llvm::DenseMap<ParmVarDecl *, llvm::SmallVector<ParmVarDecl *, 1> >
613    UnparsedDefaultArgInstantiationsMap;
614
615  /// \brief A mapping from parameters with unparsed default arguments to the
616  /// set of instantiations of each parameter.
617  ///
618  /// This mapping is a temporary data structure used when parsing
619  /// nested class templates or nested classes of class templates,
620  /// where we might end up instantiating an inner class before the
621  /// default arguments of its methods have been parsed.
622  UnparsedDefaultArgInstantiationsMap UnparsedDefaultArgInstantiations;
623
624  // Contains the locations of the beginning of unparsed default
625  // argument locations.
626  llvm::DenseMap<ParmVarDecl *,SourceLocation> UnparsedDefaultArgLocs;
627
628  /// UndefinedInternals - all the used, undefined objects with
629  /// internal linkage in this translation unit.
630  llvm::DenseMap<NamedDecl*, SourceLocation> UndefinedInternals;
631
632  typedef std::pair<ObjCMethodList, ObjCMethodList> GlobalMethods;
633  typedef llvm::DenseMap<Selector, GlobalMethods> GlobalMethodPool;
634
635  /// Method Pool - allows efficient lookup when typechecking messages to "id".
636  /// We need to maintain a list, since selectors can have differing signatures
637  /// across classes. In Cocoa, this happens to be extremely uncommon (only 1%
638  /// of selectors are "overloaded").
639  GlobalMethodPool MethodPool;
640
641  /// Method selectors used in a @selector expression. Used for implementation
642  /// of -Wselector.
643  llvm::DenseMap<Selector, SourceLocation> ReferencedSelectors;
644
645  GlobalMethodPool::iterator ReadMethodPool(Selector Sel);
646
647  /// Private Helper predicate to check for 'self'.
648  bool isSelfExpr(Expr *RExpr);
649public:
650  Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer,
651       bool CompleteTranslationUnit = true,
652       CodeCompleteConsumer *CompletionConsumer = 0);
653  ~Sema();
654
655  /// \brief Perform initialization that occurs after the parser has been
656  /// initialized but before it parses anything.
657  void Initialize();
658
659  const LangOptions &getLangOptions() const { return LangOpts; }
660  OpenCLOptions &getOpenCLOptions() { return OpenCLFeatures; }
661  FPOptions     &getFPOptions() { return FPFeatures; }
662
663  Diagnostic &getDiagnostics() const { return Diags; }
664  SourceManager &getSourceManager() const { return SourceMgr; }
665  const TargetAttributesSema &getTargetAttributesSema() const;
666  Preprocessor &getPreprocessor() const { return PP; }
667  ASTContext &getASTContext() const { return Context; }
668  ASTConsumer &getASTConsumer() const { return Consumer; }
669  ASTMutationListener *getASTMutationListener() const;
670
671  /// \brief Helper class that creates diagnostics with optional
672  /// template instantiation stacks.
673  ///
674  /// This class provides a wrapper around the basic DiagnosticBuilder
675  /// class that emits diagnostics. SemaDiagnosticBuilder is
676  /// responsible for emitting the diagnostic (as DiagnosticBuilder
677  /// does) and, if the diagnostic comes from inside a template
678  /// instantiation, printing the template instantiation stack as
679  /// well.
680  class SemaDiagnosticBuilder : public DiagnosticBuilder {
681    Sema &SemaRef;
682    unsigned DiagID;
683
684  public:
685    SemaDiagnosticBuilder(DiagnosticBuilder &DB, Sema &SemaRef, unsigned DiagID)
686      : DiagnosticBuilder(DB), SemaRef(SemaRef), DiagID(DiagID) { }
687
688    explicit SemaDiagnosticBuilder(Sema &SemaRef)
689      : DiagnosticBuilder(DiagnosticBuilder::Suppress), SemaRef(SemaRef) { }
690
691    ~SemaDiagnosticBuilder();
692  };
693
694  /// \brief Emit a diagnostic.
695  SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID);
696
697  /// \brief Emit a partial diagnostic.
698  SemaDiagnosticBuilder Diag(SourceLocation Loc, const PartialDiagnostic& PD);
699
700  /// \brief Build a partial diagnostic.
701  PartialDiagnostic PDiag(unsigned DiagID = 0); // in SemaInternal.h
702
703  bool findMacroSpelling(SourceLocation &loc, llvm::StringRef name);
704
705  ExprResult Owned(Expr* E) { return E; }
706  ExprResult Owned(ExprResult R) { return R; }
707  StmtResult Owned(Stmt* S) { return S; }
708
709  void ActOnEndOfTranslationUnit();
710
711  void CheckDelegatingCtorCycles();
712
713  Scope *getScopeForContext(DeclContext *Ctx);
714
715  void PushFunctionScope();
716  void PushBlockScope(Scope *BlockScope, BlockDecl *Block);
717  void PopFunctionOrBlockScope(const sema::AnalysisBasedWarnings::Policy *WP =0,
718                               const Decl *D = 0, const BlockExpr *blkExpr = 0);
719
720  sema::FunctionScopeInfo *getCurFunction() const {
721    return FunctionScopes.back();
722  }
723
724  bool hasAnyErrorsInThisFunction() const;
725
726  /// \brief Retrieve the current block, if any.
727  sema::BlockScopeInfo *getCurBlock();
728
729  /// WeakTopLevelDeclDecls - access to #pragma weak-generated Decls
730  llvm::SmallVector<Decl*,2> &WeakTopLevelDecls() { return WeakTopLevelDecl; }
731
732  //===--------------------------------------------------------------------===//
733  // Type Analysis / Processing: SemaType.cpp.
734  //
735
736  QualType adjustParameterType(QualType T);
737  QualType BuildQualifiedType(QualType T, SourceLocation Loc, Qualifiers Qs);
738  QualType BuildQualifiedType(QualType T, SourceLocation Loc, unsigned CVR) {
739    return BuildQualifiedType(T, Loc, Qualifiers::fromCVRMask(CVR));
740  }
741  QualType BuildPointerType(QualType T,
742                            SourceLocation Loc, DeclarationName Entity);
743  QualType BuildReferenceType(QualType T, bool LValueRef,
744                              SourceLocation Loc, DeclarationName Entity);
745  QualType BuildArrayType(QualType T, ArrayType::ArraySizeModifier ASM,
746                          Expr *ArraySize, unsigned Quals,
747                          SourceRange Brackets, DeclarationName Entity);
748  QualType BuildExtVectorType(QualType T, Expr *ArraySize,
749                              SourceLocation AttrLoc);
750  QualType BuildFunctionType(QualType T,
751                             QualType *ParamTypes, unsigned NumParamTypes,
752                             bool Variadic, unsigned Quals,
753                             RefQualifierKind RefQualifier,
754                             SourceLocation Loc, DeclarationName Entity,
755                             FunctionType::ExtInfo Info);
756  QualType BuildMemberPointerType(QualType T, QualType Class,
757                                  SourceLocation Loc,
758                                  DeclarationName Entity);
759  QualType BuildBlockPointerType(QualType T,
760                                 SourceLocation Loc, DeclarationName Entity);
761  QualType BuildParenType(QualType T);
762
763  TypeSourceInfo *GetTypeForDeclarator(Declarator &D, Scope *S,
764                                       TagDecl **OwnedDecl = 0,
765                                       bool AllowAutoInTypeName = false);
766  TypeSourceInfo *GetTypeSourceInfoForDeclarator(Declarator &D, QualType T,
767                                               TypeSourceInfo *ReturnTypeInfo);
768  /// \brief Package the given type and TSI into a ParsedType.
769  ParsedType CreateParsedType(QualType T, TypeSourceInfo *TInfo);
770  DeclarationNameInfo GetNameForDeclarator(Declarator &D);
771  DeclarationNameInfo GetNameFromUnqualifiedId(const UnqualifiedId &Name);
772  static QualType GetTypeFromParser(ParsedType Ty, TypeSourceInfo **TInfo = 0);
773  bool CheckSpecifiedExceptionType(QualType T, const SourceRange &Range);
774  bool CheckDistantExceptionSpec(QualType T);
775  bool CheckEquivalentExceptionSpec(FunctionDecl *Old, FunctionDecl *New);
776  bool CheckEquivalentExceptionSpec(
777      const FunctionProtoType *Old, SourceLocation OldLoc,
778      const FunctionProtoType *New, SourceLocation NewLoc);
779  bool CheckEquivalentExceptionSpec(
780      const PartialDiagnostic &DiagID, const PartialDiagnostic & NoteID,
781      const FunctionProtoType *Old, SourceLocation OldLoc,
782      const FunctionProtoType *New, SourceLocation NewLoc,
783      bool *MissingExceptionSpecification = 0,
784      bool *MissingEmptyExceptionSpecification = 0,
785      bool AllowNoexceptAllMatchWithNoSpec = false,
786      bool IsOperatorNew = false);
787  bool CheckExceptionSpecSubset(
788      const PartialDiagnostic &DiagID, const PartialDiagnostic & NoteID,
789      const FunctionProtoType *Superset, SourceLocation SuperLoc,
790      const FunctionProtoType *Subset, SourceLocation SubLoc);
791  bool CheckParamExceptionSpec(const PartialDiagnostic & NoteID,
792      const FunctionProtoType *Target, SourceLocation TargetLoc,
793      const FunctionProtoType *Source, SourceLocation SourceLoc);
794
795  TypeResult ActOnTypeName(Scope *S, Declarator &D);
796
797  bool RequireCompleteType(SourceLocation Loc, QualType T,
798                           const PartialDiagnostic &PD,
799                           std::pair<SourceLocation, PartialDiagnostic> Note);
800  bool RequireCompleteType(SourceLocation Loc, QualType T,
801                           const PartialDiagnostic &PD);
802  bool RequireCompleteType(SourceLocation Loc, QualType T,
803                           unsigned DiagID);
804
805  QualType getElaboratedType(ElaboratedTypeKeyword Keyword,
806                             const CXXScopeSpec &SS, QualType T);
807
808  QualType BuildTypeofExprType(Expr *E, SourceLocation Loc);
809  QualType BuildDecltypeType(Expr *E, SourceLocation Loc);
810
811  //===--------------------------------------------------------------------===//
812  // Symbol table / Decl tracking callbacks: SemaDecl.cpp.
813  //
814
815  DeclGroupPtrTy ConvertDeclToDeclGroup(Decl *Ptr);
816
817  void DiagnoseUseOfUnimplementedSelectors();
818
819  ParsedType getTypeName(IdentifierInfo &II, SourceLocation NameLoc,
820                         Scope *S, CXXScopeSpec *SS = 0,
821                         bool isClassName = false,
822                         bool HasTrailingDot = false,
823                         ParsedType ObjectType = ParsedType(),
824                         bool WantNontrivialTypeSourceInfo = false);
825  TypeSpecifierType isTagName(IdentifierInfo &II, Scope *S);
826  bool isMicrosoftMissingTypename(const CXXScopeSpec *SS);
827  bool DiagnoseUnknownTypeName(const IdentifierInfo &II,
828                               SourceLocation IILoc,
829                               Scope *S,
830                               CXXScopeSpec *SS,
831                               ParsedType &SuggestedType);
832
833  /// \brief Describes the result of the name lookup and resolution performed
834  /// by \c ClassifyName().
835  enum NameClassificationKind {
836    NC_Unknown,
837    NC_Error,
838    NC_Keyword,
839    NC_Type,
840    NC_Expression,
841    NC_NestedNameSpecifier,
842    NC_TypeTemplate,
843    NC_FunctionTemplate
844  };
845
846  class NameClassification {
847    NameClassificationKind Kind;
848    ExprResult Expr;
849    TemplateName Template;
850    ParsedType Type;
851    const IdentifierInfo *Keyword;
852
853    explicit NameClassification(NameClassificationKind Kind) : Kind(Kind) {}
854
855  public:
856    NameClassification(ExprResult Expr) : Kind(NC_Expression), Expr(Expr) {}
857
858    NameClassification(ParsedType Type) : Kind(NC_Type), Type(Type) {}
859
860    NameClassification(const IdentifierInfo *Keyword)
861      : Kind(NC_Keyword), Keyword(Keyword) { }
862
863    static NameClassification Error() {
864      return NameClassification(NC_Error);
865    }
866
867    static NameClassification Unknown() {
868      return NameClassification(NC_Unknown);
869    }
870
871    static NameClassification NestedNameSpecifier() {
872      return NameClassification(NC_NestedNameSpecifier);
873    }
874
875    static NameClassification TypeTemplate(TemplateName Name) {
876      NameClassification Result(NC_TypeTemplate);
877      Result.Template = Name;
878      return Result;
879    }
880
881    static NameClassification FunctionTemplate(TemplateName Name) {
882      NameClassification Result(NC_FunctionTemplate);
883      Result.Template = Name;
884      return Result;
885    }
886
887    NameClassificationKind getKind() const { return Kind; }
888
889    ParsedType getType() const {
890      assert(Kind == NC_Type);
891      return Type;
892    }
893
894    ExprResult getExpression() const {
895      assert(Kind == NC_Expression);
896      return Expr;
897    }
898
899    TemplateName getTemplateName() const {
900      assert(Kind == NC_TypeTemplate || Kind == NC_FunctionTemplate);
901      return Template;
902    }
903
904    TemplateNameKind getTemplateNameKind() const {
905      assert(Kind == NC_TypeTemplate || Kind == NC_FunctionTemplate);
906      return Kind == NC_TypeTemplate? TNK_Type_template : TNK_Function_template;
907    }
908};
909
910  /// \brief Perform name lookup on the given name, classifying it based on
911  /// the results of name lookup and the following token.
912  ///
913  /// This routine is used by the parser to resolve identifiers and help direct
914  /// parsing. When the identifier cannot be found, this routine will attempt
915  /// to correct the typo and classify based on the resulting name.
916  ///
917  /// \param S The scope in which we're performing name lookup.
918  ///
919  /// \param SS The nested-name-specifier that precedes the name.
920  ///
921  /// \param Name The identifier. If typo correction finds an alternative name,
922  /// this pointer parameter will be updated accordingly.
923  ///
924  /// \param NameLoc The location of the identifier.
925  ///
926  /// \param NextToken The token following the identifier. Used to help
927  /// disambiguate the name.
928  NameClassification ClassifyName(Scope *S,
929                                  CXXScopeSpec &SS,
930                                  IdentifierInfo *&Name,
931                                  SourceLocation NameLoc,
932                                  const Token &NextToken);
933
934  Decl *ActOnDeclarator(Scope *S, Declarator &D,
935                        bool IsFunctionDefintion = false);
936
937  Decl *HandleDeclarator(Scope *S, Declarator &D,
938                         MultiTemplateParamsArg TemplateParameterLists,
939                         bool IsFunctionDefinition);
940  void RegisterLocallyScopedExternCDecl(NamedDecl *ND,
941                                        const LookupResult &Previous,
942                                        Scope *S);
943  bool DiagnoseClassNameShadow(DeclContext *DC, DeclarationNameInfo Info);
944  void DiagnoseFunctionSpecifiers(Declarator& D);
945  void CheckShadow(Scope *S, VarDecl *D, const LookupResult& R);
946  void CheckShadow(Scope *S, VarDecl *D);
947  void CheckCastAlign(Expr *Op, QualType T, SourceRange TRange);
948  void CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *D);
949  NamedDecl* ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
950                                    QualType R, TypeSourceInfo *TInfo,
951                                    LookupResult &Previous, bool &Redeclaration);
952  NamedDecl* ActOnTypedefNameDecl(Scope* S, DeclContext* DC, TypedefNameDecl *D,
953                                  LookupResult &Previous, bool &Redeclaration);
954  NamedDecl* ActOnVariableDeclarator(Scope* S, Declarator& D, DeclContext* DC,
955                                     QualType R, TypeSourceInfo *TInfo,
956                                     LookupResult &Previous,
957                                     MultiTemplateParamsArg TemplateParamLists,
958                                     bool &Redeclaration);
959  void CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous,
960                                bool &Redeclaration);
961  void CheckCompleteVariableDeclaration(VarDecl *var);
962  NamedDecl* ActOnFunctionDeclarator(Scope* S, Declarator& D, DeclContext* DC,
963                                     QualType R, TypeSourceInfo *TInfo,
964                                     LookupResult &Previous,
965                                     MultiTemplateParamsArg TemplateParamLists,
966                                     bool IsFunctionDefinition,
967                                     bool &Redeclaration);
968  bool AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD);
969  void DiagnoseHiddenVirtualMethods(CXXRecordDecl *DC, CXXMethodDecl *MD);
970  void CheckFunctionDeclaration(Scope *S,
971                                FunctionDecl *NewFD, LookupResult &Previous,
972                                bool IsExplicitSpecialization,
973                                bool &Redeclaration);
974  void CheckMain(FunctionDecl *FD);
975  Decl *ActOnParamDeclarator(Scope *S, Declarator &D);
976  ParmVarDecl *BuildParmVarDeclForTypedef(DeclContext *DC,
977                                          SourceLocation Loc,
978                                          QualType T);
979  ParmVarDecl *CheckParameter(DeclContext *DC, SourceLocation StartLoc,
980                              SourceLocation NameLoc, IdentifierInfo *Name,
981                              QualType T, TypeSourceInfo *TSInfo,
982                              StorageClass SC, StorageClass SCAsWritten);
983  void ActOnParamDefaultArgument(Decl *param,
984                                 SourceLocation EqualLoc,
985                                 Expr *defarg);
986  void ActOnParamUnparsedDefaultArgument(Decl *param,
987                                         SourceLocation EqualLoc,
988                                         SourceLocation ArgLoc);
989  void ActOnParamDefaultArgumentError(Decl *param);
990  bool SetParamDefaultArgument(ParmVarDecl *Param, Expr *DefaultArg,
991                               SourceLocation EqualLoc);
992
993  void AddInitializerToDecl(Decl *dcl, Expr *init, bool DirectInit,
994                            bool TypeMayContainAuto);
995  void ActOnUninitializedDecl(Decl *dcl, bool TypeMayContainAuto);
996  void ActOnInitializerError(Decl *Dcl);
997  void ActOnCXXForRangeDecl(Decl *D);
998  void SetDeclDeleted(Decl *dcl, SourceLocation DelLoc);
999  void SetDeclDefaulted(Decl *dcl, SourceLocation DefaultLoc);
1000  void FinalizeDeclaration(Decl *D);
1001  DeclGroupPtrTy FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
1002                                         Decl **Group,
1003                                         unsigned NumDecls);
1004  DeclGroupPtrTy BuildDeclaratorGroup(Decl **Group, unsigned NumDecls,
1005                                      bool TypeMayContainAuto = true);
1006  void ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
1007                                       SourceLocation LocAfterDecls);
1008  void CheckForFunctionRedefinition(FunctionDecl *FD);
1009  Decl *ActOnStartOfFunctionDef(Scope *S, Declarator &D);
1010  Decl *ActOnStartOfFunctionDef(Scope *S, Decl *D);
1011  void ActOnStartOfObjCMethodDef(Scope *S, Decl *D);
1012
1013  Decl *ActOnFinishFunctionBody(Decl *Decl, Stmt *Body);
1014  Decl *ActOnFinishFunctionBody(Decl *Decl, Stmt *Body, bool IsInstantiation);
1015
1016  /// \brief Diagnose any unused parameters in the given sequence of
1017  /// ParmVarDecl pointers.
1018  void DiagnoseUnusedParameters(ParmVarDecl * const *Begin,
1019                                ParmVarDecl * const *End);
1020
1021  /// \brief Diagnose whether the size of parameters or return value of a
1022  /// function or obj-c method definition is pass-by-value and larger than a
1023  /// specified threshold.
1024  void DiagnoseSizeOfParametersAndReturnValue(ParmVarDecl * const *Begin,
1025                                              ParmVarDecl * const *End,
1026                                              QualType ReturnTy,
1027                                              NamedDecl *D);
1028
1029  void DiagnoseInvalidJumps(Stmt *Body);
1030  Decl *ActOnFileScopeAsmDecl(Expr *expr,
1031                              SourceLocation AsmLoc,
1032                              SourceLocation RParenLoc);
1033
1034  /// Scope actions.
1035  void ActOnPopScope(SourceLocation Loc, Scope *S);
1036  void ActOnTranslationUnitScope(Scope *S);
1037
1038  Decl *ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS,
1039                                   DeclSpec &DS);
1040  Decl *ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS,
1041                                   DeclSpec &DS,
1042                                   MultiTemplateParamsArg TemplateParams);
1043
1044  StmtResult ActOnVlaStmt(const DeclSpec &DS);
1045
1046  Decl *BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
1047                                    AccessSpecifier AS,
1048                                    RecordDecl *Record);
1049
1050  Decl *BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
1051                                       RecordDecl *Record);
1052
1053  bool isAcceptableTagRedeclaration(const TagDecl *Previous,
1054                                    TagTypeKind NewTag,
1055                                    SourceLocation NewTagLoc,
1056                                    const IdentifierInfo &Name);
1057
1058  enum TagUseKind {
1059    TUK_Reference,   // Reference to a tag:  'struct foo *X;'
1060    TUK_Declaration, // Fwd decl of a tag:   'struct foo;'
1061    TUK_Definition,  // Definition of a tag: 'struct foo { int X; } Y;'
1062    TUK_Friend       // Friend declaration:  'friend struct foo;'
1063  };
1064
1065  Decl *ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
1066                 SourceLocation KWLoc, CXXScopeSpec &SS,
1067                 IdentifierInfo *Name, SourceLocation NameLoc,
1068                 AttributeList *Attr, AccessSpecifier AS,
1069                 MultiTemplateParamsArg TemplateParameterLists,
1070                 bool &OwnedDecl, bool &IsDependent, bool ScopedEnum,
1071                 bool ScopedEnumUsesClassTag, TypeResult UnderlyingType);
1072
1073  Decl *ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
1074                                unsigned TagSpec, SourceLocation TagLoc,
1075                                CXXScopeSpec &SS,
1076                                IdentifierInfo *Name, SourceLocation NameLoc,
1077                                AttributeList *Attr,
1078                                MultiTemplateParamsArg TempParamLists);
1079
1080  TypeResult ActOnDependentTag(Scope *S,
1081                               unsigned TagSpec,
1082                               TagUseKind TUK,
1083                               const CXXScopeSpec &SS,
1084                               IdentifierInfo *Name,
1085                               SourceLocation TagLoc,
1086                               SourceLocation NameLoc);
1087
1088  void ActOnDefs(Scope *S, Decl *TagD, SourceLocation DeclStart,
1089                 IdentifierInfo *ClassName,
1090                 llvm::SmallVectorImpl<Decl *> &Decls);
1091  Decl *ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
1092                   Declarator &D, Expr *BitfieldWidth);
1093
1094  FieldDecl *HandleField(Scope *S, RecordDecl *TagD, SourceLocation DeclStart,
1095                         Declarator &D, Expr *BitfieldWidth,
1096                         AccessSpecifier AS);
1097
1098  FieldDecl *CheckFieldDecl(DeclarationName Name, QualType T,
1099                            TypeSourceInfo *TInfo,
1100                            RecordDecl *Record, SourceLocation Loc,
1101                            bool Mutable, Expr *BitfieldWidth,
1102                            SourceLocation TSSL,
1103                            AccessSpecifier AS, NamedDecl *PrevDecl,
1104                            Declarator *D = 0);
1105
1106  enum CXXSpecialMember {
1107    CXXInvalid = -1,
1108    CXXDefaultConstructor = 0,
1109    CXXCopyConstructor = 1,
1110    CXXCopyAssignment = 2,
1111    CXXDestructor = 3
1112  };
1113  bool CheckNontrivialField(FieldDecl *FD);
1114  void DiagnoseNontrivial(const RecordType* Record, CXXSpecialMember mem);
1115  CXXSpecialMember getSpecialMember(const CXXMethodDecl *MD);
1116  void ActOnLastBitfield(SourceLocation DeclStart, Decl *IntfDecl,
1117                         llvm::SmallVectorImpl<Decl *> &AllIvarDecls);
1118  Decl *ActOnIvar(Scope *S, SourceLocation DeclStart, Decl *IntfDecl,
1119                  Declarator &D, Expr *BitfieldWidth,
1120                  tok::ObjCKeywordKind visibility);
1121
1122  // This is used for both record definitions and ObjC interface declarations.
1123  void ActOnFields(Scope* S, SourceLocation RecLoc, Decl *TagDecl,
1124                   Decl **Fields, unsigned NumFields,
1125                   SourceLocation LBrac, SourceLocation RBrac,
1126                   AttributeList *AttrList);
1127
1128  /// ActOnTagStartDefinition - Invoked when we have entered the
1129  /// scope of a tag's definition (e.g., for an enumeration, class,
1130  /// struct, or union).
1131  void ActOnTagStartDefinition(Scope *S, Decl *TagDecl);
1132
1133  /// ActOnStartCXXMemberDeclarations - Invoked when we have parsed a
1134  /// C++ record definition's base-specifiers clause and are starting its
1135  /// member declarations.
1136  void ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagDecl,
1137                                       SourceLocation FinalLoc,
1138                                       SourceLocation LBraceLoc);
1139
1140  /// ActOnTagFinishDefinition - Invoked once we have finished parsing
1141  /// the definition of a tag (enumeration, class, struct, or union).
1142  void ActOnTagFinishDefinition(Scope *S, Decl *TagDecl,
1143                                SourceLocation RBraceLoc);
1144
1145  /// ActOnTagDefinitionError - Invoked when there was an unrecoverable
1146  /// error parsing the definition of a tag.
1147  void ActOnTagDefinitionError(Scope *S, Decl *TagDecl);
1148
1149  EnumConstantDecl *CheckEnumConstant(EnumDecl *Enum,
1150                                      EnumConstantDecl *LastEnumConst,
1151                                      SourceLocation IdLoc,
1152                                      IdentifierInfo *Id,
1153                                      Expr *val);
1154
1155  Decl *ActOnEnumConstant(Scope *S, Decl *EnumDecl, Decl *LastEnumConstant,
1156                          SourceLocation IdLoc, IdentifierInfo *Id,
1157                          AttributeList *Attrs,
1158                          SourceLocation EqualLoc, Expr *Val);
1159  void ActOnEnumBody(SourceLocation EnumLoc, SourceLocation LBraceLoc,
1160                     SourceLocation RBraceLoc, Decl *EnumDecl,
1161                     Decl **Elements, unsigned NumElements,
1162                     Scope *S, AttributeList *Attr);
1163
1164  DeclContext *getContainingDC(DeclContext *DC);
1165
1166  /// Set the current declaration context until it gets popped.
1167  void PushDeclContext(Scope *S, DeclContext *DC);
1168  void PopDeclContext();
1169
1170  /// EnterDeclaratorContext - Used when we must lookup names in the context
1171  /// of a declarator's nested name specifier.
1172  void EnterDeclaratorContext(Scope *S, DeclContext *DC);
1173  void ExitDeclaratorContext(Scope *S);
1174
1175  DeclContext *getFunctionLevelDeclContext();
1176
1177  /// getCurFunctionDecl - If inside of a function body, this returns a pointer
1178  /// to the function decl for the function being parsed.  If we're currently
1179  /// in a 'block', this returns the containing context.
1180  FunctionDecl *getCurFunctionDecl();
1181
1182  /// getCurMethodDecl - If inside of a method body, this returns a pointer to
1183  /// the method decl for the method being parsed.  If we're currently
1184  /// in a 'block', this returns the containing context.
1185  ObjCMethodDecl *getCurMethodDecl();
1186
1187  /// getCurFunctionOrMethodDecl - Return the Decl for the current ObjC method
1188  /// or C function we're in, otherwise return null.  If we're currently
1189  /// in a 'block', this returns the containing context.
1190  NamedDecl *getCurFunctionOrMethodDecl();
1191
1192  /// Add this decl to the scope shadowed decl chains.
1193  void PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext = true);
1194
1195  /// isDeclInScope - If 'Ctx' is a function/method, isDeclInScope returns true
1196  /// if 'D' is in Scope 'S', otherwise 'S' is ignored and isDeclInScope returns
1197  /// true if 'D' belongs to the given declaration context.
1198  ///
1199  /// \param ExplicitInstantiationOrSpecialization When true, we are checking
1200  /// whether the declaration is in scope for the purposes of explicit template
1201  /// instantiation or specialization. The default is false.
1202  bool isDeclInScope(NamedDecl *&D, DeclContext *Ctx, Scope *S = 0,
1203                     bool ExplicitInstantiationOrSpecialization = false);
1204
1205  /// Finds the scope corresponding to the given decl context, if it
1206  /// happens to be an enclosing scope.  Otherwise return NULL.
1207  static Scope *getScopeForDeclContext(Scope *S, DeclContext *DC);
1208
1209  /// Subroutines of ActOnDeclarator().
1210  TypedefDecl *ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
1211                                TypeSourceInfo *TInfo);
1212  void MergeTypedefNameDecl(TypedefNameDecl *New, LookupResult &OldDecls);
1213  bool MergeFunctionDecl(FunctionDecl *New, Decl *Old);
1214  bool MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old);
1215  void mergeObjCMethodDecls(ObjCMethodDecl *New, const ObjCMethodDecl *Old);
1216  void MergeVarDecl(VarDecl *New, LookupResult &OldDecls);
1217  void MergeVarDeclTypes(VarDecl *New, VarDecl *Old);
1218  void MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old);
1219  bool MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old);
1220
1221  // AssignmentAction - This is used by all the assignment diagnostic functions
1222  // to represent what is actually causing the operation
1223  enum AssignmentAction {
1224    AA_Assigning,
1225    AA_Passing,
1226    AA_Returning,
1227    AA_Converting,
1228    AA_Initializing,
1229    AA_Sending,
1230    AA_Casting
1231  };
1232
1233  /// C++ Overloading.
1234  enum OverloadKind {
1235    /// This is a legitimate overload: the existing declarations are
1236    /// functions or function templates with different signatures.
1237    Ovl_Overload,
1238
1239    /// This is not an overload because the signature exactly matches
1240    /// an existing declaration.
1241    Ovl_Match,
1242
1243    /// This is not an overload because the lookup results contain a
1244    /// non-function.
1245    Ovl_NonFunction
1246  };
1247  OverloadKind CheckOverload(Scope *S,
1248                             FunctionDecl *New,
1249                             const LookupResult &OldDecls,
1250                             NamedDecl *&OldDecl,
1251                             bool IsForUsingDecl);
1252  bool IsOverload(FunctionDecl *New, FunctionDecl *Old, bool IsForUsingDecl);
1253
1254  bool TryImplicitConversion(InitializationSequence &Sequence,
1255                             const InitializedEntity &Entity,
1256                             Expr *From,
1257                             bool SuppressUserConversions,
1258                             bool AllowExplicit,
1259                             bool InOverloadResolution,
1260                             bool CStyle);
1261
1262  bool IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType);
1263  bool IsFloatingPointPromotion(QualType FromType, QualType ToType);
1264  bool IsComplexPromotion(QualType FromType, QualType ToType);
1265  bool IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
1266                           bool InOverloadResolution,
1267                           QualType& ConvertedType, bool &IncompatibleObjC);
1268  bool isObjCPointerConversion(QualType FromType, QualType ToType,
1269                               QualType& ConvertedType, bool &IncompatibleObjC);
1270  bool IsBlockPointerConversion(QualType FromType, QualType ToType,
1271                                QualType& ConvertedType);
1272  bool FunctionArgTypesAreEqual(const FunctionProtoType *OldType,
1273                                const FunctionProtoType *NewType);
1274
1275  bool CheckPointerConversion(Expr *From, QualType ToType,
1276                              CastKind &Kind,
1277                              CXXCastPath& BasePath,
1278                              bool IgnoreBaseAccess);
1279  bool IsMemberPointerConversion(Expr *From, QualType FromType, QualType ToType,
1280                                 bool InOverloadResolution,
1281                                 QualType &ConvertedType);
1282  bool CheckMemberPointerConversion(Expr *From, QualType ToType,
1283                                    CastKind &Kind,
1284                                    CXXCastPath &BasePath,
1285                                    bool IgnoreBaseAccess);
1286  bool IsQualificationConversion(QualType FromType, QualType ToType,
1287                                 bool CStyle);
1288  bool DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType);
1289
1290
1291  ExprResult PerformMoveOrCopyInitialization(const InitializedEntity &Entity,
1292                                             const VarDecl *NRVOCandidate,
1293                                             QualType ResultType,
1294                                             Expr *Value);
1295
1296  bool CanPerformCopyInitialization(const InitializedEntity &Entity,
1297                                    ExprResult Init);
1298  ExprResult PerformCopyInitialization(const InitializedEntity &Entity,
1299                                       SourceLocation EqualLoc,
1300                                       ExprResult Init);
1301  ExprResult PerformObjectArgumentInitialization(Expr *From,
1302                                                 NestedNameSpecifier *Qualifier,
1303                                                 NamedDecl *FoundDecl,
1304                                                 CXXMethodDecl *Method);
1305
1306  ExprResult PerformContextuallyConvertToBool(Expr *From);
1307  ExprResult PerformContextuallyConvertToObjCId(Expr *From);
1308
1309  ExprResult
1310  ConvertToIntegralOrEnumerationType(SourceLocation Loc, Expr *FromE,
1311                                     const PartialDiagnostic &NotIntDiag,
1312                                     const PartialDiagnostic &IncompleteDiag,
1313                                     const PartialDiagnostic &ExplicitConvDiag,
1314                                     const PartialDiagnostic &ExplicitConvNote,
1315                                     const PartialDiagnostic &AmbigDiag,
1316                                     const PartialDiagnostic &AmbigNote,
1317                                     const PartialDiagnostic &ConvDiag);
1318
1319  ExprResult PerformObjectMemberConversion(Expr *From,
1320                                           NestedNameSpecifier *Qualifier,
1321                                           NamedDecl *FoundDecl,
1322                                           NamedDecl *Member);
1323
1324  // Members have to be NamespaceDecl* or TranslationUnitDecl*.
1325  // TODO: make this is a typesafe union.
1326  typedef llvm::SmallPtrSet<DeclContext   *, 16> AssociatedNamespaceSet;
1327  typedef llvm::SmallPtrSet<CXXRecordDecl *, 16> AssociatedClassSet;
1328
1329  void AddOverloadCandidate(NamedDecl *Function,
1330                            DeclAccessPair FoundDecl,
1331                            Expr **Args, unsigned NumArgs,
1332                            OverloadCandidateSet &CandidateSet);
1333
1334  void AddOverloadCandidate(FunctionDecl *Function,
1335                            DeclAccessPair FoundDecl,
1336                            Expr **Args, unsigned NumArgs,
1337                            OverloadCandidateSet& CandidateSet,
1338                            bool SuppressUserConversions = false,
1339                            bool PartialOverloading = false);
1340  void AddFunctionCandidates(const UnresolvedSetImpl &Functions,
1341                             Expr **Args, unsigned NumArgs,
1342                             OverloadCandidateSet& CandidateSet,
1343                             bool SuppressUserConversions = false);
1344  void AddMethodCandidate(DeclAccessPair FoundDecl,
1345                          QualType ObjectType,
1346                          Expr::Classification ObjectClassification,
1347                          Expr **Args, unsigned NumArgs,
1348                          OverloadCandidateSet& CandidateSet,
1349                          bool SuppressUserConversion = false);
1350  void AddMethodCandidate(CXXMethodDecl *Method,
1351                          DeclAccessPair FoundDecl,
1352                          CXXRecordDecl *ActingContext, QualType ObjectType,
1353                          Expr::Classification ObjectClassification,
1354                          Expr **Args, unsigned NumArgs,
1355                          OverloadCandidateSet& CandidateSet,
1356                          bool SuppressUserConversions = false);
1357  void AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
1358                                  DeclAccessPair FoundDecl,
1359                                  CXXRecordDecl *ActingContext,
1360                                 TemplateArgumentListInfo *ExplicitTemplateArgs,
1361                                  QualType ObjectType,
1362                                  Expr::Classification ObjectClassification,
1363                                  Expr **Args, unsigned NumArgs,
1364                                  OverloadCandidateSet& CandidateSet,
1365                                  bool SuppressUserConversions = false);
1366  void AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
1367                                    DeclAccessPair FoundDecl,
1368                                 TemplateArgumentListInfo *ExplicitTemplateArgs,
1369                                    Expr **Args, unsigned NumArgs,
1370                                    OverloadCandidateSet& CandidateSet,
1371                                    bool SuppressUserConversions = false);
1372  void AddConversionCandidate(CXXConversionDecl *Conversion,
1373                              DeclAccessPair FoundDecl,
1374                              CXXRecordDecl *ActingContext,
1375                              Expr *From, QualType ToType,
1376                              OverloadCandidateSet& CandidateSet);
1377  void AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
1378                                      DeclAccessPair FoundDecl,
1379                                      CXXRecordDecl *ActingContext,
1380                                      Expr *From, QualType ToType,
1381                                      OverloadCandidateSet &CandidateSet);
1382  void AddSurrogateCandidate(CXXConversionDecl *Conversion,
1383                             DeclAccessPair FoundDecl,
1384                             CXXRecordDecl *ActingContext,
1385                             const FunctionProtoType *Proto,
1386                             Expr *Object, Expr **Args, unsigned NumArgs,
1387                             OverloadCandidateSet& CandidateSet);
1388  void AddMemberOperatorCandidates(OverloadedOperatorKind Op,
1389                                   SourceLocation OpLoc,
1390                                   Expr **Args, unsigned NumArgs,
1391                                   OverloadCandidateSet& CandidateSet,
1392                                   SourceRange OpRange = SourceRange());
1393  void AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
1394                           Expr **Args, unsigned NumArgs,
1395                           OverloadCandidateSet& CandidateSet,
1396                           bool IsAssignmentOperator = false,
1397                           unsigned NumContextualBoolArguments = 0);
1398  void AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
1399                                    SourceLocation OpLoc,
1400                                    Expr **Args, unsigned NumArgs,
1401                                    OverloadCandidateSet& CandidateSet);
1402  void AddArgumentDependentLookupCandidates(DeclarationName Name,
1403                                            bool Operator,
1404                                            Expr **Args, unsigned NumArgs,
1405                                TemplateArgumentListInfo *ExplicitTemplateArgs,
1406                                            OverloadCandidateSet& CandidateSet,
1407                                            bool PartialOverloading = false,
1408                                        bool StdNamespaceIsAssociated = false);
1409
1410  // Emit as a 'note' the specific overload candidate
1411  void NoteOverloadCandidate(FunctionDecl *Fn);
1412
1413  // Emit as a series of 'note's all template and non-templates
1414  // identified by the expression Expr
1415  void NoteAllOverloadCandidates(Expr* E);
1416
1417  // [PossiblyAFunctionType]  -->   [Return]
1418  // NonFunctionType --> NonFunctionType
1419  // R (A) --> R(A)
1420  // R (*)(A) --> R (A)
1421  // R (&)(A) --> R (A)
1422  // R (S::*)(A) --> R (A)
1423  QualType ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType);
1424
1425  FunctionDecl *ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr, QualType TargetType,
1426                                                   bool Complain,
1427                                                   DeclAccessPair &Found);
1428
1429  FunctionDecl *ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
1430                                                   bool Complain = false,
1431                                                   DeclAccessPair* Found = 0);
1432
1433  ExprResult ResolveAndFixSingleFunctionTemplateSpecialization(
1434                      Expr *SrcExpr, bool DoFunctionPointerConverion = false,
1435                      bool Complain = false,
1436                      const SourceRange& OpRangeForComplaining = SourceRange(),
1437                      QualType DestTypeForComplaining = QualType(),
1438                      unsigned DiagIDForComplaining = 0);
1439
1440
1441  Expr *FixOverloadedFunctionReference(Expr *E,
1442                                       DeclAccessPair FoundDecl,
1443                                       FunctionDecl *Fn);
1444  ExprResult FixOverloadedFunctionReference(ExprResult,
1445                                            DeclAccessPair FoundDecl,
1446                                            FunctionDecl *Fn);
1447
1448  void AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
1449                                   Expr **Args, unsigned NumArgs,
1450                                   OverloadCandidateSet &CandidateSet,
1451                                   bool PartialOverloading = false);
1452
1453  ExprResult BuildOverloadedCallExpr(Scope *S, Expr *Fn,
1454                                     UnresolvedLookupExpr *ULE,
1455                                     SourceLocation LParenLoc,
1456                                     Expr **Args, unsigned NumArgs,
1457                                     SourceLocation RParenLoc,
1458                                     Expr *ExecConfig);
1459
1460  ExprResult CreateOverloadedUnaryOp(SourceLocation OpLoc,
1461                                     unsigned Opc,
1462                                     const UnresolvedSetImpl &Fns,
1463                                     Expr *input);
1464
1465  ExprResult CreateOverloadedBinOp(SourceLocation OpLoc,
1466                                   unsigned Opc,
1467                                   const UnresolvedSetImpl &Fns,
1468                                   Expr *LHS, Expr *RHS);
1469
1470  ExprResult CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
1471                                                SourceLocation RLoc,
1472                                                Expr *Base,Expr *Idx);
1473
1474  ExprResult
1475  BuildCallToMemberFunction(Scope *S, Expr *MemExpr,
1476                            SourceLocation LParenLoc, Expr **Args,
1477                            unsigned NumArgs, SourceLocation RParenLoc);
1478  ExprResult
1479  BuildCallToObjectOfClassType(Scope *S, Expr *Object, SourceLocation LParenLoc,
1480                               Expr **Args, unsigned NumArgs,
1481                               SourceLocation RParenLoc);
1482
1483  ExprResult BuildOverloadedArrowExpr(Scope *S, Expr *Base,
1484                                      SourceLocation OpLoc);
1485
1486  /// CheckCallReturnType - Checks that a call expression's return type is
1487  /// complete. Returns true on failure. The location passed in is the location
1488  /// that best represents the call.
1489  bool CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
1490                           CallExpr *CE, FunctionDecl *FD);
1491
1492  /// Helpers for dealing with blocks and functions.
1493  bool CheckParmsForFunctionDef(ParmVarDecl **Param, ParmVarDecl **ParamEnd,
1494                                bool CheckParameterNames);
1495  void CheckCXXDefaultArguments(FunctionDecl *FD);
1496  void CheckExtraCXXDefaultArguments(Declarator &D);
1497  Scope *getNonFieldDeclScope(Scope *S);
1498
1499  /// \name Name lookup
1500  ///
1501  /// These routines provide name lookup that is used during semantic
1502  /// analysis to resolve the various kinds of names (identifiers,
1503  /// overloaded operator names, constructor names, etc.) into zero or
1504  /// more declarations within a particular scope. The major entry
1505  /// points are LookupName, which performs unqualified name lookup,
1506  /// and LookupQualifiedName, which performs qualified name lookup.
1507  ///
1508  /// All name lookup is performed based on some specific criteria,
1509  /// which specify what names will be visible to name lookup and how
1510  /// far name lookup should work. These criteria are important both
1511  /// for capturing language semantics (certain lookups will ignore
1512  /// certain names, for example) and for performance, since name
1513  /// lookup is often a bottleneck in the compilation of C++. Name
1514  /// lookup criteria is specified via the LookupCriteria enumeration.
1515  ///
1516  /// The results of name lookup can vary based on the kind of name
1517  /// lookup performed, the current language, and the translation
1518  /// unit. In C, for example, name lookup will either return nothing
1519  /// (no entity found) or a single declaration. In C++, name lookup
1520  /// can additionally refer to a set of overloaded functions or
1521  /// result in an ambiguity. All of the possible results of name
1522  /// lookup are captured by the LookupResult class, which provides
1523  /// the ability to distinguish among them.
1524  //@{
1525
1526  /// @brief Describes the kind of name lookup to perform.
1527  enum LookupNameKind {
1528    /// Ordinary name lookup, which finds ordinary names (functions,
1529    /// variables, typedefs, etc.) in C and most kinds of names
1530    /// (functions, variables, members, types, etc.) in C++.
1531    LookupOrdinaryName = 0,
1532    /// Tag name lookup, which finds the names of enums, classes,
1533    /// structs, and unions.
1534    LookupTagName,
1535    /// Label name lookup.
1536    LookupLabel,
1537    /// Member name lookup, which finds the names of
1538    /// class/struct/union members.
1539    LookupMemberName,
1540    /// Look up of an operator name (e.g., operator+) for use with
1541    /// operator overloading. This lookup is similar to ordinary name
1542    /// lookup, but will ignore any declarations that are class members.
1543    LookupOperatorName,
1544    /// Look up of a name that precedes the '::' scope resolution
1545    /// operator in C++. This lookup completely ignores operator, object,
1546    /// function, and enumerator names (C++ [basic.lookup.qual]p1).
1547    LookupNestedNameSpecifierName,
1548    /// Look up a namespace name within a C++ using directive or
1549    /// namespace alias definition, ignoring non-namespace names (C++
1550    /// [basic.lookup.udir]p1).
1551    LookupNamespaceName,
1552    /// Look up all declarations in a scope with the given name,
1553    /// including resolved using declarations.  This is appropriate
1554    /// for checking redeclarations for a using declaration.
1555    LookupUsingDeclName,
1556    /// Look up an ordinary name that is going to be redeclared as a
1557    /// name with linkage. This lookup ignores any declarations that
1558    /// are outside of the current scope unless they have linkage. See
1559    /// C99 6.2.2p4-5 and C++ [basic.link]p6.
1560    LookupRedeclarationWithLinkage,
1561    /// Look up the name of an Objective-C protocol.
1562    LookupObjCProtocolName,
1563    /// \brief Look up any declaration with any name.
1564    LookupAnyName
1565  };
1566
1567  /// \brief Specifies whether (or how) name lookup is being performed for a
1568  /// redeclaration (vs. a reference).
1569  enum RedeclarationKind {
1570    /// \brief The lookup is a reference to this name that is not for the
1571    /// purpose of redeclaring the name.
1572    NotForRedeclaration = 0,
1573    /// \brief The lookup results will be used for redeclaration of a name,
1574    /// if an entity by that name already exists.
1575    ForRedeclaration
1576  };
1577
1578private:
1579  bool CppLookupName(LookupResult &R, Scope *S);
1580
1581public:
1582  /// \brief Look up a name, looking for a single declaration.  Return
1583  /// null if the results were absent, ambiguous, or overloaded.
1584  ///
1585  /// It is preferable to use the elaborated form and explicitly handle
1586  /// ambiguity and overloaded.
1587  NamedDecl *LookupSingleName(Scope *S, DeclarationName Name,
1588                              SourceLocation Loc,
1589                              LookupNameKind NameKind,
1590                              RedeclarationKind Redecl
1591                                = NotForRedeclaration);
1592  bool LookupName(LookupResult &R, Scope *S,
1593                  bool AllowBuiltinCreation = false);
1594  bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
1595                           bool InUnqualifiedLookup = false);
1596  bool LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS,
1597                        bool AllowBuiltinCreation = false,
1598                        bool EnteringContext = false);
1599  ObjCProtocolDecl *LookupProtocol(IdentifierInfo *II, SourceLocation IdLoc);
1600
1601  void LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S,
1602                                    QualType T1, QualType T2,
1603                                    UnresolvedSetImpl &Functions);
1604
1605  LabelDecl *LookupOrCreateLabel(IdentifierInfo *II, SourceLocation IdentLoc,
1606                                 SourceLocation GnuLabelLoc = SourceLocation());
1607
1608  DeclContextLookupResult LookupConstructors(CXXRecordDecl *Class);
1609  CXXDestructorDecl *LookupDestructor(CXXRecordDecl *Class);
1610
1611  void ArgumentDependentLookup(DeclarationName Name, bool Operator,
1612                               Expr **Args, unsigned NumArgs,
1613                               ADLResult &Functions,
1614                               bool StdNamespaceIsAssociated = false);
1615
1616  void LookupVisibleDecls(Scope *S, LookupNameKind Kind,
1617                          VisibleDeclConsumer &Consumer,
1618                          bool IncludeGlobalScope = true);
1619  void LookupVisibleDecls(DeclContext *Ctx, LookupNameKind Kind,
1620                          VisibleDeclConsumer &Consumer,
1621                          bool IncludeGlobalScope = true);
1622
1623  /// \brief The context in which typo-correction occurs.
1624  ///
1625  /// The typo-correction context affects which keywords (if any) are
1626  /// considered when trying to correct for typos.
1627  enum CorrectTypoContext {
1628    /// \brief An unknown context, where any keyword might be valid.
1629    CTC_Unknown,
1630    /// \brief A context where no keywords are used (e.g. we expect an actual
1631    /// name).
1632    CTC_NoKeywords,
1633    /// \brief A context where we're correcting a type name.
1634    CTC_Type,
1635    /// \brief An expression context.
1636    CTC_Expression,
1637    /// \brief A type cast, or anything else that can be followed by a '<'.
1638    CTC_CXXCasts,
1639    /// \brief A member lookup context.
1640    CTC_MemberLookup,
1641    /// \brief An Objective-C ivar lookup context (e.g., self->ivar).
1642    CTC_ObjCIvarLookup,
1643    /// \brief An Objective-C property lookup context (e.g., self.prop).
1644    CTC_ObjCPropertyLookup,
1645    /// \brief The receiver of an Objective-C message send within an
1646    /// Objective-C method where 'super' is a valid keyword.
1647    CTC_ObjCMessageReceiver
1648  };
1649
1650  DeclarationName CorrectTypo(LookupResult &R, Scope *S, CXXScopeSpec *SS,
1651                              DeclContext *MemberContext = 0,
1652                              bool EnteringContext = false,
1653                              CorrectTypoContext CTC = CTC_Unknown,
1654                              const ObjCObjectPointerType *OPT = 0);
1655
1656  void FindAssociatedClassesAndNamespaces(Expr **Args, unsigned NumArgs,
1657                                   AssociatedNamespaceSet &AssociatedNamespaces,
1658                                   AssociatedClassSet &AssociatedClasses);
1659
1660  void FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S,
1661                            bool ConsiderLinkage,
1662                            bool ExplicitInstantiationOrSpecialization);
1663
1664  bool DiagnoseAmbiguousLookup(LookupResult &Result);
1665  //@}
1666
1667  ObjCInterfaceDecl *getObjCInterfaceDecl(IdentifierInfo *&Id,
1668                                          SourceLocation IdLoc,
1669                                          bool TypoCorrection = false);
1670  NamedDecl *LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID,
1671                                 Scope *S, bool ForRedeclaration,
1672                                 SourceLocation Loc);
1673  NamedDecl *ImplicitlyDefineFunction(SourceLocation Loc, IdentifierInfo &II,
1674                                      Scope *S);
1675  void AddKnownFunctionAttributes(FunctionDecl *FD);
1676
1677  // More parsing and symbol table subroutines.
1678
1679  // Decl attributes - this routine is the top level dispatcher.
1680  void ProcessDeclAttributes(Scope *S, Decl *D, const Declarator &PD,
1681                           bool NonInheritable = true, bool Inheritable = true);
1682  void ProcessDeclAttributeList(Scope *S, Decl *D, const AttributeList *AL,
1683                           bool NonInheritable = true, bool Inheritable = true);
1684
1685  bool CheckRegparmAttr(const AttributeList &attr, unsigned &value);
1686  bool CheckCallingConvAttr(const AttributeList &attr, CallingConv &CC);
1687  bool CheckNoReturnAttr(const AttributeList &attr);
1688
1689  void WarnUndefinedMethod(SourceLocation ImpLoc, ObjCMethodDecl *method,
1690                           bool &IncompleteImpl, unsigned DiagID);
1691  void WarnConflictingTypedMethods(ObjCMethodDecl *ImpMethod,
1692                                   ObjCMethodDecl *MethodDecl,
1693                                   bool IsProtocolMethodDecl);
1694
1695  bool isPropertyReadonly(ObjCPropertyDecl *PropertyDecl,
1696                          ObjCInterfaceDecl *IDecl);
1697
1698  typedef llvm::DenseSet<Selector, llvm::DenseMapInfo<Selector> > SelectorSet;
1699
1700  /// CheckProtocolMethodDefs - This routine checks unimplemented
1701  /// methods declared in protocol, and those referenced by it.
1702  /// \param IDecl - Used for checking for methods which may have been
1703  /// inherited.
1704  void CheckProtocolMethodDefs(SourceLocation ImpLoc,
1705                               ObjCProtocolDecl *PDecl,
1706                               bool& IncompleteImpl,
1707                               const SelectorSet &InsMap,
1708                               const SelectorSet &ClsMap,
1709                               ObjCContainerDecl *CDecl);
1710
1711  /// CheckImplementationIvars - This routine checks if the instance variables
1712  /// listed in the implelementation match those listed in the interface.
1713  void CheckImplementationIvars(ObjCImplementationDecl *ImpDecl,
1714                                ObjCIvarDecl **Fields, unsigned nIvars,
1715                                SourceLocation Loc);
1716
1717  /// \brief Determine whether we can synthesize a provisional ivar for the
1718  /// given name.
1719  ObjCPropertyDecl *canSynthesizeProvisionalIvar(IdentifierInfo *II);
1720
1721  /// \brief Determine whether we can synthesize a provisional ivar for the
1722  /// given property.
1723  bool canSynthesizeProvisionalIvar(ObjCPropertyDecl *Property);
1724
1725  /// ImplMethodsVsClassMethods - This is main routine to warn if any method
1726  /// remains unimplemented in the class or category @implementation.
1727  void ImplMethodsVsClassMethods(Scope *S, ObjCImplDecl* IMPDecl,
1728                                 ObjCContainerDecl* IDecl,
1729                                 bool IncompleteImpl = false);
1730
1731  /// DiagnoseUnimplementedProperties - This routine warns on those properties
1732  /// which must be implemented by this implementation.
1733  void DiagnoseUnimplementedProperties(Scope *S, ObjCImplDecl* IMPDecl,
1734                                       ObjCContainerDecl *CDecl,
1735                                       const SelectorSet &InsMap);
1736
1737  /// DefaultSynthesizeProperties - This routine default synthesizes all
1738  /// properties which must be synthesized in class's @implementation.
1739  void DefaultSynthesizeProperties (Scope *S, ObjCImplDecl* IMPDecl,
1740                                    ObjCInterfaceDecl *IDecl);
1741
1742  /// CollectImmediateProperties - This routine collects all properties in
1743  /// the class and its conforming protocols; but not those it its super class.
1744  void CollectImmediateProperties(ObjCContainerDecl *CDecl,
1745            llvm::DenseMap<IdentifierInfo *, ObjCPropertyDecl*>& PropMap,
1746            llvm::DenseMap<IdentifierInfo *, ObjCPropertyDecl*>& SuperPropMap);
1747
1748
1749  /// LookupPropertyDecl - Looks up a property in the current class and all
1750  /// its protocols.
1751  ObjCPropertyDecl *LookupPropertyDecl(const ObjCContainerDecl *CDecl,
1752                                       IdentifierInfo *II);
1753
1754  /// Called by ActOnProperty to handle @property declarations in
1755  ////  class extensions.
1756  Decl *HandlePropertyInClassExtension(Scope *S,
1757                                       ObjCCategoryDecl *CDecl,
1758                                       SourceLocation AtLoc,
1759                                       FieldDeclarator &FD,
1760                                       Selector GetterSel,
1761                                       Selector SetterSel,
1762                                       const bool isAssign,
1763                                       const bool isReadWrite,
1764                                       const unsigned Attributes,
1765                                       bool *isOverridingProperty,
1766                                       TypeSourceInfo *T,
1767                                       tok::ObjCKeywordKind MethodImplKind);
1768
1769  /// Called by ActOnProperty and HandlePropertyInClassExtension to
1770  ///  handle creating the ObjcPropertyDecl for a category or @interface.
1771  ObjCPropertyDecl *CreatePropertyDecl(Scope *S,
1772                                       ObjCContainerDecl *CDecl,
1773                                       SourceLocation AtLoc,
1774                                       FieldDeclarator &FD,
1775                                       Selector GetterSel,
1776                                       Selector SetterSel,
1777                                       const bool isAssign,
1778                                       const bool isReadWrite,
1779                                       const unsigned Attributes,
1780                                       TypeSourceInfo *T,
1781                                       tok::ObjCKeywordKind MethodImplKind,
1782                                       DeclContext *lexicalDC = 0);
1783
1784  /// AtomicPropertySetterGetterRules - This routine enforces the rule (via
1785  /// warning) when atomic property has one but not the other user-declared
1786  /// setter or getter.
1787  void AtomicPropertySetterGetterRules(ObjCImplDecl* IMPDecl,
1788                                       ObjCContainerDecl* IDecl);
1789
1790  void DiagnoseDuplicateIvars(ObjCInterfaceDecl *ID, ObjCInterfaceDecl *SID);
1791
1792  /// MatchTwoMethodDeclarations - Checks if two methods' type match and returns
1793  /// true, or false, accordingly.
1794  bool MatchTwoMethodDeclarations(const ObjCMethodDecl *Method,
1795                                  const ObjCMethodDecl *PrevMethod,
1796                                  bool matchBasedOnSizeAndAlignment = false,
1797                                  bool matchBasedOnStrictEqulity = false);
1798
1799  /// MatchAllMethodDeclarations - Check methods declaraed in interface or
1800  /// or protocol against those declared in their implementations.
1801  void MatchAllMethodDeclarations(const SelectorSet &InsMap,
1802                                  const SelectorSet &ClsMap,
1803                                  SelectorSet &InsMapSeen,
1804                                  SelectorSet &ClsMapSeen,
1805                                  ObjCImplDecl* IMPDecl,
1806                                  ObjCContainerDecl* IDecl,
1807                                  bool &IncompleteImpl,
1808                                  bool ImmediateClass);
1809
1810private:
1811  /// AddMethodToGlobalPool - Add an instance or factory method to the global
1812  /// pool. See descriptoin of AddInstanceMethodToGlobalPool.
1813  void AddMethodToGlobalPool(ObjCMethodDecl *Method, bool impl, bool instance);
1814
1815  /// LookupMethodInGlobalPool - Returns the instance or factory method and
1816  /// optionally warns if there are multiple signatures.
1817  ObjCMethodDecl *LookupMethodInGlobalPool(Selector Sel, SourceRange R,
1818                                           bool receiverIdOrClass,
1819                                           bool warn, bool instance);
1820
1821public:
1822  /// AddInstanceMethodToGlobalPool - All instance methods in a translation
1823  /// unit are added to a global pool. This allows us to efficiently associate
1824  /// a selector with a method declaraation for purposes of typechecking
1825  /// messages sent to "id" (where the class of the object is unknown).
1826  void AddInstanceMethodToGlobalPool(ObjCMethodDecl *Method, bool impl=false) {
1827    AddMethodToGlobalPool(Method, impl, /*instance*/true);
1828  }
1829
1830  /// AddFactoryMethodToGlobalPool - Same as above, but for factory methods.
1831  void AddFactoryMethodToGlobalPool(ObjCMethodDecl *Method, bool impl=false) {
1832    AddMethodToGlobalPool(Method, impl, /*instance*/false);
1833  }
1834
1835  /// LookupInstanceMethodInGlobalPool - Returns the method and warns if
1836  /// there are multiple signatures.
1837  ObjCMethodDecl *LookupInstanceMethodInGlobalPool(Selector Sel, SourceRange R,
1838                                                   bool receiverIdOrClass=false,
1839                                                   bool warn=true) {
1840    return LookupMethodInGlobalPool(Sel, R, receiverIdOrClass,
1841                                    warn, /*instance*/true);
1842  }
1843
1844  /// LookupFactoryMethodInGlobalPool - Returns the method and warns if
1845  /// there are multiple signatures.
1846  ObjCMethodDecl *LookupFactoryMethodInGlobalPool(Selector Sel, SourceRange R,
1847                                                  bool receiverIdOrClass=false,
1848                                                  bool warn=true) {
1849    return LookupMethodInGlobalPool(Sel, R, receiverIdOrClass,
1850                                    warn, /*instance*/false);
1851  }
1852
1853  /// LookupImplementedMethodInGlobalPool - Returns the method which has an
1854  /// implementation.
1855  ObjCMethodDecl *LookupImplementedMethodInGlobalPool(Selector Sel);
1856
1857  /// CollectIvarsToConstructOrDestruct - Collect those ivars which require
1858  /// initialization.
1859  void CollectIvarsToConstructOrDestruct(ObjCInterfaceDecl *OI,
1860                                  llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars);
1861
1862  //===--------------------------------------------------------------------===//
1863  // Statement Parsing Callbacks: SemaStmt.cpp.
1864public:
1865  class FullExprArg {
1866  public:
1867    FullExprArg(Sema &actions) : E(0) { }
1868
1869    // FIXME: The const_cast here is ugly. RValue references would make this
1870    // much nicer (or we could duplicate a bunch of the move semantics
1871    // emulation code from Ownership.h).
1872    FullExprArg(const FullExprArg& Other) : E(Other.E) {}
1873
1874    ExprResult release() {
1875      return move(E);
1876    }
1877
1878    Expr *get() const { return E; }
1879
1880    Expr *operator->() {
1881      return E;
1882    }
1883
1884  private:
1885    // FIXME: No need to make the entire Sema class a friend when it's just
1886    // Sema::MakeFullExpr that needs access to the constructor below.
1887    friend class Sema;
1888
1889    explicit FullExprArg(Expr *expr) : E(expr) {}
1890
1891    Expr *E;
1892  };
1893
1894  FullExprArg MakeFullExpr(Expr *Arg) {
1895    return FullExprArg(ActOnFinishFullExpr(Arg).release());
1896  }
1897
1898  StmtResult ActOnExprStmt(FullExprArg Expr);
1899
1900  StmtResult ActOnNullStmt(SourceLocation SemiLoc,
1901                        SourceLocation LeadingEmptyMacroLoc = SourceLocation());
1902  StmtResult ActOnCompoundStmt(SourceLocation L, SourceLocation R,
1903                                       MultiStmtArg Elts,
1904                                       bool isStmtExpr);
1905  StmtResult ActOnDeclStmt(DeclGroupPtrTy Decl,
1906                                   SourceLocation StartLoc,
1907                                   SourceLocation EndLoc);
1908  void ActOnForEachDeclStmt(DeclGroupPtrTy Decl);
1909  StmtResult ActOnForEachLValueExpr(Expr *E);
1910  StmtResult ActOnCaseStmt(SourceLocation CaseLoc, Expr *LHSVal,
1911                                   SourceLocation DotDotDotLoc, Expr *RHSVal,
1912                                   SourceLocation ColonLoc);
1913  void ActOnCaseStmtBody(Stmt *CaseStmt, Stmt *SubStmt);
1914
1915  StmtResult ActOnDefaultStmt(SourceLocation DefaultLoc,
1916                                      SourceLocation ColonLoc,
1917                                      Stmt *SubStmt, Scope *CurScope);
1918  StmtResult ActOnLabelStmt(SourceLocation IdentLoc, LabelDecl *TheDecl,
1919                            SourceLocation ColonLoc, Stmt *SubStmt);
1920
1921  StmtResult ActOnIfStmt(SourceLocation IfLoc,
1922                         FullExprArg CondVal, Decl *CondVar,
1923                         Stmt *ThenVal,
1924                         SourceLocation ElseLoc, Stmt *ElseVal);
1925  StmtResult ActOnStartOfSwitchStmt(SourceLocation SwitchLoc,
1926                                            Expr *Cond,
1927                                            Decl *CondVar);
1928  StmtResult ActOnFinishSwitchStmt(SourceLocation SwitchLoc,
1929                                           Stmt *Switch, Stmt *Body);
1930  StmtResult ActOnWhileStmt(SourceLocation WhileLoc,
1931                            FullExprArg Cond,
1932                            Decl *CondVar, Stmt *Body);
1933  StmtResult ActOnDoStmt(SourceLocation DoLoc, Stmt *Body,
1934                                 SourceLocation WhileLoc,
1935                                 SourceLocation CondLParen, Expr *Cond,
1936                                 SourceLocation CondRParen);
1937
1938  StmtResult ActOnForStmt(SourceLocation ForLoc,
1939                          SourceLocation LParenLoc,
1940                          Stmt *First, FullExprArg Second,
1941                          Decl *SecondVar,
1942                          FullExprArg Third,
1943                          SourceLocation RParenLoc,
1944                          Stmt *Body);
1945  StmtResult ActOnObjCForCollectionStmt(SourceLocation ForColLoc,
1946                                        SourceLocation LParenLoc,
1947                                        Stmt *First, Expr *Second,
1948                                        SourceLocation RParenLoc, Stmt *Body);
1949  StmtResult ActOnCXXForRangeStmt(SourceLocation ForLoc,
1950                                  SourceLocation LParenLoc, Stmt *LoopVar,
1951                                  SourceLocation ColonLoc, Expr *Collection,
1952                                  SourceLocation RParenLoc);
1953  StmtResult BuildCXXForRangeStmt(SourceLocation ForLoc,
1954                                  SourceLocation ColonLoc,
1955                                  Stmt *RangeDecl, Stmt *BeginEndDecl,
1956                                  Expr *Cond, Expr *Inc,
1957                                  Stmt *LoopVarDecl,
1958                                  SourceLocation RParenLoc);
1959  StmtResult FinishCXXForRangeStmt(Stmt *ForRange, Stmt *Body);
1960
1961  StmtResult ActOnGotoStmt(SourceLocation GotoLoc,
1962                           SourceLocation LabelLoc,
1963                           LabelDecl *TheDecl);
1964  StmtResult ActOnIndirectGotoStmt(SourceLocation GotoLoc,
1965                                   SourceLocation StarLoc,
1966                                   Expr *DestExp);
1967  StmtResult ActOnContinueStmt(SourceLocation ContinueLoc, Scope *CurScope);
1968  StmtResult ActOnBreakStmt(SourceLocation GotoLoc, Scope *CurScope);
1969
1970  const VarDecl *getCopyElisionCandidate(QualType ReturnType, Expr *E,
1971                                         bool AllowFunctionParameters);
1972
1973  StmtResult ActOnReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp);
1974  StmtResult ActOnBlockReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp);
1975
1976  StmtResult ActOnAsmStmt(SourceLocation AsmLoc,
1977                          bool IsSimple, bool IsVolatile,
1978                          unsigned NumOutputs, unsigned NumInputs,
1979                          IdentifierInfo **Names,
1980                          MultiExprArg Constraints,
1981                          MultiExprArg Exprs,
1982                          Expr *AsmString,
1983                          MultiExprArg Clobbers,
1984                          SourceLocation RParenLoc,
1985                          bool MSAsm = false);
1986
1987
1988  VarDecl *BuildObjCExceptionDecl(TypeSourceInfo *TInfo, QualType ExceptionType,
1989                                  SourceLocation StartLoc,
1990                                  SourceLocation IdLoc, IdentifierInfo *Id,
1991                                  bool Invalid = false);
1992
1993  Decl *ActOnObjCExceptionDecl(Scope *S, Declarator &D);
1994
1995  StmtResult ActOnObjCAtCatchStmt(SourceLocation AtLoc, SourceLocation RParen,
1996                                  Decl *Parm, Stmt *Body);
1997
1998  StmtResult ActOnObjCAtFinallyStmt(SourceLocation AtLoc, Stmt *Body);
1999
2000  StmtResult ActOnObjCAtTryStmt(SourceLocation AtLoc, Stmt *Try,
2001                                MultiStmtArg Catch, Stmt *Finally);
2002
2003  StmtResult BuildObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw);
2004  StmtResult ActOnObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw,
2005                                  Scope *CurScope);
2006  StmtResult ActOnObjCAtSynchronizedStmt(SourceLocation AtLoc,
2007                                         Expr *SynchExpr,
2008                                         Stmt *SynchBody);
2009
2010  VarDecl *BuildExceptionDeclaration(Scope *S, TypeSourceInfo *TInfo,
2011                                     SourceLocation StartLoc,
2012                                     SourceLocation IdLoc,
2013                                     IdentifierInfo *Id);
2014  Decl *ActOnExceptionDeclarator(Scope *S, Declarator &D);
2015
2016  StmtResult ActOnCXXCatchBlock(SourceLocation CatchLoc,
2017                                Decl *ExDecl, Stmt *HandlerBlock);
2018  StmtResult ActOnCXXTryBlock(SourceLocation TryLoc, Stmt *TryBlock,
2019                              MultiStmtArg Handlers);
2020
2021  StmtResult ActOnSEHTryBlock(bool IsCXXTry, // try (true) or __try (false) ?
2022                              SourceLocation TryLoc,
2023                              Stmt *TryBlock,
2024                              Stmt *Handler);
2025
2026  StmtResult ActOnSEHExceptBlock(SourceLocation Loc,
2027                                 Expr *FilterExpr,
2028                                 Stmt *Block);
2029
2030  StmtResult ActOnSEHFinallyBlock(SourceLocation Loc,
2031                                  Stmt *Block);
2032
2033  void DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock);
2034
2035  bool ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const;
2036
2037  /// \brief If it's a file scoped decl that must warn if not used, keep track
2038  /// of it.
2039  void MarkUnusedFileScopedDecl(const DeclaratorDecl *D);
2040
2041  /// DiagnoseUnusedExprResult - If the statement passed in is an expression
2042  /// whose result is unused, warn.
2043  void DiagnoseUnusedExprResult(const Stmt *S);
2044  void DiagnoseUnusedDecl(const NamedDecl *ND);
2045
2046  ParsingDeclState PushParsingDeclaration() {
2047    return DelayedDiagnostics.pushParsingDecl();
2048  }
2049  void PopParsingDeclaration(ParsingDeclState state, Decl *decl) {
2050    DelayedDiagnostics::popParsingDecl(*this, state, decl);
2051  }
2052
2053  typedef ProcessingContextState ParsingClassState;
2054  ParsingClassState PushParsingClass() {
2055    return DelayedDiagnostics.pushContext();
2056  }
2057  void PopParsingClass(ParsingClassState state) {
2058    DelayedDiagnostics.popContext(state);
2059  }
2060
2061  void EmitDeprecationWarning(NamedDecl *D, llvm::StringRef Message,
2062                              SourceLocation Loc,
2063                              const ObjCInterfaceDecl *UnknownObjCClass=0);
2064
2065  void HandleDelayedDeprecationCheck(sema::DelayedDiagnostic &DD, Decl *Ctx);
2066
2067  //===--------------------------------------------------------------------===//
2068  // Expression Parsing Callbacks: SemaExpr.cpp.
2069
2070  bool DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc,
2071                         const ObjCInterfaceDecl *UnknownObjCClass=0);
2072  std::string getDeletedOrUnavailableSuffix(const FunctionDecl *FD);
2073  bool DiagnosePropertyAccessorMismatch(ObjCPropertyDecl *PD,
2074                                        ObjCMethodDecl *Getter,
2075                                        SourceLocation Loc);
2076  void DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
2077                             Expr **Args, unsigned NumArgs);
2078
2079  void PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext);
2080
2081  void PopExpressionEvaluationContext();
2082
2083  void MarkDeclarationReferenced(SourceLocation Loc, Decl *D);
2084  void MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T);
2085  void MarkDeclarationsReferencedInExpr(Expr *E);
2086
2087  /// \brief Figure out if an expression could be turned into a call.
2088  bool isExprCallable(const Expr &E, QualType &ZeroArgCallReturnTy,
2089                      UnresolvedSetImpl &NonTemplateOverloads);
2090  /// \brief Give notes for a set of overloads.
2091  void NoteOverloads(const UnresolvedSetImpl &Overloads,
2092                     const SourceLocation FinalNoteLoc);
2093
2094  /// \brief Conditionally issue a diagnostic based on the current
2095  /// evaluation context.
2096  ///
2097  /// \param stmt - If stmt is non-null, delay reporting the diagnostic until
2098  ///  the function body is parsed, and then do a basic reachability analysis to
2099  ///  determine if the statement is reachable.  If it is unreachable, the
2100  ///  diagnostic will not be emitted.
2101  bool DiagRuntimeBehavior(SourceLocation Loc, const Stmt *stmt,
2102                           const PartialDiagnostic &PD);
2103
2104  // Primary Expressions.
2105  SourceRange getExprRange(Expr *E) const;
2106
2107  ObjCIvarDecl *SynthesizeProvisionalIvar(LookupResult &Lookup,
2108                                          IdentifierInfo *II,
2109                                          SourceLocation NameLoc);
2110
2111  ExprResult ActOnIdExpression(Scope *S, CXXScopeSpec &SS, UnqualifiedId &Name,
2112                               bool HasTrailingLParen, bool IsAddressOfOperand);
2113
2114  bool DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
2115                           CorrectTypoContext CTC = CTC_Unknown);
2116
2117  ExprResult LookupInObjCMethod(LookupResult &R, Scope *S, IdentifierInfo *II,
2118                                bool AllowBuiltinCreation=false);
2119
2120  ExprResult ActOnDependentIdExpression(const CXXScopeSpec &SS,
2121                                        const DeclarationNameInfo &NameInfo,
2122                                        bool isAddressOfOperand,
2123                                const TemplateArgumentListInfo *TemplateArgs);
2124
2125  ExprResult BuildDeclRefExpr(ValueDecl *D, QualType Ty,
2126                              ExprValueKind VK,
2127                              SourceLocation Loc,
2128                              const CXXScopeSpec *SS = 0);
2129  ExprResult BuildDeclRefExpr(ValueDecl *D, QualType Ty,
2130                              ExprValueKind VK,
2131                              const DeclarationNameInfo &NameInfo,
2132                              const CXXScopeSpec *SS = 0);
2133  ExprResult
2134  BuildAnonymousStructUnionMemberReference(const CXXScopeSpec &SS,
2135                                           SourceLocation nameLoc,
2136                                           IndirectFieldDecl *indirectField,
2137                                           Expr *baseObjectExpr = 0,
2138                                      SourceLocation opLoc = SourceLocation());
2139  ExprResult BuildPossibleImplicitMemberExpr(const CXXScopeSpec &SS,
2140                                             LookupResult &R,
2141                                const TemplateArgumentListInfo *TemplateArgs);
2142  ExprResult BuildImplicitMemberExpr(const CXXScopeSpec &SS,
2143                                     LookupResult &R,
2144                                const TemplateArgumentListInfo *TemplateArgs,
2145                                     bool IsDefiniteInstance);
2146  bool UseArgumentDependentLookup(const CXXScopeSpec &SS,
2147                                  const LookupResult &R,
2148                                  bool HasTrailingLParen);
2149
2150  ExprResult BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS,
2151                                         const DeclarationNameInfo &NameInfo);
2152  ExprResult BuildDependentDeclRefExpr(const CXXScopeSpec &SS,
2153                                const DeclarationNameInfo &NameInfo,
2154                                const TemplateArgumentListInfo *TemplateArgs);
2155
2156  ExprResult BuildDeclarationNameExpr(const CXXScopeSpec &SS,
2157                                      LookupResult &R,
2158                                      bool ADL);
2159  ExprResult BuildDeclarationNameExpr(const CXXScopeSpec &SS,
2160                                      const DeclarationNameInfo &NameInfo,
2161                                      NamedDecl *D);
2162
2163  ExprResult ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind);
2164  ExprResult ActOnNumericConstant(const Token &);
2165  ExprResult ActOnCharacterConstant(const Token &);
2166  ExprResult ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *Val);
2167  ExprResult ActOnParenOrParenListExpr(SourceLocation L,
2168                                       SourceLocation R,
2169                                       MultiExprArg Val,
2170                                       ParsedType TypeOfCast = ParsedType());
2171
2172  /// ActOnStringLiteral - The specified tokens were lexed as pasted string
2173  /// fragments (e.g. "foo" "bar" L"baz").
2174  ExprResult ActOnStringLiteral(const Token *Toks, unsigned NumToks);
2175
2176  ExprResult ActOnGenericSelectionExpr(SourceLocation KeyLoc,
2177                                       SourceLocation DefaultLoc,
2178                                       SourceLocation RParenLoc,
2179                                       Expr *ControllingExpr,
2180                                       MultiTypeArg Types,
2181                                       MultiExprArg Exprs);
2182  ExprResult CreateGenericSelectionExpr(SourceLocation KeyLoc,
2183                                        SourceLocation DefaultLoc,
2184                                        SourceLocation RParenLoc,
2185                                        Expr *ControllingExpr,
2186                                        TypeSourceInfo **Types,
2187                                        Expr **Exprs,
2188                                        unsigned NumAssocs);
2189
2190  // Binary/Unary Operators.  'Tok' is the token for the operator.
2191  ExprResult CreateBuiltinUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc,
2192                                  Expr *InputArg);
2193  ExprResult BuildUnaryOp(Scope *S, SourceLocation OpLoc,
2194                          UnaryOperatorKind Opc, Expr *input);
2195  ExprResult ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
2196                          tok::TokenKind Op, Expr *Input);
2197
2198  ExprResult CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *T,
2199                                            SourceLocation OpLoc,
2200                                            UnaryExprOrTypeTrait ExprKind,
2201                                            SourceRange R);
2202  ExprResult CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
2203                                            UnaryExprOrTypeTrait ExprKind,
2204                                            SourceRange R);
2205  ExprResult
2206    ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
2207                                  UnaryExprOrTypeTrait ExprKind,
2208                                  bool isType, void *TyOrEx,
2209                                  const SourceRange &ArgRange);
2210
2211  ExprResult CheckPlaceholderExpr(Expr *E);
2212  bool CheckVecStepExpr(Expr *E, SourceLocation OpLoc, SourceRange R);
2213
2214  bool CheckUnaryExprOrTypeTraitOperand(QualType type, SourceLocation OpLoc,
2215                                        SourceRange R,
2216                                        UnaryExprOrTypeTrait ExprKind);
2217  ExprResult ActOnSizeofParameterPackExpr(Scope *S,
2218                                          SourceLocation OpLoc,
2219                                          IdentifierInfo &Name,
2220                                          SourceLocation NameLoc,
2221                                          SourceLocation RParenLoc);
2222  ExprResult ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
2223                                 tok::TokenKind Kind, Expr *Input);
2224
2225  ExprResult ActOnArraySubscriptExpr(Scope *S, Expr *Base, SourceLocation LLoc,
2226                                     Expr *Idx, SourceLocation RLoc);
2227  ExprResult CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
2228                                             Expr *Idx, SourceLocation RLoc);
2229
2230  ExprResult BuildMemberReferenceExpr(Expr *Base, QualType BaseType,
2231                                      SourceLocation OpLoc, bool IsArrow,
2232                                      CXXScopeSpec &SS,
2233                                      NamedDecl *FirstQualifierInScope,
2234                                const DeclarationNameInfo &NameInfo,
2235                                const TemplateArgumentListInfo *TemplateArgs);
2236
2237  ExprResult BuildMemberReferenceExpr(Expr *Base, QualType BaseType,
2238                                      SourceLocation OpLoc, bool IsArrow,
2239                                      const CXXScopeSpec &SS,
2240                                      NamedDecl *FirstQualifierInScope,
2241                                      LookupResult &R,
2242                                 const TemplateArgumentListInfo *TemplateArgs,
2243                                      bool SuppressQualifierCheck = false);
2244
2245  ExprResult LookupMemberExpr(LookupResult &R, ExprResult &Base,
2246                              bool &IsArrow, SourceLocation OpLoc,
2247                              CXXScopeSpec &SS,
2248                              Decl *ObjCImpDecl,
2249                              bool HasTemplateArgs);
2250
2251  bool CheckQualifiedMemberReference(Expr *BaseExpr, QualType BaseType,
2252                                     const CXXScopeSpec &SS,
2253                                     const LookupResult &R);
2254
2255  ExprResult ActOnDependentMemberExpr(Expr *Base, QualType BaseType,
2256                                      bool IsArrow, SourceLocation OpLoc,
2257                                      const CXXScopeSpec &SS,
2258                                      NamedDecl *FirstQualifierInScope,
2259                               const DeclarationNameInfo &NameInfo,
2260                               const TemplateArgumentListInfo *TemplateArgs);
2261
2262  ExprResult ActOnMemberAccessExpr(Scope *S, Expr *Base,
2263                                   SourceLocation OpLoc,
2264                                   tok::TokenKind OpKind,
2265                                   CXXScopeSpec &SS,
2266                                   UnqualifiedId &Member,
2267                                   Decl *ObjCImpDecl,
2268                                   bool HasTrailingLParen);
2269
2270  void ActOnDefaultCtorInitializers(Decl *CDtorDecl);
2271  bool ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
2272                               FunctionDecl *FDecl,
2273                               const FunctionProtoType *Proto,
2274                               Expr **Args, unsigned NumArgs,
2275                               SourceLocation RParenLoc);
2276
2277  /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
2278  /// This provides the location of the left/right parens and a list of comma
2279  /// locations.
2280  ExprResult ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
2281                           MultiExprArg Args, SourceLocation RParenLoc,
2282                           Expr *ExecConfig = 0);
2283  ExprResult BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
2284                                   SourceLocation LParenLoc,
2285                                   Expr **Args, unsigned NumArgs,
2286                                   SourceLocation RParenLoc,
2287                                   Expr *ExecConfig = 0);
2288
2289  ExprResult ActOnCUDAExecConfigExpr(Scope *S, SourceLocation LLLLoc,
2290                                MultiExprArg ExecConfig, SourceLocation GGGLoc);
2291
2292  ExprResult ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
2293                           ParsedType Ty, SourceLocation RParenLoc,
2294                           Expr *Op);
2295  ExprResult BuildCStyleCastExpr(SourceLocation LParenLoc,
2296                                 TypeSourceInfo *Ty,
2297                                 SourceLocation RParenLoc,
2298                                 Expr *Op);
2299
2300  bool TypeIsVectorType(ParsedType Ty) {
2301    return GetTypeFromParser(Ty)->isVectorType();
2302  }
2303
2304  ExprResult MaybeConvertParenListExprToParenExpr(Scope *S, Expr *ME);
2305  ExprResult ActOnCastOfParenListExpr(Scope *S, SourceLocation LParenLoc,
2306                                      SourceLocation RParenLoc, Expr *E,
2307                                      TypeSourceInfo *TInfo);
2308
2309  ExprResult ActOnCompoundLiteral(SourceLocation LParenLoc,
2310                                  ParsedType Ty,
2311                                  SourceLocation RParenLoc,
2312                                  Expr *Op);
2313
2314  ExprResult BuildCompoundLiteralExpr(SourceLocation LParenLoc,
2315                                      TypeSourceInfo *TInfo,
2316                                      SourceLocation RParenLoc,
2317                                      Expr *InitExpr);
2318
2319  ExprResult ActOnInitList(SourceLocation LParenLoc,
2320                           MultiExprArg InitList,
2321                           SourceLocation RParenLoc);
2322
2323  ExprResult ActOnDesignatedInitializer(Designation &Desig,
2324                                        SourceLocation Loc,
2325                                        bool GNUSyntax,
2326                                        ExprResult Init);
2327
2328  ExprResult ActOnBinOp(Scope *S, SourceLocation TokLoc,
2329                        tok::TokenKind Kind, Expr *LHS, Expr *RHS);
2330  ExprResult BuildBinOp(Scope *S, SourceLocation OpLoc,
2331                        BinaryOperatorKind Opc, Expr *lhs, Expr *rhs);
2332  ExprResult CreateBuiltinBinOp(SourceLocation TokLoc,
2333                                BinaryOperatorKind Opc, Expr *lhs, Expr *rhs);
2334
2335  /// ActOnConditionalOp - Parse a ?: operation.  Note that 'LHS' may be null
2336  /// in the case of a the GNU conditional expr extension.
2337  ExprResult ActOnConditionalOp(SourceLocation QuestionLoc,
2338                                SourceLocation ColonLoc,
2339                                Expr *Cond, Expr *LHS, Expr *RHS);
2340
2341  /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
2342  ExprResult ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
2343                            LabelDecl *LD);
2344
2345  ExprResult ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
2346                           SourceLocation RPLoc); // "({..})"
2347
2348  // __builtin_offsetof(type, identifier(.identifier|[expr])*)
2349  struct OffsetOfComponent {
2350    SourceLocation LocStart, LocEnd;
2351    bool isBrackets;  // true if [expr], false if .ident
2352    union {
2353      IdentifierInfo *IdentInfo;
2354      ExprTy *E;
2355    } U;
2356  };
2357
2358  /// __builtin_offsetof(type, a.b[123][456].c)
2359  ExprResult BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
2360                                  TypeSourceInfo *TInfo,
2361                                  OffsetOfComponent *CompPtr,
2362                                  unsigned NumComponents,
2363                                  SourceLocation RParenLoc);
2364  ExprResult ActOnBuiltinOffsetOf(Scope *S,
2365                                  SourceLocation BuiltinLoc,
2366                                  SourceLocation TypeLoc,
2367                                  ParsedType Arg1,
2368                                  OffsetOfComponent *CompPtr,
2369                                  unsigned NumComponents,
2370                                  SourceLocation RParenLoc);
2371
2372  // __builtin_choose_expr(constExpr, expr1, expr2)
2373  ExprResult ActOnChooseExpr(SourceLocation BuiltinLoc,
2374                             Expr *cond, Expr *expr1,
2375                             Expr *expr2, SourceLocation RPLoc);
2376
2377  // __builtin_va_arg(expr, type)
2378  ExprResult ActOnVAArg(SourceLocation BuiltinLoc,
2379                        Expr *expr, ParsedType type,
2380                        SourceLocation RPLoc);
2381  ExprResult BuildVAArgExpr(SourceLocation BuiltinLoc,
2382                            Expr *expr, TypeSourceInfo *TInfo,
2383                            SourceLocation RPLoc);
2384
2385  // __null
2386  ExprResult ActOnGNUNullExpr(SourceLocation TokenLoc);
2387
2388  bool CheckCaseExpression(Expr *expr);
2389
2390  bool CheckMicrosoftIfExistsSymbol(CXXScopeSpec &SS, UnqualifiedId &Name);
2391
2392  //===------------------------- "Block" Extension ------------------------===//
2393
2394  /// ActOnBlockStart - This callback is invoked when a block literal is
2395  /// started.
2396  void ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope);
2397
2398  /// ActOnBlockArguments - This callback allows processing of block arguments.
2399  /// If there are no arguments, this is still invoked.
2400  void ActOnBlockArguments(Declarator &ParamInfo, Scope *CurScope);
2401
2402  /// ActOnBlockError - If there is an error parsing a block, this callback
2403  /// is invoked to pop the information about the block from the action impl.
2404  void ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope);
2405
2406  /// ActOnBlockStmtExpr - This is called when the body of a block statement
2407  /// literal was successfully completed.  ^(int x){...}
2408  ExprResult ActOnBlockStmtExpr(SourceLocation CaretLoc,
2409                                        Stmt *Body, Scope *CurScope);
2410
2411  //===---------------------------- C++ Features --------------------------===//
2412
2413  // Act on C++ namespaces
2414  Decl *ActOnStartNamespaceDef(Scope *S, SourceLocation InlineLoc,
2415                               SourceLocation NamespaceLoc,
2416                               SourceLocation IdentLoc,
2417                               IdentifierInfo *Ident,
2418                               SourceLocation LBrace,
2419                               AttributeList *AttrList);
2420  void ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace);
2421
2422  NamespaceDecl *getStdNamespace() const;
2423  NamespaceDecl *getOrCreateStdNamespace();
2424
2425  CXXRecordDecl *getStdBadAlloc() const;
2426
2427  Decl *ActOnUsingDirective(Scope *CurScope,
2428                            SourceLocation UsingLoc,
2429                            SourceLocation NamespcLoc,
2430                            CXXScopeSpec &SS,
2431                            SourceLocation IdentLoc,
2432                            IdentifierInfo *NamespcName,
2433                            AttributeList *AttrList);
2434
2435  void PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir);
2436
2437  Decl *ActOnNamespaceAliasDef(Scope *CurScope,
2438                               SourceLocation NamespaceLoc,
2439                               SourceLocation AliasLoc,
2440                               IdentifierInfo *Alias,
2441                               CXXScopeSpec &SS,
2442                               SourceLocation IdentLoc,
2443                               IdentifierInfo *Ident);
2444
2445  void HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow);
2446  bool CheckUsingShadowDecl(UsingDecl *UD, NamedDecl *Target,
2447                            const LookupResult &PreviousDecls);
2448  UsingShadowDecl *BuildUsingShadowDecl(Scope *S, UsingDecl *UD,
2449                                        NamedDecl *Target);
2450
2451  bool CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
2452                                   bool isTypeName,
2453                                   const CXXScopeSpec &SS,
2454                                   SourceLocation NameLoc,
2455                                   const LookupResult &Previous);
2456  bool CheckUsingDeclQualifier(SourceLocation UsingLoc,
2457                               const CXXScopeSpec &SS,
2458                               SourceLocation NameLoc);
2459
2460  NamedDecl *BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
2461                                   SourceLocation UsingLoc,
2462                                   CXXScopeSpec &SS,
2463                                   const DeclarationNameInfo &NameInfo,
2464                                   AttributeList *AttrList,
2465                                   bool IsInstantiation,
2466                                   bool IsTypeName,
2467                                   SourceLocation TypenameLoc);
2468
2469  bool CheckInheritedConstructorUsingDecl(UsingDecl *UD);
2470
2471  Decl *ActOnUsingDeclaration(Scope *CurScope,
2472                              AccessSpecifier AS,
2473                              bool HasUsingKeyword,
2474                              SourceLocation UsingLoc,
2475                              CXXScopeSpec &SS,
2476                              UnqualifiedId &Name,
2477                              AttributeList *AttrList,
2478                              bool IsTypeName,
2479                              SourceLocation TypenameLoc);
2480  Decl *ActOnAliasDeclaration(Scope *CurScope,
2481                              AccessSpecifier AS,
2482                              MultiTemplateParamsArg TemplateParams,
2483                              SourceLocation UsingLoc,
2484                              UnqualifiedId &Name,
2485                              TypeResult Type);
2486
2487  /// AddCXXDirectInitializerToDecl - This action is called immediately after
2488  /// ActOnDeclarator, when a C++ direct initializer is present.
2489  /// e.g: "int x(1);"
2490  void AddCXXDirectInitializerToDecl(Decl *Dcl,
2491                                     SourceLocation LParenLoc,
2492                                     MultiExprArg Exprs,
2493                                     SourceLocation RParenLoc,
2494                                     bool TypeMayContainAuto);
2495
2496  /// InitializeVarWithConstructor - Creates an CXXConstructExpr
2497  /// and sets it as the initializer for the the passed in VarDecl.
2498  bool InitializeVarWithConstructor(VarDecl *VD,
2499                                    CXXConstructorDecl *Constructor,
2500                                    MultiExprArg Exprs);
2501
2502  /// BuildCXXConstructExpr - Creates a complete call to a constructor,
2503  /// including handling of its default argument expressions.
2504  ///
2505  /// \param ConstructKind - a CXXConstructExpr::ConstructionKind
2506  ExprResult
2507  BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
2508                        CXXConstructorDecl *Constructor, MultiExprArg Exprs,
2509                        bool RequiresZeroInit, unsigned ConstructKind,
2510                        SourceRange ParenRange);
2511
2512  // FIXME: Can re remove this and have the above BuildCXXConstructExpr check if
2513  // the constructor can be elidable?
2514  ExprResult
2515  BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
2516                        CXXConstructorDecl *Constructor, bool Elidable,
2517                        MultiExprArg Exprs, bool RequiresZeroInit,
2518                        unsigned ConstructKind,
2519                        SourceRange ParenRange);
2520
2521  /// BuildCXXDefaultArgExpr - Creates a CXXDefaultArgExpr, instantiating
2522  /// the default expr if needed.
2523  ExprResult BuildCXXDefaultArgExpr(SourceLocation CallLoc,
2524                                    FunctionDecl *FD,
2525                                    ParmVarDecl *Param);
2526
2527  /// FinalizeVarWithDestructor - Prepare for calling destructor on the
2528  /// constructed variable.
2529  void FinalizeVarWithDestructor(VarDecl *VD, const RecordType *DeclInitType);
2530
2531  /// \brief Helper class that collects exception specifications for
2532  /// implicitly-declared special member functions.
2533  class ImplicitExceptionSpecification {
2534    // Pointer to allow copying
2535    ASTContext *Context;
2536    // We order exception specifications thus:
2537    // noexcept is the most restrictive, but is only used in C++0x.
2538    // throw() comes next.
2539    // Then a throw(collected exceptions)
2540    // Finally no specification.
2541    // throw(...) is used instead if any called function uses it.
2542    ExceptionSpecificationType ComputedEST;
2543    llvm::SmallPtrSet<CanQualType, 4> ExceptionsSeen;
2544    llvm::SmallVector<QualType, 4> Exceptions;
2545
2546    void ClearExceptions() {
2547      ExceptionsSeen.clear();
2548      Exceptions.clear();
2549    }
2550
2551  public:
2552    explicit ImplicitExceptionSpecification(ASTContext &Context)
2553      : Context(&Context), ComputedEST(EST_BasicNoexcept) {
2554      if (!Context.getLangOptions().CPlusPlus0x)
2555        ComputedEST = EST_DynamicNone;
2556    }
2557
2558    /// \brief Get the computed exception specification type.
2559    ExceptionSpecificationType getExceptionSpecType() const {
2560      assert(ComputedEST != EST_ComputedNoexcept &&
2561             "noexcept(expr) should not be a possible result");
2562      return ComputedEST;
2563    }
2564
2565    /// \brief The number of exceptions in the exception specification.
2566    unsigned size() const { return Exceptions.size(); }
2567
2568    /// \brief The set of exceptions in the exception specification.
2569    const QualType *data() const { return Exceptions.data(); }
2570
2571    /// \brief Integrate another called method into the collected data.
2572    void CalledDecl(CXXMethodDecl *Method);
2573
2574    FunctionProtoType::ExtProtoInfo getEPI() const {
2575      FunctionProtoType::ExtProtoInfo EPI;
2576      EPI.ExceptionSpecType = getExceptionSpecType();
2577      EPI.NumExceptions = size();
2578      EPI.Exceptions = data();
2579      return EPI;
2580    }
2581  };
2582
2583  /// \brief Determine what sort of exception specification a defaulted
2584  /// copy constructor of a class will have.
2585  ImplicitExceptionSpecification
2586  ComputeDefaultedDefaultCtorExceptionSpec(CXXRecordDecl *ClassDecl);
2587
2588  /// \brief Determine what sort of exception specification a defaulted
2589  /// default constructor of a class will have, and whether the parameter
2590  /// will be const.
2591  std::pair<ImplicitExceptionSpecification, bool>
2592  ComputeDefaultedCopyCtorExceptionSpecAndConst(CXXRecordDecl *ClassDecl);
2593
2594  /// \brief Determine what sort of exception specification a defautled
2595  /// copy assignment operator of a class will have, and whether the
2596  /// parameter will be const.
2597  std::pair<ImplicitExceptionSpecification, bool>
2598  ComputeDefaultedCopyAssignmentExceptionSpecAndConst(CXXRecordDecl *ClassDecl);
2599
2600  /// \brief Determine what sort of exception specification a defaulted
2601  /// destructor of a class will have.
2602  ImplicitExceptionSpecification
2603  ComputeDefaultedDtorExceptionSpec(CXXRecordDecl *ClassDecl);
2604
2605  /// \brief Determine if a defaulted default constructor ought to be
2606  /// deleted.
2607  bool ShouldDeleteDefaultConstructor(CXXConstructorDecl *CD);
2608
2609  /// \brief Determine if a defaulted copy constructor ought to be
2610  /// deleted.
2611  bool ShouldDeleteCopyConstructor(CXXConstructorDecl *CD);
2612
2613  /// \brief Determine if a defaulted copy assignment operator ought to be
2614  /// deleted.
2615  bool ShouldDeleteCopyAssignmentOperator(CXXMethodDecl *MD);
2616
2617  /// \brief Determine if a defaulted destructor ought to be deleted.
2618  bool ShouldDeleteDestructor(CXXDestructorDecl *DD);
2619
2620  /// \brief Declare the implicit default constructor for the given class.
2621  ///
2622  /// \param ClassDecl The class declaration into which the implicit
2623  /// default constructor will be added.
2624  ///
2625  /// \returns The implicitly-declared default constructor.
2626  CXXConstructorDecl *DeclareImplicitDefaultConstructor(
2627                                                     CXXRecordDecl *ClassDecl);
2628
2629  /// DefineImplicitDefaultConstructor - Checks for feasibility of
2630  /// defining this constructor as the default constructor.
2631  void DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
2632                                        CXXConstructorDecl *Constructor);
2633
2634  /// \brief Declare the implicit destructor for the given class.
2635  ///
2636  /// \param ClassDecl The class declaration into which the implicit
2637  /// destructor will be added.
2638  ///
2639  /// \returns The implicitly-declared destructor.
2640  CXXDestructorDecl *DeclareImplicitDestructor(CXXRecordDecl *ClassDecl);
2641
2642  /// DefineImplicitDestructor - Checks for feasibility of
2643  /// defining this destructor as the default destructor.
2644  void DefineImplicitDestructor(SourceLocation CurrentLocation,
2645                                CXXDestructorDecl *Destructor);
2646
2647  /// \brief Build an exception spec for destructors that don't have one.
2648  ///
2649  /// C++11 says that user-defined destructors with no exception spec get one
2650  /// that looks as if the destructor was implicitly declared.
2651  void AdjustDestructorExceptionSpec(CXXRecordDecl *ClassDecl,
2652                                     CXXDestructorDecl *Destructor);
2653
2654  /// \brief Declare all inherited constructors for the given class.
2655  ///
2656  /// \param ClassDecl The class declaration into which the inherited
2657  /// constructors will be added.
2658  void DeclareInheritedConstructors(CXXRecordDecl *ClassDecl);
2659
2660  /// \brief Declare the implicit copy constructor for the given class.
2661  ///
2662  /// \param S The scope of the class, which may be NULL if this is a
2663  /// template instantiation.
2664  ///
2665  /// \param ClassDecl The class declaration into which the implicit
2666  /// copy constructor will be added.
2667  ///
2668  /// \returns The implicitly-declared copy constructor.
2669  CXXConstructorDecl *DeclareImplicitCopyConstructor(CXXRecordDecl *ClassDecl);
2670
2671  /// DefineImplicitCopyConstructor - Checks for feasibility of
2672  /// defining this constructor as the copy constructor.
2673  void DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
2674                                     CXXConstructorDecl *Constructor);
2675
2676  /// \brief Declare the implicit copy assignment operator for the given class.
2677  ///
2678  /// \param S The scope of the class, which may be NULL if this is a
2679  /// template instantiation.
2680  ///
2681  /// \param ClassDecl The class declaration into which the implicit
2682  /// copy-assignment operator will be added.
2683  ///
2684  /// \returns The implicitly-declared copy assignment operator.
2685  CXXMethodDecl *DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl);
2686
2687  /// \brief Defined an implicitly-declared copy assignment operator.
2688  void DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
2689                                    CXXMethodDecl *MethodDecl);
2690
2691  /// \brief Force the declaration of any implicitly-declared members of this
2692  /// class.
2693  void ForceDeclarationOfImplicitMembers(CXXRecordDecl *Class);
2694
2695  /// MaybeBindToTemporary - If the passed in expression has a record type with
2696  /// a non-trivial destructor, this will return CXXBindTemporaryExpr. Otherwise
2697  /// it simply returns the passed in expression.
2698  ExprResult MaybeBindToTemporary(Expr *E);
2699
2700  bool CompleteConstructorCall(CXXConstructorDecl *Constructor,
2701                               MultiExprArg ArgsPtr,
2702                               SourceLocation Loc,
2703                               ASTOwningVector<Expr*> &ConvertedArgs);
2704
2705  ParsedType getDestructorName(SourceLocation TildeLoc,
2706                               IdentifierInfo &II, SourceLocation NameLoc,
2707                               Scope *S, CXXScopeSpec &SS,
2708                               ParsedType ObjectType,
2709                               bool EnteringContext);
2710
2711  // Checks that reinterpret casts don't have undefined behavior.
2712  void CheckCompatibleReinterpretCast(QualType SrcType, QualType DestType,
2713                                      bool IsDereference, SourceRange Range);
2714
2715  /// ActOnCXXNamedCast - Parse {dynamic,static,reinterpret,const}_cast's.
2716  ExprResult ActOnCXXNamedCast(SourceLocation OpLoc,
2717                               tok::TokenKind Kind,
2718                               SourceLocation LAngleBracketLoc,
2719                               ParsedType Ty,
2720                               SourceLocation RAngleBracketLoc,
2721                               SourceLocation LParenLoc,
2722                               Expr *E,
2723                               SourceLocation RParenLoc);
2724
2725  ExprResult BuildCXXNamedCast(SourceLocation OpLoc,
2726                               tok::TokenKind Kind,
2727                               TypeSourceInfo *Ty,
2728                               Expr *E,
2729                               SourceRange AngleBrackets,
2730                               SourceRange Parens);
2731
2732  ExprResult BuildCXXTypeId(QualType TypeInfoType,
2733                            SourceLocation TypeidLoc,
2734                            TypeSourceInfo *Operand,
2735                            SourceLocation RParenLoc);
2736  ExprResult BuildCXXTypeId(QualType TypeInfoType,
2737                            SourceLocation TypeidLoc,
2738                            Expr *Operand,
2739                            SourceLocation RParenLoc);
2740
2741  /// ActOnCXXTypeid - Parse typeid( something ).
2742  ExprResult ActOnCXXTypeid(SourceLocation OpLoc,
2743                            SourceLocation LParenLoc, bool isType,
2744                            void *TyOrExpr,
2745                            SourceLocation RParenLoc);
2746
2747  ExprResult BuildCXXUuidof(QualType TypeInfoType,
2748                            SourceLocation TypeidLoc,
2749                            TypeSourceInfo *Operand,
2750                            SourceLocation RParenLoc);
2751  ExprResult BuildCXXUuidof(QualType TypeInfoType,
2752                            SourceLocation TypeidLoc,
2753                            Expr *Operand,
2754                            SourceLocation RParenLoc);
2755
2756  /// ActOnCXXUuidof - Parse __uuidof( something ).
2757  ExprResult ActOnCXXUuidof(SourceLocation OpLoc,
2758                            SourceLocation LParenLoc, bool isType,
2759                            void *TyOrExpr,
2760                            SourceLocation RParenLoc);
2761
2762
2763  //// ActOnCXXThis -  Parse 'this' pointer.
2764  ExprResult ActOnCXXThis(SourceLocation loc);
2765
2766  /// tryCaptureCXXThis - Try to capture a 'this' pointer.  Returns a
2767  /// pointer to an instance method whose 'this' pointer is
2768  /// capturable, or null if this is not possible.
2769  CXXMethodDecl *tryCaptureCXXThis();
2770
2771  /// ActOnCXXBoolLiteral - Parse {true,false} literals.
2772  ExprResult ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind);
2773
2774  /// ActOnCXXNullPtrLiteral - Parse 'nullptr'.
2775  ExprResult ActOnCXXNullPtrLiteral(SourceLocation Loc);
2776
2777  //// ActOnCXXThrow -  Parse throw expressions.
2778  ExprResult ActOnCXXThrow(SourceLocation OpLoc, Expr *expr);
2779  ExprResult CheckCXXThrowOperand(SourceLocation ThrowLoc, Expr *E);
2780
2781  /// ActOnCXXTypeConstructExpr - Parse construction of a specified type.
2782  /// Can be interpreted either as function-style casting ("int(x)")
2783  /// or class type construction ("ClassType(x,y,z)")
2784  /// or creation of a value-initialized type ("int()").
2785  ExprResult ActOnCXXTypeConstructExpr(ParsedType TypeRep,
2786                                       SourceLocation LParenLoc,
2787                                       MultiExprArg Exprs,
2788                                       SourceLocation RParenLoc);
2789
2790  ExprResult BuildCXXTypeConstructExpr(TypeSourceInfo *Type,
2791                                       SourceLocation LParenLoc,
2792                                       MultiExprArg Exprs,
2793                                       SourceLocation RParenLoc);
2794
2795  /// ActOnCXXNew - Parsed a C++ 'new' expression.
2796  ExprResult ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
2797                         SourceLocation PlacementLParen,
2798                         MultiExprArg PlacementArgs,
2799                         SourceLocation PlacementRParen,
2800                         SourceRange TypeIdParens, Declarator &D,
2801                         SourceLocation ConstructorLParen,
2802                         MultiExprArg ConstructorArgs,
2803                         SourceLocation ConstructorRParen);
2804  ExprResult BuildCXXNew(SourceLocation StartLoc, bool UseGlobal,
2805                         SourceLocation PlacementLParen,
2806                         MultiExprArg PlacementArgs,
2807                         SourceLocation PlacementRParen,
2808                         SourceRange TypeIdParens,
2809                         QualType AllocType,
2810                         TypeSourceInfo *AllocTypeInfo,
2811                         Expr *ArraySize,
2812                         SourceLocation ConstructorLParen,
2813                         MultiExprArg ConstructorArgs,
2814                         SourceLocation ConstructorRParen,
2815                         bool TypeMayContainAuto = true);
2816
2817  bool CheckAllocatedType(QualType AllocType, SourceLocation Loc,
2818                          SourceRange R);
2819  bool FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,
2820                               bool UseGlobal, QualType AllocType, bool IsArray,
2821                               Expr **PlaceArgs, unsigned NumPlaceArgs,
2822                               FunctionDecl *&OperatorNew,
2823                               FunctionDecl *&OperatorDelete);
2824  bool FindAllocationOverload(SourceLocation StartLoc, SourceRange Range,
2825                              DeclarationName Name, Expr** Args,
2826                              unsigned NumArgs, DeclContext *Ctx,
2827                              bool AllowMissing, FunctionDecl *&Operator,
2828                              bool Diagnose = true);
2829  void DeclareGlobalNewDelete();
2830  void DeclareGlobalAllocationFunction(DeclarationName Name, QualType Return,
2831                                       QualType Argument,
2832                                       bool addMallocAttr = false);
2833
2834  bool FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD,
2835                                DeclarationName Name, FunctionDecl* &Operator,
2836                                bool Diagnose = true);
2837
2838  /// ActOnCXXDelete - Parsed a C++ 'delete' expression
2839  ExprResult ActOnCXXDelete(SourceLocation StartLoc,
2840                            bool UseGlobal, bool ArrayForm,
2841                            Expr *Operand);
2842
2843  DeclResult ActOnCXXConditionDeclaration(Scope *S, Declarator &D);
2844  ExprResult CheckConditionVariable(VarDecl *ConditionVar,
2845                                    SourceLocation StmtLoc,
2846                                    bool ConvertToBoolean);
2847
2848  ExprResult ActOnNoexceptExpr(SourceLocation KeyLoc, SourceLocation LParen,
2849                               Expr *Operand, SourceLocation RParen);
2850  ExprResult BuildCXXNoexceptExpr(SourceLocation KeyLoc, Expr *Operand,
2851                                  SourceLocation RParen);
2852
2853  /// ActOnUnaryTypeTrait - Parsed one of the unary type trait support
2854  /// pseudo-functions.
2855  ExprResult ActOnUnaryTypeTrait(UnaryTypeTrait OTT,
2856                                 SourceLocation KWLoc,
2857                                 ParsedType Ty,
2858                                 SourceLocation RParen);
2859
2860  ExprResult BuildUnaryTypeTrait(UnaryTypeTrait OTT,
2861                                 SourceLocation KWLoc,
2862                                 TypeSourceInfo *T,
2863                                 SourceLocation RParen);
2864
2865  /// ActOnBinaryTypeTrait - Parsed one of the bianry type trait support
2866  /// pseudo-functions.
2867  ExprResult ActOnBinaryTypeTrait(BinaryTypeTrait OTT,
2868                                  SourceLocation KWLoc,
2869                                  ParsedType LhsTy,
2870                                  ParsedType RhsTy,
2871                                  SourceLocation RParen);
2872
2873  ExprResult BuildBinaryTypeTrait(BinaryTypeTrait BTT,
2874                                  SourceLocation KWLoc,
2875                                  TypeSourceInfo *LhsT,
2876                                  TypeSourceInfo *RhsT,
2877                                  SourceLocation RParen);
2878
2879  /// ActOnArrayTypeTrait - Parsed one of the bianry type trait support
2880  /// pseudo-functions.
2881  ExprResult ActOnArrayTypeTrait(ArrayTypeTrait ATT,
2882                                 SourceLocation KWLoc,
2883                                 ParsedType LhsTy,
2884                                 Expr *DimExpr,
2885                                 SourceLocation RParen);
2886
2887  ExprResult BuildArrayTypeTrait(ArrayTypeTrait ATT,
2888                                 SourceLocation KWLoc,
2889                                 TypeSourceInfo *TSInfo,
2890                                 Expr *DimExpr,
2891                                 SourceLocation RParen);
2892
2893  /// ActOnExpressionTrait - Parsed one of the unary type trait support
2894  /// pseudo-functions.
2895  ExprResult ActOnExpressionTrait(ExpressionTrait OET,
2896                                  SourceLocation KWLoc,
2897                                  Expr *Queried,
2898                                  SourceLocation RParen);
2899
2900  ExprResult BuildExpressionTrait(ExpressionTrait OET,
2901                                  SourceLocation KWLoc,
2902                                  Expr *Queried,
2903                                  SourceLocation RParen);
2904
2905  ExprResult ActOnStartCXXMemberReference(Scope *S,
2906                                          Expr *Base,
2907                                          SourceLocation OpLoc,
2908                                          tok::TokenKind OpKind,
2909                                          ParsedType &ObjectType,
2910                                          bool &MayBePseudoDestructor);
2911
2912  ExprResult DiagnoseDtorReference(SourceLocation NameLoc, Expr *MemExpr);
2913
2914  ExprResult BuildPseudoDestructorExpr(Expr *Base,
2915                                       SourceLocation OpLoc,
2916                                       tok::TokenKind OpKind,
2917                                       const CXXScopeSpec &SS,
2918                                       TypeSourceInfo *ScopeType,
2919                                       SourceLocation CCLoc,
2920                                       SourceLocation TildeLoc,
2921                                     PseudoDestructorTypeStorage DestroyedType,
2922                                       bool HasTrailingLParen);
2923
2924  ExprResult ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
2925                                       SourceLocation OpLoc,
2926                                       tok::TokenKind OpKind,
2927                                       CXXScopeSpec &SS,
2928                                       UnqualifiedId &FirstTypeName,
2929                                       SourceLocation CCLoc,
2930                                       SourceLocation TildeLoc,
2931                                       UnqualifiedId &SecondTypeName,
2932                                       bool HasTrailingLParen);
2933
2934  /// MaybeCreateExprWithCleanups - If the current full-expression
2935  /// requires any cleanups, surround it with a ExprWithCleanups node.
2936  /// Otherwise, just returns the passed-in expression.
2937  Expr *MaybeCreateExprWithCleanups(Expr *SubExpr);
2938  Stmt *MaybeCreateStmtWithCleanups(Stmt *SubStmt);
2939  ExprResult MaybeCreateExprWithCleanups(ExprResult SubExpr);
2940
2941  ExprResult ActOnFinishFullExpr(Expr *Expr);
2942  StmtResult ActOnFinishFullStmt(Stmt *Stmt);
2943
2944  // Marks SS invalid if it represents an incomplete type.
2945  bool RequireCompleteDeclContext(CXXScopeSpec &SS, DeclContext *DC);
2946
2947  DeclContext *computeDeclContext(QualType T);
2948  DeclContext *computeDeclContext(const CXXScopeSpec &SS,
2949                                  bool EnteringContext = false);
2950  bool isDependentScopeSpecifier(const CXXScopeSpec &SS);
2951  CXXRecordDecl *getCurrentInstantiationOf(NestedNameSpecifier *NNS);
2952  bool isUnknownSpecialization(const CXXScopeSpec &SS);
2953
2954  /// \brief The parser has parsed a global nested-name-specifier '::'.
2955  ///
2956  /// \param S The scope in which this nested-name-specifier occurs.
2957  ///
2958  /// \param CCLoc The location of the '::'.
2959  ///
2960  /// \param SS The nested-name-specifier, which will be updated in-place
2961  /// to reflect the parsed nested-name-specifier.
2962  ///
2963  /// \returns true if an error occurred, false otherwise.
2964  bool ActOnCXXGlobalScopeSpecifier(Scope *S, SourceLocation CCLoc,
2965                                    CXXScopeSpec &SS);
2966
2967  bool isAcceptableNestedNameSpecifier(NamedDecl *SD);
2968  NamedDecl *FindFirstQualifierInScope(Scope *S, NestedNameSpecifier *NNS);
2969
2970  bool isNonTypeNestedNameSpecifier(Scope *S, CXXScopeSpec &SS,
2971                                    SourceLocation IdLoc,
2972                                    IdentifierInfo &II,
2973                                    ParsedType ObjectType);
2974
2975  bool BuildCXXNestedNameSpecifier(Scope *S,
2976                                   IdentifierInfo &Identifier,
2977                                   SourceLocation IdentifierLoc,
2978                                   SourceLocation CCLoc,
2979                                   QualType ObjectType,
2980                                   bool EnteringContext,
2981                                   CXXScopeSpec &SS,
2982                                   NamedDecl *ScopeLookupResult,
2983                                   bool ErrorRecoveryLookup);
2984
2985  /// \brief The parser has parsed a nested-name-specifier 'identifier::'.
2986  ///
2987  /// \param S The scope in which this nested-name-specifier occurs.
2988  ///
2989  /// \param Identifier The identifier preceding the '::'.
2990  ///
2991  /// \param IdentifierLoc The location of the identifier.
2992  ///
2993  /// \param CCLoc The location of the '::'.
2994  ///
2995  /// \param ObjectType The type of the object, if we're parsing
2996  /// nested-name-specifier in a member access expression.
2997  ///
2998  /// \param EnteringContext Whether we're entering the context nominated by
2999  /// this nested-name-specifier.
3000  ///
3001  /// \param SS The nested-name-specifier, which is both an input
3002  /// parameter (the nested-name-specifier before this type) and an
3003  /// output parameter (containing the full nested-name-specifier,
3004  /// including this new type).
3005  ///
3006  /// \returns true if an error occurred, false otherwise.
3007  bool ActOnCXXNestedNameSpecifier(Scope *S,
3008                                   IdentifierInfo &Identifier,
3009                                   SourceLocation IdentifierLoc,
3010                                   SourceLocation CCLoc,
3011                                   ParsedType ObjectType,
3012                                   bool EnteringContext,
3013                                   CXXScopeSpec &SS);
3014
3015  bool IsInvalidUnlessNestedName(Scope *S, CXXScopeSpec &SS,
3016                                 IdentifierInfo &Identifier,
3017                                 SourceLocation IdentifierLoc,
3018                                 SourceLocation ColonLoc,
3019                                 ParsedType ObjectType,
3020                                 bool EnteringContext);
3021
3022  /// \brief The parser has parsed a nested-name-specifier
3023  /// 'template[opt] template-name < template-args >::'.
3024  ///
3025  /// \param S The scope in which this nested-name-specifier occurs.
3026  ///
3027  /// \param TemplateLoc The location of the 'template' keyword, if any.
3028  ///
3029  /// \param SS The nested-name-specifier, which is both an input
3030  /// parameter (the nested-name-specifier before this type) and an
3031  /// output parameter (containing the full nested-name-specifier,
3032  /// including this new type).
3033  ///
3034  /// \param TemplateLoc the location of the 'template' keyword, if any.
3035  /// \param TemplateName The template name.
3036  /// \param TemplateNameLoc The location of the template name.
3037  /// \param LAngleLoc The location of the opening angle bracket  ('<').
3038  /// \param TemplateArgs The template arguments.
3039  /// \param RAngleLoc The location of the closing angle bracket  ('>').
3040  /// \param CCLoc The location of the '::'.
3041
3042  /// \param EnteringContext Whether we're entering the context of the
3043  /// nested-name-specifier.
3044  ///
3045  ///
3046  /// \returns true if an error occurred, false otherwise.
3047  bool ActOnCXXNestedNameSpecifier(Scope *S,
3048                                   SourceLocation TemplateLoc,
3049                                   CXXScopeSpec &SS,
3050                                   TemplateTy Template,
3051                                   SourceLocation TemplateNameLoc,
3052                                   SourceLocation LAngleLoc,
3053                                   ASTTemplateArgsPtr TemplateArgs,
3054                                   SourceLocation RAngleLoc,
3055                                   SourceLocation CCLoc,
3056                                   bool EnteringContext);
3057
3058  /// \brief Given a C++ nested-name-specifier, produce an annotation value
3059  /// that the parser can use later to reconstruct the given
3060  /// nested-name-specifier.
3061  ///
3062  /// \param SS A nested-name-specifier.
3063  ///
3064  /// \returns A pointer containing all of the information in the
3065  /// nested-name-specifier \p SS.
3066  void *SaveNestedNameSpecifierAnnotation(CXXScopeSpec &SS);
3067
3068  /// \brief Given an annotation pointer for a nested-name-specifier, restore
3069  /// the nested-name-specifier structure.
3070  ///
3071  /// \param Annotation The annotation pointer, produced by
3072  /// \c SaveNestedNameSpecifierAnnotation().
3073  ///
3074  /// \param AnnotationRange The source range corresponding to the annotation.
3075  ///
3076  /// \param SS The nested-name-specifier that will be updated with the contents
3077  /// of the annotation pointer.
3078  void RestoreNestedNameSpecifierAnnotation(void *Annotation,
3079                                            SourceRange AnnotationRange,
3080                                            CXXScopeSpec &SS);
3081
3082  bool ShouldEnterDeclaratorScope(Scope *S, const CXXScopeSpec &SS);
3083
3084  /// ActOnCXXEnterDeclaratorScope - Called when a C++ scope specifier (global
3085  /// scope or nested-name-specifier) is parsed, part of a declarator-id.
3086  /// After this method is called, according to [C++ 3.4.3p3], names should be
3087  /// looked up in the declarator-id's scope, until the declarator is parsed and
3088  /// ActOnCXXExitDeclaratorScope is called.
3089  /// The 'SS' should be a non-empty valid CXXScopeSpec.
3090  bool ActOnCXXEnterDeclaratorScope(Scope *S, CXXScopeSpec &SS);
3091
3092  /// ActOnCXXExitDeclaratorScope - Called when a declarator that previously
3093  /// invoked ActOnCXXEnterDeclaratorScope(), is finished. 'SS' is the same
3094  /// CXXScopeSpec that was passed to ActOnCXXEnterDeclaratorScope as well.
3095  /// Used to indicate that names should revert to being looked up in the
3096  /// defining scope.
3097  void ActOnCXXExitDeclaratorScope(Scope *S, const CXXScopeSpec &SS);
3098
3099  /// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse an
3100  /// initializer for the declaration 'Dcl'.
3101  /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
3102  /// static data member of class X, names should be looked up in the scope of
3103  /// class X.
3104  void ActOnCXXEnterDeclInitializer(Scope *S, Decl *Dcl);
3105
3106  /// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
3107  /// initializer for the declaration 'Dcl'.
3108  void ActOnCXXExitDeclInitializer(Scope *S, Decl *Dcl);
3109
3110  // ParseObjCStringLiteral - Parse Objective-C string literals.
3111  ExprResult ParseObjCStringLiteral(SourceLocation *AtLocs,
3112                                    Expr **Strings,
3113                                    unsigned NumStrings);
3114
3115  ExprResult BuildObjCEncodeExpression(SourceLocation AtLoc,
3116                                  TypeSourceInfo *EncodedTypeInfo,
3117                                  SourceLocation RParenLoc);
3118  ExprResult BuildCXXMemberCallExpr(Expr *Exp, NamedDecl *FoundDecl,
3119                                    CXXMethodDecl *Method);
3120
3121  ExprResult ParseObjCEncodeExpression(SourceLocation AtLoc,
3122                                       SourceLocation EncodeLoc,
3123                                       SourceLocation LParenLoc,
3124                                       ParsedType Ty,
3125                                       SourceLocation RParenLoc);
3126
3127  // ParseObjCSelectorExpression - Build selector expression for @selector
3128  ExprResult ParseObjCSelectorExpression(Selector Sel,
3129                                         SourceLocation AtLoc,
3130                                         SourceLocation SelLoc,
3131                                         SourceLocation LParenLoc,
3132                                         SourceLocation RParenLoc);
3133
3134  // ParseObjCProtocolExpression - Build protocol expression for @protocol
3135  ExprResult ParseObjCProtocolExpression(IdentifierInfo * ProtocolName,
3136                                         SourceLocation AtLoc,
3137                                         SourceLocation ProtoLoc,
3138                                         SourceLocation LParenLoc,
3139                                         SourceLocation RParenLoc);
3140
3141  //===--------------------------------------------------------------------===//
3142  // C++ Declarations
3143  //
3144  Decl *ActOnStartLinkageSpecification(Scope *S,
3145                                       SourceLocation ExternLoc,
3146                                       SourceLocation LangLoc,
3147                                       llvm::StringRef Lang,
3148                                       SourceLocation LBraceLoc);
3149  Decl *ActOnFinishLinkageSpecification(Scope *S,
3150                                        Decl *LinkageSpec,
3151                                        SourceLocation RBraceLoc);
3152
3153
3154  //===--------------------------------------------------------------------===//
3155  // C++ Classes
3156  //
3157  bool isCurrentClassName(const IdentifierInfo &II, Scope *S,
3158                          const CXXScopeSpec *SS = 0);
3159
3160  Decl *ActOnAccessSpecifier(AccessSpecifier Access,
3161                             SourceLocation ASLoc,
3162                             SourceLocation ColonLoc);
3163
3164  Decl *ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS,
3165                                 Declarator &D,
3166                                 MultiTemplateParamsArg TemplateParameterLists,
3167                                 Expr *BitfieldWidth, const VirtSpecifiers &VS,
3168                                 Expr *Init, bool IsDefinition);
3169
3170  MemInitResult ActOnMemInitializer(Decl *ConstructorD,
3171                                    Scope *S,
3172                                    CXXScopeSpec &SS,
3173                                    IdentifierInfo *MemberOrBase,
3174                                    ParsedType TemplateTypeTy,
3175                                    SourceLocation IdLoc,
3176                                    SourceLocation LParenLoc,
3177                                    Expr **Args, unsigned NumArgs,
3178                                    SourceLocation RParenLoc,
3179                                    SourceLocation EllipsisLoc);
3180
3181  MemInitResult BuildMemberInitializer(ValueDecl *Member, Expr **Args,
3182                                       unsigned NumArgs, SourceLocation IdLoc,
3183                                       SourceLocation LParenLoc,
3184                                       SourceLocation RParenLoc);
3185
3186  MemInitResult BuildBaseInitializer(QualType BaseType,
3187                                     TypeSourceInfo *BaseTInfo,
3188                                     Expr **Args, unsigned NumArgs,
3189                                     SourceLocation LParenLoc,
3190                                     SourceLocation RParenLoc,
3191                                     CXXRecordDecl *ClassDecl,
3192                                     SourceLocation EllipsisLoc);
3193
3194  MemInitResult BuildDelegatingInitializer(TypeSourceInfo *TInfo,
3195                                           Expr **Args, unsigned NumArgs,
3196                                           SourceLocation BaseLoc,
3197                                           SourceLocation RParenLoc,
3198                                           SourceLocation LParenLoc,
3199                                           CXXRecordDecl *ClassDecl);
3200
3201  bool SetDelegatingInitializer(CXXConstructorDecl *Constructor,
3202                                CXXCtorInitializer *Initializer);
3203
3204  bool SetCtorInitializers(CXXConstructorDecl *Constructor,
3205                           CXXCtorInitializer **Initializers,
3206                           unsigned NumInitializers, bool AnyErrors);
3207
3208  void SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation);
3209
3210
3211  /// MarkBaseAndMemberDestructorsReferenced - Given a record decl,
3212  /// mark all the non-trivial destructors of its members and bases as
3213  /// referenced.
3214  void MarkBaseAndMemberDestructorsReferenced(SourceLocation Loc,
3215                                              CXXRecordDecl *Record);
3216
3217  /// \brief The list of classes whose vtables have been used within
3218  /// this translation unit, and the source locations at which the
3219  /// first use occurred.
3220  typedef std::pair<CXXRecordDecl*, SourceLocation> VTableUse;
3221
3222  /// \brief The list of vtables that are required but have not yet been
3223  /// materialized.
3224  llvm::SmallVector<VTableUse, 16> VTableUses;
3225
3226  /// \brief The set of classes whose vtables have been used within
3227  /// this translation unit, and a bit that will be true if the vtable is
3228  /// required to be emitted (otherwise, it should be emitted only if needed
3229  /// by code generation).
3230  llvm::DenseMap<CXXRecordDecl *, bool> VTablesUsed;
3231
3232  /// \brief A list of all of the dynamic classes in this translation
3233  /// unit.
3234  llvm::SmallVector<CXXRecordDecl *, 16> DynamicClasses;
3235
3236  /// \brief Note that the vtable for the given class was used at the
3237  /// given location.
3238  void MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
3239                      bool DefinitionRequired = false);
3240
3241  /// MarkVirtualMembersReferenced - Will mark all members of the given
3242  /// CXXRecordDecl referenced.
3243  void MarkVirtualMembersReferenced(SourceLocation Loc,
3244                                    const CXXRecordDecl *RD);
3245
3246  /// \brief Define all of the vtables that have been used in this
3247  /// translation unit and reference any virtual members used by those
3248  /// vtables.
3249  ///
3250  /// \returns true if any work was done, false otherwise.
3251  bool DefineUsedVTables();
3252
3253  void AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl);
3254
3255  void ActOnMemInitializers(Decl *ConstructorDecl,
3256                            SourceLocation ColonLoc,
3257                            MemInitTy **MemInits, unsigned NumMemInits,
3258                            bool AnyErrors);
3259
3260  void CheckCompletedCXXClass(CXXRecordDecl *Record);
3261  void ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
3262                                         Decl *TagDecl,
3263                                         SourceLocation LBrac,
3264                                         SourceLocation RBrac,
3265                                         AttributeList *AttrList);
3266
3267  void ActOnReenterTemplateScope(Scope *S, Decl *Template);
3268  void ActOnReenterDeclaratorTemplateScope(Scope *S, DeclaratorDecl *D);
3269  void ActOnStartDelayedMemberDeclarations(Scope *S, Decl *Record);
3270  void ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *Method);
3271  void ActOnDelayedCXXMethodParameter(Scope *S, Decl *Param);
3272  void ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *Method);
3273  void ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *Record);
3274  void MarkAsLateParsedTemplate(FunctionDecl *FD, bool Flag = true);
3275  bool IsInsideALocalClassWithinATemplateFunction();
3276
3277  Decl *ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
3278                                     Expr *AssertExpr,
3279                                     Expr *AssertMessageExpr,
3280                                     SourceLocation RParenLoc);
3281
3282  FriendDecl *CheckFriendTypeDecl(SourceLocation FriendLoc,
3283                                  TypeSourceInfo *TSInfo);
3284  Decl *ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
3285                                MultiTemplateParamsArg TemplateParams);
3286  Decl *ActOnFriendFunctionDecl(Scope *S, Declarator &D, bool IsDefinition,
3287                                    MultiTemplateParamsArg TemplateParams);
3288
3289  QualType CheckConstructorDeclarator(Declarator &D, QualType R,
3290                                      StorageClass& SC);
3291  void CheckConstructor(CXXConstructorDecl *Constructor);
3292  QualType CheckDestructorDeclarator(Declarator &D, QualType R,
3293                                     StorageClass& SC);
3294  bool CheckDestructor(CXXDestructorDecl *Destructor);
3295  void CheckConversionDeclarator(Declarator &D, QualType &R,
3296                                 StorageClass& SC);
3297  Decl *ActOnConversionDeclarator(CXXConversionDecl *Conversion);
3298
3299  void CheckExplicitlyDefaultedMethods(CXXRecordDecl *Record);
3300  void CheckExplicitlyDefaultedDefaultConstructor(CXXConstructorDecl *Ctor);
3301  void CheckExplicitlyDefaultedCopyConstructor(CXXConstructorDecl *Ctor);
3302  void CheckExplicitlyDefaultedCopyAssignment(CXXMethodDecl *Method);
3303  void CheckExplicitlyDefaultedDestructor(CXXDestructorDecl *Dtor);
3304
3305  //===--------------------------------------------------------------------===//
3306  // C++ Derived Classes
3307  //
3308
3309  /// ActOnBaseSpecifier - Parsed a base specifier
3310  CXXBaseSpecifier *CheckBaseSpecifier(CXXRecordDecl *Class,
3311                                       SourceRange SpecifierRange,
3312                                       bool Virtual, AccessSpecifier Access,
3313                                       TypeSourceInfo *TInfo,
3314                                       SourceLocation EllipsisLoc);
3315
3316  BaseResult ActOnBaseSpecifier(Decl *classdecl,
3317                                SourceRange SpecifierRange,
3318                                bool Virtual, AccessSpecifier Access,
3319                                ParsedType basetype,
3320                                SourceLocation BaseLoc,
3321                                SourceLocation EllipsisLoc);
3322
3323  bool AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
3324                            unsigned NumBases);
3325  void ActOnBaseSpecifiers(Decl *ClassDecl, BaseTy **Bases, unsigned NumBases);
3326
3327  bool IsDerivedFrom(QualType Derived, QualType Base);
3328  bool IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths);
3329
3330  // FIXME: I don't like this name.
3331  void BuildBasePathArray(const CXXBasePaths &Paths, CXXCastPath &BasePath);
3332
3333  bool BasePathInvolvesVirtualBase(const CXXCastPath &BasePath);
3334
3335  bool CheckDerivedToBaseConversion(QualType Derived, QualType Base,
3336                                    SourceLocation Loc, SourceRange Range,
3337                                    CXXCastPath *BasePath = 0,
3338                                    bool IgnoreAccess = false);
3339  bool CheckDerivedToBaseConversion(QualType Derived, QualType Base,
3340                                    unsigned InaccessibleBaseID,
3341                                    unsigned AmbigiousBaseConvID,
3342                                    SourceLocation Loc, SourceRange Range,
3343                                    DeclarationName Name,
3344                                    CXXCastPath *BasePath);
3345
3346  std::string getAmbiguousPathsDisplayString(CXXBasePaths &Paths);
3347
3348  /// CheckOverridingFunctionReturnType - Checks whether the return types are
3349  /// covariant, according to C++ [class.virtual]p5.
3350  bool CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
3351                                         const CXXMethodDecl *Old);
3352
3353  /// CheckOverridingFunctionExceptionSpec - Checks whether the exception
3354  /// spec is a subset of base spec.
3355  bool CheckOverridingFunctionExceptionSpec(const CXXMethodDecl *New,
3356                                            const CXXMethodDecl *Old);
3357
3358  bool CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange);
3359
3360  /// CheckOverrideControl - Check C++0x override control semantics.
3361  void CheckOverrideControl(const Decl *D);
3362
3363  /// CheckForFunctionMarkedFinal - Checks whether a virtual member function
3364  /// overrides a virtual member function marked 'final', according to
3365  /// C++0x [class.virtual]p3.
3366  bool CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
3367                                              const CXXMethodDecl *Old);
3368
3369
3370  //===--------------------------------------------------------------------===//
3371  // C++ Access Control
3372  //
3373
3374  enum AccessResult {
3375    AR_accessible,
3376    AR_inaccessible,
3377    AR_dependent,
3378    AR_delayed
3379  };
3380
3381  bool SetMemberAccessSpecifier(NamedDecl *MemberDecl,
3382                                NamedDecl *PrevMemberDecl,
3383                                AccessSpecifier LexicalAS);
3384
3385  AccessResult CheckUnresolvedMemberAccess(UnresolvedMemberExpr *E,
3386                                           DeclAccessPair FoundDecl);
3387  AccessResult CheckUnresolvedLookupAccess(UnresolvedLookupExpr *E,
3388                                           DeclAccessPair FoundDecl);
3389  AccessResult CheckAllocationAccess(SourceLocation OperatorLoc,
3390                                     SourceRange PlacementRange,
3391                                     CXXRecordDecl *NamingClass,
3392                                     DeclAccessPair FoundDecl,
3393                                     bool Diagnose = true);
3394  AccessResult CheckConstructorAccess(SourceLocation Loc,
3395                                      CXXConstructorDecl *D,
3396                                      const InitializedEntity &Entity,
3397                                      AccessSpecifier Access,
3398                                      bool IsCopyBindingRefToTemp = false);
3399  AccessResult CheckDestructorAccess(SourceLocation Loc,
3400                                     CXXDestructorDecl *Dtor,
3401                                     const PartialDiagnostic &PDiag);
3402  AccessResult CheckDirectMemberAccess(SourceLocation Loc,
3403                                       NamedDecl *D,
3404                                       const PartialDiagnostic &PDiag);
3405  AccessResult CheckMemberOperatorAccess(SourceLocation Loc,
3406                                         Expr *ObjectExpr,
3407                                         Expr *ArgExpr,
3408                                         DeclAccessPair FoundDecl);
3409  AccessResult CheckAddressOfMemberAccess(Expr *OvlExpr,
3410                                          DeclAccessPair FoundDecl);
3411  AccessResult CheckBaseClassAccess(SourceLocation AccessLoc,
3412                                    QualType Base, QualType Derived,
3413                                    const CXXBasePath &Path,
3414                                    unsigned DiagID,
3415                                    bool ForceCheck = false,
3416                                    bool ForceUnprivileged = false);
3417  void CheckLookupAccess(const LookupResult &R);
3418
3419  void HandleDependentAccessCheck(const DependentDiagnostic &DD,
3420                         const MultiLevelTemplateArgumentList &TemplateArgs);
3421  void PerformDependentDiagnostics(const DeclContext *Pattern,
3422                        const MultiLevelTemplateArgumentList &TemplateArgs);
3423
3424  void HandleDelayedAccessCheck(sema::DelayedDiagnostic &DD, Decl *Ctx);
3425
3426  /// A flag to suppress access checking.
3427  bool SuppressAccessChecking;
3428
3429  /// \brief When true, access checking violations are treated as SFINAE
3430  /// failures rather than hard errors.
3431  bool AccessCheckingSFINAE;
3432
3433  void ActOnStartSuppressingAccessChecks();
3434  void ActOnStopSuppressingAccessChecks();
3435
3436  enum AbstractDiagSelID {
3437    AbstractNone = -1,
3438    AbstractReturnType,
3439    AbstractParamType,
3440    AbstractVariableType,
3441    AbstractFieldType,
3442    AbstractArrayType
3443  };
3444
3445  bool RequireNonAbstractType(SourceLocation Loc, QualType T,
3446                              const PartialDiagnostic &PD);
3447  void DiagnoseAbstractType(const CXXRecordDecl *RD);
3448
3449  bool RequireNonAbstractType(SourceLocation Loc, QualType T, unsigned DiagID,
3450                              AbstractDiagSelID SelID = AbstractNone);
3451
3452  //===--------------------------------------------------------------------===//
3453  // C++ Overloaded Operators [C++ 13.5]
3454  //
3455
3456  bool CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl);
3457
3458  bool CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl);
3459
3460  //===--------------------------------------------------------------------===//
3461  // C++ Templates [C++ 14]
3462  //
3463  void FilterAcceptableTemplateNames(LookupResult &R);
3464  bool hasAnyAcceptableTemplateNames(LookupResult &R);
3465
3466  void LookupTemplateName(LookupResult &R, Scope *S, CXXScopeSpec &SS,
3467                          QualType ObjectType, bool EnteringContext,
3468                          bool &MemberOfUnknownSpecialization);
3469
3470  TemplateNameKind isTemplateName(Scope *S,
3471                                  CXXScopeSpec &SS,
3472                                  bool hasTemplateKeyword,
3473                                  UnqualifiedId &Name,
3474                                  ParsedType ObjectType,
3475                                  bool EnteringContext,
3476                                  TemplateTy &Template,
3477                                  bool &MemberOfUnknownSpecialization);
3478
3479  bool DiagnoseUnknownTemplateName(const IdentifierInfo &II,
3480                                   SourceLocation IILoc,
3481                                   Scope *S,
3482                                   const CXXScopeSpec *SS,
3483                                   TemplateTy &SuggestedTemplate,
3484                                   TemplateNameKind &SuggestedKind);
3485
3486  bool DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl);
3487  TemplateDecl *AdjustDeclIfTemplate(Decl *&Decl);
3488
3489  Decl *ActOnTypeParameter(Scope *S, bool Typename, bool Ellipsis,
3490                           SourceLocation EllipsisLoc,
3491                           SourceLocation KeyLoc,
3492                           IdentifierInfo *ParamName,
3493                           SourceLocation ParamNameLoc,
3494                           unsigned Depth, unsigned Position,
3495                           SourceLocation EqualLoc,
3496                           ParsedType DefaultArg);
3497
3498  QualType CheckNonTypeTemplateParameterType(QualType T, SourceLocation Loc);
3499  Decl *ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
3500                                      unsigned Depth,
3501                                      unsigned Position,
3502                                      SourceLocation EqualLoc,
3503                                      Expr *DefaultArg);
3504  Decl *ActOnTemplateTemplateParameter(Scope *S,
3505                                       SourceLocation TmpLoc,
3506                                       TemplateParamsTy *Params,
3507                                       SourceLocation EllipsisLoc,
3508                                       IdentifierInfo *ParamName,
3509                                       SourceLocation ParamNameLoc,
3510                                       unsigned Depth,
3511                                       unsigned Position,
3512                                       SourceLocation EqualLoc,
3513                                       ParsedTemplateArgument DefaultArg);
3514
3515  TemplateParamsTy *
3516  ActOnTemplateParameterList(unsigned Depth,
3517                             SourceLocation ExportLoc,
3518                             SourceLocation TemplateLoc,
3519                             SourceLocation LAngleLoc,
3520                             Decl **Params, unsigned NumParams,
3521                             SourceLocation RAngleLoc);
3522
3523  /// \brief The context in which we are checking a template parameter
3524  /// list.
3525  enum TemplateParamListContext {
3526    TPC_ClassTemplate,
3527    TPC_FunctionTemplate,
3528    TPC_ClassTemplateMember,
3529    TPC_FriendFunctionTemplate,
3530    TPC_FriendFunctionTemplateDefinition,
3531    TPC_TypeAliasTemplate
3532  };
3533
3534  bool CheckTemplateParameterList(TemplateParameterList *NewParams,
3535                                  TemplateParameterList *OldParams,
3536                                  TemplateParamListContext TPC);
3537  TemplateParameterList *
3538  MatchTemplateParametersToScopeSpecifier(SourceLocation DeclStartLoc,
3539                                          SourceLocation DeclLoc,
3540                                          const CXXScopeSpec &SS,
3541                                          TemplateParameterList **ParamLists,
3542                                          unsigned NumParamLists,
3543                                          bool IsFriend,
3544                                          bool &IsExplicitSpecialization,
3545                                          bool &Invalid);
3546
3547  DeclResult CheckClassTemplate(Scope *S, unsigned TagSpec, TagUseKind TUK,
3548                                SourceLocation KWLoc, CXXScopeSpec &SS,
3549                                IdentifierInfo *Name, SourceLocation NameLoc,
3550                                AttributeList *Attr,
3551                                TemplateParameterList *TemplateParams,
3552                                AccessSpecifier AS,
3553                                unsigned NumOuterTemplateParamLists,
3554                            TemplateParameterList **OuterTemplateParamLists);
3555
3556  void translateTemplateArguments(const ASTTemplateArgsPtr &In,
3557                                  TemplateArgumentListInfo &Out);
3558
3559  void NoteAllFoundTemplates(TemplateName Name);
3560
3561  QualType CheckTemplateIdType(TemplateName Template,
3562                               SourceLocation TemplateLoc,
3563                              TemplateArgumentListInfo &TemplateArgs);
3564
3565  TypeResult
3566  ActOnTemplateIdType(CXXScopeSpec &SS,
3567                      TemplateTy Template, SourceLocation TemplateLoc,
3568                      SourceLocation LAngleLoc,
3569                      ASTTemplateArgsPtr TemplateArgs,
3570                      SourceLocation RAngleLoc);
3571
3572  /// \brief Parsed an elaborated-type-specifier that refers to a template-id,
3573  /// such as \c class T::template apply<U>.
3574  ///
3575  /// \param TUK
3576  TypeResult ActOnTagTemplateIdType(TagUseKind TUK,
3577                                    TypeSpecifierType TagSpec,
3578                                    SourceLocation TagLoc,
3579                                    CXXScopeSpec &SS,
3580                                    TemplateTy TemplateD,
3581                                    SourceLocation TemplateLoc,
3582                                    SourceLocation LAngleLoc,
3583                                    ASTTemplateArgsPtr TemplateArgsIn,
3584                                    SourceLocation RAngleLoc);
3585
3586
3587  ExprResult BuildTemplateIdExpr(const CXXScopeSpec &SS,
3588                                 LookupResult &R,
3589                                 bool RequiresADL,
3590                               const TemplateArgumentListInfo &TemplateArgs);
3591  ExprResult BuildQualifiedTemplateIdExpr(CXXScopeSpec &SS,
3592                               const DeclarationNameInfo &NameInfo,
3593                               const TemplateArgumentListInfo &TemplateArgs);
3594
3595  TemplateNameKind ActOnDependentTemplateName(Scope *S,
3596                                              SourceLocation TemplateKWLoc,
3597                                              CXXScopeSpec &SS,
3598                                              UnqualifiedId &Name,
3599                                              ParsedType ObjectType,
3600                                              bool EnteringContext,
3601                                              TemplateTy &Template);
3602
3603  DeclResult
3604  ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec, TagUseKind TUK,
3605                                   SourceLocation KWLoc,
3606                                   CXXScopeSpec &SS,
3607                                   TemplateTy Template,
3608                                   SourceLocation TemplateNameLoc,
3609                                   SourceLocation LAngleLoc,
3610                                   ASTTemplateArgsPtr TemplateArgs,
3611                                   SourceLocation RAngleLoc,
3612                                   AttributeList *Attr,
3613                                 MultiTemplateParamsArg TemplateParameterLists);
3614
3615  Decl *ActOnTemplateDeclarator(Scope *S,
3616                                MultiTemplateParamsArg TemplateParameterLists,
3617                                Declarator &D);
3618
3619  Decl *ActOnStartOfFunctionTemplateDef(Scope *FnBodyScope,
3620                                  MultiTemplateParamsArg TemplateParameterLists,
3621                                        Declarator &D);
3622
3623  bool
3624  CheckSpecializationInstantiationRedecl(SourceLocation NewLoc,
3625                                         TemplateSpecializationKind NewTSK,
3626                                         NamedDecl *PrevDecl,
3627                                         TemplateSpecializationKind PrevTSK,
3628                                         SourceLocation PrevPtOfInstantiation,
3629                                         bool &SuppressNew);
3630
3631  bool CheckDependentFunctionTemplateSpecialization(FunctionDecl *FD,
3632                    const TemplateArgumentListInfo &ExplicitTemplateArgs,
3633                                                    LookupResult &Previous);
3634
3635  bool CheckFunctionTemplateSpecialization(FunctionDecl *FD,
3636                         TemplateArgumentListInfo *ExplicitTemplateArgs,
3637                                           LookupResult &Previous);
3638  bool CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous);
3639
3640  DeclResult
3641  ActOnExplicitInstantiation(Scope *S,
3642                             SourceLocation ExternLoc,
3643                             SourceLocation TemplateLoc,
3644                             unsigned TagSpec,
3645                             SourceLocation KWLoc,
3646                             const CXXScopeSpec &SS,
3647                             TemplateTy Template,
3648                             SourceLocation TemplateNameLoc,
3649                             SourceLocation LAngleLoc,
3650                             ASTTemplateArgsPtr TemplateArgs,
3651                             SourceLocation RAngleLoc,
3652                             AttributeList *Attr);
3653
3654  DeclResult
3655  ActOnExplicitInstantiation(Scope *S,
3656                             SourceLocation ExternLoc,
3657                             SourceLocation TemplateLoc,
3658                             unsigned TagSpec,
3659                             SourceLocation KWLoc,
3660                             CXXScopeSpec &SS,
3661                             IdentifierInfo *Name,
3662                             SourceLocation NameLoc,
3663                             AttributeList *Attr);
3664
3665  DeclResult ActOnExplicitInstantiation(Scope *S,
3666                                        SourceLocation ExternLoc,
3667                                        SourceLocation TemplateLoc,
3668                                        Declarator &D);
3669
3670  TemplateArgumentLoc
3671  SubstDefaultTemplateArgumentIfAvailable(TemplateDecl *Template,
3672                                          SourceLocation TemplateLoc,
3673                                          SourceLocation RAngleLoc,
3674                                          Decl *Param,
3675                          llvm::SmallVectorImpl<TemplateArgument> &Converted);
3676
3677  /// \brief Specifies the context in which a particular template
3678  /// argument is being checked.
3679  enum CheckTemplateArgumentKind {
3680    /// \brief The template argument was specified in the code or was
3681    /// instantiated with some deduced template arguments.
3682    CTAK_Specified,
3683
3684    /// \brief The template argument was deduced via template argument
3685    /// deduction.
3686    CTAK_Deduced,
3687
3688    /// \brief The template argument was deduced from an array bound
3689    /// via template argument deduction.
3690    CTAK_DeducedFromArrayBound
3691  };
3692
3693  bool CheckTemplateArgument(NamedDecl *Param,
3694                             const TemplateArgumentLoc &Arg,
3695                             NamedDecl *Template,
3696                             SourceLocation TemplateLoc,
3697                             SourceLocation RAngleLoc,
3698                             unsigned ArgumentPackIndex,
3699                           llvm::SmallVectorImpl<TemplateArgument> &Converted,
3700                             CheckTemplateArgumentKind CTAK = CTAK_Specified);
3701
3702  /// \brief Check that the given template arguments can be be provided to
3703  /// the given template, converting the arguments along the way.
3704  ///
3705  /// \param Template The template to which the template arguments are being
3706  /// provided.
3707  ///
3708  /// \param TemplateLoc The location of the template name in the source.
3709  ///
3710  /// \param TemplateArgs The list of template arguments. If the template is
3711  /// a template template parameter, this function may extend the set of
3712  /// template arguments to also include substituted, defaulted template
3713  /// arguments.
3714  ///
3715  /// \param PartialTemplateArgs True if the list of template arguments is
3716  /// intentionally partial, e.g., because we're checking just the initial
3717  /// set of template arguments.
3718  ///
3719  /// \param Converted Will receive the converted, canonicalized template
3720  /// arguments.
3721  ///
3722  /// \returns True if an error occurred, false otherwise.
3723  bool CheckTemplateArgumentList(TemplateDecl *Template,
3724                                 SourceLocation TemplateLoc,
3725                                 TemplateArgumentListInfo &TemplateArgs,
3726                                 bool PartialTemplateArgs,
3727                           llvm::SmallVectorImpl<TemplateArgument> &Converted);
3728
3729  bool CheckTemplateTypeArgument(TemplateTypeParmDecl *Param,
3730                                 const TemplateArgumentLoc &Arg,
3731                           llvm::SmallVectorImpl<TemplateArgument> &Converted);
3732
3733  bool CheckTemplateArgument(TemplateTypeParmDecl *Param,
3734                             TypeSourceInfo *Arg);
3735  bool CheckTemplateArgumentPointerToMember(Expr *Arg,
3736                                            TemplateArgument &Converted);
3737  ExprResult CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
3738                                   QualType InstantiatedParamType, Expr *Arg,
3739                                   TemplateArgument &Converted,
3740                                   CheckTemplateArgumentKind CTAK = CTAK_Specified);
3741  bool CheckTemplateArgument(TemplateTemplateParmDecl *Param,
3742                             const TemplateArgumentLoc &Arg);
3743
3744  ExprResult
3745  BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg,
3746                                          QualType ParamType,
3747                                          SourceLocation Loc);
3748  ExprResult
3749  BuildExpressionFromIntegralTemplateArgument(const TemplateArgument &Arg,
3750                                              SourceLocation Loc);
3751
3752  /// \brief Enumeration describing how template parameter lists are compared
3753  /// for equality.
3754  enum TemplateParameterListEqualKind {
3755    /// \brief We are matching the template parameter lists of two templates
3756    /// that might be redeclarations.
3757    ///
3758    /// \code
3759    /// template<typename T> struct X;
3760    /// template<typename T> struct X;
3761    /// \endcode
3762    TPL_TemplateMatch,
3763
3764    /// \brief We are matching the template parameter lists of two template
3765    /// template parameters as part of matching the template parameter lists
3766    /// of two templates that might be redeclarations.
3767    ///
3768    /// \code
3769    /// template<template<int I> class TT> struct X;
3770    /// template<template<int Value> class Other> struct X;
3771    /// \endcode
3772    TPL_TemplateTemplateParmMatch,
3773
3774    /// \brief We are matching the template parameter lists of a template
3775    /// template argument against the template parameter lists of a template
3776    /// template parameter.
3777    ///
3778    /// \code
3779    /// template<template<int Value> class Metafun> struct X;
3780    /// template<int Value> struct integer_c;
3781    /// X<integer_c> xic;
3782    /// \endcode
3783    TPL_TemplateTemplateArgumentMatch
3784  };
3785
3786  bool TemplateParameterListsAreEqual(TemplateParameterList *New,
3787                                      TemplateParameterList *Old,
3788                                      bool Complain,
3789                                      TemplateParameterListEqualKind Kind,
3790                                      SourceLocation TemplateArgLoc
3791                                        = SourceLocation());
3792
3793  bool CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams);
3794
3795  /// \brief Called when the parser has parsed a C++ typename
3796  /// specifier, e.g., "typename T::type".
3797  ///
3798  /// \param S The scope in which this typename type occurs.
3799  /// \param TypenameLoc the location of the 'typename' keyword
3800  /// \param SS the nested-name-specifier following the typename (e.g., 'T::').
3801  /// \param II the identifier we're retrieving (e.g., 'type' in the example).
3802  /// \param IdLoc the location of the identifier.
3803  TypeResult
3804  ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
3805                    const CXXScopeSpec &SS, const IdentifierInfo &II,
3806                    SourceLocation IdLoc);
3807
3808  /// \brief Called when the parser has parsed a C++ typename
3809  /// specifier that ends in a template-id, e.g.,
3810  /// "typename MetaFun::template apply<T1, T2>".
3811  ///
3812  /// \param S The scope in which this typename type occurs.
3813  /// \param TypenameLoc the location of the 'typename' keyword
3814  /// \param SS the nested-name-specifier following the typename (e.g., 'T::').
3815  /// \param TemplateLoc the location of the 'template' keyword, if any.
3816  /// \param TemplateName The template name.
3817  /// \param TemplateNameLoc The location of the template name.
3818  /// \param LAngleLoc The location of the opening angle bracket  ('<').
3819  /// \param TemplateArgs The template arguments.
3820  /// \param RAngleLoc The location of the closing angle bracket  ('>').
3821  TypeResult
3822  ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
3823                    const CXXScopeSpec &SS,
3824                    SourceLocation TemplateLoc,
3825                    TemplateTy Template,
3826                    SourceLocation TemplateNameLoc,
3827                    SourceLocation LAngleLoc,
3828                    ASTTemplateArgsPtr TemplateArgs,
3829                    SourceLocation RAngleLoc);
3830
3831  QualType CheckTypenameType(ElaboratedTypeKeyword Keyword,
3832                             SourceLocation KeywordLoc,
3833                             NestedNameSpecifierLoc QualifierLoc,
3834                             const IdentifierInfo &II,
3835                             SourceLocation IILoc);
3836
3837  TypeSourceInfo *RebuildTypeInCurrentInstantiation(TypeSourceInfo *T,
3838                                                    SourceLocation Loc,
3839                                                    DeclarationName Name);
3840  bool RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS);
3841
3842  ExprResult RebuildExprInCurrentInstantiation(Expr *E);
3843
3844  std::string
3845  getTemplateArgumentBindingsText(const TemplateParameterList *Params,
3846                                  const TemplateArgumentList &Args);
3847
3848  std::string
3849  getTemplateArgumentBindingsText(const TemplateParameterList *Params,
3850                                  const TemplateArgument *Args,
3851                                  unsigned NumArgs);
3852
3853  //===--------------------------------------------------------------------===//
3854  // C++ Variadic Templates (C++0x [temp.variadic])
3855  //===--------------------------------------------------------------------===//
3856
3857  /// \brief The context in which an unexpanded parameter pack is
3858  /// being diagnosed.
3859  ///
3860  /// Note that the values of this enumeration line up with the first
3861  /// argument to the \c err_unexpanded_parameter_pack diagnostic.
3862  enum UnexpandedParameterPackContext {
3863    /// \brief An arbitrary expression.
3864    UPPC_Expression = 0,
3865
3866    /// \brief The base type of a class type.
3867    UPPC_BaseType,
3868
3869    /// \brief The type of an arbitrary declaration.
3870    UPPC_DeclarationType,
3871
3872    /// \brief The type of a data member.
3873    UPPC_DataMemberType,
3874
3875    /// \brief The size of a bit-field.
3876    UPPC_BitFieldWidth,
3877
3878    /// \brief The expression in a static assertion.
3879    UPPC_StaticAssertExpression,
3880
3881    /// \brief The fixed underlying type of an enumeration.
3882    UPPC_FixedUnderlyingType,
3883
3884    /// \brief The enumerator value.
3885    UPPC_EnumeratorValue,
3886
3887    /// \brief A using declaration.
3888    UPPC_UsingDeclaration,
3889
3890    /// \brief A friend declaration.
3891    UPPC_FriendDeclaration,
3892
3893    /// \brief A declaration qualifier.
3894    UPPC_DeclarationQualifier,
3895
3896    /// \brief An initializer.
3897    UPPC_Initializer,
3898
3899    /// \brief A default argument.
3900    UPPC_DefaultArgument,
3901
3902    /// \brief The type of a non-type template parameter.
3903    UPPC_NonTypeTemplateParameterType,
3904
3905    /// \brief The type of an exception.
3906    UPPC_ExceptionType,
3907
3908    /// \brief Partial specialization.
3909    UPPC_PartialSpecialization
3910  };
3911
3912  /// \brief If the given type contains an unexpanded parameter pack,
3913  /// diagnose the error.
3914  ///
3915  /// \param Loc The source location where a diagnostc should be emitted.
3916  ///
3917  /// \param T The type that is being checked for unexpanded parameter
3918  /// packs.
3919  ///
3920  /// \returns true if an error occurred, false otherwise.
3921  bool DiagnoseUnexpandedParameterPack(SourceLocation Loc, TypeSourceInfo *T,
3922                                       UnexpandedParameterPackContext UPPC);
3923
3924  /// \brief If the given expression contains an unexpanded parameter
3925  /// pack, diagnose the error.
3926  ///
3927  /// \param E The expression that is being checked for unexpanded
3928  /// parameter packs.
3929  ///
3930  /// \returns true if an error occurred, false otherwise.
3931  bool DiagnoseUnexpandedParameterPack(Expr *E,
3932                       UnexpandedParameterPackContext UPPC = UPPC_Expression);
3933
3934  /// \brief If the given nested-name-specifier contains an unexpanded
3935  /// parameter pack, diagnose the error.
3936  ///
3937  /// \param SS The nested-name-specifier that is being checked for
3938  /// unexpanded parameter packs.
3939  ///
3940  /// \returns true if an error occurred, false otherwise.
3941  bool DiagnoseUnexpandedParameterPack(const CXXScopeSpec &SS,
3942                                       UnexpandedParameterPackContext UPPC);
3943
3944  /// \brief If the given name contains an unexpanded parameter pack,
3945  /// diagnose the error.
3946  ///
3947  /// \param NameInfo The name (with source location information) that
3948  /// is being checked for unexpanded parameter packs.
3949  ///
3950  /// \returns true if an error occurred, false otherwise.
3951  bool DiagnoseUnexpandedParameterPack(const DeclarationNameInfo &NameInfo,
3952                                       UnexpandedParameterPackContext UPPC);
3953
3954  /// \brief If the given template name contains an unexpanded parameter pack,
3955  /// diagnose the error.
3956  ///
3957  /// \param Loc The location of the template name.
3958  ///
3959  /// \param Template The template name that is being checked for unexpanded
3960  /// parameter packs.
3961  ///
3962  /// \returns true if an error occurred, false otherwise.
3963  bool DiagnoseUnexpandedParameterPack(SourceLocation Loc,
3964                                       TemplateName Template,
3965                                       UnexpandedParameterPackContext UPPC);
3966
3967  /// \brief If the given template argument contains an unexpanded parameter
3968  /// pack, diagnose the error.
3969  ///
3970  /// \param Arg The template argument that is being checked for unexpanded
3971  /// parameter packs.
3972  ///
3973  /// \returns true if an error occurred, false otherwise.
3974  bool DiagnoseUnexpandedParameterPack(TemplateArgumentLoc Arg,
3975                                       UnexpandedParameterPackContext UPPC);
3976
3977  /// \brief Collect the set of unexpanded parameter packs within the given
3978  /// template argument.
3979  ///
3980  /// \param Arg The template argument that will be traversed to find
3981  /// unexpanded parameter packs.
3982  void collectUnexpandedParameterPacks(TemplateArgument Arg,
3983                   llvm::SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
3984
3985  /// \brief Collect the set of unexpanded parameter packs within the given
3986  /// template argument.
3987  ///
3988  /// \param Arg The template argument that will be traversed to find
3989  /// unexpanded parameter packs.
3990  void collectUnexpandedParameterPacks(TemplateArgumentLoc Arg,
3991                    llvm::SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
3992
3993  /// \brief Collect the set of unexpanded parameter packs within the given
3994  /// type.
3995  ///
3996  /// \param T The type that will be traversed to find
3997  /// unexpanded parameter packs.
3998  void collectUnexpandedParameterPacks(QualType T,
3999                   llvm::SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
4000
4001  /// \brief Collect the set of unexpanded parameter packs within the given
4002  /// type.
4003  ///
4004  /// \param TL The type that will be traversed to find
4005  /// unexpanded parameter packs.
4006  void collectUnexpandedParameterPacks(TypeLoc TL,
4007                   llvm::SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
4008
4009  /// \brief Invoked when parsing a template argument followed by an
4010  /// ellipsis, which creates a pack expansion.
4011  ///
4012  /// \param Arg The template argument preceding the ellipsis, which
4013  /// may already be invalid.
4014  ///
4015  /// \param EllipsisLoc The location of the ellipsis.
4016  ParsedTemplateArgument ActOnPackExpansion(const ParsedTemplateArgument &Arg,
4017                                            SourceLocation EllipsisLoc);
4018
4019  /// \brief Invoked when parsing a type followed by an ellipsis, which
4020  /// creates a pack expansion.
4021  ///
4022  /// \param Type The type preceding the ellipsis, which will become
4023  /// the pattern of the pack expansion.
4024  ///
4025  /// \param EllipsisLoc The location of the ellipsis.
4026  TypeResult ActOnPackExpansion(ParsedType Type, SourceLocation EllipsisLoc);
4027
4028  /// \brief Construct a pack expansion type from the pattern of the pack
4029  /// expansion.
4030  TypeSourceInfo *CheckPackExpansion(TypeSourceInfo *Pattern,
4031                                     SourceLocation EllipsisLoc,
4032                                     llvm::Optional<unsigned> NumExpansions);
4033
4034  /// \brief Construct a pack expansion type from the pattern of the pack
4035  /// expansion.
4036  QualType CheckPackExpansion(QualType Pattern,
4037                              SourceRange PatternRange,
4038                              SourceLocation EllipsisLoc,
4039                              llvm::Optional<unsigned> NumExpansions);
4040
4041  /// \brief Invoked when parsing an expression followed by an ellipsis, which
4042  /// creates a pack expansion.
4043  ///
4044  /// \param Pattern The expression preceding the ellipsis, which will become
4045  /// the pattern of the pack expansion.
4046  ///
4047  /// \param EllipsisLoc The location of the ellipsis.
4048  ExprResult ActOnPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc);
4049
4050  /// \brief Invoked when parsing an expression followed by an ellipsis, which
4051  /// creates a pack expansion.
4052  ///
4053  /// \param Pattern The expression preceding the ellipsis, which will become
4054  /// the pattern of the pack expansion.
4055  ///
4056  /// \param EllipsisLoc The location of the ellipsis.
4057  ExprResult CheckPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc,
4058                                llvm::Optional<unsigned> NumExpansions);
4059
4060  /// \brief Determine whether we could expand a pack expansion with the
4061  /// given set of parameter packs into separate arguments by repeatedly
4062  /// transforming the pattern.
4063  ///
4064  /// \param EllipsisLoc The location of the ellipsis that identifies the
4065  /// pack expansion.
4066  ///
4067  /// \param PatternRange The source range that covers the entire pattern of
4068  /// the pack expansion.
4069  ///
4070  /// \param Unexpanded The set of unexpanded parameter packs within the
4071  /// pattern.
4072  ///
4073  /// \param NumUnexpanded The number of unexpanded parameter packs in
4074  /// \p Unexpanded.
4075  ///
4076  /// \param ShouldExpand Will be set to \c true if the transformer should
4077  /// expand the corresponding pack expansions into separate arguments. When
4078  /// set, \c NumExpansions must also be set.
4079  ///
4080  /// \param RetainExpansion Whether the caller should add an unexpanded
4081  /// pack expansion after all of the expanded arguments. This is used
4082  /// when extending explicitly-specified template argument packs per
4083  /// C++0x [temp.arg.explicit]p9.
4084  ///
4085  /// \param NumExpansions The number of separate arguments that will be in
4086  /// the expanded form of the corresponding pack expansion. This is both an
4087  /// input and an output parameter, which can be set by the caller if the
4088  /// number of expansions is known a priori (e.g., due to a prior substitution)
4089  /// and will be set by the callee when the number of expansions is known.
4090  /// The callee must set this value when \c ShouldExpand is \c true; it may
4091  /// set this value in other cases.
4092  ///
4093  /// \returns true if an error occurred (e.g., because the parameter packs
4094  /// are to be instantiated with arguments of different lengths), false
4095  /// otherwise. If false, \c ShouldExpand (and possibly \c NumExpansions)
4096  /// must be set.
4097  bool CheckParameterPacksForExpansion(SourceLocation EllipsisLoc,
4098                                       SourceRange PatternRange,
4099                                     const UnexpandedParameterPack *Unexpanded,
4100                                       unsigned NumUnexpanded,
4101                             const MultiLevelTemplateArgumentList &TemplateArgs,
4102                                       bool &ShouldExpand,
4103                                       bool &RetainExpansion,
4104                                       llvm::Optional<unsigned> &NumExpansions);
4105
4106  /// \brief Determine the number of arguments in the given pack expansion
4107  /// type.
4108  ///
4109  /// This routine already assumes that the pack expansion type can be
4110  /// expanded and that the number of arguments in the expansion is
4111  /// consistent across all of the unexpanded parameter packs in its pattern.
4112  unsigned getNumArgumentsInExpansion(QualType T,
4113                            const MultiLevelTemplateArgumentList &TemplateArgs);
4114
4115  /// \brief Determine whether the given declarator contains any unexpanded
4116  /// parameter packs.
4117  ///
4118  /// This routine is used by the parser to disambiguate function declarators
4119  /// with an ellipsis prior to the ')', e.g.,
4120  ///
4121  /// \code
4122  ///   void f(T...);
4123  /// \endcode
4124  ///
4125  /// To determine whether we have an (unnamed) function parameter pack or
4126  /// a variadic function.
4127  ///
4128  /// \returns true if the declarator contains any unexpanded parameter packs,
4129  /// false otherwise.
4130  bool containsUnexpandedParameterPacks(Declarator &D);
4131
4132  //===--------------------------------------------------------------------===//
4133  // C++ Template Argument Deduction (C++ [temp.deduct])
4134  //===--------------------------------------------------------------------===//
4135
4136  /// \brief Describes the result of template argument deduction.
4137  ///
4138  /// The TemplateDeductionResult enumeration describes the result of
4139  /// template argument deduction, as returned from
4140  /// DeduceTemplateArguments(). The separate TemplateDeductionInfo
4141  /// structure provides additional information about the results of
4142  /// template argument deduction, e.g., the deduced template argument
4143  /// list (if successful) or the specific template parameters or
4144  /// deduced arguments that were involved in the failure.
4145  enum TemplateDeductionResult {
4146    /// \brief Template argument deduction was successful.
4147    TDK_Success = 0,
4148    /// \brief Template argument deduction exceeded the maximum template
4149    /// instantiation depth (which has already been diagnosed).
4150    TDK_InstantiationDepth,
4151    /// \brief Template argument deduction did not deduce a value
4152    /// for every template parameter.
4153    TDK_Incomplete,
4154    /// \brief Template argument deduction produced inconsistent
4155    /// deduced values for the given template parameter.
4156    TDK_Inconsistent,
4157    /// \brief Template argument deduction failed due to inconsistent
4158    /// cv-qualifiers on a template parameter type that would
4159    /// otherwise be deduced, e.g., we tried to deduce T in "const T"
4160    /// but were given a non-const "X".
4161    TDK_Underqualified,
4162    /// \brief Substitution of the deduced template argument values
4163    /// resulted in an error.
4164    TDK_SubstitutionFailure,
4165    /// \brief Substitution of the deduced template argument values
4166    /// into a non-deduced context produced a type or value that
4167    /// produces a type that does not match the original template
4168    /// arguments provided.
4169    TDK_NonDeducedMismatch,
4170    /// \brief When performing template argument deduction for a function
4171    /// template, there were too many call arguments.
4172    TDK_TooManyArguments,
4173    /// \brief When performing template argument deduction for a function
4174    /// template, there were too few call arguments.
4175    TDK_TooFewArguments,
4176    /// \brief The explicitly-specified template arguments were not valid
4177    /// template arguments for the given template.
4178    TDK_InvalidExplicitArguments,
4179    /// \brief The arguments included an overloaded function name that could
4180    /// not be resolved to a suitable function.
4181    TDK_FailedOverloadResolution
4182  };
4183
4184  TemplateDeductionResult
4185  DeduceTemplateArguments(ClassTemplatePartialSpecializationDecl *Partial,
4186                          const TemplateArgumentList &TemplateArgs,
4187                          sema::TemplateDeductionInfo &Info);
4188
4189  TemplateDeductionResult
4190  SubstituteExplicitTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
4191                              TemplateArgumentListInfo &ExplicitTemplateArgs,
4192                      llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced,
4193                                 llvm::SmallVectorImpl<QualType> &ParamTypes,
4194                                      QualType *FunctionType,
4195                                      sema::TemplateDeductionInfo &Info);
4196
4197  TemplateDeductionResult
4198  FinishTemplateArgumentDeduction(FunctionTemplateDecl *FunctionTemplate,
4199                      llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced,
4200                                  unsigned NumExplicitlySpecified,
4201                                  FunctionDecl *&Specialization,
4202                                  sema::TemplateDeductionInfo &Info);
4203
4204  TemplateDeductionResult
4205  DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
4206                          TemplateArgumentListInfo *ExplicitTemplateArgs,
4207                          Expr **Args, unsigned NumArgs,
4208                          FunctionDecl *&Specialization,
4209                          sema::TemplateDeductionInfo &Info);
4210
4211  TemplateDeductionResult
4212  DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
4213                          TemplateArgumentListInfo *ExplicitTemplateArgs,
4214                          QualType ArgFunctionType,
4215                          FunctionDecl *&Specialization,
4216                          sema::TemplateDeductionInfo &Info);
4217
4218  TemplateDeductionResult
4219  DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
4220                          QualType ToType,
4221                          CXXConversionDecl *&Specialization,
4222                          sema::TemplateDeductionInfo &Info);
4223
4224  TemplateDeductionResult
4225  DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
4226                          TemplateArgumentListInfo *ExplicitTemplateArgs,
4227                          FunctionDecl *&Specialization,
4228                          sema::TemplateDeductionInfo &Info);
4229
4230  bool DeduceAutoType(TypeSourceInfo *AutoType, Expr *Initializer,
4231                      TypeSourceInfo *&Result);
4232
4233  FunctionTemplateDecl *getMoreSpecializedTemplate(FunctionTemplateDecl *FT1,
4234                                                   FunctionTemplateDecl *FT2,
4235                                                   SourceLocation Loc,
4236                                           TemplatePartialOrderingContext TPOC,
4237                                                   unsigned NumCallArguments);
4238  UnresolvedSetIterator getMostSpecialized(UnresolvedSetIterator SBegin,
4239                                           UnresolvedSetIterator SEnd,
4240                                           TemplatePartialOrderingContext TPOC,
4241                                           unsigned NumCallArguments,
4242                                           SourceLocation Loc,
4243                                           const PartialDiagnostic &NoneDiag,
4244                                           const PartialDiagnostic &AmbigDiag,
4245                                        const PartialDiagnostic &CandidateDiag,
4246                                        bool Complain = true);
4247
4248  ClassTemplatePartialSpecializationDecl *
4249  getMoreSpecializedPartialSpecialization(
4250                                  ClassTemplatePartialSpecializationDecl *PS1,
4251                                  ClassTemplatePartialSpecializationDecl *PS2,
4252                                  SourceLocation Loc);
4253
4254  void MarkUsedTemplateParameters(const TemplateArgumentList &TemplateArgs,
4255                                  bool OnlyDeduced,
4256                                  unsigned Depth,
4257                                  llvm::SmallVectorImpl<bool> &Used);
4258  void MarkDeducedTemplateParameters(FunctionTemplateDecl *FunctionTemplate,
4259                                     llvm::SmallVectorImpl<bool> &Deduced);
4260
4261  //===--------------------------------------------------------------------===//
4262  // C++ Template Instantiation
4263  //
4264
4265  MultiLevelTemplateArgumentList getTemplateInstantiationArgs(NamedDecl *D,
4266                                     const TemplateArgumentList *Innermost = 0,
4267                                                bool RelativeToPrimary = false,
4268                                               const FunctionDecl *Pattern = 0);
4269
4270  /// \brief A template instantiation that is currently in progress.
4271  struct ActiveTemplateInstantiation {
4272    /// \brief The kind of template instantiation we are performing
4273    enum InstantiationKind {
4274      /// We are instantiating a template declaration. The entity is
4275      /// the declaration we're instantiating (e.g., a CXXRecordDecl).
4276      TemplateInstantiation,
4277
4278      /// We are instantiating a default argument for a template
4279      /// parameter. The Entity is the template, and
4280      /// TemplateArgs/NumTemplateArguments provides the template
4281      /// arguments as specified.
4282      /// FIXME: Use a TemplateArgumentList
4283      DefaultTemplateArgumentInstantiation,
4284
4285      /// We are instantiating a default argument for a function.
4286      /// The Entity is the ParmVarDecl, and TemplateArgs/NumTemplateArgs
4287      /// provides the template arguments as specified.
4288      DefaultFunctionArgumentInstantiation,
4289
4290      /// We are substituting explicit template arguments provided for
4291      /// a function template. The entity is a FunctionTemplateDecl.
4292      ExplicitTemplateArgumentSubstitution,
4293
4294      /// We are substituting template argument determined as part of
4295      /// template argument deduction for either a class template
4296      /// partial specialization or a function template. The
4297      /// Entity is either a ClassTemplatePartialSpecializationDecl or
4298      /// a FunctionTemplateDecl.
4299      DeducedTemplateArgumentSubstitution,
4300
4301      /// We are substituting prior template arguments into a new
4302      /// template parameter. The template parameter itself is either a
4303      /// NonTypeTemplateParmDecl or a TemplateTemplateParmDecl.
4304      PriorTemplateArgumentSubstitution,
4305
4306      /// We are checking the validity of a default template argument that
4307      /// has been used when naming a template-id.
4308      DefaultTemplateArgumentChecking
4309    } Kind;
4310
4311    /// \brief The point of instantiation within the source code.
4312    SourceLocation PointOfInstantiation;
4313
4314    /// \brief The template (or partial specialization) in which we are
4315    /// performing the instantiation, for substitutions of prior template
4316    /// arguments.
4317    NamedDecl *Template;
4318
4319    /// \brief The entity that is being instantiated.
4320    uintptr_t Entity;
4321
4322    /// \brief The list of template arguments we are substituting, if they
4323    /// are not part of the entity.
4324    const TemplateArgument *TemplateArgs;
4325
4326    /// \brief The number of template arguments in TemplateArgs.
4327    unsigned NumTemplateArgs;
4328
4329    /// \brief The template deduction info object associated with the
4330    /// substitution or checking of explicit or deduced template arguments.
4331    sema::TemplateDeductionInfo *DeductionInfo;
4332
4333    /// \brief The source range that covers the construct that cause
4334    /// the instantiation, e.g., the template-id that causes a class
4335    /// template instantiation.
4336    SourceRange InstantiationRange;
4337
4338    ActiveTemplateInstantiation()
4339      : Kind(TemplateInstantiation), Template(0), Entity(0), TemplateArgs(0),
4340        NumTemplateArgs(0), DeductionInfo(0) {}
4341
4342    /// \brief Determines whether this template is an actual instantiation
4343    /// that should be counted toward the maximum instantiation depth.
4344    bool isInstantiationRecord() const;
4345
4346    friend bool operator==(const ActiveTemplateInstantiation &X,
4347                           const ActiveTemplateInstantiation &Y) {
4348      if (X.Kind != Y.Kind)
4349        return false;
4350
4351      if (X.Entity != Y.Entity)
4352        return false;
4353
4354      switch (X.Kind) {
4355      case TemplateInstantiation:
4356        return true;
4357
4358      case PriorTemplateArgumentSubstitution:
4359      case DefaultTemplateArgumentChecking:
4360        if (X.Template != Y.Template)
4361          return false;
4362
4363        // Fall through
4364
4365      case DefaultTemplateArgumentInstantiation:
4366      case ExplicitTemplateArgumentSubstitution:
4367      case DeducedTemplateArgumentSubstitution:
4368      case DefaultFunctionArgumentInstantiation:
4369        return X.TemplateArgs == Y.TemplateArgs;
4370
4371      }
4372
4373      return true;
4374    }
4375
4376    friend bool operator!=(const ActiveTemplateInstantiation &X,
4377                           const ActiveTemplateInstantiation &Y) {
4378      return !(X == Y);
4379    }
4380  };
4381
4382  /// \brief List of active template instantiations.
4383  ///
4384  /// This vector is treated as a stack. As one template instantiation
4385  /// requires another template instantiation, additional
4386  /// instantiations are pushed onto the stack up to a
4387  /// user-configurable limit LangOptions::InstantiationDepth.
4388  llvm::SmallVector<ActiveTemplateInstantiation, 16>
4389    ActiveTemplateInstantiations;
4390
4391  /// \brief Whether we are in a SFINAE context that is not associated with
4392  /// template instantiation.
4393  ///
4394  /// This is used when setting up a SFINAE trap (\c see SFINAETrap) outside
4395  /// of a template instantiation or template argument deduction.
4396  bool InNonInstantiationSFINAEContext;
4397
4398  /// \brief The number of ActiveTemplateInstantiation entries in
4399  /// \c ActiveTemplateInstantiations that are not actual instantiations and,
4400  /// therefore, should not be counted as part of the instantiation depth.
4401  unsigned NonInstantiationEntries;
4402
4403  /// \brief The last template from which a template instantiation
4404  /// error or warning was produced.
4405  ///
4406  /// This value is used to suppress printing of redundant template
4407  /// instantiation backtraces when there are multiple errors in the
4408  /// same instantiation. FIXME: Does this belong in Sema? It's tough
4409  /// to implement it anywhere else.
4410  ActiveTemplateInstantiation LastTemplateInstantiationErrorContext;
4411
4412  /// \brief The current index into pack expansion arguments that will be
4413  /// used for substitution of parameter packs.
4414  ///
4415  /// The pack expansion index will be -1 to indicate that parameter packs
4416  /// should be instantiated as themselves. Otherwise, the index specifies
4417  /// which argument within the parameter pack will be used for substitution.
4418  int ArgumentPackSubstitutionIndex;
4419
4420  /// \brief RAII object used to change the argument pack substitution index
4421  /// within a \c Sema object.
4422  ///
4423  /// See \c ArgumentPackSubstitutionIndex for more information.
4424  class ArgumentPackSubstitutionIndexRAII {
4425    Sema &Self;
4426    int OldSubstitutionIndex;
4427
4428  public:
4429    ArgumentPackSubstitutionIndexRAII(Sema &Self, int NewSubstitutionIndex)
4430      : Self(Self), OldSubstitutionIndex(Self.ArgumentPackSubstitutionIndex) {
4431      Self.ArgumentPackSubstitutionIndex = NewSubstitutionIndex;
4432    }
4433
4434    ~ArgumentPackSubstitutionIndexRAII() {
4435      Self.ArgumentPackSubstitutionIndex = OldSubstitutionIndex;
4436    }
4437  };
4438
4439  friend class ArgumentPackSubstitutionRAII;
4440
4441  /// \brief The stack of calls expression undergoing template instantiation.
4442  ///
4443  /// The top of this stack is used by a fixit instantiating unresolved
4444  /// function calls to fix the AST to match the textual change it prints.
4445  llvm::SmallVector<CallExpr *, 8> CallsUndergoingInstantiation;
4446
4447  /// \brief For each declaration that involved template argument deduction, the
4448  /// set of diagnostics that were suppressed during that template argument
4449  /// deduction.
4450  ///
4451  /// FIXME: Serialize this structure to the AST file.
4452  llvm::DenseMap<Decl *, llvm::SmallVector<PartialDiagnosticAt, 1> >
4453    SuppressedDiagnostics;
4454
4455  /// \brief A stack object to be created when performing template
4456  /// instantiation.
4457  ///
4458  /// Construction of an object of type \c InstantiatingTemplate
4459  /// pushes the current instantiation onto the stack of active
4460  /// instantiations. If the size of this stack exceeds the maximum
4461  /// number of recursive template instantiations, construction
4462  /// produces an error and evaluates true.
4463  ///
4464  /// Destruction of this object will pop the named instantiation off
4465  /// the stack.
4466  struct InstantiatingTemplate {
4467    /// \brief Note that we are instantiating a class template,
4468    /// function template, or a member thereof.
4469    InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
4470                          Decl *Entity,
4471                          SourceRange InstantiationRange = SourceRange());
4472
4473    /// \brief Note that we are instantiating a default argument in a
4474    /// template-id.
4475    InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
4476                          TemplateDecl *Template,
4477                          const TemplateArgument *TemplateArgs,
4478                          unsigned NumTemplateArgs,
4479                          SourceRange InstantiationRange = SourceRange());
4480
4481    /// \brief Note that we are instantiating a default argument in a
4482    /// template-id.
4483    InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
4484                          FunctionTemplateDecl *FunctionTemplate,
4485                          const TemplateArgument *TemplateArgs,
4486                          unsigned NumTemplateArgs,
4487                          ActiveTemplateInstantiation::InstantiationKind Kind,
4488                          sema::TemplateDeductionInfo &DeductionInfo,
4489                          SourceRange InstantiationRange = SourceRange());
4490
4491    /// \brief Note that we are instantiating as part of template
4492    /// argument deduction for a class template partial
4493    /// specialization.
4494    InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
4495                          ClassTemplatePartialSpecializationDecl *PartialSpec,
4496                          const TemplateArgument *TemplateArgs,
4497                          unsigned NumTemplateArgs,
4498                          sema::TemplateDeductionInfo &DeductionInfo,
4499                          SourceRange InstantiationRange = SourceRange());
4500
4501    InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
4502                          ParmVarDecl *Param,
4503                          const TemplateArgument *TemplateArgs,
4504                          unsigned NumTemplateArgs,
4505                          SourceRange InstantiationRange = SourceRange());
4506
4507    /// \brief Note that we are substituting prior template arguments into a
4508    /// non-type or template template parameter.
4509    InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
4510                          NamedDecl *Template,
4511                          NonTypeTemplateParmDecl *Param,
4512                          const TemplateArgument *TemplateArgs,
4513                          unsigned NumTemplateArgs,
4514                          SourceRange InstantiationRange);
4515
4516    InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
4517                          NamedDecl *Template,
4518                          TemplateTemplateParmDecl *Param,
4519                          const TemplateArgument *TemplateArgs,
4520                          unsigned NumTemplateArgs,
4521                          SourceRange InstantiationRange);
4522
4523    /// \brief Note that we are checking the default template argument
4524    /// against the template parameter for a given template-id.
4525    InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
4526                          TemplateDecl *Template,
4527                          NamedDecl *Param,
4528                          const TemplateArgument *TemplateArgs,
4529                          unsigned NumTemplateArgs,
4530                          SourceRange InstantiationRange);
4531
4532
4533    /// \brief Note that we have finished instantiating this template.
4534    void Clear();
4535
4536    ~InstantiatingTemplate() { Clear(); }
4537
4538    /// \brief Determines whether we have exceeded the maximum
4539    /// recursive template instantiations.
4540    operator bool() const { return Invalid; }
4541
4542  private:
4543    Sema &SemaRef;
4544    bool Invalid;
4545    bool SavedInNonInstantiationSFINAEContext;
4546    bool CheckInstantiationDepth(SourceLocation PointOfInstantiation,
4547                                 SourceRange InstantiationRange);
4548
4549    InstantiatingTemplate(const InstantiatingTemplate&); // not implemented
4550
4551    InstantiatingTemplate&
4552    operator=(const InstantiatingTemplate&); // not implemented
4553  };
4554
4555  void PrintInstantiationStack();
4556
4557  /// \brief Determines whether we are currently in a context where
4558  /// template argument substitution failures are not considered
4559  /// errors.
4560  ///
4561  /// \returns An empty \c llvm::Optional if we're not in a SFINAE context.
4562  /// Otherwise, contains a pointer that, if non-NULL, contains the nearest
4563  /// template-deduction context object, which can be used to capture
4564  /// diagnostics that will be suppressed.
4565  llvm::Optional<sema::TemplateDeductionInfo *> isSFINAEContext() const;
4566
4567  /// \brief RAII class used to determine whether SFINAE has
4568  /// trapped any errors that occur during template argument
4569  /// deduction.`
4570  class SFINAETrap {
4571    Sema &SemaRef;
4572    unsigned PrevSFINAEErrors;
4573    bool PrevInNonInstantiationSFINAEContext;
4574    bool PrevAccessCheckingSFINAE;
4575
4576  public:
4577    explicit SFINAETrap(Sema &SemaRef, bool AccessCheckingSFINAE = false)
4578      : SemaRef(SemaRef), PrevSFINAEErrors(SemaRef.NumSFINAEErrors),
4579        PrevInNonInstantiationSFINAEContext(
4580                                      SemaRef.InNonInstantiationSFINAEContext),
4581        PrevAccessCheckingSFINAE(SemaRef.AccessCheckingSFINAE)
4582    {
4583      if (!SemaRef.isSFINAEContext())
4584        SemaRef.InNonInstantiationSFINAEContext = true;
4585      SemaRef.AccessCheckingSFINAE = AccessCheckingSFINAE;
4586    }
4587
4588    ~SFINAETrap() {
4589      SemaRef.NumSFINAEErrors = PrevSFINAEErrors;
4590      SemaRef.InNonInstantiationSFINAEContext
4591        = PrevInNonInstantiationSFINAEContext;
4592      SemaRef.AccessCheckingSFINAE = PrevAccessCheckingSFINAE;
4593    }
4594
4595    /// \brief Determine whether any SFINAE errors have been trapped.
4596    bool hasErrorOccurred() const {
4597      return SemaRef.NumSFINAEErrors > PrevSFINAEErrors;
4598    }
4599  };
4600
4601  /// \brief The current instantiation scope used to store local
4602  /// variables.
4603  LocalInstantiationScope *CurrentInstantiationScope;
4604
4605  /// \brief The number of typos corrected by CorrectTypo.
4606  unsigned TyposCorrected;
4607
4608  typedef llvm::DenseMap<IdentifierInfo *, std::pair<llvm::StringRef, bool> >
4609    UnqualifiedTyposCorrectedMap;
4610
4611  /// \brief A cache containing the results of typo correction for unqualified
4612  /// name lookup.
4613  ///
4614  /// The string is the string that we corrected to (which may be empty, if
4615  /// there was no correction), while the boolean will be true when the
4616  /// string represents a keyword.
4617  UnqualifiedTyposCorrectedMap UnqualifiedTyposCorrected;
4618
4619  /// \brief Worker object for performing CFG-based warnings.
4620  sema::AnalysisBasedWarnings AnalysisWarnings;
4621
4622  /// \brief An entity for which implicit template instantiation is required.
4623  ///
4624  /// The source location associated with the declaration is the first place in
4625  /// the source code where the declaration was "used". It is not necessarily
4626  /// the point of instantiation (which will be either before or after the
4627  /// namespace-scope declaration that triggered this implicit instantiation),
4628  /// However, it is the location that diagnostics should generally refer to,
4629  /// because users will need to know what code triggered the instantiation.
4630  typedef std::pair<ValueDecl *, SourceLocation> PendingImplicitInstantiation;
4631
4632  /// \brief The queue of implicit template instantiations that are required
4633  /// but have not yet been performed.
4634  std::deque<PendingImplicitInstantiation> PendingInstantiations;
4635
4636  /// \brief The queue of implicit template instantiations that are required
4637  /// and must be performed within the current local scope.
4638  ///
4639  /// This queue is only used for member functions of local classes in
4640  /// templates, which must be instantiated in the same scope as their
4641  /// enclosing function, so that they can reference function-local
4642  /// types, static variables, enumerators, etc.
4643  std::deque<PendingImplicitInstantiation> PendingLocalImplicitInstantiations;
4644
4645  bool PerformPendingInstantiations(bool LocalOnly = false);
4646
4647  TypeSourceInfo *SubstType(TypeSourceInfo *T,
4648                            const MultiLevelTemplateArgumentList &TemplateArgs,
4649                            SourceLocation Loc, DeclarationName Entity);
4650
4651  QualType SubstType(QualType T,
4652                     const MultiLevelTemplateArgumentList &TemplateArgs,
4653                     SourceLocation Loc, DeclarationName Entity);
4654
4655  TypeSourceInfo *SubstType(TypeLoc TL,
4656                            const MultiLevelTemplateArgumentList &TemplateArgs,
4657                            SourceLocation Loc, DeclarationName Entity);
4658
4659  TypeSourceInfo *SubstFunctionDeclType(TypeSourceInfo *T,
4660                            const MultiLevelTemplateArgumentList &TemplateArgs,
4661                                        SourceLocation Loc,
4662                                        DeclarationName Entity);
4663  ParmVarDecl *SubstParmVarDecl(ParmVarDecl *D,
4664                            const MultiLevelTemplateArgumentList &TemplateArgs,
4665                                int indexAdjustment,
4666                                llvm::Optional<unsigned> NumExpansions);
4667  bool SubstParmTypes(SourceLocation Loc,
4668                      ParmVarDecl **Params, unsigned NumParams,
4669                      const MultiLevelTemplateArgumentList &TemplateArgs,
4670                      llvm::SmallVectorImpl<QualType> &ParamTypes,
4671                      llvm::SmallVectorImpl<ParmVarDecl *> *OutParams = 0);
4672  ExprResult SubstExpr(Expr *E,
4673                       const MultiLevelTemplateArgumentList &TemplateArgs);
4674
4675  /// \brief Substitute the given template arguments into a list of
4676  /// expressions, expanding pack expansions if required.
4677  ///
4678  /// \param Exprs The list of expressions to substitute into.
4679  ///
4680  /// \param NumExprs The number of expressions in \p Exprs.
4681  ///
4682  /// \param IsCall Whether this is some form of call, in which case
4683  /// default arguments will be dropped.
4684  ///
4685  /// \param TemplateArgs The set of template arguments to substitute.
4686  ///
4687  /// \param Outputs Will receive all of the substituted arguments.
4688  ///
4689  /// \returns true if an error occurred, false otherwise.
4690  bool SubstExprs(Expr **Exprs, unsigned NumExprs, bool IsCall,
4691                  const MultiLevelTemplateArgumentList &TemplateArgs,
4692                  llvm::SmallVectorImpl<Expr *> &Outputs);
4693
4694  StmtResult SubstStmt(Stmt *S,
4695                       const MultiLevelTemplateArgumentList &TemplateArgs);
4696
4697  Decl *SubstDecl(Decl *D, DeclContext *Owner,
4698                  const MultiLevelTemplateArgumentList &TemplateArgs);
4699
4700  bool
4701  SubstBaseSpecifiers(CXXRecordDecl *Instantiation,
4702                      CXXRecordDecl *Pattern,
4703                      const MultiLevelTemplateArgumentList &TemplateArgs);
4704
4705  bool
4706  InstantiateClass(SourceLocation PointOfInstantiation,
4707                   CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern,
4708                   const MultiLevelTemplateArgumentList &TemplateArgs,
4709                   TemplateSpecializationKind TSK,
4710                   bool Complain = true);
4711
4712  void InstantiateAttrs(const MultiLevelTemplateArgumentList &TemplateArgs,
4713                        Decl *Pattern, Decl *Inst);
4714
4715  bool
4716  InstantiateClassTemplateSpecialization(SourceLocation PointOfInstantiation,
4717                           ClassTemplateSpecializationDecl *ClassTemplateSpec,
4718                           TemplateSpecializationKind TSK,
4719                           bool Complain = true);
4720
4721  void InstantiateClassMembers(SourceLocation PointOfInstantiation,
4722                               CXXRecordDecl *Instantiation,
4723                            const MultiLevelTemplateArgumentList &TemplateArgs,
4724                               TemplateSpecializationKind TSK);
4725
4726  void InstantiateClassTemplateSpecializationMembers(
4727                                          SourceLocation PointOfInstantiation,
4728                           ClassTemplateSpecializationDecl *ClassTemplateSpec,
4729                                                TemplateSpecializationKind TSK);
4730
4731  NestedNameSpecifierLoc
4732  SubstNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS,
4733                           const MultiLevelTemplateArgumentList &TemplateArgs);
4734
4735  DeclarationNameInfo
4736  SubstDeclarationNameInfo(const DeclarationNameInfo &NameInfo,
4737                           const MultiLevelTemplateArgumentList &TemplateArgs);
4738  TemplateName
4739  SubstTemplateName(NestedNameSpecifierLoc QualifierLoc, TemplateName Name,
4740                    SourceLocation Loc,
4741                    const MultiLevelTemplateArgumentList &TemplateArgs);
4742  bool Subst(const TemplateArgumentLoc *Args, unsigned NumArgs,
4743             TemplateArgumentListInfo &Result,
4744             const MultiLevelTemplateArgumentList &TemplateArgs);
4745
4746  void InstantiateFunctionDefinition(SourceLocation PointOfInstantiation,
4747                                     FunctionDecl *Function,
4748                                     bool Recursive = false,
4749                                     bool DefinitionRequired = false);
4750  void InstantiateStaticDataMemberDefinition(
4751                                     SourceLocation PointOfInstantiation,
4752                                     VarDecl *Var,
4753                                     bool Recursive = false,
4754                                     bool DefinitionRequired = false);
4755
4756  void InstantiateMemInitializers(CXXConstructorDecl *New,
4757                                  const CXXConstructorDecl *Tmpl,
4758                            const MultiLevelTemplateArgumentList &TemplateArgs);
4759
4760  NamedDecl *FindInstantiatedDecl(SourceLocation Loc, NamedDecl *D,
4761                          const MultiLevelTemplateArgumentList &TemplateArgs);
4762  DeclContext *FindInstantiatedContext(SourceLocation Loc, DeclContext *DC,
4763                          const MultiLevelTemplateArgumentList &TemplateArgs);
4764
4765  // Objective-C declarations.
4766  Decl *ActOnStartClassInterface(SourceLocation AtInterfaceLoc,
4767                                 IdentifierInfo *ClassName,
4768                                 SourceLocation ClassLoc,
4769                                 IdentifierInfo *SuperName,
4770                                 SourceLocation SuperLoc,
4771                                 Decl * const *ProtoRefs,
4772                                 unsigned NumProtoRefs,
4773                                 const SourceLocation *ProtoLocs,
4774                                 SourceLocation EndProtoLoc,
4775                                 AttributeList *AttrList);
4776
4777  Decl *ActOnCompatiblityAlias(
4778                    SourceLocation AtCompatibilityAliasLoc,
4779                    IdentifierInfo *AliasName,  SourceLocation AliasLocation,
4780                    IdentifierInfo *ClassName, SourceLocation ClassLocation);
4781
4782  bool CheckForwardProtocolDeclarationForCircularDependency(
4783    IdentifierInfo *PName,
4784    SourceLocation &PLoc, SourceLocation PrevLoc,
4785    const ObjCList<ObjCProtocolDecl> &PList);
4786
4787  Decl *ActOnStartProtocolInterface(
4788                    SourceLocation AtProtoInterfaceLoc,
4789                    IdentifierInfo *ProtocolName, SourceLocation ProtocolLoc,
4790                    Decl * const *ProtoRefNames, unsigned NumProtoRefs,
4791                    const SourceLocation *ProtoLocs,
4792                    SourceLocation EndProtoLoc,
4793                    AttributeList *AttrList);
4794
4795  Decl *ActOnStartCategoryInterface(SourceLocation AtInterfaceLoc,
4796                                    IdentifierInfo *ClassName,
4797                                    SourceLocation ClassLoc,
4798                                    IdentifierInfo *CategoryName,
4799                                    SourceLocation CategoryLoc,
4800                                    Decl * const *ProtoRefs,
4801                                    unsigned NumProtoRefs,
4802                                    const SourceLocation *ProtoLocs,
4803                                    SourceLocation EndProtoLoc);
4804
4805  Decl *ActOnStartClassImplementation(
4806                    SourceLocation AtClassImplLoc,
4807                    IdentifierInfo *ClassName, SourceLocation ClassLoc,
4808                    IdentifierInfo *SuperClassname,
4809                    SourceLocation SuperClassLoc);
4810
4811  Decl *ActOnStartCategoryImplementation(SourceLocation AtCatImplLoc,
4812                                         IdentifierInfo *ClassName,
4813                                         SourceLocation ClassLoc,
4814                                         IdentifierInfo *CatName,
4815                                         SourceLocation CatLoc);
4816
4817  Decl *ActOnForwardClassDeclaration(SourceLocation Loc,
4818                                     IdentifierInfo **IdentList,
4819                                     SourceLocation *IdentLocs,
4820                                     unsigned NumElts);
4821
4822  Decl *ActOnForwardProtocolDeclaration(SourceLocation AtProtoclLoc,
4823                                        const IdentifierLocPair *IdentList,
4824                                        unsigned NumElts,
4825                                        AttributeList *attrList);
4826
4827  void FindProtocolDeclaration(bool WarnOnDeclarations,
4828                               const IdentifierLocPair *ProtocolId,
4829                               unsigned NumProtocols,
4830                               llvm::SmallVectorImpl<Decl *> &Protocols);
4831
4832  /// Ensure attributes are consistent with type.
4833  /// \param [in, out] Attributes The attributes to check; they will
4834  /// be modified to be consistent with \arg PropertyTy.
4835  void CheckObjCPropertyAttributes(Decl *PropertyPtrTy,
4836                                   SourceLocation Loc,
4837                                   unsigned &Attributes);
4838
4839  /// Process the specified property declaration and create decls for the
4840  /// setters and getters as needed.
4841  /// \param property The property declaration being processed
4842  /// \param DC The semantic container for the property
4843  /// \param redeclaredProperty Declaration for property if redeclared
4844  ///        in class extension.
4845  /// \param lexicalDC Container for redeclaredProperty.
4846  void ProcessPropertyDecl(ObjCPropertyDecl *property,
4847                           ObjCContainerDecl *DC,
4848                           ObjCPropertyDecl *redeclaredProperty = 0,
4849                           ObjCContainerDecl *lexicalDC = 0);
4850
4851  void DiagnosePropertyMismatch(ObjCPropertyDecl *Property,
4852                                ObjCPropertyDecl *SuperProperty,
4853                                const IdentifierInfo *Name);
4854  void ComparePropertiesInBaseAndSuper(ObjCInterfaceDecl *IDecl);
4855
4856  void CompareMethodParamsInBaseAndSuper(Decl *IDecl,
4857                                         ObjCMethodDecl *MethodDecl,
4858                                         bool IsInstance);
4859
4860  void CompareProperties(Decl *CDecl, Decl *MergeProtocols);
4861
4862  void DiagnoseClassExtensionDupMethods(ObjCCategoryDecl *CAT,
4863                                        ObjCInterfaceDecl *ID);
4864
4865  void MatchOneProtocolPropertiesInClass(Decl *CDecl,
4866                                         ObjCProtocolDecl *PDecl);
4867
4868  void ActOnAtEnd(Scope *S, SourceRange AtEnd, Decl *classDecl,
4869                  Decl **allMethods = 0, unsigned allNum = 0,
4870                  Decl **allProperties = 0, unsigned pNum = 0,
4871                  DeclGroupPtrTy *allTUVars = 0, unsigned tuvNum = 0);
4872
4873  Decl *ActOnProperty(Scope *S, SourceLocation AtLoc,
4874                      FieldDeclarator &FD, ObjCDeclSpec &ODS,
4875                      Selector GetterSel, Selector SetterSel,
4876                      Decl *ClassCategory,
4877                      bool *OverridingProperty,
4878                      tok::ObjCKeywordKind MethodImplKind,
4879                      DeclContext *lexicalDC = 0);
4880
4881  Decl *ActOnPropertyImplDecl(Scope *S,
4882                              SourceLocation AtLoc,
4883                              SourceLocation PropertyLoc,
4884                              bool ImplKind,Decl *ClassImplDecl,
4885                              IdentifierInfo *PropertyId,
4886                              IdentifierInfo *PropertyIvar,
4887                              SourceLocation PropertyIvarLoc);
4888
4889  struct ObjCArgInfo {
4890    IdentifierInfo *Name;
4891    SourceLocation NameLoc;
4892    // The Type is null if no type was specified, and the DeclSpec is invalid
4893    // in this case.
4894    ParsedType Type;
4895    ObjCDeclSpec DeclSpec;
4896
4897    /// ArgAttrs - Attribute list for this argument.
4898    AttributeList *ArgAttrs;
4899  };
4900
4901  Decl *ActOnMethodDeclaration(
4902    Scope *S,
4903    SourceLocation BeginLoc, // location of the + or -.
4904    SourceLocation EndLoc,   // location of the ; or {.
4905    tok::TokenKind MethodType,
4906    Decl *ClassDecl, ObjCDeclSpec &ReturnQT, ParsedType ReturnType,
4907    Selector Sel,
4908    // optional arguments. The number of types/arguments is obtained
4909    // from the Sel.getNumArgs().
4910    ObjCArgInfo *ArgInfo,
4911    DeclaratorChunk::ParamInfo *CParamInfo, unsigned CNumArgs, // c-style args
4912    AttributeList *AttrList, tok::ObjCKeywordKind MethodImplKind,
4913    bool isVariadic, bool MethodDefinition);
4914
4915  // Helper method for ActOnClassMethod/ActOnInstanceMethod.
4916  // Will search "local" class/category implementations for a method decl.
4917  // Will also search in class's root looking for instance method.
4918  // Returns 0 if no method is found.
4919  ObjCMethodDecl *LookupPrivateClassMethod(Selector Sel,
4920                                           ObjCInterfaceDecl *CDecl);
4921  ObjCMethodDecl *LookupPrivateInstanceMethod(Selector Sel,
4922                                              ObjCInterfaceDecl *ClassDecl);
4923  ObjCMethodDecl *LookupMethodInQualifiedType(Selector Sel,
4924                                              const ObjCObjectPointerType *OPT,
4925                                              bool IsInstance);
4926
4927  ExprResult
4928  HandleExprPropertyRefExpr(const ObjCObjectPointerType *OPT,
4929                            Expr *BaseExpr,
4930                            DeclarationName MemberName,
4931                            SourceLocation MemberLoc,
4932                            SourceLocation SuperLoc, QualType SuperType,
4933                            bool Super);
4934
4935  ExprResult
4936  ActOnClassPropertyRefExpr(IdentifierInfo &receiverName,
4937                            IdentifierInfo &propertyName,
4938                            SourceLocation receiverNameLoc,
4939                            SourceLocation propertyNameLoc);
4940
4941  ObjCMethodDecl *tryCaptureObjCSelf();
4942
4943  /// \brief Describes the kind of message expression indicated by a message
4944  /// send that starts with an identifier.
4945  enum ObjCMessageKind {
4946    /// \brief The message is sent to 'super'.
4947    ObjCSuperMessage,
4948    /// \brief The message is an instance message.
4949    ObjCInstanceMessage,
4950    /// \brief The message is a class message, and the identifier is a type
4951    /// name.
4952    ObjCClassMessage
4953  };
4954
4955  ObjCMessageKind getObjCMessageKind(Scope *S,
4956                                     IdentifierInfo *Name,
4957                                     SourceLocation NameLoc,
4958                                     bool IsSuper,
4959                                     bool HasTrailingDot,
4960                                     ParsedType &ReceiverType);
4961
4962  ExprResult ActOnSuperMessage(Scope *S, SourceLocation SuperLoc,
4963                               Selector Sel,
4964                               SourceLocation LBracLoc,
4965                               SourceLocation SelectorLoc,
4966                               SourceLocation RBracLoc,
4967                               MultiExprArg Args);
4968
4969  ExprResult BuildClassMessage(TypeSourceInfo *ReceiverTypeInfo,
4970                               QualType ReceiverType,
4971                               SourceLocation SuperLoc,
4972                               Selector Sel,
4973                               ObjCMethodDecl *Method,
4974                               SourceLocation LBracLoc,
4975                               SourceLocation SelectorLoc,
4976                               SourceLocation RBracLoc,
4977                               MultiExprArg Args);
4978
4979  ExprResult ActOnClassMessage(Scope *S,
4980                               ParsedType Receiver,
4981                               Selector Sel,
4982                               SourceLocation LBracLoc,
4983                               SourceLocation SelectorLoc,
4984                               SourceLocation RBracLoc,
4985                               MultiExprArg Args);
4986
4987  ExprResult BuildInstanceMessage(Expr *Receiver,
4988                                  QualType ReceiverType,
4989                                  SourceLocation SuperLoc,
4990                                  Selector Sel,
4991                                  ObjCMethodDecl *Method,
4992                                  SourceLocation LBracLoc,
4993                                  SourceLocation SelectorLoc,
4994                                  SourceLocation RBracLoc,
4995                                  MultiExprArg Args);
4996
4997  ExprResult ActOnInstanceMessage(Scope *S,
4998                                  Expr *Receiver,
4999                                  Selector Sel,
5000                                  SourceLocation LBracLoc,
5001                                  SourceLocation SelectorLoc,
5002                                  SourceLocation RBracLoc,
5003                                  MultiExprArg Args);
5004
5005
5006  enum PragmaOptionsAlignKind {
5007    POAK_Native,  // #pragma options align=native
5008    POAK_Natural, // #pragma options align=natural
5009    POAK_Packed,  // #pragma options align=packed
5010    POAK_Power,   // #pragma options align=power
5011    POAK_Mac68k,  // #pragma options align=mac68k
5012    POAK_Reset    // #pragma options align=reset
5013  };
5014
5015  /// ActOnPragmaOptionsAlign - Called on well formed #pragma options align.
5016  void ActOnPragmaOptionsAlign(PragmaOptionsAlignKind Kind,
5017                               SourceLocation PragmaLoc,
5018                               SourceLocation KindLoc);
5019
5020  enum PragmaPackKind {
5021    PPK_Default, // #pragma pack([n])
5022    PPK_Show,    // #pragma pack(show), only supported by MSVC.
5023    PPK_Push,    // #pragma pack(push, [identifier], [n])
5024    PPK_Pop      // #pragma pack(pop, [identifier], [n])
5025  };
5026
5027  enum PragmaMSStructKind {
5028    PMSST_OFF,  // #pragms ms_struct off
5029    PMSST_ON    // #pragms ms_struct on
5030  };
5031
5032  /// ActOnPragmaPack - Called on well formed #pragma pack(...).
5033  void ActOnPragmaPack(PragmaPackKind Kind,
5034                       IdentifierInfo *Name,
5035                       Expr *Alignment,
5036                       SourceLocation PragmaLoc,
5037                       SourceLocation LParenLoc,
5038                       SourceLocation RParenLoc);
5039
5040  /// ActOnPragmaMSStruct - Called on well formed #pragms ms_struct [on|off].
5041  void ActOnPragmaMSStruct(PragmaMSStructKind Kind);
5042
5043  /// ActOnPragmaUnused - Called on well-formed '#pragma unused'.
5044  void ActOnPragmaUnused(const Token &Identifier,
5045                         Scope *curScope,
5046                         SourceLocation PragmaLoc);
5047
5048  /// ActOnPragmaVisibility - Called on well formed #pragma GCC visibility... .
5049  void ActOnPragmaVisibility(bool IsPush, const IdentifierInfo* VisType,
5050                             SourceLocation PragmaLoc);
5051
5052  NamedDecl *DeclClonePragmaWeak(NamedDecl *ND, IdentifierInfo *II);
5053  void DeclApplyPragmaWeak(Scope *S, NamedDecl *ND, WeakInfo &W);
5054
5055  /// ActOnPragmaWeakID - Called on well formed #pragma weak ident.
5056  void ActOnPragmaWeakID(IdentifierInfo* WeakName,
5057                         SourceLocation PragmaLoc,
5058                         SourceLocation WeakNameLoc);
5059
5060  /// ActOnPragmaWeakAlias - Called on well formed #pragma weak ident = ident.
5061  void ActOnPragmaWeakAlias(IdentifierInfo* WeakName,
5062                            IdentifierInfo* AliasName,
5063                            SourceLocation PragmaLoc,
5064                            SourceLocation WeakNameLoc,
5065                            SourceLocation AliasNameLoc);
5066
5067  /// ActOnPragmaFPContract - Called on well formed
5068  /// #pragma {STDC,OPENCL} FP_CONTRACT
5069  void ActOnPragmaFPContract(tok::OnOffSwitch OOS);
5070
5071  /// AddAlignmentAttributesForRecord - Adds any needed alignment attributes to
5072  /// a the record decl, to handle '#pragma pack' and '#pragma options align'.
5073  void AddAlignmentAttributesForRecord(RecordDecl *RD);
5074
5075  /// AddMsStructLayoutForRecord - Adds ms_struct layout attribute to record.
5076  void AddMsStructLayoutForRecord(RecordDecl *RD);
5077
5078  /// FreePackedContext - Deallocate and null out PackContext.
5079  void FreePackedContext();
5080
5081  /// PushNamespaceVisibilityAttr - Note that we've entered a
5082  /// namespace with a visibility attribute.
5083  void PushNamespaceVisibilityAttr(const VisibilityAttr *Attr);
5084
5085  /// AddPushedVisibilityAttribute - If '#pragma GCC visibility' was used,
5086  /// add an appropriate visibility attribute.
5087  void AddPushedVisibilityAttribute(Decl *RD);
5088
5089  /// PopPragmaVisibility - Pop the top element of the visibility stack; used
5090  /// for '#pragma GCC visibility' and visibility attributes on namespaces.
5091  void PopPragmaVisibility();
5092
5093  /// FreeVisContext - Deallocate and null out VisContext.
5094  void FreeVisContext();
5095
5096  /// AddAlignedAttr - Adds an aligned attribute to a particular declaration.
5097  void AddAlignedAttr(SourceLocation AttrLoc, Decl *D, Expr *E);
5098  void AddAlignedAttr(SourceLocation AttrLoc, Decl *D, TypeSourceInfo *T);
5099
5100  /// CastCategory - Get the correct forwarded implicit cast result category
5101  /// from the inner expression.
5102  ExprValueKind CastCategory(Expr *E);
5103
5104  /// ImpCastExprToType - If Expr is not of type 'Type', insert an implicit
5105  /// cast.  If there is already an implicit cast, merge into the existing one.
5106  /// If isLvalue, the result of the cast is an lvalue.
5107  ExprResult ImpCastExprToType(Expr *E, QualType Type, CastKind CK,
5108                               ExprValueKind VK = VK_RValue,
5109                               const CXXCastPath *BasePath = 0);
5110
5111  /// ScalarTypeToBooleanCastKind - Returns the cast kind corresponding
5112  /// to the conversion from scalar type ScalarTy to the Boolean type.
5113  static CastKind ScalarTypeToBooleanCastKind(QualType ScalarTy);
5114
5115  /// IgnoredValueConversions - Given that an expression's result is
5116  /// syntactically ignored, perform any conversions that are
5117  /// required.
5118  ExprResult IgnoredValueConversions(Expr *E);
5119
5120  // UsualUnaryConversions - promotes integers (C99 6.3.1.1p2) and converts
5121  // functions and arrays to their respective pointers (C99 6.3.2.1).
5122  ExprResult UsualUnaryConversions(Expr *E);
5123
5124  // DefaultFunctionArrayConversion - converts functions and arrays
5125  // to their respective pointers (C99 6.3.2.1).
5126  ExprResult DefaultFunctionArrayConversion(Expr *E);
5127
5128  // DefaultFunctionArrayLvalueConversion - converts functions and
5129  // arrays to their respective pointers and performs the
5130  // lvalue-to-rvalue conversion.
5131  ExprResult DefaultFunctionArrayLvalueConversion(Expr *E);
5132
5133  // DefaultLvalueConversion - performs lvalue-to-rvalue conversion on
5134  // the operand.  This is DefaultFunctionArrayLvalueConversion,
5135  // except that it assumes the operand isn't of function or array
5136  // type.
5137  ExprResult DefaultLvalueConversion(Expr *E);
5138
5139  // DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
5140  // do not have a prototype. Integer promotions are performed on each
5141  // argument, and arguments that have type float are promoted to double.
5142  ExprResult DefaultArgumentPromotion(Expr *E);
5143
5144  // Used for emitting the right warning by DefaultVariadicArgumentPromotion
5145  enum VariadicCallType {
5146    VariadicFunction,
5147    VariadicBlock,
5148    VariadicMethod,
5149    VariadicConstructor,
5150    VariadicDoesNotApply
5151  };
5152
5153  /// GatherArgumentsForCall - Collector argument expressions for various
5154  /// form of call prototypes.
5155  bool GatherArgumentsForCall(SourceLocation CallLoc,
5156                              FunctionDecl *FDecl,
5157                              const FunctionProtoType *Proto,
5158                              unsigned FirstProtoArg,
5159                              Expr **Args, unsigned NumArgs,
5160                              llvm::SmallVector<Expr *, 8> &AllArgs,
5161                              VariadicCallType CallType = VariadicDoesNotApply);
5162
5163  // DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
5164  // will warn if the resulting type is not a POD type.
5165  ExprResult DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
5166                                              FunctionDecl *FDecl);
5167
5168  // UsualArithmeticConversions - performs the UsualUnaryConversions on it's
5169  // operands and then handles various conversions that are common to binary
5170  // operators (C99 6.3.1.8). If both operands aren't arithmetic, this
5171  // routine returns the first non-arithmetic type found. The client is
5172  // responsible for emitting appropriate error diagnostics.
5173  QualType UsualArithmeticConversions(ExprResult &lExpr, ExprResult &rExpr,
5174                                      bool isCompAssign = false);
5175
5176  /// AssignConvertType - All of the 'assignment' semantic checks return this
5177  /// enum to indicate whether the assignment was allowed.  These checks are
5178  /// done for simple assignments, as well as initialization, return from
5179  /// function, argument passing, etc.  The query is phrased in terms of a
5180  /// source and destination type.
5181  enum AssignConvertType {
5182    /// Compatible - the types are compatible according to the standard.
5183    Compatible,
5184
5185    /// PointerToInt - The assignment converts a pointer to an int, which we
5186    /// accept as an extension.
5187    PointerToInt,
5188
5189    /// IntToPointer - The assignment converts an int to a pointer, which we
5190    /// accept as an extension.
5191    IntToPointer,
5192
5193    /// FunctionVoidPointer - The assignment is between a function pointer and
5194    /// void*, which the standard doesn't allow, but we accept as an extension.
5195    FunctionVoidPointer,
5196
5197    /// IncompatiblePointer - The assignment is between two pointers types that
5198    /// are not compatible, but we accept them as an extension.
5199    IncompatiblePointer,
5200
5201    /// IncompatiblePointer - The assignment is between two pointers types which
5202    /// point to integers which have a different sign, but are otherwise identical.
5203    /// This is a subset of the above, but broken out because it's by far the most
5204    /// common case of incompatible pointers.
5205    IncompatiblePointerSign,
5206
5207    /// CompatiblePointerDiscardsQualifiers - The assignment discards
5208    /// c/v/r qualifiers, which we accept as an extension.
5209    CompatiblePointerDiscardsQualifiers,
5210
5211    /// IncompatiblePointerDiscardsQualifiers - The assignment
5212    /// discards qualifiers that we don't permit to be discarded,
5213    /// like address spaces.
5214    IncompatiblePointerDiscardsQualifiers,
5215
5216    /// IncompatibleNestedPointerQualifiers - The assignment is between two
5217    /// nested pointer types, and the qualifiers other than the first two
5218    /// levels differ e.g. char ** -> const char **, but we accept them as an
5219    /// extension.
5220    IncompatibleNestedPointerQualifiers,
5221
5222    /// IncompatibleVectors - The assignment is between two vector types that
5223    /// have the same size, which we accept as an extension.
5224    IncompatibleVectors,
5225
5226    /// IntToBlockPointer - The assignment converts an int to a block
5227    /// pointer. We disallow this.
5228    IntToBlockPointer,
5229
5230    /// IncompatibleBlockPointer - The assignment is between two block
5231    /// pointers types that are not compatible.
5232    IncompatibleBlockPointer,
5233
5234    /// IncompatibleObjCQualifiedId - The assignment is between a qualified
5235    /// id type and something else (that is incompatible with it). For example,
5236    /// "id <XXX>" = "Foo *", where "Foo *" doesn't implement the XXX protocol.
5237    IncompatibleObjCQualifiedId,
5238
5239    /// Incompatible - We reject this conversion outright, it is invalid to
5240    /// represent it in the AST.
5241    Incompatible
5242  };
5243
5244  /// DiagnoseAssignmentResult - Emit a diagnostic, if required, for the
5245  /// assignment conversion type specified by ConvTy.  This returns true if the
5246  /// conversion was invalid or false if the conversion was accepted.
5247  bool DiagnoseAssignmentResult(AssignConvertType ConvTy,
5248                                SourceLocation Loc,
5249                                QualType DstType, QualType SrcType,
5250                                Expr *SrcExpr, AssignmentAction Action,
5251                                bool *Complained = 0);
5252
5253  /// CheckAssignmentConstraints - Perform type checking for assignment,
5254  /// argument passing, variable initialization, and function return values.
5255  /// C99 6.5.16.
5256  AssignConvertType CheckAssignmentConstraints(SourceLocation Loc,
5257                                               QualType lhs, QualType rhs);
5258
5259  /// Check assignment constraints and prepare for a conversion of the
5260  /// RHS to the LHS type.
5261  AssignConvertType CheckAssignmentConstraints(QualType lhs, ExprResult &rhs,
5262                                               CastKind &Kind);
5263
5264  // CheckSingleAssignmentConstraints - Currently used by
5265  // CheckAssignmentOperands, and ActOnReturnStmt. Prior to type checking,
5266  // this routine performs the default function/array converions.
5267  AssignConvertType CheckSingleAssignmentConstraints(QualType lhs,
5268                                                     ExprResult &rExprRes);
5269
5270  // \brief If the lhs type is a transparent union, check whether we
5271  // can initialize the transparent union with the given expression.
5272  AssignConvertType CheckTransparentUnionArgumentConstraints(QualType lhs,
5273                                                             ExprResult &rExpr);
5274
5275  bool IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType);
5276
5277  bool CheckExceptionSpecCompatibility(Expr *From, QualType ToType);
5278
5279  ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
5280                                       AssignmentAction Action,
5281                                       bool AllowExplicit = false);
5282  ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
5283                                       AssignmentAction Action,
5284                                       bool AllowExplicit,
5285                                       ImplicitConversionSequence& ICS);
5286  ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
5287                                       const ImplicitConversionSequence& ICS,
5288                                       AssignmentAction Action,
5289                                       bool CStyle = false);
5290  ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
5291                                       const StandardConversionSequence& SCS,
5292                                       AssignmentAction Action,
5293                                       bool CStyle);
5294
5295  /// the following "Check" methods will return a valid/converted QualType
5296  /// or a null QualType (indicating an error diagnostic was issued).
5297
5298  /// type checking binary operators (subroutines of CreateBuiltinBinOp).
5299  QualType InvalidOperands(SourceLocation l, ExprResult &lex, ExprResult &rex);
5300  QualType CheckPointerToMemberOperands( // C++ 5.5
5301    ExprResult &lex, ExprResult &rex, ExprValueKind &VK,
5302    SourceLocation OpLoc, bool isIndirect);
5303  QualType CheckMultiplyDivideOperands( // C99 6.5.5
5304    ExprResult &lex, ExprResult &rex, SourceLocation OpLoc, bool isCompAssign,
5305                                       bool isDivide);
5306  QualType CheckRemainderOperands( // C99 6.5.5
5307    ExprResult &lex, ExprResult &rex, SourceLocation OpLoc, bool isCompAssign = false);
5308  QualType CheckAdditionOperands( // C99 6.5.6
5309    ExprResult &lex, ExprResult &rex, SourceLocation OpLoc, QualType* CompLHSTy = 0);
5310  QualType CheckSubtractionOperands( // C99 6.5.6
5311    ExprResult &lex, ExprResult &rex, SourceLocation OpLoc, QualType* CompLHSTy = 0);
5312  QualType CheckShiftOperands( // C99 6.5.7
5313    ExprResult &lex, ExprResult &rex, SourceLocation OpLoc, unsigned Opc,
5314    bool isCompAssign = false);
5315  QualType CheckCompareOperands( // C99 6.5.8/9
5316    ExprResult &lex, ExprResult &rex, SourceLocation OpLoc, unsigned Opc,
5317                                bool isRelational);
5318  QualType CheckBitwiseOperands( // C99 6.5.[10...12]
5319    ExprResult &lex, ExprResult &rex, SourceLocation OpLoc, bool isCompAssign = false);
5320  QualType CheckLogicalOperands( // C99 6.5.[13,14]
5321    ExprResult &lex, ExprResult &rex, SourceLocation OpLoc, unsigned Opc);
5322  // CheckAssignmentOperands is used for both simple and compound assignment.
5323  // For simple assignment, pass both expressions and a null converted type.
5324  // For compound assignment, pass both expressions and the converted type.
5325  QualType CheckAssignmentOperands( // C99 6.5.16.[1,2]
5326    Expr *lex, ExprResult &rex, SourceLocation OpLoc, QualType convertedType);
5327
5328  void ConvertPropertyForLValue(ExprResult &LHS, ExprResult &RHS, QualType& LHSTy);
5329  ExprResult ConvertPropertyForRValue(Expr *E);
5330
5331  QualType CheckConditionalOperands( // C99 6.5.15
5332    ExprResult &cond, ExprResult &lhs, ExprResult &rhs,
5333    ExprValueKind &VK, ExprObjectKind &OK, SourceLocation questionLoc);
5334  QualType CXXCheckConditionalOperands( // C++ 5.16
5335    ExprResult &cond, ExprResult &lhs, ExprResult &rhs,
5336    ExprValueKind &VK, ExprObjectKind &OK, SourceLocation questionLoc);
5337  QualType FindCompositePointerType(SourceLocation Loc, Expr *&E1, Expr *&E2,
5338                                    bool *NonStandardCompositeType = 0);
5339  QualType FindCompositePointerType(SourceLocation Loc, ExprResult &E1, ExprResult &E2,
5340                                    bool *NonStandardCompositeType = 0) {
5341    Expr *E1Tmp = E1.take(), *E2Tmp = E2.take();
5342    QualType Composite = FindCompositePointerType(Loc, E1Tmp, E2Tmp, NonStandardCompositeType);
5343    E1 = Owned(E1Tmp);
5344    E2 = Owned(E2Tmp);
5345    return Composite;
5346  }
5347
5348  QualType FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
5349                                        SourceLocation questionLoc);
5350
5351  bool DiagnoseConditionalForNull(Expr *LHS, Expr *RHS,
5352                                  SourceLocation QuestionLoc);
5353
5354  /// type checking for vector binary operators.
5355  QualType CheckVectorOperands(SourceLocation l, ExprResult &lex, ExprResult &rex);
5356  QualType CheckVectorCompareOperands(ExprResult &lex, ExprResult &rx,
5357                                      SourceLocation l, bool isRel);
5358
5359  /// type checking declaration initializers (C99 6.7.8)
5360  bool CheckInitList(const InitializedEntity &Entity,
5361                     InitListExpr *&InitList, QualType &DeclType);
5362  bool CheckForConstantInitializer(Expr *e, QualType t);
5363
5364  // type checking C++ declaration initializers (C++ [dcl.init]).
5365
5366  /// ReferenceCompareResult - Expresses the result of comparing two
5367  /// types (cv1 T1 and cv2 T2) to determine their compatibility for the
5368  /// purposes of initialization by reference (C++ [dcl.init.ref]p4).
5369  enum ReferenceCompareResult {
5370    /// Ref_Incompatible - The two types are incompatible, so direct
5371    /// reference binding is not possible.
5372    Ref_Incompatible = 0,
5373    /// Ref_Related - The two types are reference-related, which means
5374    /// that their unqualified forms (T1 and T2) are either the same
5375    /// or T1 is a base class of T2.
5376    Ref_Related,
5377    /// Ref_Compatible_With_Added_Qualification - The two types are
5378    /// reference-compatible with added qualification, meaning that
5379    /// they are reference-compatible and the qualifiers on T1 (cv1)
5380    /// are greater than the qualifiers on T2 (cv2).
5381    Ref_Compatible_With_Added_Qualification,
5382    /// Ref_Compatible - The two types are reference-compatible and
5383    /// have equivalent qualifiers (cv1 == cv2).
5384    Ref_Compatible
5385  };
5386
5387  ReferenceCompareResult CompareReferenceRelationship(SourceLocation Loc,
5388                                                      QualType T1, QualType T2,
5389                                                      bool &DerivedToBase,
5390                                                      bool &ObjCConversion);
5391
5392  /// CheckCastTypes - Check type constraints for casting between types under
5393  /// C semantics, or forward to CXXCheckCStyleCast in C++.
5394  ExprResult CheckCastTypes(SourceRange TyRange, QualType CastTy, Expr *CastExpr,
5395                            CastKind &Kind, ExprValueKind &VK, CXXCastPath &BasePath,
5396                            bool FunctionalStyle = false);
5397
5398  ExprResult checkUnknownAnyCast(SourceRange TyRange, QualType castType,
5399                                 Expr *castExpr, CastKind &castKind,
5400                                 ExprValueKind &valueKind, CXXCastPath &BasePath);
5401
5402  // CheckVectorCast - check type constraints for vectors.
5403  // Since vectors are an extension, there are no C standard reference for this.
5404  // We allow casting between vectors and integer datatypes of the same size.
5405  // returns true if the cast is invalid
5406  bool CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
5407                       CastKind &Kind);
5408
5409  // CheckExtVectorCast - check type constraints for extended vectors.
5410  // Since vectors are an extension, there are no C standard reference for this.
5411  // We allow casting between vectors and integer datatypes of the same size,
5412  // or vectors and the element type of that vector.
5413  // returns the cast expr
5414  ExprResult CheckExtVectorCast(SourceRange R, QualType VectorTy, Expr *CastExpr,
5415                                CastKind &Kind);
5416
5417  /// CXXCheckCStyleCast - Check constraints of a C-style or function-style
5418  /// cast under C++ semantics.
5419  ExprResult CXXCheckCStyleCast(SourceRange R, QualType CastTy, ExprValueKind &VK,
5420                                Expr *CastExpr, CastKind &Kind,
5421                                CXXCastPath &BasePath, bool FunctionalStyle);
5422
5423  /// CheckMessageArgumentTypes - Check types in an Obj-C message send.
5424  /// \param Method - May be null.
5425  /// \param [out] ReturnType - The return type of the send.
5426  /// \return true iff there were any incompatible types.
5427  bool CheckMessageArgumentTypes(Expr **Args, unsigned NumArgs, Selector Sel,
5428                                 ObjCMethodDecl *Method, bool isClassMessage,
5429                                 SourceLocation lbrac, SourceLocation rbrac,
5430                                 QualType &ReturnType, ExprValueKind &VK);
5431
5432  /// CheckBooleanCondition - Diagnose problems involving the use of
5433  /// the given expression as a boolean condition (e.g. in an if
5434  /// statement).  Also performs the standard function and array
5435  /// decays, possibly changing the input variable.
5436  ///
5437  /// \param Loc - A location associated with the condition, e.g. the
5438  /// 'if' keyword.
5439  /// \return true iff there were any errors
5440  ExprResult CheckBooleanCondition(Expr *CondExpr, SourceLocation Loc);
5441
5442  ExprResult ActOnBooleanCondition(Scope *S, SourceLocation Loc,
5443                                           Expr *SubExpr);
5444
5445  /// DiagnoseAssignmentAsCondition - Given that an expression is
5446  /// being used as a boolean condition, warn if it's an assignment.
5447  void DiagnoseAssignmentAsCondition(Expr *E);
5448
5449  /// \brief Redundant parentheses over an equality comparison can indicate
5450  /// that the user intended an assignment used as condition.
5451  void DiagnoseEqualityWithExtraParens(ParenExpr *parenE);
5452
5453  /// CheckCXXBooleanCondition - Returns true if conversion to bool is invalid.
5454  ExprResult CheckCXXBooleanCondition(Expr *CondExpr);
5455
5456  /// ConvertIntegerToTypeWarnOnOverflow - Convert the specified APInt to have
5457  /// the specified width and sign.  If an overflow occurs, detect it and emit
5458  /// the specified diagnostic.
5459  void ConvertIntegerToTypeWarnOnOverflow(llvm::APSInt &OldVal,
5460                                          unsigned NewWidth, bool NewSign,
5461                                          SourceLocation Loc, unsigned DiagID);
5462
5463  /// Checks that the Objective-C declaration is declared in the global scope.
5464  /// Emits an error and marks the declaration as invalid if it's not declared
5465  /// in the global scope.
5466  bool CheckObjCDeclScope(Decl *D);
5467
5468  /// VerifyIntegerConstantExpression - verifies that an expression is an ICE,
5469  /// and reports the appropriate diagnostics. Returns false on success.
5470  /// Can optionally return the value of the expression.
5471  bool VerifyIntegerConstantExpression(const Expr *E, llvm::APSInt *Result = 0);
5472
5473  /// VerifyBitField - verifies that a bit field expression is an ICE and has
5474  /// the correct width, and that the field type is valid.
5475  /// Returns false on success.
5476  /// Can optionally return whether the bit-field is of width 0
5477  bool VerifyBitField(SourceLocation FieldLoc, IdentifierInfo *FieldName,
5478                      QualType FieldTy, const Expr *BitWidth,
5479                      bool *ZeroWidth = 0);
5480
5481  /// \name Code completion
5482  //@{
5483  /// \brief Describes the context in which code completion occurs.
5484  enum ParserCompletionContext {
5485    /// \brief Code completion occurs at top-level or namespace context.
5486    PCC_Namespace,
5487    /// \brief Code completion occurs within a class, struct, or union.
5488    PCC_Class,
5489    /// \brief Code completion occurs within an Objective-C interface, protocol,
5490    /// or category.
5491    PCC_ObjCInterface,
5492    /// \brief Code completion occurs within an Objective-C implementation or
5493    /// category implementation
5494    PCC_ObjCImplementation,
5495    /// \brief Code completion occurs within the list of instance variables
5496    /// in an Objective-C interface, protocol, category, or implementation.
5497    PCC_ObjCInstanceVariableList,
5498    /// \brief Code completion occurs following one or more template
5499    /// headers.
5500    PCC_Template,
5501    /// \brief Code completion occurs following one or more template
5502    /// headers within a class.
5503    PCC_MemberTemplate,
5504    /// \brief Code completion occurs within an expression.
5505    PCC_Expression,
5506    /// \brief Code completion occurs within a statement, which may
5507    /// also be an expression or a declaration.
5508    PCC_Statement,
5509    /// \brief Code completion occurs at the beginning of the
5510    /// initialization statement (or expression) in a for loop.
5511    PCC_ForInit,
5512    /// \brief Code completion occurs within the condition of an if,
5513    /// while, switch, or for statement.
5514    PCC_Condition,
5515    /// \brief Code completion occurs within the body of a function on a
5516    /// recovery path, where we do not have a specific handle on our position
5517    /// in the grammar.
5518    PCC_RecoveryInFunction,
5519    /// \brief Code completion occurs where only a type is permitted.
5520    PCC_Type,
5521    /// \brief Code completion occurs in a parenthesized expression, which
5522    /// might also be a type cast.
5523    PCC_ParenthesizedExpression,
5524    /// \brief Code completion occurs within a sequence of declaration
5525    /// specifiers within a function, method, or block.
5526    PCC_LocalDeclarationSpecifiers
5527  };
5528
5529  void CodeCompleteOrdinaryName(Scope *S,
5530                                ParserCompletionContext CompletionContext);
5531  void CodeCompleteDeclSpec(Scope *S, DeclSpec &DS,
5532                            bool AllowNonIdentifiers,
5533                            bool AllowNestedNameSpecifiers);
5534
5535  struct CodeCompleteExpressionData;
5536  void CodeCompleteExpression(Scope *S,
5537                              const CodeCompleteExpressionData &Data);
5538  void CodeCompleteMemberReferenceExpr(Scope *S, Expr *Base,
5539                                       SourceLocation OpLoc,
5540                                       bool IsArrow);
5541  void CodeCompletePostfixExpression(Scope *S, ExprResult LHS);
5542  void CodeCompleteTag(Scope *S, unsigned TagSpec);
5543  void CodeCompleteTypeQualifiers(DeclSpec &DS);
5544  void CodeCompleteCase(Scope *S);
5545  void CodeCompleteCall(Scope *S, Expr *Fn, Expr **Args, unsigned NumArgs);
5546  void CodeCompleteInitializer(Scope *S, Decl *D);
5547  void CodeCompleteReturn(Scope *S);
5548  void CodeCompleteAssignmentRHS(Scope *S, Expr *LHS);
5549
5550  void CodeCompleteQualifiedId(Scope *S, CXXScopeSpec &SS,
5551                               bool EnteringContext);
5552  void CodeCompleteUsing(Scope *S);
5553  void CodeCompleteUsingDirective(Scope *S);
5554  void CodeCompleteNamespaceDecl(Scope *S);
5555  void CodeCompleteNamespaceAliasDecl(Scope *S);
5556  void CodeCompleteOperatorName(Scope *S);
5557  void CodeCompleteConstructorInitializer(Decl *Constructor,
5558                                          CXXCtorInitializer** Initializers,
5559                                          unsigned NumInitializers);
5560
5561  void CodeCompleteObjCAtDirective(Scope *S, Decl *ObjCImpDecl,
5562                                   bool InInterface);
5563  void CodeCompleteObjCAtVisibility(Scope *S);
5564  void CodeCompleteObjCAtStatement(Scope *S);
5565  void CodeCompleteObjCAtExpression(Scope *S);
5566  void CodeCompleteObjCPropertyFlags(Scope *S, ObjCDeclSpec &ODS);
5567  void CodeCompleteObjCPropertyGetter(Scope *S, Decl *ClassDecl);
5568  void CodeCompleteObjCPropertySetter(Scope *S, Decl *ClassDecl);
5569  void CodeCompleteObjCPassingType(Scope *S, ObjCDeclSpec &DS,
5570                                   bool IsParameter);
5571  void CodeCompleteObjCMessageReceiver(Scope *S);
5572  void CodeCompleteObjCSuperMessage(Scope *S, SourceLocation SuperLoc,
5573                                    IdentifierInfo **SelIdents,
5574                                    unsigned NumSelIdents,
5575                                    bool AtArgumentExpression);
5576  void CodeCompleteObjCClassMessage(Scope *S, ParsedType Receiver,
5577                                    IdentifierInfo **SelIdents,
5578                                    unsigned NumSelIdents,
5579                                    bool AtArgumentExpression,
5580                                    bool IsSuper = false);
5581  void CodeCompleteObjCInstanceMessage(Scope *S, ExprTy *Receiver,
5582                                       IdentifierInfo **SelIdents,
5583                                       unsigned NumSelIdents,
5584                                       bool AtArgumentExpression,
5585                                       ObjCInterfaceDecl *Super = 0);
5586  void CodeCompleteObjCForCollection(Scope *S,
5587                                     DeclGroupPtrTy IterationVar);
5588  void CodeCompleteObjCSelector(Scope *S,
5589                                IdentifierInfo **SelIdents,
5590                                unsigned NumSelIdents);
5591  void CodeCompleteObjCProtocolReferences(IdentifierLocPair *Protocols,
5592                                          unsigned NumProtocols);
5593  void CodeCompleteObjCProtocolDecl(Scope *S);
5594  void CodeCompleteObjCInterfaceDecl(Scope *S);
5595  void CodeCompleteObjCSuperclass(Scope *S,
5596                                  IdentifierInfo *ClassName,
5597                                  SourceLocation ClassNameLoc);
5598  void CodeCompleteObjCImplementationDecl(Scope *S);
5599  void CodeCompleteObjCInterfaceCategory(Scope *S,
5600                                         IdentifierInfo *ClassName,
5601                                         SourceLocation ClassNameLoc);
5602  void CodeCompleteObjCImplementationCategory(Scope *S,
5603                                              IdentifierInfo *ClassName,
5604                                              SourceLocation ClassNameLoc);
5605  void CodeCompleteObjCPropertyDefinition(Scope *S, Decl *ObjCImpDecl);
5606  void CodeCompleteObjCPropertySynthesizeIvar(Scope *S,
5607                                              IdentifierInfo *PropertyName,
5608                                              Decl *ObjCImpDecl);
5609  void CodeCompleteObjCMethodDecl(Scope *S,
5610                                  bool IsInstanceMethod,
5611                                  ParsedType ReturnType,
5612                                  Decl *IDecl);
5613  void CodeCompleteObjCMethodDeclSelector(Scope *S,
5614                                          bool IsInstanceMethod,
5615                                          bool AtParameterName,
5616                                          ParsedType ReturnType,
5617                                          IdentifierInfo **SelIdents,
5618                                          unsigned NumSelIdents);
5619  void CodeCompletePreprocessorDirective(bool InConditional);
5620  void CodeCompleteInPreprocessorConditionalExclusion(Scope *S);
5621  void CodeCompletePreprocessorMacroName(bool IsDefinition);
5622  void CodeCompletePreprocessorExpression();
5623  void CodeCompletePreprocessorMacroArgument(Scope *S,
5624                                             IdentifierInfo *Macro,
5625                                             MacroInfo *MacroInfo,
5626                                             unsigned Argument);
5627  void CodeCompleteNaturalLanguage();
5628  void GatherGlobalCodeCompletions(CodeCompletionAllocator &Allocator,
5629                  llvm::SmallVectorImpl<CodeCompletionResult> &Results);
5630  //@}
5631
5632  void PrintStats() const {}
5633
5634  //===--------------------------------------------------------------------===//
5635  // Extra semantic analysis beyond the C type system
5636
5637public:
5638  SourceLocation getLocationOfStringLiteralByte(const StringLiteral *SL,
5639                                                unsigned ByteNo) const;
5640
5641private:
5642  void CheckArrayAccess(const Expr *E);
5643  bool CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall);
5644  bool CheckBlockCall(NamedDecl *NDecl, CallExpr *TheCall);
5645
5646  bool CheckablePrintfAttr(const FormatAttr *Format, CallExpr *TheCall);
5647  bool CheckObjCString(Expr *Arg);
5648
5649  ExprResult CheckBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
5650  bool CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
5651
5652  bool SemaBuiltinVAStart(CallExpr *TheCall);
5653  bool SemaBuiltinUnorderedCompare(CallExpr *TheCall);
5654  bool SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs);
5655
5656public:
5657  // Used by C++ template instantiation.
5658  ExprResult SemaBuiltinShuffleVector(CallExpr *TheCall);
5659
5660private:
5661  bool SemaBuiltinPrefetch(CallExpr *TheCall);
5662  bool SemaBuiltinObjectSize(CallExpr *TheCall);
5663  bool SemaBuiltinLongjmp(CallExpr *TheCall);
5664  ExprResult SemaBuiltinAtomicOverloaded(ExprResult TheCallResult);
5665  bool SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
5666                              llvm::APSInt &Result);
5667
5668  bool SemaCheckStringLiteral(const Expr *E, const CallExpr *TheCall,
5669                              bool HasVAListArg, unsigned format_idx,
5670                              unsigned firstDataArg, bool isPrintf);
5671
5672  void CheckFormatString(const StringLiteral *FExpr, const Expr *OrigFormatExpr,
5673                         const CallExpr *TheCall, bool HasVAListArg,
5674                         unsigned format_idx, unsigned firstDataArg,
5675                         bool isPrintf);
5676
5677  void CheckNonNullArguments(const NonNullAttr *NonNull,
5678                             const Expr * const *ExprArgs,
5679                             SourceLocation CallSiteLoc);
5680
5681  void CheckPrintfScanfArguments(const CallExpr *TheCall, bool HasVAListArg,
5682                                 unsigned format_idx, unsigned firstDataArg,
5683                                 bool isPrintf);
5684
5685  void CheckMemsetcpymoveArguments(const CallExpr *Call,
5686                                   const IdentifierInfo *FnName);
5687
5688  void CheckReturnStackAddr(Expr *RetValExp, QualType lhsType,
5689                            SourceLocation ReturnLoc);
5690  void CheckFloatComparison(SourceLocation loc, Expr* lex, Expr* rex);
5691  void CheckImplicitConversions(Expr *E, SourceLocation CC = SourceLocation());
5692
5693  void CheckBitFieldInitialization(SourceLocation InitLoc, FieldDecl *Field,
5694                                   Expr *Init);
5695
5696  /// \brief The parser's current scope.
5697  ///
5698  /// The parser maintains this state here.
5699  Scope *CurScope;
5700
5701protected:
5702  friend class Parser;
5703  friend class InitializationSequence;
5704
5705  /// \brief Retrieve the parser's current scope.
5706  Scope *getCurScope() const { return CurScope; }
5707};
5708
5709/// \brief RAII object that enters a new expression evaluation context.
5710class EnterExpressionEvaluationContext {
5711  Sema &Actions;
5712
5713public:
5714  EnterExpressionEvaluationContext(Sema &Actions,
5715                                   Sema::ExpressionEvaluationContext NewContext)
5716    : Actions(Actions) {
5717    Actions.PushExpressionEvaluationContext(NewContext);
5718  }
5719
5720  ~EnterExpressionEvaluationContext() {
5721    Actions.PopExpressionEvaluationContext();
5722  }
5723};
5724
5725}  // end namespace clang
5726
5727#endif
5728