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