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