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