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