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