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