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