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