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