Sema.h revision eee3ef177a171c06f826c331e7a9e256d01eaeb0
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  ExprResult PerformObjectArgumentInitialization(Expr *From,
1347                                                 NestedNameSpecifier *Qualifier,
1348                                                 NamedDecl *FoundDecl,
1349                                                 CXXMethodDecl *Method);
1350
1351  ExprResult PerformContextuallyConvertToBool(Expr *From);
1352  ExprResult PerformContextuallyConvertToObjCId(Expr *From);
1353
1354  ExprResult
1355  ConvertToIntegralOrEnumerationType(SourceLocation Loc, Expr *FromE,
1356                                     const PartialDiagnostic &NotIntDiag,
1357                                     const PartialDiagnostic &IncompleteDiag,
1358                                     const PartialDiagnostic &ExplicitConvDiag,
1359                                     const PartialDiagnostic &ExplicitConvNote,
1360                                     const PartialDiagnostic &AmbigDiag,
1361                                     const PartialDiagnostic &AmbigNote,
1362                                     const PartialDiagnostic &ConvDiag);
1363
1364  ExprResult PerformObjectMemberConversion(Expr *From,
1365                                           NestedNameSpecifier *Qualifier,
1366                                           NamedDecl *FoundDecl,
1367                                           NamedDecl *Member);
1368
1369  // Members have to be NamespaceDecl* or TranslationUnitDecl*.
1370  // TODO: make this is a typesafe union.
1371  typedef llvm::SmallPtrSet<DeclContext   *, 16> AssociatedNamespaceSet;
1372  typedef llvm::SmallPtrSet<CXXRecordDecl *, 16> AssociatedClassSet;
1373
1374  void AddOverloadCandidate(NamedDecl *Function,
1375                            DeclAccessPair FoundDecl,
1376                            Expr **Args, unsigned NumArgs,
1377                            OverloadCandidateSet &CandidateSet);
1378
1379  void AddOverloadCandidate(FunctionDecl *Function,
1380                            DeclAccessPair FoundDecl,
1381                            Expr **Args, unsigned NumArgs,
1382                            OverloadCandidateSet& CandidateSet,
1383                            bool SuppressUserConversions = false,
1384                            bool PartialOverloading = false);
1385  void AddFunctionCandidates(const UnresolvedSetImpl &Functions,
1386                             Expr **Args, unsigned NumArgs,
1387                             OverloadCandidateSet& CandidateSet,
1388                             bool SuppressUserConversions = false);
1389  void AddMethodCandidate(DeclAccessPair FoundDecl,
1390                          QualType ObjectType,
1391                          Expr::Classification ObjectClassification,
1392                          Expr **Args, unsigned NumArgs,
1393                          OverloadCandidateSet& CandidateSet,
1394                          bool SuppressUserConversion = false);
1395  void AddMethodCandidate(CXXMethodDecl *Method,
1396                          DeclAccessPair FoundDecl,
1397                          CXXRecordDecl *ActingContext, QualType ObjectType,
1398                          Expr::Classification ObjectClassification,
1399                          Expr **Args, unsigned NumArgs,
1400                          OverloadCandidateSet& CandidateSet,
1401                          bool SuppressUserConversions = false);
1402  void AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
1403                                  DeclAccessPair FoundDecl,
1404                                  CXXRecordDecl *ActingContext,
1405                                 TemplateArgumentListInfo *ExplicitTemplateArgs,
1406                                  QualType ObjectType,
1407                                  Expr::Classification ObjectClassification,
1408                                  Expr **Args, unsigned NumArgs,
1409                                  OverloadCandidateSet& CandidateSet,
1410                                  bool SuppressUserConversions = false);
1411  void AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
1412                                    DeclAccessPair FoundDecl,
1413                                 TemplateArgumentListInfo *ExplicitTemplateArgs,
1414                                    Expr **Args, unsigned NumArgs,
1415                                    OverloadCandidateSet& CandidateSet,
1416                                    bool SuppressUserConversions = false);
1417  void AddConversionCandidate(CXXConversionDecl *Conversion,
1418                              DeclAccessPair FoundDecl,
1419                              CXXRecordDecl *ActingContext,
1420                              Expr *From, QualType ToType,
1421                              OverloadCandidateSet& CandidateSet);
1422  void AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
1423                                      DeclAccessPair FoundDecl,
1424                                      CXXRecordDecl *ActingContext,
1425                                      Expr *From, QualType ToType,
1426                                      OverloadCandidateSet &CandidateSet);
1427  void AddSurrogateCandidate(CXXConversionDecl *Conversion,
1428                             DeclAccessPair FoundDecl,
1429                             CXXRecordDecl *ActingContext,
1430                             const FunctionProtoType *Proto,
1431                             Expr *Object, Expr **Args, unsigned NumArgs,
1432                             OverloadCandidateSet& CandidateSet);
1433  void AddMemberOperatorCandidates(OverloadedOperatorKind Op,
1434                                   SourceLocation OpLoc,
1435                                   Expr **Args, unsigned NumArgs,
1436                                   OverloadCandidateSet& CandidateSet,
1437                                   SourceRange OpRange = SourceRange());
1438  void AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
1439                           Expr **Args, unsigned NumArgs,
1440                           OverloadCandidateSet& CandidateSet,
1441                           bool IsAssignmentOperator = false,
1442                           unsigned NumContextualBoolArguments = 0);
1443  void AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
1444                                    SourceLocation OpLoc,
1445                                    Expr **Args, unsigned NumArgs,
1446                                    OverloadCandidateSet& CandidateSet);
1447  void AddArgumentDependentLookupCandidates(DeclarationName Name,
1448                                            bool Operator,
1449                                            Expr **Args, unsigned NumArgs,
1450                                TemplateArgumentListInfo *ExplicitTemplateArgs,
1451                                            OverloadCandidateSet& CandidateSet,
1452                                            bool PartialOverloading = false,
1453                                        bool StdNamespaceIsAssociated = false);
1454
1455  // Emit as a 'note' the specific overload candidate
1456  void NoteOverloadCandidate(FunctionDecl *Fn);
1457
1458  // Emit as a series of 'note's all template and non-templates
1459  // identified by the expression Expr
1460  void NoteAllOverloadCandidates(Expr* E);
1461
1462  // [PossiblyAFunctionType]  -->   [Return]
1463  // NonFunctionType --> NonFunctionType
1464  // R (A) --> R(A)
1465  // R (*)(A) --> R (A)
1466  // R (&)(A) --> R (A)
1467  // R (S::*)(A) --> R (A)
1468  QualType ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType);
1469
1470  FunctionDecl *ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr, QualType TargetType,
1471                                                   bool Complain,
1472                                                   DeclAccessPair &Found);
1473
1474  FunctionDecl *ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
1475                                                   bool Complain = false,
1476                                                   DeclAccessPair* Found = 0);
1477
1478  ExprResult ResolveAndFixSingleFunctionTemplateSpecialization(
1479                      Expr *SrcExpr, bool DoFunctionPointerConverion = false,
1480                      bool Complain = false,
1481                      const SourceRange& OpRangeForComplaining = SourceRange(),
1482                      QualType DestTypeForComplaining = QualType(),
1483                      unsigned DiagIDForComplaining = 0);
1484
1485
1486  Expr *FixOverloadedFunctionReference(Expr *E,
1487                                       DeclAccessPair FoundDecl,
1488                                       FunctionDecl *Fn);
1489  ExprResult FixOverloadedFunctionReference(ExprResult,
1490                                            DeclAccessPair FoundDecl,
1491                                            FunctionDecl *Fn);
1492
1493  void AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
1494                                   Expr **Args, unsigned NumArgs,
1495                                   OverloadCandidateSet &CandidateSet,
1496                                   bool PartialOverloading = false);
1497
1498  ExprResult BuildOverloadedCallExpr(Scope *S, Expr *Fn,
1499                                     UnresolvedLookupExpr *ULE,
1500                                     SourceLocation LParenLoc,
1501                                     Expr **Args, unsigned NumArgs,
1502                                     SourceLocation RParenLoc,
1503                                     Expr *ExecConfig);
1504
1505  ExprResult CreateOverloadedUnaryOp(SourceLocation OpLoc,
1506                                     unsigned Opc,
1507                                     const UnresolvedSetImpl &Fns,
1508                                     Expr *input);
1509
1510  ExprResult CreateOverloadedBinOp(SourceLocation OpLoc,
1511                                   unsigned Opc,
1512                                   const UnresolvedSetImpl &Fns,
1513                                   Expr *LHS, Expr *RHS);
1514
1515  ExprResult CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
1516                                                SourceLocation RLoc,
1517                                                Expr *Base,Expr *Idx);
1518
1519  ExprResult
1520  BuildCallToMemberFunction(Scope *S, Expr *MemExpr,
1521                            SourceLocation LParenLoc, Expr **Args,
1522                            unsigned NumArgs, SourceLocation RParenLoc);
1523  ExprResult
1524  BuildCallToObjectOfClassType(Scope *S, Expr *Object, SourceLocation LParenLoc,
1525                               Expr **Args, unsigned NumArgs,
1526                               SourceLocation RParenLoc);
1527
1528  ExprResult BuildOverloadedArrowExpr(Scope *S, Expr *Base,
1529                                      SourceLocation OpLoc);
1530
1531  /// CheckCallReturnType - Checks that a call expression's return type is
1532  /// complete. Returns true on failure. The location passed in is the location
1533  /// that best represents the call.
1534  bool CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
1535                           CallExpr *CE, FunctionDecl *FD);
1536
1537  /// Helpers for dealing with blocks and functions.
1538  bool CheckParmsForFunctionDef(ParmVarDecl **Param, ParmVarDecl **ParamEnd,
1539                                bool CheckParameterNames);
1540  void CheckCXXDefaultArguments(FunctionDecl *FD);
1541  void CheckExtraCXXDefaultArguments(Declarator &D);
1542  Scope *getNonFieldDeclScope(Scope *S);
1543
1544  /// \name Name lookup
1545  ///
1546  /// These routines provide name lookup that is used during semantic
1547  /// analysis to resolve the various kinds of names (identifiers,
1548  /// overloaded operator names, constructor names, etc.) into zero or
1549  /// more declarations within a particular scope. The major entry
1550  /// points are LookupName, which performs unqualified name lookup,
1551  /// and LookupQualifiedName, which performs qualified name lookup.
1552  ///
1553  /// All name lookup is performed based on some specific criteria,
1554  /// which specify what names will be visible to name lookup and how
1555  /// far name lookup should work. These criteria are important both
1556  /// for capturing language semantics (certain lookups will ignore
1557  /// certain names, for example) and for performance, since name
1558  /// lookup is often a bottleneck in the compilation of C++. Name
1559  /// lookup criteria is specified via the LookupCriteria enumeration.
1560  ///
1561  /// The results of name lookup can vary based on the kind of name
1562  /// lookup performed, the current language, and the translation
1563  /// unit. In C, for example, name lookup will either return nothing
1564  /// (no entity found) or a single declaration. In C++, name lookup
1565  /// can additionally refer to a set of overloaded functions or
1566  /// result in an ambiguity. All of the possible results of name
1567  /// lookup are captured by the LookupResult class, which provides
1568  /// the ability to distinguish among them.
1569  //@{
1570
1571  /// @brief Describes the kind of name lookup to perform.
1572  enum LookupNameKind {
1573    /// Ordinary name lookup, which finds ordinary names (functions,
1574    /// variables, typedefs, etc.) in C and most kinds of names
1575    /// (functions, variables, members, types, etc.) in C++.
1576    LookupOrdinaryName = 0,
1577    /// Tag name lookup, which finds the names of enums, classes,
1578    /// structs, and unions.
1579    LookupTagName,
1580    /// Label name lookup.
1581    LookupLabel,
1582    /// Member name lookup, which finds the names of
1583    /// class/struct/union members.
1584    LookupMemberName,
1585    /// Look up of an operator name (e.g., operator+) for use with
1586    /// operator overloading. This lookup is similar to ordinary name
1587    /// lookup, but will ignore any declarations that are class members.
1588    LookupOperatorName,
1589    /// Look up of a name that precedes the '::' scope resolution
1590    /// operator in C++. This lookup completely ignores operator, object,
1591    /// function, and enumerator names (C++ [basic.lookup.qual]p1).
1592    LookupNestedNameSpecifierName,
1593    /// Look up a namespace name within a C++ using directive or
1594    /// namespace alias definition, ignoring non-namespace names (C++
1595    /// [basic.lookup.udir]p1).
1596    LookupNamespaceName,
1597    /// Look up all declarations in a scope with the given name,
1598    /// including resolved using declarations.  This is appropriate
1599    /// for checking redeclarations for a using declaration.
1600    LookupUsingDeclName,
1601    /// Look up an ordinary name that is going to be redeclared as a
1602    /// name with linkage. This lookup ignores any declarations that
1603    /// are outside of the current scope unless they have linkage. See
1604    /// C99 6.2.2p4-5 and C++ [basic.link]p6.
1605    LookupRedeclarationWithLinkage,
1606    /// Look up the name of an Objective-C protocol.
1607    LookupObjCProtocolName,
1608    /// Look up implicit 'self' parameter of an objective-c method.
1609    LookupObjCImplicitSelfParam,
1610    /// \brief Look up any declaration with any name.
1611    LookupAnyName
1612  };
1613
1614  /// \brief Specifies whether (or how) name lookup is being performed for a
1615  /// redeclaration (vs. a reference).
1616  enum RedeclarationKind {
1617    /// \brief The lookup is a reference to this name that is not for the
1618    /// purpose of redeclaring the name.
1619    NotForRedeclaration = 0,
1620    /// \brief The lookup results will be used for redeclaration of a name,
1621    /// if an entity by that name already exists.
1622    ForRedeclaration
1623  };
1624
1625private:
1626  bool CppLookupName(LookupResult &R, Scope *S);
1627
1628  SpecialMemberOverloadResult *LookupSpecialMember(CXXRecordDecl *D,
1629                                                   CXXSpecialMember SM,
1630                                                   bool ConstArg,
1631                                                   bool VolatileArg,
1632                                                   bool RValueThis,
1633                                                   bool ConstThis,
1634                                                   bool VolatileThis);
1635
1636  // \brief The set of known/encountered (unique, canonicalized) NamespaceDecls.
1637  //
1638  // The boolean value will be true to indicate that the namespace was loaded
1639  // from an AST/PCH file, or false otherwise.
1640  llvm::DenseMap<NamespaceDecl*, bool> KnownNamespaces;
1641
1642  /// \brief Whether we have already loaded known namespaces from an extenal
1643  /// source.
1644  bool LoadedExternalKnownNamespaces;
1645
1646public:
1647  /// \brief Look up a name, looking for a single declaration.  Return
1648  /// null if the results were absent, ambiguous, or overloaded.
1649  ///
1650  /// It is preferable to use the elaborated form and explicitly handle
1651  /// ambiguity and overloaded.
1652  NamedDecl *LookupSingleName(Scope *S, DeclarationName Name,
1653                              SourceLocation Loc,
1654                              LookupNameKind NameKind,
1655                              RedeclarationKind Redecl
1656                                = NotForRedeclaration);
1657  bool LookupName(LookupResult &R, Scope *S,
1658                  bool AllowBuiltinCreation = false);
1659  bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
1660                           bool InUnqualifiedLookup = false);
1661  bool LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS,
1662                        bool AllowBuiltinCreation = false,
1663                        bool EnteringContext = false);
1664  ObjCProtocolDecl *LookupProtocol(IdentifierInfo *II, SourceLocation IdLoc);
1665
1666  void LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S,
1667                                    QualType T1, QualType T2,
1668                                    UnresolvedSetImpl &Functions);
1669
1670  LabelDecl *LookupOrCreateLabel(IdentifierInfo *II, SourceLocation IdentLoc,
1671                                 SourceLocation GnuLabelLoc = SourceLocation());
1672
1673  DeclContextLookupResult LookupConstructors(CXXRecordDecl *Class);
1674  CXXConstructorDecl *LookupDefaultConstructor(CXXRecordDecl *Class);
1675  CXXConstructorDecl *LookupCopyingConstructor(CXXRecordDecl *Class,
1676                                               unsigned Quals,
1677                                               bool *ConstParam = 0);
1678  CXXMethodDecl *LookupCopyingAssignment(CXXRecordDecl *Class, unsigned Quals,
1679                                         bool RValueThis, unsigned ThisQuals,
1680                                         bool *ConstParam = 0);
1681  CXXDestructorDecl *LookupDestructor(CXXRecordDecl *Class);
1682
1683  void ArgumentDependentLookup(DeclarationName Name, bool Operator,
1684                               Expr **Args, unsigned NumArgs,
1685                               ADLResult &Functions,
1686                               bool StdNamespaceIsAssociated = false);
1687
1688  void LookupVisibleDecls(Scope *S, LookupNameKind Kind,
1689                          VisibleDeclConsumer &Consumer,
1690                          bool IncludeGlobalScope = true);
1691  void LookupVisibleDecls(DeclContext *Ctx, LookupNameKind Kind,
1692                          VisibleDeclConsumer &Consumer,
1693                          bool IncludeGlobalScope = true);
1694
1695  /// \brief The context in which typo-correction occurs.
1696  ///
1697  /// The typo-correction context affects which keywords (if any) are
1698  /// considered when trying to correct for typos.
1699  enum CorrectTypoContext {
1700    /// \brief An unknown context, where any keyword might be valid.
1701    CTC_Unknown,
1702    /// \brief A context where no keywords are used (e.g. we expect an actual
1703    /// name).
1704    CTC_NoKeywords,
1705    /// \brief A context where we're correcting a type name.
1706    CTC_Type,
1707    /// \brief An expression context.
1708    CTC_Expression,
1709    /// \brief A type cast, or anything else that can be followed by a '<'.
1710    CTC_CXXCasts,
1711    /// \brief A member lookup context.
1712    CTC_MemberLookup,
1713    /// \brief An Objective-C ivar lookup context (e.g., self->ivar).
1714    CTC_ObjCIvarLookup,
1715    /// \brief An Objective-C property lookup context (e.g., self.prop).
1716    CTC_ObjCPropertyLookup,
1717    /// \brief The receiver of an Objective-C message send within an
1718    /// Objective-C method where 'super' is a valid keyword.
1719    CTC_ObjCMessageReceiver
1720  };
1721
1722  TypoCorrection CorrectTypo(const DeclarationNameInfo &Typo,
1723                             Sema::LookupNameKind LookupKind,
1724                             Scope *S, CXXScopeSpec *SS,
1725                             DeclContext *MemberContext = NULL,
1726                             bool EnteringContext = false,
1727                             CorrectTypoContext CTC = CTC_Unknown,
1728                             const ObjCObjectPointerType *OPT = NULL);
1729
1730  void FindAssociatedClassesAndNamespaces(Expr **Args, unsigned NumArgs,
1731                                   AssociatedNamespaceSet &AssociatedNamespaces,
1732                                   AssociatedClassSet &AssociatedClasses);
1733
1734  void FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S,
1735                            bool ConsiderLinkage,
1736                            bool ExplicitInstantiationOrSpecialization);
1737
1738  bool DiagnoseAmbiguousLookup(LookupResult &Result);
1739  //@}
1740
1741  ObjCInterfaceDecl *getObjCInterfaceDecl(IdentifierInfo *&Id,
1742                                          SourceLocation IdLoc,
1743                                          bool TypoCorrection = false);
1744  NamedDecl *LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID,
1745                                 Scope *S, bool ForRedeclaration,
1746                                 SourceLocation Loc);
1747  NamedDecl *ImplicitlyDefineFunction(SourceLocation Loc, IdentifierInfo &II,
1748                                      Scope *S);
1749  void AddKnownFunctionAttributes(FunctionDecl *FD);
1750
1751  // More parsing and symbol table subroutines.
1752
1753  // Decl attributes - this routine is the top level dispatcher.
1754  void ProcessDeclAttributes(Scope *S, Decl *D, const Declarator &PD,
1755                           bool NonInheritable = true, bool Inheritable = true);
1756  void ProcessDeclAttributeList(Scope *S, Decl *D, const AttributeList *AL,
1757                           bool NonInheritable = true, bool Inheritable = true);
1758
1759  bool CheckRegparmAttr(const AttributeList &attr, unsigned &value);
1760  bool CheckCallingConvAttr(const AttributeList &attr, CallingConv &CC);
1761  bool CheckNoReturnAttr(const AttributeList &attr);
1762
1763  void WarnUndefinedMethod(SourceLocation ImpLoc, ObjCMethodDecl *method,
1764                           bool &IncompleteImpl, unsigned DiagID);
1765  void WarnConflictingTypedMethods(ObjCMethodDecl *Method,
1766                                   ObjCMethodDecl *MethodDecl,
1767                                   bool IsProtocolMethodDecl,
1768                                   bool IsDeclaration = false);
1769
1770  bool isPropertyReadonly(ObjCPropertyDecl *PropertyDecl,
1771                          ObjCInterfaceDecl *IDecl);
1772
1773  typedef llvm::DenseSet<Selector, llvm::DenseMapInfo<Selector> > SelectorSet;
1774
1775  /// CheckProtocolMethodDefs - This routine checks unimplemented
1776  /// methods declared in protocol, and those referenced by it.
1777  /// \param IDecl - Used for checking for methods which may have been
1778  /// inherited.
1779  void CheckProtocolMethodDefs(SourceLocation ImpLoc,
1780                               ObjCProtocolDecl *PDecl,
1781                               bool& IncompleteImpl,
1782                               const SelectorSet &InsMap,
1783                               const SelectorSet &ClsMap,
1784                               ObjCContainerDecl *CDecl);
1785
1786  /// CheckImplementationIvars - This routine checks if the instance variables
1787  /// listed in the implelementation match those listed in the interface.
1788  void CheckImplementationIvars(ObjCImplementationDecl *ImpDecl,
1789                                ObjCIvarDecl **Fields, unsigned nIvars,
1790                                SourceLocation Loc);
1791
1792  /// \brief Determine whether we can synthesize a provisional ivar for the
1793  /// given name.
1794  ObjCPropertyDecl *canSynthesizeProvisionalIvar(IdentifierInfo *II);
1795
1796  /// \brief Determine whether we can synthesize a provisional ivar for the
1797  /// given property.
1798  bool canSynthesizeProvisionalIvar(ObjCPropertyDecl *Property);
1799
1800  /// ImplMethodsVsClassMethods - This is main routine to warn if any method
1801  /// remains unimplemented in the class or category @implementation.
1802  void ImplMethodsVsClassMethods(Scope *S, ObjCImplDecl* IMPDecl,
1803                                 ObjCContainerDecl* IDecl,
1804                                 bool IncompleteImpl = false);
1805
1806  /// DiagnoseUnimplementedProperties - This routine warns on those properties
1807  /// which must be implemented by this implementation.
1808  void DiagnoseUnimplementedProperties(Scope *S, ObjCImplDecl* IMPDecl,
1809                                       ObjCContainerDecl *CDecl,
1810                                       const SelectorSet &InsMap);
1811
1812  /// DefaultSynthesizeProperties - This routine default synthesizes all
1813  /// properties which must be synthesized in class's @implementation.
1814  void DefaultSynthesizeProperties (Scope *S, ObjCImplDecl* IMPDecl,
1815                                    ObjCInterfaceDecl *IDecl);
1816
1817  /// CollectImmediateProperties - This routine collects all properties in
1818  /// the class and its conforming protocols; but not those it its super class.
1819  void CollectImmediateProperties(ObjCContainerDecl *CDecl,
1820            llvm::DenseMap<IdentifierInfo *, ObjCPropertyDecl*>& PropMap,
1821            llvm::DenseMap<IdentifierInfo *, ObjCPropertyDecl*>& SuperPropMap);
1822
1823
1824  /// LookupPropertyDecl - Looks up a property in the current class and all
1825  /// its protocols.
1826  ObjCPropertyDecl *LookupPropertyDecl(const ObjCContainerDecl *CDecl,
1827                                       IdentifierInfo *II);
1828
1829  /// Called by ActOnProperty to handle @property declarations in
1830  ////  class extensions.
1831  Decl *HandlePropertyInClassExtension(Scope *S,
1832                                       ObjCCategoryDecl *CDecl,
1833                                       SourceLocation AtLoc,
1834                                       FieldDeclarator &FD,
1835                                       Selector GetterSel,
1836                                       Selector SetterSel,
1837                                       const bool isAssign,
1838                                       const bool isReadWrite,
1839                                       const unsigned Attributes,
1840                                       bool *isOverridingProperty,
1841                                       TypeSourceInfo *T,
1842                                       tok::ObjCKeywordKind MethodImplKind);
1843
1844  /// Called by ActOnProperty and HandlePropertyInClassExtension to
1845  ///  handle creating the ObjcPropertyDecl for a category or @interface.
1846  ObjCPropertyDecl *CreatePropertyDecl(Scope *S,
1847                                       ObjCContainerDecl *CDecl,
1848                                       SourceLocation AtLoc,
1849                                       FieldDeclarator &FD,
1850                                       Selector GetterSel,
1851                                       Selector SetterSel,
1852                                       const bool isAssign,
1853                                       const bool isReadWrite,
1854                                       const unsigned Attributes,
1855                                       TypeSourceInfo *T,
1856                                       tok::ObjCKeywordKind MethodImplKind,
1857                                       DeclContext *lexicalDC = 0);
1858
1859  /// AtomicPropertySetterGetterRules - This routine enforces the rule (via
1860  /// warning) when atomic property has one but not the other user-declared
1861  /// setter or getter.
1862  void AtomicPropertySetterGetterRules(ObjCImplDecl* IMPDecl,
1863                                       ObjCContainerDecl* IDecl);
1864
1865  void DiagnoseOwningPropertyGetterSynthesis(const ObjCImplementationDecl *D);
1866
1867  void DiagnoseDuplicateIvars(ObjCInterfaceDecl *ID, ObjCInterfaceDecl *SID);
1868
1869  enum MethodMatchStrategy {
1870    MMS_loose,
1871    MMS_strict
1872  };
1873
1874  /// MatchTwoMethodDeclarations - Checks if two methods' type match and returns
1875  /// true, or false, accordingly.
1876  bool MatchTwoMethodDeclarations(const ObjCMethodDecl *Method,
1877                                  const ObjCMethodDecl *PrevMethod,
1878                                  MethodMatchStrategy strategy = MMS_strict);
1879
1880  /// MatchAllMethodDeclarations - Check methods declaraed in interface or
1881  /// or protocol against those declared in their implementations.
1882  void MatchAllMethodDeclarations(const SelectorSet &InsMap,
1883                                  const SelectorSet &ClsMap,
1884                                  SelectorSet &InsMapSeen,
1885                                  SelectorSet &ClsMapSeen,
1886                                  ObjCImplDecl* IMPDecl,
1887                                  ObjCContainerDecl* IDecl,
1888                                  bool &IncompleteImpl,
1889                                  bool ImmediateClass);
1890
1891  /// MatchMethodsInClassAndItsProtocol - Check that any redeclaration of
1892  /// method in protocol in its qualified class match in their type and
1893  /// issue warnings otherwise.
1894  void MatchMethodsInClassAndItsProtocol(const ObjCInterfaceDecl *CDecl);
1895
1896private:
1897  /// AddMethodToGlobalPool - Add an instance or factory method to the global
1898  /// pool. See descriptoin of AddInstanceMethodToGlobalPool.
1899  void AddMethodToGlobalPool(ObjCMethodDecl *Method, bool impl, bool instance);
1900
1901  /// LookupMethodInGlobalPool - Returns the instance or factory method and
1902  /// optionally warns if there are multiple signatures.
1903  ObjCMethodDecl *LookupMethodInGlobalPool(Selector Sel, SourceRange R,
1904                                           bool receiverIdOrClass,
1905                                           bool warn, bool instance);
1906
1907public:
1908  /// AddInstanceMethodToGlobalPool - All instance methods in a translation
1909  /// unit are added to a global pool. This allows us to efficiently associate
1910  /// a selector with a method declaraation for purposes of typechecking
1911  /// messages sent to "id" (where the class of the object is unknown).
1912  void AddInstanceMethodToGlobalPool(ObjCMethodDecl *Method, bool impl=false) {
1913    AddMethodToGlobalPool(Method, impl, /*instance*/true);
1914  }
1915
1916  /// AddFactoryMethodToGlobalPool - Same as above, but for factory methods.
1917  void AddFactoryMethodToGlobalPool(ObjCMethodDecl *Method, bool impl=false) {
1918    AddMethodToGlobalPool(Method, impl, /*instance*/false);
1919  }
1920
1921  /// LookupInstanceMethodInGlobalPool - Returns the method and warns if
1922  /// there are multiple signatures.
1923  ObjCMethodDecl *LookupInstanceMethodInGlobalPool(Selector Sel, SourceRange R,
1924                                                   bool receiverIdOrClass=false,
1925                                                   bool warn=true) {
1926    return LookupMethodInGlobalPool(Sel, R, receiverIdOrClass,
1927                                    warn, /*instance*/true);
1928  }
1929
1930  /// LookupFactoryMethodInGlobalPool - Returns the method and warns if
1931  /// there are multiple signatures.
1932  ObjCMethodDecl *LookupFactoryMethodInGlobalPool(Selector Sel, SourceRange R,
1933                                                  bool receiverIdOrClass=false,
1934                                                  bool warn=true) {
1935    return LookupMethodInGlobalPool(Sel, R, receiverIdOrClass,
1936                                    warn, /*instance*/false);
1937  }
1938
1939  /// LookupImplementedMethodInGlobalPool - Returns the method which has an
1940  /// implementation.
1941  ObjCMethodDecl *LookupImplementedMethodInGlobalPool(Selector Sel);
1942
1943  /// CollectIvarsToConstructOrDestruct - Collect those ivars which require
1944  /// initialization.
1945  void CollectIvarsToConstructOrDestruct(ObjCInterfaceDecl *OI,
1946                                  SmallVectorImpl<ObjCIvarDecl*> &Ivars);
1947
1948  //===--------------------------------------------------------------------===//
1949  // Statement Parsing Callbacks: SemaStmt.cpp.
1950public:
1951  class FullExprArg {
1952  public:
1953    FullExprArg(Sema &actions) : E(0) { }
1954
1955    // FIXME: The const_cast here is ugly. RValue references would make this
1956    // much nicer (or we could duplicate a bunch of the move semantics
1957    // emulation code from Ownership.h).
1958    FullExprArg(const FullExprArg& Other) : E(Other.E) {}
1959
1960    ExprResult release() {
1961      return move(E);
1962    }
1963
1964    Expr *get() const { return E; }
1965
1966    Expr *operator->() {
1967      return E;
1968    }
1969
1970  private:
1971    // FIXME: No need to make the entire Sema class a friend when it's just
1972    // Sema::MakeFullExpr that needs access to the constructor below.
1973    friend class Sema;
1974
1975    explicit FullExprArg(Expr *expr) : E(expr) {}
1976
1977    Expr *E;
1978  };
1979
1980  FullExprArg MakeFullExpr(Expr *Arg) {
1981    return FullExprArg(ActOnFinishFullExpr(Arg).release());
1982  }
1983
1984  StmtResult ActOnExprStmt(FullExprArg Expr);
1985
1986  StmtResult ActOnNullStmt(SourceLocation SemiLoc,
1987                        SourceLocation LeadingEmptyMacroLoc = SourceLocation());
1988  StmtResult ActOnCompoundStmt(SourceLocation L, SourceLocation R,
1989                                       MultiStmtArg Elts,
1990                                       bool isStmtExpr);
1991  StmtResult ActOnDeclStmt(DeclGroupPtrTy Decl,
1992                                   SourceLocation StartLoc,
1993                                   SourceLocation EndLoc);
1994  void ActOnForEachDeclStmt(DeclGroupPtrTy Decl);
1995  StmtResult ActOnForEachLValueExpr(Expr *E);
1996  StmtResult ActOnCaseStmt(SourceLocation CaseLoc, Expr *LHSVal,
1997                                   SourceLocation DotDotDotLoc, Expr *RHSVal,
1998                                   SourceLocation ColonLoc);
1999  void ActOnCaseStmtBody(Stmt *CaseStmt, Stmt *SubStmt);
2000
2001  StmtResult ActOnDefaultStmt(SourceLocation DefaultLoc,
2002                                      SourceLocation ColonLoc,
2003                                      Stmt *SubStmt, Scope *CurScope);
2004  StmtResult ActOnLabelStmt(SourceLocation IdentLoc, LabelDecl *TheDecl,
2005                            SourceLocation ColonLoc, Stmt *SubStmt);
2006
2007  StmtResult ActOnIfStmt(SourceLocation IfLoc,
2008                         FullExprArg CondVal, Decl *CondVar,
2009                         Stmt *ThenVal,
2010                         SourceLocation ElseLoc, Stmt *ElseVal);
2011  StmtResult ActOnStartOfSwitchStmt(SourceLocation SwitchLoc,
2012                                            Expr *Cond,
2013                                            Decl *CondVar);
2014  StmtResult ActOnFinishSwitchStmt(SourceLocation SwitchLoc,
2015                                           Stmt *Switch, Stmt *Body);
2016  StmtResult ActOnWhileStmt(SourceLocation WhileLoc,
2017                            FullExprArg Cond,
2018                            Decl *CondVar, Stmt *Body);
2019  StmtResult ActOnDoStmt(SourceLocation DoLoc, Stmt *Body,
2020                                 SourceLocation WhileLoc,
2021                                 SourceLocation CondLParen, Expr *Cond,
2022                                 SourceLocation CondRParen);
2023
2024  StmtResult ActOnForStmt(SourceLocation ForLoc,
2025                          SourceLocation LParenLoc,
2026                          Stmt *First, FullExprArg Second,
2027                          Decl *SecondVar,
2028                          FullExprArg Third,
2029                          SourceLocation RParenLoc,
2030                          Stmt *Body);
2031  StmtResult ActOnObjCForCollectionStmt(SourceLocation ForColLoc,
2032                                        SourceLocation LParenLoc,
2033                                        Stmt *First, Expr *Second,
2034                                        SourceLocation RParenLoc, Stmt *Body);
2035  StmtResult ActOnCXXForRangeStmt(SourceLocation ForLoc,
2036                                  SourceLocation LParenLoc, Stmt *LoopVar,
2037                                  SourceLocation ColonLoc, Expr *Collection,
2038                                  SourceLocation RParenLoc);
2039  StmtResult BuildCXXForRangeStmt(SourceLocation ForLoc,
2040                                  SourceLocation ColonLoc,
2041                                  Stmt *RangeDecl, Stmt *BeginEndDecl,
2042                                  Expr *Cond, Expr *Inc,
2043                                  Stmt *LoopVarDecl,
2044                                  SourceLocation RParenLoc);
2045  StmtResult FinishCXXForRangeStmt(Stmt *ForRange, Stmt *Body);
2046
2047  StmtResult ActOnGotoStmt(SourceLocation GotoLoc,
2048                           SourceLocation LabelLoc,
2049                           LabelDecl *TheDecl);
2050  StmtResult ActOnIndirectGotoStmt(SourceLocation GotoLoc,
2051                                   SourceLocation StarLoc,
2052                                   Expr *DestExp);
2053  StmtResult ActOnContinueStmt(SourceLocation ContinueLoc, Scope *CurScope);
2054  StmtResult ActOnBreakStmt(SourceLocation GotoLoc, Scope *CurScope);
2055
2056  const VarDecl *getCopyElisionCandidate(QualType ReturnType, Expr *E,
2057                                         bool AllowFunctionParameters);
2058
2059  StmtResult ActOnReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp);
2060  StmtResult ActOnBlockReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp);
2061
2062  StmtResult ActOnAsmStmt(SourceLocation AsmLoc,
2063                          bool IsSimple, bool IsVolatile,
2064                          unsigned NumOutputs, unsigned NumInputs,
2065                          IdentifierInfo **Names,
2066                          MultiExprArg Constraints,
2067                          MultiExprArg Exprs,
2068                          Expr *AsmString,
2069                          MultiExprArg Clobbers,
2070                          SourceLocation RParenLoc,
2071                          bool MSAsm = false);
2072
2073
2074  VarDecl *BuildObjCExceptionDecl(TypeSourceInfo *TInfo, QualType ExceptionType,
2075                                  SourceLocation StartLoc,
2076                                  SourceLocation IdLoc, IdentifierInfo *Id,
2077                                  bool Invalid = false);
2078
2079  Decl *ActOnObjCExceptionDecl(Scope *S, Declarator &D);
2080
2081  StmtResult ActOnObjCAtCatchStmt(SourceLocation AtLoc, SourceLocation RParen,
2082                                  Decl *Parm, Stmt *Body);
2083
2084  StmtResult ActOnObjCAtFinallyStmt(SourceLocation AtLoc, Stmt *Body);
2085
2086  StmtResult ActOnObjCAtTryStmt(SourceLocation AtLoc, Stmt *Try,
2087                                MultiStmtArg Catch, Stmt *Finally);
2088
2089  StmtResult BuildObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw);
2090  StmtResult ActOnObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw,
2091                                  Scope *CurScope);
2092  StmtResult ActOnObjCAtSynchronizedStmt(SourceLocation AtLoc,
2093                                         Expr *SynchExpr,
2094                                         Stmt *SynchBody);
2095
2096  StmtResult ActOnObjCAutoreleasePoolStmt(SourceLocation AtLoc, Stmt *Body);
2097
2098  VarDecl *BuildExceptionDeclaration(Scope *S, TypeSourceInfo *TInfo,
2099                                     SourceLocation StartLoc,
2100                                     SourceLocation IdLoc,
2101                                     IdentifierInfo *Id);
2102
2103  Decl *ActOnExceptionDeclarator(Scope *S, Declarator &D);
2104
2105  StmtResult ActOnCXXCatchBlock(SourceLocation CatchLoc,
2106                                Decl *ExDecl, Stmt *HandlerBlock);
2107  StmtResult ActOnCXXTryBlock(SourceLocation TryLoc, Stmt *TryBlock,
2108                              MultiStmtArg Handlers);
2109
2110  StmtResult ActOnSEHTryBlock(bool IsCXXTry, // try (true) or __try (false) ?
2111                              SourceLocation TryLoc,
2112                              Stmt *TryBlock,
2113                              Stmt *Handler);
2114
2115  StmtResult ActOnSEHExceptBlock(SourceLocation Loc,
2116                                 Expr *FilterExpr,
2117                                 Stmt *Block);
2118
2119  StmtResult ActOnSEHFinallyBlock(SourceLocation Loc,
2120                                  Stmt *Block);
2121
2122  void DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock);
2123
2124  bool ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const;
2125
2126  /// \brief If it's a file scoped decl that must warn if not used, keep track
2127  /// of it.
2128  void MarkUnusedFileScopedDecl(const DeclaratorDecl *D);
2129
2130  /// DiagnoseUnusedExprResult - If the statement passed in is an expression
2131  /// whose result is unused, warn.
2132  void DiagnoseUnusedExprResult(const Stmt *S);
2133  void DiagnoseUnusedDecl(const NamedDecl *ND);
2134
2135  ParsingDeclState PushParsingDeclaration() {
2136    return DelayedDiagnostics.pushParsingDecl();
2137  }
2138  void PopParsingDeclaration(ParsingDeclState state, Decl *decl) {
2139    DelayedDiagnostics::popParsingDecl(*this, state, decl);
2140  }
2141
2142  typedef ProcessingContextState ParsingClassState;
2143  ParsingClassState PushParsingClass() {
2144    return DelayedDiagnostics.pushContext();
2145  }
2146  void PopParsingClass(ParsingClassState state) {
2147    DelayedDiagnostics.popContext(state);
2148  }
2149
2150  void EmitDeprecationWarning(NamedDecl *D, StringRef Message,
2151                              SourceLocation Loc,
2152                              const ObjCInterfaceDecl *UnknownObjCClass=0);
2153
2154  void HandleDelayedDeprecationCheck(sema::DelayedDiagnostic &DD, Decl *Ctx);
2155
2156  bool makeUnavailableInSystemHeader(SourceLocation loc,
2157                                     StringRef message);
2158
2159  //===--------------------------------------------------------------------===//
2160  // Expression Parsing Callbacks: SemaExpr.cpp.
2161
2162  bool DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc,
2163                         const ObjCInterfaceDecl *UnknownObjCClass=0);
2164  std::string getDeletedOrUnavailableSuffix(const FunctionDecl *FD);
2165  bool DiagnosePropertyAccessorMismatch(ObjCPropertyDecl *PD,
2166                                        ObjCMethodDecl *Getter,
2167                                        SourceLocation Loc);
2168  void DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
2169                             Expr **Args, unsigned NumArgs);
2170
2171  void PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext);
2172
2173  void PopExpressionEvaluationContext();
2174
2175  void DiscardCleanupsInEvaluationContext();
2176
2177  void MarkDeclarationReferenced(SourceLocation Loc, Decl *D);
2178  void MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T);
2179  void MarkDeclarationsReferencedInExpr(Expr *E);
2180
2181  /// \brief Figure out if an expression could be turned into a call.
2182  bool isExprCallable(const Expr &E, QualType &ZeroArgCallReturnTy,
2183                      UnresolvedSetImpl &NonTemplateOverloads);
2184  /// \brief Give notes for a set of overloads.
2185  void NoteOverloads(const UnresolvedSetImpl &Overloads,
2186                     const SourceLocation FinalNoteLoc);
2187
2188  /// \brief Conditionally issue a diagnostic based on the current
2189  /// evaluation context.
2190  ///
2191  /// \param stmt - If stmt is non-null, delay reporting the diagnostic until
2192  ///  the function body is parsed, and then do a basic reachability analysis to
2193  ///  determine if the statement is reachable.  If it is unreachable, the
2194  ///  diagnostic will not be emitted.
2195  bool DiagRuntimeBehavior(SourceLocation Loc, const Stmt *stmt,
2196                           const PartialDiagnostic &PD);
2197
2198  // Primary Expressions.
2199  SourceRange getExprRange(Expr *E) const;
2200
2201  ObjCIvarDecl *SynthesizeProvisionalIvar(LookupResult &Lookup,
2202                                          IdentifierInfo *II,
2203                                          SourceLocation NameLoc);
2204
2205  ExprResult ActOnIdExpression(Scope *S, CXXScopeSpec &SS, UnqualifiedId &Name,
2206                               bool HasTrailingLParen, bool IsAddressOfOperand);
2207
2208  void DecomposeUnqualifiedId(const UnqualifiedId &Id,
2209                              TemplateArgumentListInfo &Buffer,
2210                              DeclarationNameInfo &NameInfo,
2211                              const TemplateArgumentListInfo *&TemplateArgs);
2212
2213  bool DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
2214                           CorrectTypoContext CTC = CTC_Unknown);
2215
2216  ExprResult LookupInObjCMethod(LookupResult &R, Scope *S, IdentifierInfo *II,
2217                                bool AllowBuiltinCreation=false);
2218
2219  ExprResult ActOnDependentIdExpression(const CXXScopeSpec &SS,
2220                                        const DeclarationNameInfo &NameInfo,
2221                                        bool isAddressOfOperand,
2222                                const TemplateArgumentListInfo *TemplateArgs);
2223
2224  ExprResult BuildDeclRefExpr(ValueDecl *D, QualType Ty,
2225                              ExprValueKind VK,
2226                              SourceLocation Loc,
2227                              const CXXScopeSpec *SS = 0);
2228  ExprResult BuildDeclRefExpr(ValueDecl *D, QualType Ty,
2229                              ExprValueKind VK,
2230                              const DeclarationNameInfo &NameInfo,
2231                              const CXXScopeSpec *SS = 0);
2232  ExprResult
2233  BuildAnonymousStructUnionMemberReference(const CXXScopeSpec &SS,
2234                                           SourceLocation nameLoc,
2235                                           IndirectFieldDecl *indirectField,
2236                                           Expr *baseObjectExpr = 0,
2237                                      SourceLocation opLoc = SourceLocation());
2238  ExprResult BuildPossibleImplicitMemberExpr(const CXXScopeSpec &SS,
2239                                             LookupResult &R,
2240                                const TemplateArgumentListInfo *TemplateArgs);
2241  ExprResult BuildImplicitMemberExpr(const CXXScopeSpec &SS,
2242                                     LookupResult &R,
2243                                const TemplateArgumentListInfo *TemplateArgs,
2244                                     bool IsDefiniteInstance);
2245  bool UseArgumentDependentLookup(const CXXScopeSpec &SS,
2246                                  const LookupResult &R,
2247                                  bool HasTrailingLParen);
2248
2249  ExprResult BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS,
2250                                         const DeclarationNameInfo &NameInfo);
2251  ExprResult BuildDependentDeclRefExpr(const CXXScopeSpec &SS,
2252                                const DeclarationNameInfo &NameInfo,
2253                                const TemplateArgumentListInfo *TemplateArgs);
2254
2255  ExprResult BuildDeclarationNameExpr(const CXXScopeSpec &SS,
2256                                      LookupResult &R,
2257                                      bool ADL);
2258  ExprResult BuildDeclarationNameExpr(const CXXScopeSpec &SS,
2259                                      const DeclarationNameInfo &NameInfo,
2260                                      NamedDecl *D);
2261
2262  ExprResult ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind);
2263  ExprResult ActOnNumericConstant(const Token &);
2264  ExprResult ActOnCharacterConstant(const Token &);
2265  ExprResult ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *Val);
2266  ExprResult ActOnParenOrParenListExpr(SourceLocation L,
2267                                       SourceLocation R,
2268                                       MultiExprArg Val);
2269
2270  /// ActOnStringLiteral - The specified tokens were lexed as pasted string
2271  /// fragments (e.g. "foo" "bar" L"baz").
2272  ExprResult ActOnStringLiteral(const Token *Toks, unsigned NumToks);
2273
2274  ExprResult ActOnGenericSelectionExpr(SourceLocation KeyLoc,
2275                                       SourceLocation DefaultLoc,
2276                                       SourceLocation RParenLoc,
2277                                       Expr *ControllingExpr,
2278                                       MultiTypeArg Types,
2279                                       MultiExprArg Exprs);
2280  ExprResult CreateGenericSelectionExpr(SourceLocation KeyLoc,
2281                                        SourceLocation DefaultLoc,
2282                                        SourceLocation RParenLoc,
2283                                        Expr *ControllingExpr,
2284                                        TypeSourceInfo **Types,
2285                                        Expr **Exprs,
2286                                        unsigned NumAssocs);
2287
2288  // Binary/Unary Operators.  'Tok' is the token for the operator.
2289  ExprResult CreateBuiltinUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc,
2290                                  Expr *InputArg);
2291  ExprResult BuildUnaryOp(Scope *S, SourceLocation OpLoc,
2292                          UnaryOperatorKind Opc, Expr *input);
2293  ExprResult ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
2294                          tok::TokenKind Op, Expr *Input);
2295
2296  ExprResult CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *T,
2297                                            SourceLocation OpLoc,
2298                                            UnaryExprOrTypeTrait ExprKind,
2299                                            SourceRange R);
2300  ExprResult CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
2301                                            UnaryExprOrTypeTrait ExprKind);
2302  ExprResult
2303    ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
2304                                  UnaryExprOrTypeTrait ExprKind,
2305                                  bool isType, void *TyOrEx,
2306                                  const SourceRange &ArgRange);
2307
2308  ExprResult CheckPlaceholderExpr(Expr *E);
2309  bool CheckVecStepExpr(Expr *E);
2310
2311  bool CheckUnaryExprOrTypeTraitOperand(Expr *E, UnaryExprOrTypeTrait ExprKind);
2312  bool CheckUnaryExprOrTypeTraitOperand(QualType type, SourceLocation OpLoc,
2313                                        SourceRange R,
2314                                        UnaryExprOrTypeTrait ExprKind);
2315  ExprResult ActOnSizeofParameterPackExpr(Scope *S,
2316                                          SourceLocation OpLoc,
2317                                          IdentifierInfo &Name,
2318                                          SourceLocation NameLoc,
2319                                          SourceLocation RParenLoc);
2320  ExprResult ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
2321                                 tok::TokenKind Kind, Expr *Input);
2322
2323  ExprResult ActOnArraySubscriptExpr(Scope *S, Expr *Base, SourceLocation LLoc,
2324                                     Expr *Idx, SourceLocation RLoc);
2325  ExprResult CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
2326                                             Expr *Idx, SourceLocation RLoc);
2327
2328  ExprResult BuildMemberReferenceExpr(Expr *Base, QualType BaseType,
2329                                      SourceLocation OpLoc, bool IsArrow,
2330                                      CXXScopeSpec &SS,
2331                                      NamedDecl *FirstQualifierInScope,
2332                                const DeclarationNameInfo &NameInfo,
2333                                const TemplateArgumentListInfo *TemplateArgs);
2334
2335  ExprResult BuildMemberReferenceExpr(Expr *Base, QualType BaseType,
2336                                      SourceLocation OpLoc, bool IsArrow,
2337                                      const CXXScopeSpec &SS,
2338                                      NamedDecl *FirstQualifierInScope,
2339                                      LookupResult &R,
2340                                 const TemplateArgumentListInfo *TemplateArgs,
2341                                      bool SuppressQualifierCheck = false);
2342
2343  ExprResult LookupMemberExpr(LookupResult &R, ExprResult &Base,
2344                              bool &IsArrow, SourceLocation OpLoc,
2345                              CXXScopeSpec &SS,
2346                              Decl *ObjCImpDecl,
2347                              bool HasTemplateArgs);
2348
2349  bool CheckQualifiedMemberReference(Expr *BaseExpr, QualType BaseType,
2350                                     const CXXScopeSpec &SS,
2351                                     const LookupResult &R);
2352
2353  ExprResult ActOnDependentMemberExpr(Expr *Base, QualType BaseType,
2354                                      bool IsArrow, SourceLocation OpLoc,
2355                                      const CXXScopeSpec &SS,
2356                                      NamedDecl *FirstQualifierInScope,
2357                               const DeclarationNameInfo &NameInfo,
2358                               const TemplateArgumentListInfo *TemplateArgs);
2359
2360  ExprResult ActOnMemberAccessExpr(Scope *S, Expr *Base,
2361                                   SourceLocation OpLoc,
2362                                   tok::TokenKind OpKind,
2363                                   CXXScopeSpec &SS,
2364                                   UnqualifiedId &Member,
2365                                   Decl *ObjCImpDecl,
2366                                   bool HasTrailingLParen);
2367
2368  void ActOnDefaultCtorInitializers(Decl *CDtorDecl);
2369  bool ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
2370                               FunctionDecl *FDecl,
2371                               const FunctionProtoType *Proto,
2372                               Expr **Args, unsigned NumArgs,
2373                               SourceLocation RParenLoc);
2374
2375  /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
2376  /// This provides the location of the left/right parens and a list of comma
2377  /// locations.
2378  ExprResult ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
2379                           MultiExprArg Args, SourceLocation RParenLoc,
2380                           Expr *ExecConfig = 0);
2381  ExprResult BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
2382                                   SourceLocation LParenLoc,
2383                                   Expr **Args, unsigned NumArgs,
2384                                   SourceLocation RParenLoc,
2385                                   Expr *ExecConfig = 0);
2386
2387  ExprResult ActOnCUDAExecConfigExpr(Scope *S, SourceLocation LLLLoc,
2388                                MultiExprArg ExecConfig, SourceLocation GGGLoc);
2389
2390  ExprResult ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
2391                           Declarator &D, ParsedType &Ty,
2392                           SourceLocation RParenLoc, Expr *Op);
2393  ExprResult BuildCStyleCastExpr(SourceLocation LParenLoc,
2394                                 TypeSourceInfo *Ty,
2395                                 SourceLocation RParenLoc,
2396                                 Expr *Op);
2397
2398  /// \brief Build an altivec or OpenCL literal.
2399  ExprResult BuildVectorLiteral(SourceLocation LParenLoc,
2400                                SourceLocation RParenLoc, Expr *E,
2401                                TypeSourceInfo *TInfo);
2402
2403  ExprResult MaybeConvertParenListExprToParenExpr(Scope *S, Expr *ME);
2404
2405  ExprResult ActOnCompoundLiteral(SourceLocation LParenLoc,
2406                                  ParsedType Ty,
2407                                  SourceLocation RParenLoc,
2408                                  Expr *Op);
2409
2410  ExprResult BuildCompoundLiteralExpr(SourceLocation LParenLoc,
2411                                      TypeSourceInfo *TInfo,
2412                                      SourceLocation RParenLoc,
2413                                      Expr *InitExpr);
2414
2415  ExprResult ActOnInitList(SourceLocation LParenLoc,
2416                           MultiExprArg InitList,
2417                           SourceLocation RParenLoc);
2418
2419  ExprResult ActOnDesignatedInitializer(Designation &Desig,
2420                                        SourceLocation Loc,
2421                                        bool GNUSyntax,
2422                                        ExprResult Init);
2423
2424  ExprResult ActOnBinOp(Scope *S, SourceLocation TokLoc,
2425                        tok::TokenKind Kind, Expr *LHS, Expr *RHS);
2426  ExprResult BuildBinOp(Scope *S, SourceLocation OpLoc,
2427                        BinaryOperatorKind Opc, Expr *lhs, Expr *rhs);
2428  ExprResult CreateBuiltinBinOp(SourceLocation TokLoc,
2429                                BinaryOperatorKind Opc, Expr *lhs, Expr *rhs);
2430
2431  /// ActOnConditionalOp - Parse a ?: operation.  Note that 'LHS' may be null
2432  /// in the case of a the GNU conditional expr extension.
2433  ExprResult ActOnConditionalOp(SourceLocation QuestionLoc,
2434                                SourceLocation ColonLoc,
2435                                Expr *Cond, Expr *LHS, Expr *RHS);
2436
2437  /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
2438  ExprResult ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
2439                            LabelDecl *LD);
2440
2441  ExprResult ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
2442                           SourceLocation RPLoc); // "({..})"
2443
2444  // __builtin_offsetof(type, identifier(.identifier|[expr])*)
2445  struct OffsetOfComponent {
2446    SourceLocation LocStart, LocEnd;
2447    bool isBrackets;  // true if [expr], false if .ident
2448    union {
2449      IdentifierInfo *IdentInfo;
2450      ExprTy *E;
2451    } U;
2452  };
2453
2454  /// __builtin_offsetof(type, a.b[123][456].c)
2455  ExprResult BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
2456                                  TypeSourceInfo *TInfo,
2457                                  OffsetOfComponent *CompPtr,
2458                                  unsigned NumComponents,
2459                                  SourceLocation RParenLoc);
2460  ExprResult ActOnBuiltinOffsetOf(Scope *S,
2461                                  SourceLocation BuiltinLoc,
2462                                  SourceLocation TypeLoc,
2463                                  ParsedType Arg1,
2464                                  OffsetOfComponent *CompPtr,
2465                                  unsigned NumComponents,
2466                                  SourceLocation RParenLoc);
2467
2468  // __builtin_choose_expr(constExpr, expr1, expr2)
2469  ExprResult ActOnChooseExpr(SourceLocation BuiltinLoc,
2470                             Expr *cond, Expr *expr1,
2471                             Expr *expr2, SourceLocation RPLoc);
2472
2473  // __builtin_va_arg(expr, type)
2474  ExprResult ActOnVAArg(SourceLocation BuiltinLoc,
2475                        Expr *expr, ParsedType type,
2476                        SourceLocation RPLoc);
2477  ExprResult BuildVAArgExpr(SourceLocation BuiltinLoc,
2478                            Expr *expr, TypeSourceInfo *TInfo,
2479                            SourceLocation RPLoc);
2480
2481  // __null
2482  ExprResult ActOnGNUNullExpr(SourceLocation TokenLoc);
2483
2484  bool CheckCaseExpression(Expr *expr);
2485
2486  bool CheckMicrosoftIfExistsSymbol(CXXScopeSpec &SS, UnqualifiedId &Name);
2487
2488  //===------------------------- "Block" Extension ------------------------===//
2489
2490  /// ActOnBlockStart - This callback is invoked when a block literal is
2491  /// started.
2492  void ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope);
2493
2494  /// ActOnBlockArguments - This callback allows processing of block arguments.
2495  /// If there are no arguments, this is still invoked.
2496  void ActOnBlockArguments(Declarator &ParamInfo, Scope *CurScope);
2497
2498  /// ActOnBlockError - If there is an error parsing a block, this callback
2499  /// is invoked to pop the information about the block from the action impl.
2500  void ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope);
2501
2502  /// ActOnBlockStmtExpr - This is called when the body of a block statement
2503  /// literal was successfully completed.  ^(int x){...}
2504  ExprResult ActOnBlockStmtExpr(SourceLocation CaretLoc,
2505                                        Stmt *Body, Scope *CurScope);
2506
2507  //===---------------------------- OpenCL Features -----------------------===//
2508
2509  /// __builtin_astype(...)
2510  ExprResult ActOnAsTypeExpr(Expr *expr, ParsedType DestTy,
2511                             SourceLocation BuiltinLoc,
2512                             SourceLocation RParenLoc);
2513
2514  //===---------------------------- C++ Features --------------------------===//
2515
2516  // Act on C++ namespaces
2517  Decl *ActOnStartNamespaceDef(Scope *S, SourceLocation InlineLoc,
2518                               SourceLocation NamespaceLoc,
2519                               SourceLocation IdentLoc,
2520                               IdentifierInfo *Ident,
2521                               SourceLocation LBrace,
2522                               AttributeList *AttrList);
2523  void ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace);
2524
2525  NamespaceDecl *getStdNamespace() const;
2526  NamespaceDecl *getOrCreateStdNamespace();
2527
2528  CXXRecordDecl *getStdBadAlloc() const;
2529
2530  Decl *ActOnUsingDirective(Scope *CurScope,
2531                            SourceLocation UsingLoc,
2532                            SourceLocation NamespcLoc,
2533                            CXXScopeSpec &SS,
2534                            SourceLocation IdentLoc,
2535                            IdentifierInfo *NamespcName,
2536                            AttributeList *AttrList);
2537
2538  void PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir);
2539
2540  Decl *ActOnNamespaceAliasDef(Scope *CurScope,
2541                               SourceLocation NamespaceLoc,
2542                               SourceLocation AliasLoc,
2543                               IdentifierInfo *Alias,
2544                               CXXScopeSpec &SS,
2545                               SourceLocation IdentLoc,
2546                               IdentifierInfo *Ident);
2547
2548  void HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow);
2549  bool CheckUsingShadowDecl(UsingDecl *UD, NamedDecl *Target,
2550                            const LookupResult &PreviousDecls);
2551  UsingShadowDecl *BuildUsingShadowDecl(Scope *S, UsingDecl *UD,
2552                                        NamedDecl *Target);
2553
2554  bool CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
2555                                   bool isTypeName,
2556                                   const CXXScopeSpec &SS,
2557                                   SourceLocation NameLoc,
2558                                   const LookupResult &Previous);
2559  bool CheckUsingDeclQualifier(SourceLocation UsingLoc,
2560                               const CXXScopeSpec &SS,
2561                               SourceLocation NameLoc);
2562
2563  NamedDecl *BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
2564                                   SourceLocation UsingLoc,
2565                                   CXXScopeSpec &SS,
2566                                   const DeclarationNameInfo &NameInfo,
2567                                   AttributeList *AttrList,
2568                                   bool IsInstantiation,
2569                                   bool IsTypeName,
2570                                   SourceLocation TypenameLoc);
2571
2572  bool CheckInheritedConstructorUsingDecl(UsingDecl *UD);
2573
2574  Decl *ActOnUsingDeclaration(Scope *CurScope,
2575                              AccessSpecifier AS,
2576                              bool HasUsingKeyword,
2577                              SourceLocation UsingLoc,
2578                              CXXScopeSpec &SS,
2579                              UnqualifiedId &Name,
2580                              AttributeList *AttrList,
2581                              bool IsTypeName,
2582                              SourceLocation TypenameLoc);
2583  Decl *ActOnAliasDeclaration(Scope *CurScope,
2584                              AccessSpecifier AS,
2585                              MultiTemplateParamsArg TemplateParams,
2586                              SourceLocation UsingLoc,
2587                              UnqualifiedId &Name,
2588                              TypeResult Type);
2589
2590  /// AddCXXDirectInitializerToDecl - This action is called immediately after
2591  /// ActOnDeclarator, when a C++ direct initializer is present.
2592  /// e.g: "int x(1);"
2593  void AddCXXDirectInitializerToDecl(Decl *Dcl,
2594                                     SourceLocation LParenLoc,
2595                                     MultiExprArg Exprs,
2596                                     SourceLocation RParenLoc,
2597                                     bool TypeMayContainAuto);
2598
2599  /// InitializeVarWithConstructor - Creates an CXXConstructExpr
2600  /// and sets it as the initializer for the the passed in VarDecl.
2601  bool InitializeVarWithConstructor(VarDecl *VD,
2602                                    CXXConstructorDecl *Constructor,
2603                                    MultiExprArg Exprs);
2604
2605  /// BuildCXXConstructExpr - Creates a complete call to a constructor,
2606  /// including handling of its default argument expressions.
2607  ///
2608  /// \param ConstructKind - a CXXConstructExpr::ConstructionKind
2609  ExprResult
2610  BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
2611                        CXXConstructorDecl *Constructor, MultiExprArg Exprs,
2612                        bool RequiresZeroInit, unsigned ConstructKind,
2613                        SourceRange ParenRange);
2614
2615  // FIXME: Can re remove this and have the above BuildCXXConstructExpr check if
2616  // the constructor can be elidable?
2617  ExprResult
2618  BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
2619                        CXXConstructorDecl *Constructor, bool Elidable,
2620                        MultiExprArg Exprs, bool RequiresZeroInit,
2621                        unsigned ConstructKind,
2622                        SourceRange ParenRange);
2623
2624  /// BuildCXXDefaultArgExpr - Creates a CXXDefaultArgExpr, instantiating
2625  /// the default expr if needed.
2626  ExprResult BuildCXXDefaultArgExpr(SourceLocation CallLoc,
2627                                    FunctionDecl *FD,
2628                                    ParmVarDecl *Param);
2629
2630  /// FinalizeVarWithDestructor - Prepare for calling destructor on the
2631  /// constructed variable.
2632  void FinalizeVarWithDestructor(VarDecl *VD, const RecordType *DeclInitType);
2633
2634  /// \brief Helper class that collects exception specifications for
2635  /// implicitly-declared special member functions.
2636  class ImplicitExceptionSpecification {
2637    // Pointer to allow copying
2638    ASTContext *Context;
2639    // We order exception specifications thus:
2640    // noexcept is the most restrictive, but is only used in C++0x.
2641    // throw() comes next.
2642    // Then a throw(collected exceptions)
2643    // Finally no specification.
2644    // throw(...) is used instead if any called function uses it.
2645    //
2646    // If this exception specification cannot be known yet (for instance,
2647    // because this is the exception specification for a defaulted default
2648    // constructor and we haven't finished parsing the deferred parts of the
2649    // class yet), the C++0x standard does not specify how to behave. We
2650    // record this as an 'unknown' exception specification, which overrules
2651    // any other specification (even 'none', to keep this rule simple).
2652    ExceptionSpecificationType ComputedEST;
2653    llvm::SmallPtrSet<CanQualType, 4> ExceptionsSeen;
2654    SmallVector<QualType, 4> Exceptions;
2655
2656    void ClearExceptions() {
2657      ExceptionsSeen.clear();
2658      Exceptions.clear();
2659    }
2660
2661  public:
2662    explicit ImplicitExceptionSpecification(ASTContext &Context)
2663      : Context(&Context), ComputedEST(EST_BasicNoexcept) {
2664      if (!Context.getLangOptions().CPlusPlus0x)
2665        ComputedEST = EST_DynamicNone;
2666    }
2667
2668    /// \brief Get the computed exception specification type.
2669    ExceptionSpecificationType getExceptionSpecType() const {
2670      assert(ComputedEST != EST_ComputedNoexcept &&
2671             "noexcept(expr) should not be a possible result");
2672      return ComputedEST;
2673    }
2674
2675    /// \brief The number of exceptions in the exception specification.
2676    unsigned size() const { return Exceptions.size(); }
2677
2678    /// \brief The set of exceptions in the exception specification.
2679    const QualType *data() const { return Exceptions.data(); }
2680
2681    /// \brief Integrate another called method into the collected data.
2682    void CalledDecl(CXXMethodDecl *Method);
2683
2684    /// \brief Integrate an invoked expression into the collected data.
2685    void CalledExpr(Expr *E);
2686
2687    /// \brief Specify that the exception specification can't be detemined yet.
2688    void SetDelayed() {
2689      ClearExceptions();
2690      ComputedEST = EST_Delayed;
2691    }
2692
2693    FunctionProtoType::ExtProtoInfo getEPI() const {
2694      FunctionProtoType::ExtProtoInfo EPI;
2695      EPI.ExceptionSpecType = getExceptionSpecType();
2696      EPI.NumExceptions = size();
2697      EPI.Exceptions = data();
2698      return EPI;
2699    }
2700  };
2701
2702  /// \brief Determine what sort of exception specification a defaulted
2703  /// copy constructor of a class will have.
2704  ImplicitExceptionSpecification
2705  ComputeDefaultedDefaultCtorExceptionSpec(CXXRecordDecl *ClassDecl);
2706
2707  /// \brief Determine what sort of exception specification a defaulted
2708  /// default constructor of a class will have, and whether the parameter
2709  /// will be const.
2710  std::pair<ImplicitExceptionSpecification, bool>
2711  ComputeDefaultedCopyCtorExceptionSpecAndConst(CXXRecordDecl *ClassDecl);
2712
2713  /// \brief Determine what sort of exception specification a defautled
2714  /// copy assignment operator of a class will have, and whether the
2715  /// parameter will be const.
2716  std::pair<ImplicitExceptionSpecification, bool>
2717  ComputeDefaultedCopyAssignmentExceptionSpecAndConst(CXXRecordDecl *ClassDecl);
2718
2719  /// \brief Determine what sort of exception specification a defaulted
2720  /// destructor of a class will have.
2721  ImplicitExceptionSpecification
2722  ComputeDefaultedDtorExceptionSpec(CXXRecordDecl *ClassDecl);
2723
2724  /// \brief Determine if a defaulted default constructor ought to be
2725  /// deleted.
2726  bool ShouldDeleteDefaultConstructor(CXXConstructorDecl *CD);
2727
2728  /// \brief Determine if a defaulted copy constructor ought to be
2729  /// deleted.
2730  bool ShouldDeleteCopyConstructor(CXXConstructorDecl *CD);
2731
2732  /// \brief Determine if a defaulted copy assignment operator ought to be
2733  /// deleted.
2734  bool ShouldDeleteCopyAssignmentOperator(CXXMethodDecl *MD);
2735
2736  /// \brief Determine if a defaulted destructor ought to be deleted.
2737  bool ShouldDeleteDestructor(CXXDestructorDecl *DD);
2738
2739  /// \brief Declare the implicit default constructor for the given class.
2740  ///
2741  /// \param ClassDecl The class declaration into which the implicit
2742  /// default constructor will be added.
2743  ///
2744  /// \returns The implicitly-declared default constructor.
2745  CXXConstructorDecl *DeclareImplicitDefaultConstructor(
2746                                                     CXXRecordDecl *ClassDecl);
2747
2748  /// DefineImplicitDefaultConstructor - Checks for feasibility of
2749  /// defining this constructor as the default constructor.
2750  void DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
2751                                        CXXConstructorDecl *Constructor);
2752
2753  /// \brief Declare the implicit destructor for the given class.
2754  ///
2755  /// \param ClassDecl The class declaration into which the implicit
2756  /// destructor will be added.
2757  ///
2758  /// \returns The implicitly-declared destructor.
2759  CXXDestructorDecl *DeclareImplicitDestructor(CXXRecordDecl *ClassDecl);
2760
2761  /// DefineImplicitDestructor - Checks for feasibility of
2762  /// defining this destructor as the default destructor.
2763  void DefineImplicitDestructor(SourceLocation CurrentLocation,
2764                                CXXDestructorDecl *Destructor);
2765
2766  /// \brief Build an exception spec for destructors that don't have one.
2767  ///
2768  /// C++11 says that user-defined destructors with no exception spec get one
2769  /// that looks as if the destructor was implicitly declared.
2770  void AdjustDestructorExceptionSpec(CXXRecordDecl *ClassDecl,
2771                                     CXXDestructorDecl *Destructor);
2772
2773  /// \brief Declare all inherited constructors for the given class.
2774  ///
2775  /// \param ClassDecl The class declaration into which the inherited
2776  /// constructors will be added.
2777  void DeclareInheritedConstructors(CXXRecordDecl *ClassDecl);
2778
2779  /// \brief Declare the implicit copy constructor for the given class.
2780  ///
2781  /// \param S The scope of the class, which may be NULL if this is a
2782  /// template instantiation.
2783  ///
2784  /// \param ClassDecl The class declaration into which the implicit
2785  /// copy constructor will be added.
2786  ///
2787  /// \returns The implicitly-declared copy constructor.
2788  CXXConstructorDecl *DeclareImplicitCopyConstructor(CXXRecordDecl *ClassDecl);
2789
2790  /// DefineImplicitCopyConstructor - Checks for feasibility of
2791  /// defining this constructor as the copy constructor.
2792  void DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
2793                                     CXXConstructorDecl *Constructor);
2794
2795  /// \brief Declare the implicit copy assignment operator for the given class.
2796  ///
2797  /// \param S The scope of the class, which may be NULL if this is a
2798  /// template instantiation.
2799  ///
2800  /// \param ClassDecl The class declaration into which the implicit
2801  /// copy-assignment operator will be added.
2802  ///
2803  /// \returns The implicitly-declared copy assignment operator.
2804  CXXMethodDecl *DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl);
2805
2806  /// \brief Defined an implicitly-declared copy assignment operator.
2807  void DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
2808                                    CXXMethodDecl *MethodDecl);
2809
2810  /// \brief Force the declaration of any implicitly-declared members of this
2811  /// class.
2812  void ForceDeclarationOfImplicitMembers(CXXRecordDecl *Class);
2813
2814  /// MaybeBindToTemporary - If the passed in expression has a record type with
2815  /// a non-trivial destructor, this will return CXXBindTemporaryExpr. Otherwise
2816  /// it simply returns the passed in expression.
2817  ExprResult MaybeBindToTemporary(Expr *E);
2818
2819  bool CompleteConstructorCall(CXXConstructorDecl *Constructor,
2820                               MultiExprArg ArgsPtr,
2821                               SourceLocation Loc,
2822                               ASTOwningVector<Expr*> &ConvertedArgs);
2823
2824  ParsedType getDestructorName(SourceLocation TildeLoc,
2825                               IdentifierInfo &II, SourceLocation NameLoc,
2826                               Scope *S, CXXScopeSpec &SS,
2827                               ParsedType ObjectType,
2828                               bool EnteringContext);
2829
2830  // Checks that reinterpret casts don't have undefined behavior.
2831  void CheckCompatibleReinterpretCast(QualType SrcType, QualType DestType,
2832                                      bool IsDereference, SourceRange Range);
2833
2834  /// ActOnCXXNamedCast - Parse {dynamic,static,reinterpret,const}_cast's.
2835  ExprResult ActOnCXXNamedCast(SourceLocation OpLoc,
2836                               tok::TokenKind Kind,
2837                               SourceLocation LAngleBracketLoc,
2838                               Declarator &D,
2839                               SourceLocation RAngleBracketLoc,
2840                               SourceLocation LParenLoc,
2841                               Expr *E,
2842                               SourceLocation RParenLoc);
2843
2844  ExprResult BuildCXXNamedCast(SourceLocation OpLoc,
2845                               tok::TokenKind Kind,
2846                               TypeSourceInfo *Ty,
2847                               Expr *E,
2848                               SourceRange AngleBrackets,
2849                               SourceRange Parens);
2850
2851  ExprResult BuildCXXTypeId(QualType TypeInfoType,
2852                            SourceLocation TypeidLoc,
2853                            TypeSourceInfo *Operand,
2854                            SourceLocation RParenLoc);
2855  ExprResult BuildCXXTypeId(QualType TypeInfoType,
2856                            SourceLocation TypeidLoc,
2857                            Expr *Operand,
2858                            SourceLocation RParenLoc);
2859
2860  /// ActOnCXXTypeid - Parse typeid( something ).
2861  ExprResult ActOnCXXTypeid(SourceLocation OpLoc,
2862                            SourceLocation LParenLoc, bool isType,
2863                            void *TyOrExpr,
2864                            SourceLocation RParenLoc);
2865
2866  ExprResult BuildCXXUuidof(QualType TypeInfoType,
2867                            SourceLocation TypeidLoc,
2868                            TypeSourceInfo *Operand,
2869                            SourceLocation RParenLoc);
2870  ExprResult BuildCXXUuidof(QualType TypeInfoType,
2871                            SourceLocation TypeidLoc,
2872                            Expr *Operand,
2873                            SourceLocation RParenLoc);
2874
2875  /// ActOnCXXUuidof - Parse __uuidof( something ).
2876  ExprResult ActOnCXXUuidof(SourceLocation OpLoc,
2877                            SourceLocation LParenLoc, bool isType,
2878                            void *TyOrExpr,
2879                            SourceLocation RParenLoc);
2880
2881
2882  //// ActOnCXXThis -  Parse 'this' pointer.
2883  ExprResult ActOnCXXThis(SourceLocation loc);
2884
2885  /// getAndCaptureCurrentThisType - Try to capture a 'this' pointer.  Returns
2886  /// the type of the 'this' pointer, or a null type if this is not possible.
2887  QualType getAndCaptureCurrentThisType();
2888
2889  /// ActOnCXXBoolLiteral - Parse {true,false} literals.
2890  ExprResult ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind);
2891
2892  /// ActOnCXXNullPtrLiteral - Parse 'nullptr'.
2893  ExprResult ActOnCXXNullPtrLiteral(SourceLocation Loc);
2894
2895  //// ActOnCXXThrow -  Parse throw expressions.
2896  ExprResult ActOnCXXThrow(Scope *S, SourceLocation OpLoc, Expr *expr);
2897  ExprResult BuildCXXThrow(SourceLocation OpLoc, Expr *Ex,
2898                           bool IsThrownVarInScope);
2899  ExprResult CheckCXXThrowOperand(SourceLocation ThrowLoc, Expr *E,
2900                                  bool IsThrownVarInScope);
2901
2902  /// ActOnCXXTypeConstructExpr - Parse construction of a specified type.
2903  /// Can be interpreted either as function-style casting ("int(x)")
2904  /// or class type construction ("ClassType(x,y,z)")
2905  /// or creation of a value-initialized type ("int()").
2906  ExprResult ActOnCXXTypeConstructExpr(ParsedType TypeRep,
2907                                       SourceLocation LParenLoc,
2908                                       MultiExprArg Exprs,
2909                                       SourceLocation RParenLoc);
2910
2911  ExprResult BuildCXXTypeConstructExpr(TypeSourceInfo *Type,
2912                                       SourceLocation LParenLoc,
2913                                       MultiExprArg Exprs,
2914                                       SourceLocation RParenLoc);
2915
2916  /// ActOnCXXNew - Parsed a C++ 'new' expression.
2917  ExprResult ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
2918                         SourceLocation PlacementLParen,
2919                         MultiExprArg PlacementArgs,
2920                         SourceLocation PlacementRParen,
2921                         SourceRange TypeIdParens, Declarator &D,
2922                         SourceLocation ConstructorLParen,
2923                         MultiExprArg ConstructorArgs,
2924                         SourceLocation ConstructorRParen);
2925  ExprResult BuildCXXNew(SourceLocation StartLoc, bool UseGlobal,
2926                         SourceLocation PlacementLParen,
2927                         MultiExprArg PlacementArgs,
2928                         SourceLocation PlacementRParen,
2929                         SourceRange TypeIdParens,
2930                         QualType AllocType,
2931                         TypeSourceInfo *AllocTypeInfo,
2932                         Expr *ArraySize,
2933                         SourceLocation ConstructorLParen,
2934                         MultiExprArg ConstructorArgs,
2935                         SourceLocation ConstructorRParen,
2936                         bool TypeMayContainAuto = true);
2937
2938  bool CheckAllocatedType(QualType AllocType, SourceLocation Loc,
2939                          SourceRange R);
2940  bool FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,
2941                               bool UseGlobal, QualType AllocType, bool IsArray,
2942                               Expr **PlaceArgs, unsigned NumPlaceArgs,
2943                               FunctionDecl *&OperatorNew,
2944                               FunctionDecl *&OperatorDelete);
2945  bool FindAllocationOverload(SourceLocation StartLoc, SourceRange Range,
2946                              DeclarationName Name, Expr** Args,
2947                              unsigned NumArgs, DeclContext *Ctx,
2948                              bool AllowMissing, FunctionDecl *&Operator,
2949                              bool Diagnose = true);
2950  void DeclareGlobalNewDelete();
2951  void DeclareGlobalAllocationFunction(DeclarationName Name, QualType Return,
2952                                       QualType Argument,
2953                                       bool addMallocAttr = false);
2954
2955  bool FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD,
2956                                DeclarationName Name, FunctionDecl* &Operator,
2957                                bool Diagnose = true);
2958
2959  /// ActOnCXXDelete - Parsed a C++ 'delete' expression
2960  ExprResult ActOnCXXDelete(SourceLocation StartLoc,
2961                            bool UseGlobal, bool ArrayForm,
2962                            Expr *Operand);
2963
2964  DeclResult ActOnCXXConditionDeclaration(Scope *S, Declarator &D);
2965  ExprResult CheckConditionVariable(VarDecl *ConditionVar,
2966                                    SourceLocation StmtLoc,
2967                                    bool ConvertToBoolean);
2968
2969  ExprResult ActOnNoexceptExpr(SourceLocation KeyLoc, SourceLocation LParen,
2970                               Expr *Operand, SourceLocation RParen);
2971  ExprResult BuildCXXNoexceptExpr(SourceLocation KeyLoc, Expr *Operand,
2972                                  SourceLocation RParen);
2973
2974  /// ActOnUnaryTypeTrait - Parsed one of the unary type trait support
2975  /// pseudo-functions.
2976  ExprResult ActOnUnaryTypeTrait(UnaryTypeTrait OTT,
2977                                 SourceLocation KWLoc,
2978                                 ParsedType Ty,
2979                                 SourceLocation RParen);
2980
2981  ExprResult BuildUnaryTypeTrait(UnaryTypeTrait OTT,
2982                                 SourceLocation KWLoc,
2983                                 TypeSourceInfo *T,
2984                                 SourceLocation RParen);
2985
2986  /// ActOnBinaryTypeTrait - Parsed one of the bianry type trait support
2987  /// pseudo-functions.
2988  ExprResult ActOnBinaryTypeTrait(BinaryTypeTrait OTT,
2989                                  SourceLocation KWLoc,
2990                                  ParsedType LhsTy,
2991                                  ParsedType RhsTy,
2992                                  SourceLocation RParen);
2993
2994  ExprResult BuildBinaryTypeTrait(BinaryTypeTrait BTT,
2995                                  SourceLocation KWLoc,
2996                                  TypeSourceInfo *LhsT,
2997                                  TypeSourceInfo *RhsT,
2998                                  SourceLocation RParen);
2999
3000  /// ActOnArrayTypeTrait - Parsed one of the bianry type trait support
3001  /// pseudo-functions.
3002  ExprResult ActOnArrayTypeTrait(ArrayTypeTrait ATT,
3003                                 SourceLocation KWLoc,
3004                                 ParsedType LhsTy,
3005                                 Expr *DimExpr,
3006                                 SourceLocation RParen);
3007
3008  ExprResult BuildArrayTypeTrait(ArrayTypeTrait ATT,
3009                                 SourceLocation KWLoc,
3010                                 TypeSourceInfo *TSInfo,
3011                                 Expr *DimExpr,
3012                                 SourceLocation RParen);
3013
3014  /// ActOnExpressionTrait - Parsed one of the unary type trait support
3015  /// pseudo-functions.
3016  ExprResult ActOnExpressionTrait(ExpressionTrait OET,
3017                                  SourceLocation KWLoc,
3018                                  Expr *Queried,
3019                                  SourceLocation RParen);
3020
3021  ExprResult BuildExpressionTrait(ExpressionTrait OET,
3022                                  SourceLocation KWLoc,
3023                                  Expr *Queried,
3024                                  SourceLocation RParen);
3025
3026  ExprResult ActOnStartCXXMemberReference(Scope *S,
3027                                          Expr *Base,
3028                                          SourceLocation OpLoc,
3029                                          tok::TokenKind OpKind,
3030                                          ParsedType &ObjectType,
3031                                          bool &MayBePseudoDestructor);
3032
3033  ExprResult DiagnoseDtorReference(SourceLocation NameLoc, Expr *MemExpr);
3034
3035  ExprResult BuildPseudoDestructorExpr(Expr *Base,
3036                                       SourceLocation OpLoc,
3037                                       tok::TokenKind OpKind,
3038                                       const CXXScopeSpec &SS,
3039                                       TypeSourceInfo *ScopeType,
3040                                       SourceLocation CCLoc,
3041                                       SourceLocation TildeLoc,
3042                                     PseudoDestructorTypeStorage DestroyedType,
3043                                       bool HasTrailingLParen);
3044
3045  ExprResult ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
3046                                       SourceLocation OpLoc,
3047                                       tok::TokenKind OpKind,
3048                                       CXXScopeSpec &SS,
3049                                       UnqualifiedId &FirstTypeName,
3050                                       SourceLocation CCLoc,
3051                                       SourceLocation TildeLoc,
3052                                       UnqualifiedId &SecondTypeName,
3053                                       bool HasTrailingLParen);
3054
3055  /// MaybeCreateExprWithCleanups - If the current full-expression
3056  /// requires any cleanups, surround it with a ExprWithCleanups node.
3057  /// Otherwise, just returns the passed-in expression.
3058  Expr *MaybeCreateExprWithCleanups(Expr *SubExpr);
3059  Stmt *MaybeCreateStmtWithCleanups(Stmt *SubStmt);
3060  ExprResult MaybeCreateExprWithCleanups(ExprResult SubExpr);
3061
3062  ExprResult ActOnFinishFullExpr(Expr *Expr);
3063  StmtResult ActOnFinishFullStmt(Stmt *Stmt);
3064
3065  // Marks SS invalid if it represents an incomplete type.
3066  bool RequireCompleteDeclContext(CXXScopeSpec &SS, DeclContext *DC);
3067
3068  DeclContext *computeDeclContext(QualType T);
3069  DeclContext *computeDeclContext(const CXXScopeSpec &SS,
3070                                  bool EnteringContext = false);
3071  bool isDependentScopeSpecifier(const CXXScopeSpec &SS);
3072  CXXRecordDecl *getCurrentInstantiationOf(NestedNameSpecifier *NNS);
3073  bool isUnknownSpecialization(const CXXScopeSpec &SS);
3074
3075  /// \brief The parser has parsed a global nested-name-specifier '::'.
3076  ///
3077  /// \param S The scope in which this nested-name-specifier occurs.
3078  ///
3079  /// \param CCLoc The location of the '::'.
3080  ///
3081  /// \param SS The nested-name-specifier, which will be updated in-place
3082  /// to reflect the parsed nested-name-specifier.
3083  ///
3084  /// \returns true if an error occurred, false otherwise.
3085  bool ActOnCXXGlobalScopeSpecifier(Scope *S, SourceLocation CCLoc,
3086                                    CXXScopeSpec &SS);
3087
3088  bool isAcceptableNestedNameSpecifier(NamedDecl *SD);
3089  NamedDecl *FindFirstQualifierInScope(Scope *S, NestedNameSpecifier *NNS);
3090
3091  bool isNonTypeNestedNameSpecifier(Scope *S, CXXScopeSpec &SS,
3092                                    SourceLocation IdLoc,
3093                                    IdentifierInfo &II,
3094                                    ParsedType ObjectType);
3095
3096  bool BuildCXXNestedNameSpecifier(Scope *S,
3097                                   IdentifierInfo &Identifier,
3098                                   SourceLocation IdentifierLoc,
3099                                   SourceLocation CCLoc,
3100                                   QualType ObjectType,
3101                                   bool EnteringContext,
3102                                   CXXScopeSpec &SS,
3103                                   NamedDecl *ScopeLookupResult,
3104                                   bool ErrorRecoveryLookup);
3105
3106  /// \brief The parser has parsed a nested-name-specifier 'identifier::'.
3107  ///
3108  /// \param S The scope in which this nested-name-specifier occurs.
3109  ///
3110  /// \param Identifier The identifier preceding the '::'.
3111  ///
3112  /// \param IdentifierLoc The location of the identifier.
3113  ///
3114  /// \param CCLoc The location of the '::'.
3115  ///
3116  /// \param ObjectType The type of the object, if we're parsing
3117  /// nested-name-specifier in a member access expression.
3118  ///
3119  /// \param EnteringContext Whether we're entering the context nominated by
3120  /// this nested-name-specifier.
3121  ///
3122  /// \param SS The nested-name-specifier, which is both an input
3123  /// parameter (the nested-name-specifier before this type) and an
3124  /// output parameter (containing the full nested-name-specifier,
3125  /// including this new type).
3126  ///
3127  /// \returns true if an error occurred, false otherwise.
3128  bool ActOnCXXNestedNameSpecifier(Scope *S,
3129                                   IdentifierInfo &Identifier,
3130                                   SourceLocation IdentifierLoc,
3131                                   SourceLocation CCLoc,
3132                                   ParsedType ObjectType,
3133                                   bool EnteringContext,
3134                                   CXXScopeSpec &SS);
3135
3136  bool IsInvalidUnlessNestedName(Scope *S, CXXScopeSpec &SS,
3137                                 IdentifierInfo &Identifier,
3138                                 SourceLocation IdentifierLoc,
3139                                 SourceLocation ColonLoc,
3140                                 ParsedType ObjectType,
3141                                 bool EnteringContext);
3142
3143  /// \brief The parser has parsed a nested-name-specifier
3144  /// 'template[opt] template-name < template-args >::'.
3145  ///
3146  /// \param S The scope in which this nested-name-specifier occurs.
3147  ///
3148  /// \param TemplateLoc The location of the 'template' keyword, if any.
3149  ///
3150  /// \param SS The nested-name-specifier, which is both an input
3151  /// parameter (the nested-name-specifier before this type) and an
3152  /// output parameter (containing the full nested-name-specifier,
3153  /// including this new type).
3154  ///
3155  /// \param TemplateLoc the location of the 'template' keyword, if any.
3156  /// \param TemplateName The template name.
3157  /// \param TemplateNameLoc The location of the template name.
3158  /// \param LAngleLoc The location of the opening angle bracket  ('<').
3159  /// \param TemplateArgs The template arguments.
3160  /// \param RAngleLoc The location of the closing angle bracket  ('>').
3161  /// \param CCLoc The location of the '::'.
3162
3163  /// \param EnteringContext Whether we're entering the context of the
3164  /// nested-name-specifier.
3165  ///
3166  ///
3167  /// \returns true if an error occurred, false otherwise.
3168  bool ActOnCXXNestedNameSpecifier(Scope *S,
3169                                   SourceLocation TemplateLoc,
3170                                   CXXScopeSpec &SS,
3171                                   TemplateTy Template,
3172                                   SourceLocation TemplateNameLoc,
3173                                   SourceLocation LAngleLoc,
3174                                   ASTTemplateArgsPtr TemplateArgs,
3175                                   SourceLocation RAngleLoc,
3176                                   SourceLocation CCLoc,
3177                                   bool EnteringContext);
3178
3179  /// \brief Given a C++ nested-name-specifier, produce an annotation value
3180  /// that the parser can use later to reconstruct the given
3181  /// nested-name-specifier.
3182  ///
3183  /// \param SS A nested-name-specifier.
3184  ///
3185  /// \returns A pointer containing all of the information in the
3186  /// nested-name-specifier \p SS.
3187  void *SaveNestedNameSpecifierAnnotation(CXXScopeSpec &SS);
3188
3189  /// \brief Given an annotation pointer for a nested-name-specifier, restore
3190  /// the nested-name-specifier structure.
3191  ///
3192  /// \param Annotation The annotation pointer, produced by
3193  /// \c SaveNestedNameSpecifierAnnotation().
3194  ///
3195  /// \param AnnotationRange The source range corresponding to the annotation.
3196  ///
3197  /// \param SS The nested-name-specifier that will be updated with the contents
3198  /// of the annotation pointer.
3199  void RestoreNestedNameSpecifierAnnotation(void *Annotation,
3200                                            SourceRange AnnotationRange,
3201                                            CXXScopeSpec &SS);
3202
3203  bool ShouldEnterDeclaratorScope(Scope *S, const CXXScopeSpec &SS);
3204
3205  /// ActOnCXXEnterDeclaratorScope - Called when a C++ scope specifier (global
3206  /// scope or nested-name-specifier) is parsed, part of a declarator-id.
3207  /// After this method is called, according to [C++ 3.4.3p3], names should be
3208  /// looked up in the declarator-id's scope, until the declarator is parsed and
3209  /// ActOnCXXExitDeclaratorScope is called.
3210  /// The 'SS' should be a non-empty valid CXXScopeSpec.
3211  bool ActOnCXXEnterDeclaratorScope(Scope *S, CXXScopeSpec &SS);
3212
3213  /// ActOnCXXExitDeclaratorScope - Called when a declarator that previously
3214  /// invoked ActOnCXXEnterDeclaratorScope(), is finished. 'SS' is the same
3215  /// CXXScopeSpec that was passed to ActOnCXXEnterDeclaratorScope as well.
3216  /// Used to indicate that names should revert to being looked up in the
3217  /// defining scope.
3218  void ActOnCXXExitDeclaratorScope(Scope *S, const CXXScopeSpec &SS);
3219
3220  /// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse an
3221  /// initializer for the declaration 'Dcl'.
3222  /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
3223  /// static data member of class X, names should be looked up in the scope of
3224  /// class X.
3225  void ActOnCXXEnterDeclInitializer(Scope *S, Decl *Dcl);
3226
3227  /// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
3228  /// initializer for the declaration 'Dcl'.
3229  void ActOnCXXExitDeclInitializer(Scope *S, Decl *Dcl);
3230
3231  // ParseObjCStringLiteral - Parse Objective-C string literals.
3232  ExprResult ParseObjCStringLiteral(SourceLocation *AtLocs,
3233                                    Expr **Strings,
3234                                    unsigned NumStrings);
3235
3236  ExprResult BuildObjCEncodeExpression(SourceLocation AtLoc,
3237                                  TypeSourceInfo *EncodedTypeInfo,
3238                                  SourceLocation RParenLoc);
3239  ExprResult BuildCXXMemberCallExpr(Expr *Exp, NamedDecl *FoundDecl,
3240                                    CXXMethodDecl *Method);
3241
3242  ExprResult ParseObjCEncodeExpression(SourceLocation AtLoc,
3243                                       SourceLocation EncodeLoc,
3244                                       SourceLocation LParenLoc,
3245                                       ParsedType Ty,
3246                                       SourceLocation RParenLoc);
3247
3248  // ParseObjCSelectorExpression - Build selector expression for @selector
3249  ExprResult ParseObjCSelectorExpression(Selector Sel,
3250                                         SourceLocation AtLoc,
3251                                         SourceLocation SelLoc,
3252                                         SourceLocation LParenLoc,
3253                                         SourceLocation RParenLoc);
3254
3255  // ParseObjCProtocolExpression - Build protocol expression for @protocol
3256  ExprResult ParseObjCProtocolExpression(IdentifierInfo * ProtocolName,
3257                                         SourceLocation AtLoc,
3258                                         SourceLocation ProtoLoc,
3259                                         SourceLocation LParenLoc,
3260                                         SourceLocation RParenLoc);
3261
3262  //===--------------------------------------------------------------------===//
3263  // C++ Declarations
3264  //
3265  Decl *ActOnStartLinkageSpecification(Scope *S,
3266                                       SourceLocation ExternLoc,
3267                                       SourceLocation LangLoc,
3268                                       StringRef Lang,
3269                                       SourceLocation LBraceLoc);
3270  Decl *ActOnFinishLinkageSpecification(Scope *S,
3271                                        Decl *LinkageSpec,
3272                                        SourceLocation RBraceLoc);
3273
3274
3275  //===--------------------------------------------------------------------===//
3276  // C++ Classes
3277  //
3278  bool isCurrentClassName(const IdentifierInfo &II, Scope *S,
3279                          const CXXScopeSpec *SS = 0);
3280
3281  Decl *ActOnAccessSpecifier(AccessSpecifier Access,
3282                             SourceLocation ASLoc,
3283                             SourceLocation ColonLoc);
3284
3285  Decl *ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS,
3286                                 Declarator &D,
3287                                 MultiTemplateParamsArg TemplateParameterLists,
3288                                 Expr *BitfieldWidth, const VirtSpecifiers &VS,
3289                                 Expr *Init, bool HasDeferredInit,
3290                                 bool IsDefinition);
3291  void ActOnCXXInClassMemberInitializer(Decl *VarDecl, SourceLocation EqualLoc,
3292                                        Expr *Init);
3293
3294  MemInitResult ActOnMemInitializer(Decl *ConstructorD,
3295                                    Scope *S,
3296                                    CXXScopeSpec &SS,
3297                                    IdentifierInfo *MemberOrBase,
3298                                    ParsedType TemplateTypeTy,
3299                                    SourceLocation IdLoc,
3300                                    SourceLocation LParenLoc,
3301                                    Expr **Args, unsigned NumArgs,
3302                                    SourceLocation RParenLoc,
3303                                    SourceLocation EllipsisLoc);
3304
3305  MemInitResult BuildMemberInitializer(ValueDecl *Member, Expr **Args,
3306                                       unsigned NumArgs, SourceLocation IdLoc,
3307                                       SourceLocation LParenLoc,
3308                                       SourceLocation RParenLoc);
3309
3310  MemInitResult BuildBaseInitializer(QualType BaseType,
3311                                     TypeSourceInfo *BaseTInfo,
3312                                     Expr **Args, unsigned NumArgs,
3313                                     SourceLocation LParenLoc,
3314                                     SourceLocation RParenLoc,
3315                                     CXXRecordDecl *ClassDecl,
3316                                     SourceLocation EllipsisLoc);
3317
3318  MemInitResult BuildDelegatingInitializer(TypeSourceInfo *TInfo,
3319                                           Expr **Args, unsigned NumArgs,
3320                                           SourceLocation BaseLoc,
3321                                           SourceLocation RParenLoc,
3322                                           SourceLocation LParenLoc,
3323                                           CXXRecordDecl *ClassDecl);
3324
3325  bool SetDelegatingInitializer(CXXConstructorDecl *Constructor,
3326                                CXXCtorInitializer *Initializer);
3327
3328  bool SetCtorInitializers(CXXConstructorDecl *Constructor,
3329                           CXXCtorInitializer **Initializers,
3330                           unsigned NumInitializers, bool AnyErrors);
3331
3332  void SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation);
3333
3334
3335  /// MarkBaseAndMemberDestructorsReferenced - Given a record decl,
3336  /// mark all the non-trivial destructors of its members and bases as
3337  /// referenced.
3338  void MarkBaseAndMemberDestructorsReferenced(SourceLocation Loc,
3339                                              CXXRecordDecl *Record);
3340
3341  /// \brief The list of classes whose vtables have been used within
3342  /// this translation unit, and the source locations at which the
3343  /// first use occurred.
3344  typedef std::pair<CXXRecordDecl*, SourceLocation> VTableUse;
3345
3346  /// \brief The list of vtables that are required but have not yet been
3347  /// materialized.
3348  SmallVector<VTableUse, 16> VTableUses;
3349
3350  /// \brief The set of classes whose vtables have been used within
3351  /// this translation unit, and a bit that will be true if the vtable is
3352  /// required to be emitted (otherwise, it should be emitted only if needed
3353  /// by code generation).
3354  llvm::DenseMap<CXXRecordDecl *, bool> VTablesUsed;
3355
3356  /// \brief A list of all of the dynamic classes in this translation
3357  /// unit.
3358  SmallVector<CXXRecordDecl *, 16> DynamicClasses;
3359
3360  /// \brief Note that the vtable for the given class was used at the
3361  /// given location.
3362  void MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
3363                      bool DefinitionRequired = false);
3364
3365  /// MarkVirtualMembersReferenced - Will mark all members of the given
3366  /// CXXRecordDecl referenced.
3367  void MarkVirtualMembersReferenced(SourceLocation Loc,
3368                                    const CXXRecordDecl *RD);
3369
3370  /// \brief Define all of the vtables that have been used in this
3371  /// translation unit and reference any virtual members used by those
3372  /// vtables.
3373  ///
3374  /// \returns true if any work was done, false otherwise.
3375  bool DefineUsedVTables();
3376
3377  void AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl);
3378
3379  void ActOnMemInitializers(Decl *ConstructorDecl,
3380                            SourceLocation ColonLoc,
3381                            MemInitTy **MemInits, unsigned NumMemInits,
3382                            bool AnyErrors);
3383
3384  void CheckCompletedCXXClass(CXXRecordDecl *Record);
3385  void ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
3386                                         Decl *TagDecl,
3387                                         SourceLocation LBrac,
3388                                         SourceLocation RBrac,
3389                                         AttributeList *AttrList);
3390
3391  void ActOnReenterTemplateScope(Scope *S, Decl *Template);
3392  void ActOnReenterDeclaratorTemplateScope(Scope *S, DeclaratorDecl *D);
3393  void ActOnStartDelayedMemberDeclarations(Scope *S, Decl *Record);
3394  void ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *Method);
3395  void ActOnDelayedCXXMethodParameter(Scope *S, Decl *Param);
3396  void ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *Record);
3397  void ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *Method);
3398  void ActOnFinishDelayedMemberInitializers(Decl *Record);
3399  void MarkAsLateParsedTemplate(FunctionDecl *FD, bool Flag = true);
3400  bool IsInsideALocalClassWithinATemplateFunction();
3401
3402  Decl *ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
3403                                     Expr *AssertExpr,
3404                                     Expr *AssertMessageExpr,
3405                                     SourceLocation RParenLoc);
3406
3407  FriendDecl *CheckFriendTypeDecl(SourceLocation FriendLoc,
3408                                  TypeSourceInfo *TSInfo);
3409  Decl *ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
3410                                MultiTemplateParamsArg TemplateParams);
3411  Decl *ActOnFriendFunctionDecl(Scope *S, Declarator &D, bool IsDefinition,
3412                                    MultiTemplateParamsArg TemplateParams);
3413
3414  QualType CheckConstructorDeclarator(Declarator &D, QualType R,
3415                                      StorageClass& SC);
3416  void CheckConstructor(CXXConstructorDecl *Constructor);
3417  QualType CheckDestructorDeclarator(Declarator &D, QualType R,
3418                                     StorageClass& SC);
3419  bool CheckDestructor(CXXDestructorDecl *Destructor);
3420  void CheckConversionDeclarator(Declarator &D, QualType &R,
3421                                 StorageClass& SC);
3422  Decl *ActOnConversionDeclarator(CXXConversionDecl *Conversion);
3423
3424  void CheckExplicitlyDefaultedMethods(CXXRecordDecl *Record);
3425  void CheckExplicitlyDefaultedDefaultConstructor(CXXConstructorDecl *Ctor);
3426  void CheckExplicitlyDefaultedCopyConstructor(CXXConstructorDecl *Ctor);
3427  void CheckExplicitlyDefaultedCopyAssignment(CXXMethodDecl *Method);
3428  void CheckExplicitlyDefaultedDestructor(CXXDestructorDecl *Dtor);
3429
3430  //===--------------------------------------------------------------------===//
3431  // C++ Derived Classes
3432  //
3433
3434  /// ActOnBaseSpecifier - Parsed a base specifier
3435  CXXBaseSpecifier *CheckBaseSpecifier(CXXRecordDecl *Class,
3436                                       SourceRange SpecifierRange,
3437                                       bool Virtual, AccessSpecifier Access,
3438                                       TypeSourceInfo *TInfo,
3439                                       SourceLocation EllipsisLoc);
3440
3441  BaseResult ActOnBaseSpecifier(Decl *classdecl,
3442                                SourceRange SpecifierRange,
3443                                bool Virtual, AccessSpecifier Access,
3444                                ParsedType basetype,
3445                                SourceLocation BaseLoc,
3446                                SourceLocation EllipsisLoc);
3447
3448  bool AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
3449                            unsigned NumBases);
3450  void ActOnBaseSpecifiers(Decl *ClassDecl, BaseTy **Bases, unsigned NumBases);
3451
3452  bool IsDerivedFrom(QualType Derived, QualType Base);
3453  bool IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths);
3454
3455  // FIXME: I don't like this name.
3456  void BuildBasePathArray(const CXXBasePaths &Paths, CXXCastPath &BasePath);
3457
3458  bool BasePathInvolvesVirtualBase(const CXXCastPath &BasePath);
3459
3460  bool CheckDerivedToBaseConversion(QualType Derived, QualType Base,
3461                                    SourceLocation Loc, SourceRange Range,
3462                                    CXXCastPath *BasePath = 0,
3463                                    bool IgnoreAccess = false);
3464  bool CheckDerivedToBaseConversion(QualType Derived, QualType Base,
3465                                    unsigned InaccessibleBaseID,
3466                                    unsigned AmbigiousBaseConvID,
3467                                    SourceLocation Loc, SourceRange Range,
3468                                    DeclarationName Name,
3469                                    CXXCastPath *BasePath);
3470
3471  std::string getAmbiguousPathsDisplayString(CXXBasePaths &Paths);
3472
3473  /// CheckOverridingFunctionReturnType - Checks whether the return types are
3474  /// covariant, according to C++ [class.virtual]p5.
3475  bool CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
3476                                         const CXXMethodDecl *Old);
3477
3478  /// CheckOverridingFunctionExceptionSpec - Checks whether the exception
3479  /// spec is a subset of base spec.
3480  bool CheckOverridingFunctionExceptionSpec(const CXXMethodDecl *New,
3481                                            const CXXMethodDecl *Old);
3482
3483  bool CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange);
3484
3485  /// CheckOverrideControl - Check C++0x override control semantics.
3486  void CheckOverrideControl(const Decl *D);
3487
3488  /// CheckForFunctionMarkedFinal - Checks whether a virtual member function
3489  /// overrides a virtual member function marked 'final', according to
3490  /// C++0x [class.virtual]p3.
3491  bool CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
3492                                              const CXXMethodDecl *Old);
3493
3494
3495  //===--------------------------------------------------------------------===//
3496  // C++ Access Control
3497  //
3498
3499  enum AccessResult {
3500    AR_accessible,
3501    AR_inaccessible,
3502    AR_dependent,
3503    AR_delayed
3504  };
3505
3506  bool SetMemberAccessSpecifier(NamedDecl *MemberDecl,
3507                                NamedDecl *PrevMemberDecl,
3508                                AccessSpecifier LexicalAS);
3509
3510  AccessResult CheckUnresolvedMemberAccess(UnresolvedMemberExpr *E,
3511                                           DeclAccessPair FoundDecl);
3512  AccessResult CheckUnresolvedLookupAccess(UnresolvedLookupExpr *E,
3513                                           DeclAccessPair FoundDecl);
3514  AccessResult CheckAllocationAccess(SourceLocation OperatorLoc,
3515                                     SourceRange PlacementRange,
3516                                     CXXRecordDecl *NamingClass,
3517                                     DeclAccessPair FoundDecl,
3518                                     bool Diagnose = true);
3519  AccessResult CheckConstructorAccess(SourceLocation Loc,
3520                                      CXXConstructorDecl *D,
3521                                      const InitializedEntity &Entity,
3522                                      AccessSpecifier Access,
3523                                      bool IsCopyBindingRefToTemp = false);
3524  AccessResult CheckConstructorAccess(SourceLocation Loc,
3525                                      CXXConstructorDecl *D,
3526                                      AccessSpecifier Access,
3527                                      PartialDiagnostic PD);
3528  AccessResult CheckDestructorAccess(SourceLocation Loc,
3529                                     CXXDestructorDecl *Dtor,
3530                                     const PartialDiagnostic &PDiag);
3531  AccessResult CheckDirectMemberAccess(SourceLocation Loc,
3532                                       NamedDecl *D,
3533                                       const PartialDiagnostic &PDiag);
3534  AccessResult CheckMemberOperatorAccess(SourceLocation Loc,
3535                                         Expr *ObjectExpr,
3536                                         Expr *ArgExpr,
3537                                         DeclAccessPair FoundDecl);
3538  AccessResult CheckAddressOfMemberAccess(Expr *OvlExpr,
3539                                          DeclAccessPair FoundDecl);
3540  AccessResult CheckBaseClassAccess(SourceLocation AccessLoc,
3541                                    QualType Base, QualType Derived,
3542                                    const CXXBasePath &Path,
3543                                    unsigned DiagID,
3544                                    bool ForceCheck = false,
3545                                    bool ForceUnprivileged = false);
3546  void CheckLookupAccess(const LookupResult &R);
3547
3548  void HandleDependentAccessCheck(const DependentDiagnostic &DD,
3549                         const MultiLevelTemplateArgumentList &TemplateArgs);
3550  void PerformDependentDiagnostics(const DeclContext *Pattern,
3551                        const MultiLevelTemplateArgumentList &TemplateArgs);
3552
3553  void HandleDelayedAccessCheck(sema::DelayedDiagnostic &DD, Decl *Ctx);
3554
3555  /// A flag to suppress access checking.
3556  bool SuppressAccessChecking;
3557
3558  /// \brief When true, access checking violations are treated as SFINAE
3559  /// failures rather than hard errors.
3560  bool AccessCheckingSFINAE;
3561
3562  void ActOnStartSuppressingAccessChecks();
3563  void ActOnStopSuppressingAccessChecks();
3564
3565  enum AbstractDiagSelID {
3566    AbstractNone = -1,
3567    AbstractReturnType,
3568    AbstractParamType,
3569    AbstractVariableType,
3570    AbstractFieldType,
3571    AbstractArrayType
3572  };
3573
3574  bool RequireNonAbstractType(SourceLocation Loc, QualType T,
3575                              const PartialDiagnostic &PD);
3576  void DiagnoseAbstractType(const CXXRecordDecl *RD);
3577
3578  bool RequireNonAbstractType(SourceLocation Loc, QualType T, unsigned DiagID,
3579                              AbstractDiagSelID SelID = AbstractNone);
3580
3581  //===--------------------------------------------------------------------===//
3582  // C++ Overloaded Operators [C++ 13.5]
3583  //
3584
3585  bool CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl);
3586
3587  bool CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl);
3588
3589  //===--------------------------------------------------------------------===//
3590  // C++ Templates [C++ 14]
3591  //
3592  void FilterAcceptableTemplateNames(LookupResult &R);
3593  bool hasAnyAcceptableTemplateNames(LookupResult &R);
3594
3595  void LookupTemplateName(LookupResult &R, Scope *S, CXXScopeSpec &SS,
3596                          QualType ObjectType, bool EnteringContext,
3597                          bool &MemberOfUnknownSpecialization);
3598
3599  TemplateNameKind isTemplateName(Scope *S,
3600                                  CXXScopeSpec &SS,
3601                                  bool hasTemplateKeyword,
3602                                  UnqualifiedId &Name,
3603                                  ParsedType ObjectType,
3604                                  bool EnteringContext,
3605                                  TemplateTy &Template,
3606                                  bool &MemberOfUnknownSpecialization);
3607
3608  bool DiagnoseUnknownTemplateName(const IdentifierInfo &II,
3609                                   SourceLocation IILoc,
3610                                   Scope *S,
3611                                   const CXXScopeSpec *SS,
3612                                   TemplateTy &SuggestedTemplate,
3613                                   TemplateNameKind &SuggestedKind);
3614
3615  bool DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl);
3616  TemplateDecl *AdjustDeclIfTemplate(Decl *&Decl);
3617
3618  Decl *ActOnTypeParameter(Scope *S, bool Typename, bool Ellipsis,
3619                           SourceLocation EllipsisLoc,
3620                           SourceLocation KeyLoc,
3621                           IdentifierInfo *ParamName,
3622                           SourceLocation ParamNameLoc,
3623                           unsigned Depth, unsigned Position,
3624                           SourceLocation EqualLoc,
3625                           ParsedType DefaultArg);
3626
3627  QualType CheckNonTypeTemplateParameterType(QualType T, SourceLocation Loc);
3628  Decl *ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
3629                                      unsigned Depth,
3630                                      unsigned Position,
3631                                      SourceLocation EqualLoc,
3632                                      Expr *DefaultArg);
3633  Decl *ActOnTemplateTemplateParameter(Scope *S,
3634                                       SourceLocation TmpLoc,
3635                                       TemplateParamsTy *Params,
3636                                       SourceLocation EllipsisLoc,
3637                                       IdentifierInfo *ParamName,
3638                                       SourceLocation ParamNameLoc,
3639                                       unsigned Depth,
3640                                       unsigned Position,
3641                                       SourceLocation EqualLoc,
3642                                       ParsedTemplateArgument DefaultArg);
3643
3644  TemplateParamsTy *
3645  ActOnTemplateParameterList(unsigned Depth,
3646                             SourceLocation ExportLoc,
3647                             SourceLocation TemplateLoc,
3648                             SourceLocation LAngleLoc,
3649                             Decl **Params, unsigned NumParams,
3650                             SourceLocation RAngleLoc);
3651
3652  /// \brief The context in which we are checking a template parameter
3653  /// list.
3654  enum TemplateParamListContext {
3655    TPC_ClassTemplate,
3656    TPC_FunctionTemplate,
3657    TPC_ClassTemplateMember,
3658    TPC_FriendFunctionTemplate,
3659    TPC_FriendFunctionTemplateDefinition,
3660    TPC_TypeAliasTemplate
3661  };
3662
3663  bool CheckTemplateParameterList(TemplateParameterList *NewParams,
3664                                  TemplateParameterList *OldParams,
3665                                  TemplateParamListContext TPC);
3666  TemplateParameterList *
3667  MatchTemplateParametersToScopeSpecifier(SourceLocation DeclStartLoc,
3668                                          SourceLocation DeclLoc,
3669                                          const CXXScopeSpec &SS,
3670                                          TemplateParameterList **ParamLists,
3671                                          unsigned NumParamLists,
3672                                          bool IsFriend,
3673                                          bool &IsExplicitSpecialization,
3674                                          bool &Invalid);
3675
3676  DeclResult CheckClassTemplate(Scope *S, unsigned TagSpec, TagUseKind TUK,
3677                                SourceLocation KWLoc, CXXScopeSpec &SS,
3678                                IdentifierInfo *Name, SourceLocation NameLoc,
3679                                AttributeList *Attr,
3680                                TemplateParameterList *TemplateParams,
3681                                AccessSpecifier AS,
3682                                unsigned NumOuterTemplateParamLists,
3683                            TemplateParameterList **OuterTemplateParamLists);
3684
3685  void translateTemplateArguments(const ASTTemplateArgsPtr &In,
3686                                  TemplateArgumentListInfo &Out);
3687
3688  void NoteAllFoundTemplates(TemplateName Name);
3689
3690  QualType CheckTemplateIdType(TemplateName Template,
3691                               SourceLocation TemplateLoc,
3692                              TemplateArgumentListInfo &TemplateArgs);
3693
3694  TypeResult
3695  ActOnTemplateIdType(CXXScopeSpec &SS,
3696                      TemplateTy Template, SourceLocation TemplateLoc,
3697                      SourceLocation LAngleLoc,
3698                      ASTTemplateArgsPtr TemplateArgs,
3699                      SourceLocation RAngleLoc);
3700
3701  /// \brief Parsed an elaborated-type-specifier that refers to a template-id,
3702  /// such as \c class T::template apply<U>.
3703  ///
3704  /// \param TUK
3705  TypeResult ActOnTagTemplateIdType(TagUseKind TUK,
3706                                    TypeSpecifierType TagSpec,
3707                                    SourceLocation TagLoc,
3708                                    CXXScopeSpec &SS,
3709                                    TemplateTy TemplateD,
3710                                    SourceLocation TemplateLoc,
3711                                    SourceLocation LAngleLoc,
3712                                    ASTTemplateArgsPtr TemplateArgsIn,
3713                                    SourceLocation RAngleLoc);
3714
3715
3716  ExprResult BuildTemplateIdExpr(const CXXScopeSpec &SS,
3717                                 LookupResult &R,
3718                                 bool RequiresADL,
3719                               const TemplateArgumentListInfo &TemplateArgs);
3720  ExprResult BuildQualifiedTemplateIdExpr(CXXScopeSpec &SS,
3721                               const DeclarationNameInfo &NameInfo,
3722                               const TemplateArgumentListInfo &TemplateArgs);
3723
3724  TemplateNameKind ActOnDependentTemplateName(Scope *S,
3725                                              SourceLocation TemplateKWLoc,
3726                                              CXXScopeSpec &SS,
3727                                              UnqualifiedId &Name,
3728                                              ParsedType ObjectType,
3729                                              bool EnteringContext,
3730                                              TemplateTy &Template);
3731
3732  DeclResult
3733  ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec, TagUseKind TUK,
3734                                   SourceLocation KWLoc,
3735                                   CXXScopeSpec &SS,
3736                                   TemplateTy Template,
3737                                   SourceLocation TemplateNameLoc,
3738                                   SourceLocation LAngleLoc,
3739                                   ASTTemplateArgsPtr TemplateArgs,
3740                                   SourceLocation RAngleLoc,
3741                                   AttributeList *Attr,
3742                                 MultiTemplateParamsArg TemplateParameterLists);
3743
3744  Decl *ActOnTemplateDeclarator(Scope *S,
3745                                MultiTemplateParamsArg TemplateParameterLists,
3746                                Declarator &D);
3747
3748  Decl *ActOnStartOfFunctionTemplateDef(Scope *FnBodyScope,
3749                                  MultiTemplateParamsArg TemplateParameterLists,
3750                                        Declarator &D);
3751
3752  bool
3753  CheckSpecializationInstantiationRedecl(SourceLocation NewLoc,
3754                                         TemplateSpecializationKind NewTSK,
3755                                         NamedDecl *PrevDecl,
3756                                         TemplateSpecializationKind PrevTSK,
3757                                         SourceLocation PrevPtOfInstantiation,
3758                                         bool &SuppressNew);
3759
3760  bool CheckDependentFunctionTemplateSpecialization(FunctionDecl *FD,
3761                    const TemplateArgumentListInfo &ExplicitTemplateArgs,
3762                                                    LookupResult &Previous);
3763
3764  bool CheckFunctionTemplateSpecialization(FunctionDecl *FD,
3765                         TemplateArgumentListInfo *ExplicitTemplateArgs,
3766                                           LookupResult &Previous);
3767  bool CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous);
3768
3769  DeclResult
3770  ActOnExplicitInstantiation(Scope *S,
3771                             SourceLocation ExternLoc,
3772                             SourceLocation TemplateLoc,
3773                             unsigned TagSpec,
3774                             SourceLocation KWLoc,
3775                             const CXXScopeSpec &SS,
3776                             TemplateTy Template,
3777                             SourceLocation TemplateNameLoc,
3778                             SourceLocation LAngleLoc,
3779                             ASTTemplateArgsPtr TemplateArgs,
3780                             SourceLocation RAngleLoc,
3781                             AttributeList *Attr);
3782
3783  DeclResult
3784  ActOnExplicitInstantiation(Scope *S,
3785                             SourceLocation ExternLoc,
3786                             SourceLocation TemplateLoc,
3787                             unsigned TagSpec,
3788                             SourceLocation KWLoc,
3789                             CXXScopeSpec &SS,
3790                             IdentifierInfo *Name,
3791                             SourceLocation NameLoc,
3792                             AttributeList *Attr);
3793
3794  DeclResult ActOnExplicitInstantiation(Scope *S,
3795                                        SourceLocation ExternLoc,
3796                                        SourceLocation TemplateLoc,
3797                                        Declarator &D);
3798
3799  TemplateArgumentLoc
3800  SubstDefaultTemplateArgumentIfAvailable(TemplateDecl *Template,
3801                                          SourceLocation TemplateLoc,
3802                                          SourceLocation RAngleLoc,
3803                                          Decl *Param,
3804                          SmallVectorImpl<TemplateArgument> &Converted);
3805
3806  /// \brief Specifies the context in which a particular template
3807  /// argument is being checked.
3808  enum CheckTemplateArgumentKind {
3809    /// \brief The template argument was specified in the code or was
3810    /// instantiated with some deduced template arguments.
3811    CTAK_Specified,
3812
3813    /// \brief The template argument was deduced via template argument
3814    /// deduction.
3815    CTAK_Deduced,
3816
3817    /// \brief The template argument was deduced from an array bound
3818    /// via template argument deduction.
3819    CTAK_DeducedFromArrayBound
3820  };
3821
3822  bool CheckTemplateArgument(NamedDecl *Param,
3823                             const TemplateArgumentLoc &Arg,
3824                             NamedDecl *Template,
3825                             SourceLocation TemplateLoc,
3826                             SourceLocation RAngleLoc,
3827                             unsigned ArgumentPackIndex,
3828                           SmallVectorImpl<TemplateArgument> &Converted,
3829                             CheckTemplateArgumentKind CTAK = CTAK_Specified);
3830
3831  /// \brief Check that the given template arguments can be be provided to
3832  /// the given template, converting the arguments along the way.
3833  ///
3834  /// \param Template The template to which the template arguments are being
3835  /// provided.
3836  ///
3837  /// \param TemplateLoc The location of the template name in the source.
3838  ///
3839  /// \param TemplateArgs The list of template arguments. If the template is
3840  /// a template template parameter, this function may extend the set of
3841  /// template arguments to also include substituted, defaulted template
3842  /// arguments.
3843  ///
3844  /// \param PartialTemplateArgs True if the list of template arguments is
3845  /// intentionally partial, e.g., because we're checking just the initial
3846  /// set of template arguments.
3847  ///
3848  /// \param Converted Will receive the converted, canonicalized template
3849  /// arguments.
3850  ///
3851  /// \returns True if an error occurred, false otherwise.
3852  bool CheckTemplateArgumentList(TemplateDecl *Template,
3853                                 SourceLocation TemplateLoc,
3854                                 TemplateArgumentListInfo &TemplateArgs,
3855                                 bool PartialTemplateArgs,
3856                           SmallVectorImpl<TemplateArgument> &Converted);
3857
3858  bool CheckTemplateTypeArgument(TemplateTypeParmDecl *Param,
3859                                 const TemplateArgumentLoc &Arg,
3860                           SmallVectorImpl<TemplateArgument> &Converted);
3861
3862  bool CheckTemplateArgument(TemplateTypeParmDecl *Param,
3863                             TypeSourceInfo *Arg);
3864  bool CheckTemplateArgumentPointerToMember(Expr *Arg,
3865                                            TemplateArgument &Converted);
3866  ExprResult CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
3867                                   QualType InstantiatedParamType, Expr *Arg,
3868                                   TemplateArgument &Converted,
3869                                   CheckTemplateArgumentKind CTAK = CTAK_Specified);
3870  bool CheckTemplateArgument(TemplateTemplateParmDecl *Param,
3871                             const TemplateArgumentLoc &Arg);
3872
3873  ExprResult
3874  BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg,
3875                                          QualType ParamType,
3876                                          SourceLocation Loc);
3877  ExprResult
3878  BuildExpressionFromIntegralTemplateArgument(const TemplateArgument &Arg,
3879                                              SourceLocation Loc);
3880
3881  /// \brief Enumeration describing how template parameter lists are compared
3882  /// for equality.
3883  enum TemplateParameterListEqualKind {
3884    /// \brief We are matching the template parameter lists of two templates
3885    /// that might be redeclarations.
3886    ///
3887    /// \code
3888    /// template<typename T> struct X;
3889    /// template<typename T> struct X;
3890    /// \endcode
3891    TPL_TemplateMatch,
3892
3893    /// \brief We are matching the template parameter lists of two template
3894    /// template parameters as part of matching the template parameter lists
3895    /// of two templates that might be redeclarations.
3896    ///
3897    /// \code
3898    /// template<template<int I> class TT> struct X;
3899    /// template<template<int Value> class Other> struct X;
3900    /// \endcode
3901    TPL_TemplateTemplateParmMatch,
3902
3903    /// \brief We are matching the template parameter lists of a template
3904    /// template argument against the template parameter lists of a template
3905    /// template parameter.
3906    ///
3907    /// \code
3908    /// template<template<int Value> class Metafun> struct X;
3909    /// template<int Value> struct integer_c;
3910    /// X<integer_c> xic;
3911    /// \endcode
3912    TPL_TemplateTemplateArgumentMatch
3913  };
3914
3915  bool TemplateParameterListsAreEqual(TemplateParameterList *New,
3916                                      TemplateParameterList *Old,
3917                                      bool Complain,
3918                                      TemplateParameterListEqualKind Kind,
3919                                      SourceLocation TemplateArgLoc
3920                                        = SourceLocation());
3921
3922  bool CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams);
3923
3924  /// \brief Called when the parser has parsed a C++ typename
3925  /// specifier, e.g., "typename T::type".
3926  ///
3927  /// \param S The scope in which this typename type occurs.
3928  /// \param TypenameLoc the location of the 'typename' keyword
3929  /// \param SS the nested-name-specifier following the typename (e.g., 'T::').
3930  /// \param II the identifier we're retrieving (e.g., 'type' in the example).
3931  /// \param IdLoc the location of the identifier.
3932  TypeResult
3933  ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
3934                    const CXXScopeSpec &SS, const IdentifierInfo &II,
3935                    SourceLocation IdLoc);
3936
3937  /// \brief Called when the parser has parsed a C++ typename
3938  /// specifier that ends in a template-id, e.g.,
3939  /// "typename MetaFun::template apply<T1, T2>".
3940  ///
3941  /// \param S The scope in which this typename type occurs.
3942  /// \param TypenameLoc the location of the 'typename' keyword
3943  /// \param SS the nested-name-specifier following the typename (e.g., 'T::').
3944  /// \param TemplateLoc the location of the 'template' keyword, if any.
3945  /// \param TemplateName The template name.
3946  /// \param TemplateNameLoc The location of the template name.
3947  /// \param LAngleLoc The location of the opening angle bracket  ('<').
3948  /// \param TemplateArgs The template arguments.
3949  /// \param RAngleLoc The location of the closing angle bracket  ('>').
3950  TypeResult
3951  ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
3952                    const CXXScopeSpec &SS,
3953                    SourceLocation TemplateLoc,
3954                    TemplateTy Template,
3955                    SourceLocation TemplateNameLoc,
3956                    SourceLocation LAngleLoc,
3957                    ASTTemplateArgsPtr TemplateArgs,
3958                    SourceLocation RAngleLoc);
3959
3960  QualType CheckTypenameType(ElaboratedTypeKeyword Keyword,
3961                             SourceLocation KeywordLoc,
3962                             NestedNameSpecifierLoc QualifierLoc,
3963                             const IdentifierInfo &II,
3964                             SourceLocation IILoc);
3965
3966  TypeSourceInfo *RebuildTypeInCurrentInstantiation(TypeSourceInfo *T,
3967                                                    SourceLocation Loc,
3968                                                    DeclarationName Name);
3969  bool RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS);
3970
3971  ExprResult RebuildExprInCurrentInstantiation(Expr *E);
3972
3973  std::string
3974  getTemplateArgumentBindingsText(const TemplateParameterList *Params,
3975                                  const TemplateArgumentList &Args);
3976
3977  std::string
3978  getTemplateArgumentBindingsText(const TemplateParameterList *Params,
3979                                  const TemplateArgument *Args,
3980                                  unsigned NumArgs);
3981
3982  //===--------------------------------------------------------------------===//
3983  // C++ Variadic Templates (C++0x [temp.variadic])
3984  //===--------------------------------------------------------------------===//
3985
3986  /// \brief The context in which an unexpanded parameter pack is
3987  /// being diagnosed.
3988  ///
3989  /// Note that the values of this enumeration line up with the first
3990  /// argument to the \c err_unexpanded_parameter_pack diagnostic.
3991  enum UnexpandedParameterPackContext {
3992    /// \brief An arbitrary expression.
3993    UPPC_Expression = 0,
3994
3995    /// \brief The base type of a class type.
3996    UPPC_BaseType,
3997
3998    /// \brief The type of an arbitrary declaration.
3999    UPPC_DeclarationType,
4000
4001    /// \brief The type of a data member.
4002    UPPC_DataMemberType,
4003
4004    /// \brief The size of a bit-field.
4005    UPPC_BitFieldWidth,
4006
4007    /// \brief The expression in a static assertion.
4008    UPPC_StaticAssertExpression,
4009
4010    /// \brief The fixed underlying type of an enumeration.
4011    UPPC_FixedUnderlyingType,
4012
4013    /// \brief The enumerator value.
4014    UPPC_EnumeratorValue,
4015
4016    /// \brief A using declaration.
4017    UPPC_UsingDeclaration,
4018
4019    /// \brief A friend declaration.
4020    UPPC_FriendDeclaration,
4021
4022    /// \brief A declaration qualifier.
4023    UPPC_DeclarationQualifier,
4024
4025    /// \brief An initializer.
4026    UPPC_Initializer,
4027
4028    /// \brief A default argument.
4029    UPPC_DefaultArgument,
4030
4031    /// \brief The type of a non-type template parameter.
4032    UPPC_NonTypeTemplateParameterType,
4033
4034    /// \brief The type of an exception.
4035    UPPC_ExceptionType,
4036
4037    /// \brief Partial specialization.
4038    UPPC_PartialSpecialization
4039  };
4040
4041  /// \brief If the given type contains an unexpanded parameter pack,
4042  /// diagnose the error.
4043  ///
4044  /// \param Loc The source location where a diagnostc should be emitted.
4045  ///
4046  /// \param T The type that is being checked for unexpanded parameter
4047  /// packs.
4048  ///
4049  /// \returns true if an error occurred, false otherwise.
4050  bool DiagnoseUnexpandedParameterPack(SourceLocation Loc, TypeSourceInfo *T,
4051                                       UnexpandedParameterPackContext UPPC);
4052
4053  /// \brief If the given expression contains an unexpanded parameter
4054  /// pack, diagnose the error.
4055  ///
4056  /// \param E The expression that is being checked for unexpanded
4057  /// parameter packs.
4058  ///
4059  /// \returns true if an error occurred, false otherwise.
4060  bool DiagnoseUnexpandedParameterPack(Expr *E,
4061                       UnexpandedParameterPackContext UPPC = UPPC_Expression);
4062
4063  /// \brief If the given nested-name-specifier contains an unexpanded
4064  /// parameter pack, diagnose the error.
4065  ///
4066  /// \param SS The nested-name-specifier that is being checked for
4067  /// unexpanded parameter packs.
4068  ///
4069  /// \returns true if an error occurred, false otherwise.
4070  bool DiagnoseUnexpandedParameterPack(const CXXScopeSpec &SS,
4071                                       UnexpandedParameterPackContext UPPC);
4072
4073  /// \brief If the given name contains an unexpanded parameter pack,
4074  /// diagnose the error.
4075  ///
4076  /// \param NameInfo The name (with source location information) that
4077  /// is being checked for unexpanded parameter packs.
4078  ///
4079  /// \returns true if an error occurred, false otherwise.
4080  bool DiagnoseUnexpandedParameterPack(const DeclarationNameInfo &NameInfo,
4081                                       UnexpandedParameterPackContext UPPC);
4082
4083  /// \brief If the given template name contains an unexpanded parameter pack,
4084  /// diagnose the error.
4085  ///
4086  /// \param Loc The location of the template name.
4087  ///
4088  /// \param Template The template name that is being checked for unexpanded
4089  /// parameter packs.
4090  ///
4091  /// \returns true if an error occurred, false otherwise.
4092  bool DiagnoseUnexpandedParameterPack(SourceLocation Loc,
4093                                       TemplateName Template,
4094                                       UnexpandedParameterPackContext UPPC);
4095
4096  /// \brief If the given template argument contains an unexpanded parameter
4097  /// pack, diagnose the error.
4098  ///
4099  /// \param Arg The template argument that is being checked for unexpanded
4100  /// parameter packs.
4101  ///
4102  /// \returns true if an error occurred, false otherwise.
4103  bool DiagnoseUnexpandedParameterPack(TemplateArgumentLoc Arg,
4104                                       UnexpandedParameterPackContext UPPC);
4105
4106  /// \brief Collect the set of unexpanded parameter packs within the given
4107  /// template argument.
4108  ///
4109  /// \param Arg The template argument that will be traversed to find
4110  /// unexpanded parameter packs.
4111  void collectUnexpandedParameterPacks(TemplateArgument Arg,
4112                   SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
4113
4114  /// \brief Collect the set of unexpanded parameter packs within the given
4115  /// template argument.
4116  ///
4117  /// \param Arg The template argument that will be traversed to find
4118  /// unexpanded parameter packs.
4119  void collectUnexpandedParameterPacks(TemplateArgumentLoc Arg,
4120                    SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
4121
4122  /// \brief Collect the set of unexpanded parameter packs within the given
4123  /// type.
4124  ///
4125  /// \param T The type that will be traversed to find
4126  /// unexpanded parameter packs.
4127  void collectUnexpandedParameterPacks(QualType T,
4128                   SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
4129
4130  /// \brief Collect the set of unexpanded parameter packs within the given
4131  /// type.
4132  ///
4133  /// \param TL The type that will be traversed to find
4134  /// unexpanded parameter packs.
4135  void collectUnexpandedParameterPacks(TypeLoc TL,
4136                   SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
4137
4138  /// \brief Invoked when parsing a template argument followed by an
4139  /// ellipsis, which creates a pack expansion.
4140  ///
4141  /// \param Arg The template argument preceding the ellipsis, which
4142  /// may already be invalid.
4143  ///
4144  /// \param EllipsisLoc The location of the ellipsis.
4145  ParsedTemplateArgument ActOnPackExpansion(const ParsedTemplateArgument &Arg,
4146                                            SourceLocation EllipsisLoc);
4147
4148  /// \brief Invoked when parsing a type followed by an ellipsis, which
4149  /// creates a pack expansion.
4150  ///
4151  /// \param Type The type preceding the ellipsis, which will become
4152  /// the pattern of the pack expansion.
4153  ///
4154  /// \param EllipsisLoc The location of the ellipsis.
4155  TypeResult ActOnPackExpansion(ParsedType Type, SourceLocation EllipsisLoc);
4156
4157  /// \brief Construct a pack expansion type from the pattern of the pack
4158  /// expansion.
4159  TypeSourceInfo *CheckPackExpansion(TypeSourceInfo *Pattern,
4160                                     SourceLocation EllipsisLoc,
4161                                     llvm::Optional<unsigned> NumExpansions);
4162
4163  /// \brief Construct a pack expansion type from the pattern of the pack
4164  /// expansion.
4165  QualType CheckPackExpansion(QualType Pattern,
4166                              SourceRange PatternRange,
4167                              SourceLocation EllipsisLoc,
4168                              llvm::Optional<unsigned> NumExpansions);
4169
4170  /// \brief Invoked when parsing an expression followed by an ellipsis, which
4171  /// creates a pack expansion.
4172  ///
4173  /// \param Pattern The expression preceding the ellipsis, which will become
4174  /// the pattern of the pack expansion.
4175  ///
4176  /// \param EllipsisLoc The location of the ellipsis.
4177  ExprResult ActOnPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc);
4178
4179  /// \brief Invoked when parsing an expression followed by an ellipsis, which
4180  /// creates a pack expansion.
4181  ///
4182  /// \param Pattern The expression preceding the ellipsis, which will become
4183  /// the pattern of the pack expansion.
4184  ///
4185  /// \param EllipsisLoc The location of the ellipsis.
4186  ExprResult CheckPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc,
4187                                llvm::Optional<unsigned> NumExpansions);
4188
4189  /// \brief Determine whether we could expand a pack expansion with the
4190  /// given set of parameter packs into separate arguments by repeatedly
4191  /// transforming the pattern.
4192  ///
4193  /// \param EllipsisLoc The location of the ellipsis that identifies the
4194  /// pack expansion.
4195  ///
4196  /// \param PatternRange The source range that covers the entire pattern of
4197  /// the pack expansion.
4198  ///
4199  /// \param Unexpanded The set of unexpanded parameter packs within the
4200  /// pattern.
4201  ///
4202  /// \param NumUnexpanded The number of unexpanded parameter packs in
4203  /// \p Unexpanded.
4204  ///
4205  /// \param ShouldExpand Will be set to \c true if the transformer should
4206  /// expand the corresponding pack expansions into separate arguments. When
4207  /// set, \c NumExpansions must also be set.
4208  ///
4209  /// \param RetainExpansion Whether the caller should add an unexpanded
4210  /// pack expansion after all of the expanded arguments. This is used
4211  /// when extending explicitly-specified template argument packs per
4212  /// C++0x [temp.arg.explicit]p9.
4213  ///
4214  /// \param NumExpansions The number of separate arguments that will be in
4215  /// the expanded form of the corresponding pack expansion. This is both an
4216  /// input and an output parameter, which can be set by the caller if the
4217  /// number of expansions is known a priori (e.g., due to a prior substitution)
4218  /// and will be set by the callee when the number of expansions is known.
4219  /// The callee must set this value when \c ShouldExpand is \c true; it may
4220  /// set this value in other cases.
4221  ///
4222  /// \returns true if an error occurred (e.g., because the parameter packs
4223  /// are to be instantiated with arguments of different lengths), false
4224  /// otherwise. If false, \c ShouldExpand (and possibly \c NumExpansions)
4225  /// must be set.
4226  bool CheckParameterPacksForExpansion(SourceLocation EllipsisLoc,
4227                                       SourceRange PatternRange,
4228                                     const UnexpandedParameterPack *Unexpanded,
4229                                       unsigned NumUnexpanded,
4230                             const MultiLevelTemplateArgumentList &TemplateArgs,
4231                                       bool &ShouldExpand,
4232                                       bool &RetainExpansion,
4233                                       llvm::Optional<unsigned> &NumExpansions);
4234
4235  /// \brief Determine the number of arguments in the given pack expansion
4236  /// type.
4237  ///
4238  /// This routine already assumes that the pack expansion type can be
4239  /// expanded and that the number of arguments in the expansion is
4240  /// consistent across all of the unexpanded parameter packs in its pattern.
4241  unsigned getNumArgumentsInExpansion(QualType T,
4242                            const MultiLevelTemplateArgumentList &TemplateArgs);
4243
4244  /// \brief Determine whether the given declarator contains any unexpanded
4245  /// parameter packs.
4246  ///
4247  /// This routine is used by the parser to disambiguate function declarators
4248  /// with an ellipsis prior to the ')', e.g.,
4249  ///
4250  /// \code
4251  ///   void f(T...);
4252  /// \endcode
4253  ///
4254  /// To determine whether we have an (unnamed) function parameter pack or
4255  /// a variadic function.
4256  ///
4257  /// \returns true if the declarator contains any unexpanded parameter packs,
4258  /// false otherwise.
4259  bool containsUnexpandedParameterPacks(Declarator &D);
4260
4261  //===--------------------------------------------------------------------===//
4262  // C++ Template Argument Deduction (C++ [temp.deduct])
4263  //===--------------------------------------------------------------------===//
4264
4265  /// \brief Describes the result of template argument deduction.
4266  ///
4267  /// The TemplateDeductionResult enumeration describes the result of
4268  /// template argument deduction, as returned from
4269  /// DeduceTemplateArguments(). The separate TemplateDeductionInfo
4270  /// structure provides additional information about the results of
4271  /// template argument deduction, e.g., the deduced template argument
4272  /// list (if successful) or the specific template parameters or
4273  /// deduced arguments that were involved in the failure.
4274  enum TemplateDeductionResult {
4275    /// \brief Template argument deduction was successful.
4276    TDK_Success = 0,
4277    /// \brief Template argument deduction exceeded the maximum template
4278    /// instantiation depth (which has already been diagnosed).
4279    TDK_InstantiationDepth,
4280    /// \brief Template argument deduction did not deduce a value
4281    /// for every template parameter.
4282    TDK_Incomplete,
4283    /// \brief Template argument deduction produced inconsistent
4284    /// deduced values for the given template parameter.
4285    TDK_Inconsistent,
4286    /// \brief Template argument deduction failed due to inconsistent
4287    /// cv-qualifiers on a template parameter type that would
4288    /// otherwise be deduced, e.g., we tried to deduce T in "const T"
4289    /// but were given a non-const "X".
4290    TDK_Underqualified,
4291    /// \brief Substitution of the deduced template argument values
4292    /// resulted in an error.
4293    TDK_SubstitutionFailure,
4294    /// \brief Substitution of the deduced template argument values
4295    /// into a non-deduced context produced a type or value that
4296    /// produces a type that does not match the original template
4297    /// arguments provided.
4298    TDK_NonDeducedMismatch,
4299    /// \brief When performing template argument deduction for a function
4300    /// template, there were too many call arguments.
4301    TDK_TooManyArguments,
4302    /// \brief When performing template argument deduction for a function
4303    /// template, there were too few call arguments.
4304    TDK_TooFewArguments,
4305    /// \brief The explicitly-specified template arguments were not valid
4306    /// template arguments for the given template.
4307    TDK_InvalidExplicitArguments,
4308    /// \brief The arguments included an overloaded function name that could
4309    /// not be resolved to a suitable function.
4310    TDK_FailedOverloadResolution
4311  };
4312
4313  TemplateDeductionResult
4314  DeduceTemplateArguments(ClassTemplatePartialSpecializationDecl *Partial,
4315                          const TemplateArgumentList &TemplateArgs,
4316                          sema::TemplateDeductionInfo &Info);
4317
4318  TemplateDeductionResult
4319  SubstituteExplicitTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
4320                              TemplateArgumentListInfo &ExplicitTemplateArgs,
4321                      SmallVectorImpl<DeducedTemplateArgument> &Deduced,
4322                                 SmallVectorImpl<QualType> &ParamTypes,
4323                                      QualType *FunctionType,
4324                                      sema::TemplateDeductionInfo &Info);
4325
4326  /// brief A function argument from which we performed template argument
4327  // deduction for a call.
4328  struct OriginalCallArg {
4329    OriginalCallArg(QualType OriginalParamType,
4330                    unsigned ArgIdx,
4331                    QualType OriginalArgType)
4332      : OriginalParamType(OriginalParamType), ArgIdx(ArgIdx),
4333        OriginalArgType(OriginalArgType) { }
4334
4335    QualType OriginalParamType;
4336    unsigned ArgIdx;
4337    QualType OriginalArgType;
4338  };
4339
4340  TemplateDeductionResult
4341  FinishTemplateArgumentDeduction(FunctionTemplateDecl *FunctionTemplate,
4342                      SmallVectorImpl<DeducedTemplateArgument> &Deduced,
4343                                  unsigned NumExplicitlySpecified,
4344                                  FunctionDecl *&Specialization,
4345                                  sema::TemplateDeductionInfo &Info,
4346           SmallVectorImpl<OriginalCallArg> const *OriginalCallArgs = 0);
4347
4348  TemplateDeductionResult
4349  DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
4350                          TemplateArgumentListInfo *ExplicitTemplateArgs,
4351                          Expr **Args, unsigned NumArgs,
4352                          FunctionDecl *&Specialization,
4353                          sema::TemplateDeductionInfo &Info);
4354
4355  TemplateDeductionResult
4356  DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
4357                          TemplateArgumentListInfo *ExplicitTemplateArgs,
4358                          QualType ArgFunctionType,
4359                          FunctionDecl *&Specialization,
4360                          sema::TemplateDeductionInfo &Info);
4361
4362  TemplateDeductionResult
4363  DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
4364                          QualType ToType,
4365                          CXXConversionDecl *&Specialization,
4366                          sema::TemplateDeductionInfo &Info);
4367
4368  TemplateDeductionResult
4369  DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
4370                          TemplateArgumentListInfo *ExplicitTemplateArgs,
4371                          FunctionDecl *&Specialization,
4372                          sema::TemplateDeductionInfo &Info);
4373
4374  bool DeduceAutoType(TypeSourceInfo *AutoType, Expr *Initializer,
4375                      TypeSourceInfo *&Result);
4376
4377  FunctionTemplateDecl *getMoreSpecializedTemplate(FunctionTemplateDecl *FT1,
4378                                                   FunctionTemplateDecl *FT2,
4379                                                   SourceLocation Loc,
4380                                           TemplatePartialOrderingContext TPOC,
4381                                                   unsigned NumCallArguments);
4382  UnresolvedSetIterator getMostSpecialized(UnresolvedSetIterator SBegin,
4383                                           UnresolvedSetIterator SEnd,
4384                                           TemplatePartialOrderingContext TPOC,
4385                                           unsigned NumCallArguments,
4386                                           SourceLocation Loc,
4387                                           const PartialDiagnostic &NoneDiag,
4388                                           const PartialDiagnostic &AmbigDiag,
4389                                        const PartialDiagnostic &CandidateDiag,
4390                                        bool Complain = true);
4391
4392  ClassTemplatePartialSpecializationDecl *
4393  getMoreSpecializedPartialSpecialization(
4394                                  ClassTemplatePartialSpecializationDecl *PS1,
4395                                  ClassTemplatePartialSpecializationDecl *PS2,
4396                                  SourceLocation Loc);
4397
4398  void MarkUsedTemplateParameters(const TemplateArgumentList &TemplateArgs,
4399                                  bool OnlyDeduced,
4400                                  unsigned Depth,
4401                                  SmallVectorImpl<bool> &Used);
4402  void MarkDeducedTemplateParameters(FunctionTemplateDecl *FunctionTemplate,
4403                                     SmallVectorImpl<bool> &Deduced);
4404
4405  //===--------------------------------------------------------------------===//
4406  // C++ Template Instantiation
4407  //
4408
4409  MultiLevelTemplateArgumentList getTemplateInstantiationArgs(NamedDecl *D,
4410                                     const TemplateArgumentList *Innermost = 0,
4411                                                bool RelativeToPrimary = false,
4412                                               const FunctionDecl *Pattern = 0);
4413
4414  /// \brief A template instantiation that is currently in progress.
4415  struct ActiveTemplateInstantiation {
4416    /// \brief The kind of template instantiation we are performing
4417    enum InstantiationKind {
4418      /// We are instantiating a template declaration. The entity is
4419      /// the declaration we're instantiating (e.g., a CXXRecordDecl).
4420      TemplateInstantiation,
4421
4422      /// We are instantiating a default argument for a template
4423      /// parameter. The Entity is the template, and
4424      /// TemplateArgs/NumTemplateArguments provides the template
4425      /// arguments as specified.
4426      /// FIXME: Use a TemplateArgumentList
4427      DefaultTemplateArgumentInstantiation,
4428
4429      /// We are instantiating a default argument for a function.
4430      /// The Entity is the ParmVarDecl, and TemplateArgs/NumTemplateArgs
4431      /// provides the template arguments as specified.
4432      DefaultFunctionArgumentInstantiation,
4433
4434      /// We are substituting explicit template arguments provided for
4435      /// a function template. The entity is a FunctionTemplateDecl.
4436      ExplicitTemplateArgumentSubstitution,
4437
4438      /// We are substituting template argument determined as part of
4439      /// template argument deduction for either a class template
4440      /// partial specialization or a function template. The
4441      /// Entity is either a ClassTemplatePartialSpecializationDecl or
4442      /// a FunctionTemplateDecl.
4443      DeducedTemplateArgumentSubstitution,
4444
4445      /// We are substituting prior template arguments into a new
4446      /// template parameter. The template parameter itself is either a
4447      /// NonTypeTemplateParmDecl or a TemplateTemplateParmDecl.
4448      PriorTemplateArgumentSubstitution,
4449
4450      /// We are checking the validity of a default template argument that
4451      /// has been used when naming a template-id.
4452      DefaultTemplateArgumentChecking
4453    } Kind;
4454
4455    /// \brief The point of instantiation within the source code.
4456    SourceLocation PointOfInstantiation;
4457
4458    /// \brief The template (or partial specialization) in which we are
4459    /// performing the instantiation, for substitutions of prior template
4460    /// arguments.
4461    NamedDecl *Template;
4462
4463    /// \brief The entity that is being instantiated.
4464    uintptr_t Entity;
4465
4466    /// \brief The list of template arguments we are substituting, if they
4467    /// are not part of the entity.
4468    const TemplateArgument *TemplateArgs;
4469
4470    /// \brief The number of template arguments in TemplateArgs.
4471    unsigned NumTemplateArgs;
4472
4473    /// \brief The template deduction info object associated with the
4474    /// substitution or checking of explicit or deduced template arguments.
4475    sema::TemplateDeductionInfo *DeductionInfo;
4476
4477    /// \brief The source range that covers the construct that cause
4478    /// the instantiation, e.g., the template-id that causes a class
4479    /// template instantiation.
4480    SourceRange InstantiationRange;
4481
4482    ActiveTemplateInstantiation()
4483      : Kind(TemplateInstantiation), Template(0), Entity(0), TemplateArgs(0),
4484        NumTemplateArgs(0), DeductionInfo(0) {}
4485
4486    /// \brief Determines whether this template is an actual instantiation
4487    /// that should be counted toward the maximum instantiation depth.
4488    bool isInstantiationRecord() const;
4489
4490    friend bool operator==(const ActiveTemplateInstantiation &X,
4491                           const ActiveTemplateInstantiation &Y) {
4492      if (X.Kind != Y.Kind)
4493        return false;
4494
4495      if (X.Entity != Y.Entity)
4496        return false;
4497
4498      switch (X.Kind) {
4499      case TemplateInstantiation:
4500        return true;
4501
4502      case PriorTemplateArgumentSubstitution:
4503      case DefaultTemplateArgumentChecking:
4504        if (X.Template != Y.Template)
4505          return false;
4506
4507        // Fall through
4508
4509      case DefaultTemplateArgumentInstantiation:
4510      case ExplicitTemplateArgumentSubstitution:
4511      case DeducedTemplateArgumentSubstitution:
4512      case DefaultFunctionArgumentInstantiation:
4513        return X.TemplateArgs == Y.TemplateArgs;
4514
4515      }
4516
4517      return true;
4518    }
4519
4520    friend bool operator!=(const ActiveTemplateInstantiation &X,
4521                           const ActiveTemplateInstantiation &Y) {
4522      return !(X == Y);
4523    }
4524  };
4525
4526  /// \brief List of active template instantiations.
4527  ///
4528  /// This vector is treated as a stack. As one template instantiation
4529  /// requires another template instantiation, additional
4530  /// instantiations are pushed onto the stack up to a
4531  /// user-configurable limit LangOptions::InstantiationDepth.
4532  SmallVector<ActiveTemplateInstantiation, 16>
4533    ActiveTemplateInstantiations;
4534
4535  /// \brief Whether we are in a SFINAE context that is not associated with
4536  /// template instantiation.
4537  ///
4538  /// This is used when setting up a SFINAE trap (\c see SFINAETrap) outside
4539  /// of a template instantiation or template argument deduction.
4540  bool InNonInstantiationSFINAEContext;
4541
4542  /// \brief The number of ActiveTemplateInstantiation entries in
4543  /// \c ActiveTemplateInstantiations that are not actual instantiations and,
4544  /// therefore, should not be counted as part of the instantiation depth.
4545  unsigned NonInstantiationEntries;
4546
4547  /// \brief The last template from which a template instantiation
4548  /// error or warning was produced.
4549  ///
4550  /// This value is used to suppress printing of redundant template
4551  /// instantiation backtraces when there are multiple errors in the
4552  /// same instantiation. FIXME: Does this belong in Sema? It's tough
4553  /// to implement it anywhere else.
4554  ActiveTemplateInstantiation LastTemplateInstantiationErrorContext;
4555
4556  /// \brief The current index into pack expansion arguments that will be
4557  /// used for substitution of parameter packs.
4558  ///
4559  /// The pack expansion index will be -1 to indicate that parameter packs
4560  /// should be instantiated as themselves. Otherwise, the index specifies
4561  /// which argument within the parameter pack will be used for substitution.
4562  int ArgumentPackSubstitutionIndex;
4563
4564  /// \brief RAII object used to change the argument pack substitution index
4565  /// within a \c Sema object.
4566  ///
4567  /// See \c ArgumentPackSubstitutionIndex for more information.
4568  class ArgumentPackSubstitutionIndexRAII {
4569    Sema &Self;
4570    int OldSubstitutionIndex;
4571
4572  public:
4573    ArgumentPackSubstitutionIndexRAII(Sema &Self, int NewSubstitutionIndex)
4574      : Self(Self), OldSubstitutionIndex(Self.ArgumentPackSubstitutionIndex) {
4575      Self.ArgumentPackSubstitutionIndex = NewSubstitutionIndex;
4576    }
4577
4578    ~ArgumentPackSubstitutionIndexRAII() {
4579      Self.ArgumentPackSubstitutionIndex = OldSubstitutionIndex;
4580    }
4581  };
4582
4583  friend class ArgumentPackSubstitutionRAII;
4584
4585  /// \brief The stack of calls expression undergoing template instantiation.
4586  ///
4587  /// The top of this stack is used by a fixit instantiating unresolved
4588  /// function calls to fix the AST to match the textual change it prints.
4589  SmallVector<CallExpr *, 8> CallsUndergoingInstantiation;
4590
4591  /// \brief For each declaration that involved template argument deduction, the
4592  /// set of diagnostics that were suppressed during that template argument
4593  /// deduction.
4594  ///
4595  /// FIXME: Serialize this structure to the AST file.
4596  llvm::DenseMap<Decl *, SmallVector<PartialDiagnosticAt, 1> >
4597    SuppressedDiagnostics;
4598
4599  /// \brief A stack object to be created when performing template
4600  /// instantiation.
4601  ///
4602  /// Construction of an object of type \c InstantiatingTemplate
4603  /// pushes the current instantiation onto the stack of active
4604  /// instantiations. If the size of this stack exceeds the maximum
4605  /// number of recursive template instantiations, construction
4606  /// produces an error and evaluates true.
4607  ///
4608  /// Destruction of this object will pop the named instantiation off
4609  /// the stack.
4610  struct InstantiatingTemplate {
4611    /// \brief Note that we are instantiating a class template,
4612    /// function template, or a member thereof.
4613    InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
4614                          Decl *Entity,
4615                          SourceRange InstantiationRange = SourceRange());
4616
4617    /// \brief Note that we are instantiating a default argument in a
4618    /// template-id.
4619    InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
4620                          TemplateDecl *Template,
4621                          const TemplateArgument *TemplateArgs,
4622                          unsigned NumTemplateArgs,
4623                          SourceRange InstantiationRange = SourceRange());
4624
4625    /// \brief Note that we are instantiating a default argument in a
4626    /// template-id.
4627    InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
4628                          FunctionTemplateDecl *FunctionTemplate,
4629                          const TemplateArgument *TemplateArgs,
4630                          unsigned NumTemplateArgs,
4631                          ActiveTemplateInstantiation::InstantiationKind Kind,
4632                          sema::TemplateDeductionInfo &DeductionInfo,
4633                          SourceRange InstantiationRange = SourceRange());
4634
4635    /// \brief Note that we are instantiating as part of template
4636    /// argument deduction for a class template partial
4637    /// specialization.
4638    InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
4639                          ClassTemplatePartialSpecializationDecl *PartialSpec,
4640                          const TemplateArgument *TemplateArgs,
4641                          unsigned NumTemplateArgs,
4642                          sema::TemplateDeductionInfo &DeductionInfo,
4643                          SourceRange InstantiationRange = SourceRange());
4644
4645    InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
4646                          ParmVarDecl *Param,
4647                          const TemplateArgument *TemplateArgs,
4648                          unsigned NumTemplateArgs,
4649                          SourceRange InstantiationRange = SourceRange());
4650
4651    /// \brief Note that we are substituting prior template arguments into a
4652    /// non-type or template template parameter.
4653    InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
4654                          NamedDecl *Template,
4655                          NonTypeTemplateParmDecl *Param,
4656                          const TemplateArgument *TemplateArgs,
4657                          unsigned NumTemplateArgs,
4658                          SourceRange InstantiationRange);
4659
4660    InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
4661                          NamedDecl *Template,
4662                          TemplateTemplateParmDecl *Param,
4663                          const TemplateArgument *TemplateArgs,
4664                          unsigned NumTemplateArgs,
4665                          SourceRange InstantiationRange);
4666
4667    /// \brief Note that we are checking the default template argument
4668    /// against the template parameter for a given template-id.
4669    InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
4670                          TemplateDecl *Template,
4671                          NamedDecl *Param,
4672                          const TemplateArgument *TemplateArgs,
4673                          unsigned NumTemplateArgs,
4674                          SourceRange InstantiationRange);
4675
4676
4677    /// \brief Note that we have finished instantiating this template.
4678    void Clear();
4679
4680    ~InstantiatingTemplate() { Clear(); }
4681
4682    /// \brief Determines whether we have exceeded the maximum
4683    /// recursive template instantiations.
4684    operator bool() const { return Invalid; }
4685
4686  private:
4687    Sema &SemaRef;
4688    bool Invalid;
4689    bool SavedInNonInstantiationSFINAEContext;
4690    bool CheckInstantiationDepth(SourceLocation PointOfInstantiation,
4691                                 SourceRange InstantiationRange);
4692
4693    InstantiatingTemplate(const InstantiatingTemplate&); // not implemented
4694
4695    InstantiatingTemplate&
4696    operator=(const InstantiatingTemplate&); // not implemented
4697  };
4698
4699  void PrintInstantiationStack();
4700
4701  /// \brief Determines whether we are currently in a context where
4702  /// template argument substitution failures are not considered
4703  /// errors.
4704  ///
4705  /// \returns An empty \c llvm::Optional if we're not in a SFINAE context.
4706  /// Otherwise, contains a pointer that, if non-NULL, contains the nearest
4707  /// template-deduction context object, which can be used to capture
4708  /// diagnostics that will be suppressed.
4709  llvm::Optional<sema::TemplateDeductionInfo *> isSFINAEContext() const;
4710
4711  /// \brief RAII class used to determine whether SFINAE has
4712  /// trapped any errors that occur during template argument
4713  /// deduction.`
4714  class SFINAETrap {
4715    Sema &SemaRef;
4716    unsigned PrevSFINAEErrors;
4717    bool PrevInNonInstantiationSFINAEContext;
4718    bool PrevAccessCheckingSFINAE;
4719
4720  public:
4721    explicit SFINAETrap(Sema &SemaRef, bool AccessCheckingSFINAE = false)
4722      : SemaRef(SemaRef), PrevSFINAEErrors(SemaRef.NumSFINAEErrors),
4723        PrevInNonInstantiationSFINAEContext(
4724                                      SemaRef.InNonInstantiationSFINAEContext),
4725        PrevAccessCheckingSFINAE(SemaRef.AccessCheckingSFINAE)
4726    {
4727      if (!SemaRef.isSFINAEContext())
4728        SemaRef.InNonInstantiationSFINAEContext = true;
4729      SemaRef.AccessCheckingSFINAE = AccessCheckingSFINAE;
4730    }
4731
4732    ~SFINAETrap() {
4733      SemaRef.NumSFINAEErrors = PrevSFINAEErrors;
4734      SemaRef.InNonInstantiationSFINAEContext
4735        = PrevInNonInstantiationSFINAEContext;
4736      SemaRef.AccessCheckingSFINAE = PrevAccessCheckingSFINAE;
4737    }
4738
4739    /// \brief Determine whether any SFINAE errors have been trapped.
4740    bool hasErrorOccurred() const {
4741      return SemaRef.NumSFINAEErrors > PrevSFINAEErrors;
4742    }
4743  };
4744
4745  /// \brief The current instantiation scope used to store local
4746  /// variables.
4747  LocalInstantiationScope *CurrentInstantiationScope;
4748
4749  /// \brief The number of typos corrected by CorrectTypo.
4750  unsigned TyposCorrected;
4751
4752  typedef llvm::DenseMap<IdentifierInfo *, TypoCorrection>
4753    UnqualifiedTyposCorrectedMap;
4754
4755  /// \brief A cache containing the results of typo correction for unqualified
4756  /// name lookup.
4757  ///
4758  /// The string is the string that we corrected to (which may be empty, if
4759  /// there was no correction), while the boolean will be true when the
4760  /// string represents a keyword.
4761  UnqualifiedTyposCorrectedMap UnqualifiedTyposCorrected;
4762
4763  /// \brief Worker object for performing CFG-based warnings.
4764  sema::AnalysisBasedWarnings AnalysisWarnings;
4765
4766  /// \brief An entity for which implicit template instantiation is required.
4767  ///
4768  /// The source location associated with the declaration is the first place in
4769  /// the source code where the declaration was "used". It is not necessarily
4770  /// the point of instantiation (which will be either before or after the
4771  /// namespace-scope declaration that triggered this implicit instantiation),
4772  /// However, it is the location that diagnostics should generally refer to,
4773  /// because users will need to know what code triggered the instantiation.
4774  typedef std::pair<ValueDecl *, SourceLocation> PendingImplicitInstantiation;
4775
4776  /// \brief The queue of implicit template instantiations that are required
4777  /// but have not yet been performed.
4778  std::deque<PendingImplicitInstantiation> PendingInstantiations;
4779
4780  /// \brief The queue of implicit template instantiations that are required
4781  /// and must be performed within the current local scope.
4782  ///
4783  /// This queue is only used for member functions of local classes in
4784  /// templates, which must be instantiated in the same scope as their
4785  /// enclosing function, so that they can reference function-local
4786  /// types, static variables, enumerators, etc.
4787  std::deque<PendingImplicitInstantiation> PendingLocalImplicitInstantiations;
4788
4789  void PerformPendingInstantiations(bool LocalOnly = false);
4790
4791  TypeSourceInfo *SubstType(TypeSourceInfo *T,
4792                            const MultiLevelTemplateArgumentList &TemplateArgs,
4793                            SourceLocation Loc, DeclarationName Entity);
4794
4795  QualType SubstType(QualType T,
4796                     const MultiLevelTemplateArgumentList &TemplateArgs,
4797                     SourceLocation Loc, DeclarationName Entity);
4798
4799  TypeSourceInfo *SubstType(TypeLoc TL,
4800                            const MultiLevelTemplateArgumentList &TemplateArgs,
4801                            SourceLocation Loc, DeclarationName Entity);
4802
4803  TypeSourceInfo *SubstFunctionDeclType(TypeSourceInfo *T,
4804                            const MultiLevelTemplateArgumentList &TemplateArgs,
4805                                        SourceLocation Loc,
4806                                        DeclarationName Entity);
4807  ParmVarDecl *SubstParmVarDecl(ParmVarDecl *D,
4808                            const MultiLevelTemplateArgumentList &TemplateArgs,
4809                                int indexAdjustment,
4810                                llvm::Optional<unsigned> NumExpansions);
4811  bool SubstParmTypes(SourceLocation Loc,
4812                      ParmVarDecl **Params, unsigned NumParams,
4813                      const MultiLevelTemplateArgumentList &TemplateArgs,
4814                      SmallVectorImpl<QualType> &ParamTypes,
4815                      SmallVectorImpl<ParmVarDecl *> *OutParams = 0);
4816  ExprResult SubstExpr(Expr *E,
4817                       const MultiLevelTemplateArgumentList &TemplateArgs);
4818
4819  /// \brief Substitute the given template arguments into a list of
4820  /// expressions, expanding pack expansions if required.
4821  ///
4822  /// \param Exprs The list of expressions to substitute into.
4823  ///
4824  /// \param NumExprs The number of expressions in \p Exprs.
4825  ///
4826  /// \param IsCall Whether this is some form of call, in which case
4827  /// default arguments will be dropped.
4828  ///
4829  /// \param TemplateArgs The set of template arguments to substitute.
4830  ///
4831  /// \param Outputs Will receive all of the substituted arguments.
4832  ///
4833  /// \returns true if an error occurred, false otherwise.
4834  bool SubstExprs(Expr **Exprs, unsigned NumExprs, bool IsCall,
4835                  const MultiLevelTemplateArgumentList &TemplateArgs,
4836                  SmallVectorImpl<Expr *> &Outputs);
4837
4838  StmtResult SubstStmt(Stmt *S,
4839                       const MultiLevelTemplateArgumentList &TemplateArgs);
4840
4841  Decl *SubstDecl(Decl *D, DeclContext *Owner,
4842                  const MultiLevelTemplateArgumentList &TemplateArgs);
4843
4844  bool
4845  SubstBaseSpecifiers(CXXRecordDecl *Instantiation,
4846                      CXXRecordDecl *Pattern,
4847                      const MultiLevelTemplateArgumentList &TemplateArgs);
4848
4849  bool
4850  InstantiateClass(SourceLocation PointOfInstantiation,
4851                   CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern,
4852                   const MultiLevelTemplateArgumentList &TemplateArgs,
4853                   TemplateSpecializationKind TSK,
4854                   bool Complain = true);
4855
4856  void InstantiateAttrs(const MultiLevelTemplateArgumentList &TemplateArgs,
4857                        const Decl *Pattern, Decl *Inst);
4858
4859  bool
4860  InstantiateClassTemplateSpecialization(SourceLocation PointOfInstantiation,
4861                           ClassTemplateSpecializationDecl *ClassTemplateSpec,
4862                           TemplateSpecializationKind TSK,
4863                           bool Complain = true);
4864
4865  void InstantiateClassMembers(SourceLocation PointOfInstantiation,
4866                               CXXRecordDecl *Instantiation,
4867                            const MultiLevelTemplateArgumentList &TemplateArgs,
4868                               TemplateSpecializationKind TSK);
4869
4870  void InstantiateClassTemplateSpecializationMembers(
4871                                          SourceLocation PointOfInstantiation,
4872                           ClassTemplateSpecializationDecl *ClassTemplateSpec,
4873                                                TemplateSpecializationKind TSK);
4874
4875  NestedNameSpecifierLoc
4876  SubstNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS,
4877                           const MultiLevelTemplateArgumentList &TemplateArgs);
4878
4879  DeclarationNameInfo
4880  SubstDeclarationNameInfo(const DeclarationNameInfo &NameInfo,
4881                           const MultiLevelTemplateArgumentList &TemplateArgs);
4882  TemplateName
4883  SubstTemplateName(NestedNameSpecifierLoc QualifierLoc, TemplateName Name,
4884                    SourceLocation Loc,
4885                    const MultiLevelTemplateArgumentList &TemplateArgs);
4886  bool Subst(const TemplateArgumentLoc *Args, unsigned NumArgs,
4887             TemplateArgumentListInfo &Result,
4888             const MultiLevelTemplateArgumentList &TemplateArgs);
4889
4890  void InstantiateFunctionDefinition(SourceLocation PointOfInstantiation,
4891                                     FunctionDecl *Function,
4892                                     bool Recursive = false,
4893                                     bool DefinitionRequired = false);
4894  void InstantiateStaticDataMemberDefinition(
4895                                     SourceLocation PointOfInstantiation,
4896                                     VarDecl *Var,
4897                                     bool Recursive = false,
4898                                     bool DefinitionRequired = false);
4899
4900  void InstantiateMemInitializers(CXXConstructorDecl *New,
4901                                  const CXXConstructorDecl *Tmpl,
4902                            const MultiLevelTemplateArgumentList &TemplateArgs);
4903  bool InstantiateInitializer(Expr *Init,
4904                            const MultiLevelTemplateArgumentList &TemplateArgs,
4905                              SourceLocation &LParenLoc,
4906                              ASTOwningVector<Expr*> &NewArgs,
4907                              SourceLocation &RParenLoc);
4908
4909  NamedDecl *FindInstantiatedDecl(SourceLocation Loc, NamedDecl *D,
4910                          const MultiLevelTemplateArgumentList &TemplateArgs);
4911  DeclContext *FindInstantiatedContext(SourceLocation Loc, DeclContext *DC,
4912                          const MultiLevelTemplateArgumentList &TemplateArgs);
4913
4914  // Objective-C declarations.
4915  Decl *ActOnStartClassInterface(SourceLocation AtInterfaceLoc,
4916                                 IdentifierInfo *ClassName,
4917                                 SourceLocation ClassLoc,
4918                                 IdentifierInfo *SuperName,
4919                                 SourceLocation SuperLoc,
4920                                 Decl * const *ProtoRefs,
4921                                 unsigned NumProtoRefs,
4922                                 const SourceLocation *ProtoLocs,
4923                                 SourceLocation EndProtoLoc,
4924                                 AttributeList *AttrList);
4925
4926  Decl *ActOnCompatiblityAlias(
4927                    SourceLocation AtCompatibilityAliasLoc,
4928                    IdentifierInfo *AliasName,  SourceLocation AliasLocation,
4929                    IdentifierInfo *ClassName, SourceLocation ClassLocation);
4930
4931  bool CheckForwardProtocolDeclarationForCircularDependency(
4932    IdentifierInfo *PName,
4933    SourceLocation &PLoc, SourceLocation PrevLoc,
4934    const ObjCList<ObjCProtocolDecl> &PList);
4935
4936  Decl *ActOnStartProtocolInterface(
4937                    SourceLocation AtProtoInterfaceLoc,
4938                    IdentifierInfo *ProtocolName, SourceLocation ProtocolLoc,
4939                    Decl * const *ProtoRefNames, unsigned NumProtoRefs,
4940                    const SourceLocation *ProtoLocs,
4941                    SourceLocation EndProtoLoc,
4942                    AttributeList *AttrList);
4943
4944  Decl *ActOnStartCategoryInterface(SourceLocation AtInterfaceLoc,
4945                                    IdentifierInfo *ClassName,
4946                                    SourceLocation ClassLoc,
4947                                    IdentifierInfo *CategoryName,
4948                                    SourceLocation CategoryLoc,
4949                                    Decl * const *ProtoRefs,
4950                                    unsigned NumProtoRefs,
4951                                    const SourceLocation *ProtoLocs,
4952                                    SourceLocation EndProtoLoc);
4953
4954  Decl *ActOnStartClassImplementation(
4955                    SourceLocation AtClassImplLoc,
4956                    IdentifierInfo *ClassName, SourceLocation ClassLoc,
4957                    IdentifierInfo *SuperClassname,
4958                    SourceLocation SuperClassLoc);
4959
4960  Decl *ActOnStartCategoryImplementation(SourceLocation AtCatImplLoc,
4961                                         IdentifierInfo *ClassName,
4962                                         SourceLocation ClassLoc,
4963                                         IdentifierInfo *CatName,
4964                                         SourceLocation CatLoc);
4965
4966  Decl *ActOnForwardClassDeclaration(SourceLocation Loc,
4967                                     IdentifierInfo **IdentList,
4968                                     SourceLocation *IdentLocs,
4969                                     unsigned NumElts);
4970
4971  Decl *ActOnForwardProtocolDeclaration(SourceLocation AtProtoclLoc,
4972                                        const IdentifierLocPair *IdentList,
4973                                        unsigned NumElts,
4974                                        AttributeList *attrList);
4975
4976  void FindProtocolDeclaration(bool WarnOnDeclarations,
4977                               const IdentifierLocPair *ProtocolId,
4978                               unsigned NumProtocols,
4979                               SmallVectorImpl<Decl *> &Protocols);
4980
4981  /// Ensure attributes are consistent with type.
4982  /// \param [in, out] Attributes The attributes to check; they will
4983  /// be modified to be consistent with \arg PropertyTy.
4984  void CheckObjCPropertyAttributes(Decl *PropertyPtrTy,
4985                                   SourceLocation Loc,
4986                                   unsigned &Attributes);
4987
4988  /// Process the specified property declaration and create decls for the
4989  /// setters and getters as needed.
4990  /// \param property The property declaration being processed
4991  /// \param DC The semantic container for the property
4992  /// \param redeclaredProperty Declaration for property if redeclared
4993  ///        in class extension.
4994  /// \param lexicalDC Container for redeclaredProperty.
4995  void ProcessPropertyDecl(ObjCPropertyDecl *property,
4996                           ObjCContainerDecl *DC,
4997                           ObjCPropertyDecl *redeclaredProperty = 0,
4998                           ObjCContainerDecl *lexicalDC = 0);
4999
5000  void DiagnosePropertyMismatch(ObjCPropertyDecl *Property,
5001                                ObjCPropertyDecl *SuperProperty,
5002                                const IdentifierInfo *Name);
5003  void ComparePropertiesInBaseAndSuper(ObjCInterfaceDecl *IDecl);
5004
5005  void CompareMethodParamsInBaseAndSuper(Decl *IDecl,
5006                                         ObjCMethodDecl *MethodDecl,
5007                                         bool IsInstance);
5008
5009  void CompareProperties(Decl *CDecl, Decl *MergeProtocols);
5010
5011  void DiagnoseClassExtensionDupMethods(ObjCCategoryDecl *CAT,
5012                                        ObjCInterfaceDecl *ID);
5013
5014  void MatchOneProtocolPropertiesInClass(Decl *CDecl,
5015                                         ObjCProtocolDecl *PDecl);
5016
5017  void ActOnAtEnd(Scope *S, SourceRange AtEnd, Decl *classDecl,
5018                  Decl **allMethods = 0, unsigned allNum = 0,
5019                  Decl **allProperties = 0, unsigned pNum = 0,
5020                  DeclGroupPtrTy *allTUVars = 0, unsigned tuvNum = 0);
5021
5022  Decl *ActOnProperty(Scope *S, SourceLocation AtLoc,
5023                      FieldDeclarator &FD, ObjCDeclSpec &ODS,
5024                      Selector GetterSel, Selector SetterSel,
5025                      Decl *ClassCategory,
5026                      bool *OverridingProperty,
5027                      tok::ObjCKeywordKind MethodImplKind,
5028                      DeclContext *lexicalDC = 0);
5029
5030  Decl *ActOnPropertyImplDecl(Scope *S,
5031                              SourceLocation AtLoc,
5032                              SourceLocation PropertyLoc,
5033                              bool ImplKind,Decl *ClassImplDecl,
5034                              IdentifierInfo *PropertyId,
5035                              IdentifierInfo *PropertyIvar,
5036                              SourceLocation PropertyIvarLoc);
5037
5038  enum ObjCSpecialMethodKind {
5039    OSMK_None,
5040    OSMK_Alloc,
5041    OSMK_New,
5042    OSMK_Copy,
5043    OSMK_RetainingInit,
5044    OSMK_NonRetainingInit
5045  };
5046
5047  struct ObjCArgInfo {
5048    IdentifierInfo *Name;
5049    SourceLocation NameLoc;
5050    // The Type is null if no type was specified, and the DeclSpec is invalid
5051    // in this case.
5052    ParsedType Type;
5053    ObjCDeclSpec DeclSpec;
5054
5055    /// ArgAttrs - Attribute list for this argument.
5056    AttributeList *ArgAttrs;
5057  };
5058
5059  Decl *ActOnMethodDeclaration(
5060    Scope *S,
5061    SourceLocation BeginLoc, // location of the + or -.
5062    SourceLocation EndLoc,   // location of the ; or {.
5063    tok::TokenKind MethodType,
5064    Decl *ClassDecl, ObjCDeclSpec &ReturnQT, ParsedType ReturnType,
5065    SourceLocation SelectorStartLoc, Selector Sel,
5066    // optional arguments. The number of types/arguments is obtained
5067    // from the Sel.getNumArgs().
5068    ObjCArgInfo *ArgInfo,
5069    DeclaratorChunk::ParamInfo *CParamInfo, unsigned CNumArgs, // c-style args
5070    AttributeList *AttrList, tok::ObjCKeywordKind MethodImplKind,
5071    bool isVariadic, bool MethodDefinition);
5072
5073  // Helper method for ActOnClassMethod/ActOnInstanceMethod.
5074  // Will search "local" class/category implementations for a method decl.
5075  // Will also search in class's root looking for instance method.
5076  // Returns 0 if no method is found.
5077  ObjCMethodDecl *LookupPrivateClassMethod(Selector Sel,
5078                                           ObjCInterfaceDecl *CDecl);
5079  ObjCMethodDecl *LookupPrivateInstanceMethod(Selector Sel,
5080                                              ObjCInterfaceDecl *ClassDecl);
5081  ObjCMethodDecl *LookupMethodInQualifiedType(Selector Sel,
5082                                              const ObjCObjectPointerType *OPT,
5083                                              bool IsInstance);
5084
5085  bool inferObjCARCLifetime(ValueDecl *decl);
5086
5087  ExprResult
5088  HandleExprPropertyRefExpr(const ObjCObjectPointerType *OPT,
5089                            Expr *BaseExpr,
5090                            SourceLocation OpLoc,
5091                            DeclarationName MemberName,
5092                            SourceLocation MemberLoc,
5093                            SourceLocation SuperLoc, QualType SuperType,
5094                            bool Super);
5095
5096  ExprResult
5097  ActOnClassPropertyRefExpr(IdentifierInfo &receiverName,
5098                            IdentifierInfo &propertyName,
5099                            SourceLocation receiverNameLoc,
5100                            SourceLocation propertyNameLoc);
5101
5102  ObjCMethodDecl *tryCaptureObjCSelf();
5103
5104  /// \brief Describes the kind of message expression indicated by a message
5105  /// send that starts with an identifier.
5106  enum ObjCMessageKind {
5107    /// \brief The message is sent to 'super'.
5108    ObjCSuperMessage,
5109    /// \brief The message is an instance message.
5110    ObjCInstanceMessage,
5111    /// \brief The message is a class message, and the identifier is a type
5112    /// name.
5113    ObjCClassMessage
5114  };
5115
5116  ObjCMessageKind getObjCMessageKind(Scope *S,
5117                                     IdentifierInfo *Name,
5118                                     SourceLocation NameLoc,
5119                                     bool IsSuper,
5120                                     bool HasTrailingDot,
5121                                     ParsedType &ReceiverType);
5122
5123  ExprResult ActOnSuperMessage(Scope *S, SourceLocation SuperLoc,
5124                               Selector Sel,
5125                               SourceLocation LBracLoc,
5126                               SourceLocation SelectorLoc,
5127                               SourceLocation RBracLoc,
5128                               MultiExprArg Args);
5129
5130  ExprResult BuildClassMessage(TypeSourceInfo *ReceiverTypeInfo,
5131                               QualType ReceiverType,
5132                               SourceLocation SuperLoc,
5133                               Selector Sel,
5134                               ObjCMethodDecl *Method,
5135                               SourceLocation LBracLoc,
5136                               SourceLocation SelectorLoc,
5137                               SourceLocation RBracLoc,
5138                               MultiExprArg Args);
5139
5140  ExprResult ActOnClassMessage(Scope *S,
5141                               ParsedType Receiver,
5142                               Selector Sel,
5143                               SourceLocation LBracLoc,
5144                               SourceLocation SelectorLoc,
5145                               SourceLocation RBracLoc,
5146                               MultiExprArg Args);
5147
5148  ExprResult BuildInstanceMessage(Expr *Receiver,
5149                                  QualType ReceiverType,
5150                                  SourceLocation SuperLoc,
5151                                  Selector Sel,
5152                                  ObjCMethodDecl *Method,
5153                                  SourceLocation LBracLoc,
5154                                  SourceLocation SelectorLoc,
5155                                  SourceLocation RBracLoc,
5156                                  MultiExprArg Args);
5157
5158  ExprResult ActOnInstanceMessage(Scope *S,
5159                                  Expr *Receiver,
5160                                  Selector Sel,
5161                                  SourceLocation LBracLoc,
5162                                  SourceLocation SelectorLoc,
5163                                  SourceLocation RBracLoc,
5164                                  MultiExprArg Args);
5165
5166  ExprResult BuildObjCBridgedCast(SourceLocation LParenLoc,
5167                                  ObjCBridgeCastKind Kind,
5168                                  SourceLocation BridgeKeywordLoc,
5169                                  TypeSourceInfo *TSInfo,
5170                                  Expr *SubExpr);
5171
5172  ExprResult ActOnObjCBridgedCast(Scope *S,
5173                                  SourceLocation LParenLoc,
5174                                  ObjCBridgeCastKind Kind,
5175                                  SourceLocation BridgeKeywordLoc,
5176                                  ParsedType Type,
5177                                  SourceLocation RParenLoc,
5178                                  Expr *SubExpr);
5179
5180  bool checkInitMethod(ObjCMethodDecl *method, QualType receiverTypeIfCall);
5181
5182  /// \brief Check whether the given new method is a valid override of the
5183  /// given overridden method, and set any properties that should be inherited.
5184  ///
5185  /// \returns True if an error occurred.
5186  bool CheckObjCMethodOverride(ObjCMethodDecl *NewMethod,
5187                               const ObjCMethodDecl *Overridden,
5188                               bool IsImplementation);
5189
5190  /// \brief Check whether the given method overrides any methods in its class,
5191  /// calling \c CheckObjCMethodOverride for each overridden method.
5192  bool CheckObjCMethodOverrides(ObjCMethodDecl *NewMethod, DeclContext *DC);
5193
5194  enum PragmaOptionsAlignKind {
5195    POAK_Native,  // #pragma options align=native
5196    POAK_Natural, // #pragma options align=natural
5197    POAK_Packed,  // #pragma options align=packed
5198    POAK_Power,   // #pragma options align=power
5199    POAK_Mac68k,  // #pragma options align=mac68k
5200    POAK_Reset    // #pragma options align=reset
5201  };
5202
5203  /// ActOnPragmaOptionsAlign - Called on well formed #pragma options align.
5204  void ActOnPragmaOptionsAlign(PragmaOptionsAlignKind Kind,
5205                               SourceLocation PragmaLoc,
5206                               SourceLocation KindLoc);
5207
5208  enum PragmaPackKind {
5209    PPK_Default, // #pragma pack([n])
5210    PPK_Show,    // #pragma pack(show), only supported by MSVC.
5211    PPK_Push,    // #pragma pack(push, [identifier], [n])
5212    PPK_Pop      // #pragma pack(pop, [identifier], [n])
5213  };
5214
5215  enum PragmaMSStructKind {
5216    PMSST_OFF,  // #pragms ms_struct off
5217    PMSST_ON    // #pragms ms_struct on
5218  };
5219
5220  /// ActOnPragmaPack - Called on well formed #pragma pack(...).
5221  void ActOnPragmaPack(PragmaPackKind Kind,
5222                       IdentifierInfo *Name,
5223                       Expr *Alignment,
5224                       SourceLocation PragmaLoc,
5225                       SourceLocation LParenLoc,
5226                       SourceLocation RParenLoc);
5227
5228  /// ActOnPragmaMSStruct - Called on well formed #pragms ms_struct [on|off].
5229  void ActOnPragmaMSStruct(PragmaMSStructKind Kind);
5230
5231  /// ActOnPragmaUnused - Called on well-formed '#pragma unused'.
5232  void ActOnPragmaUnused(const Token &Identifier,
5233                         Scope *curScope,
5234                         SourceLocation PragmaLoc);
5235
5236  /// ActOnPragmaVisibility - Called on well formed #pragma GCC visibility... .
5237  void ActOnPragmaVisibility(bool IsPush, const IdentifierInfo* VisType,
5238                             SourceLocation PragmaLoc);
5239
5240  NamedDecl *DeclClonePragmaWeak(NamedDecl *ND, IdentifierInfo *II);
5241  void DeclApplyPragmaWeak(Scope *S, NamedDecl *ND, WeakInfo &W);
5242
5243  /// ActOnPragmaWeakID - Called on well formed #pragma weak ident.
5244  void ActOnPragmaWeakID(IdentifierInfo* WeakName,
5245                         SourceLocation PragmaLoc,
5246                         SourceLocation WeakNameLoc);
5247
5248  /// ActOnPragmaWeakAlias - Called on well formed #pragma weak ident = ident.
5249  void ActOnPragmaWeakAlias(IdentifierInfo* WeakName,
5250                            IdentifierInfo* AliasName,
5251                            SourceLocation PragmaLoc,
5252                            SourceLocation WeakNameLoc,
5253                            SourceLocation AliasNameLoc);
5254
5255  /// ActOnPragmaFPContract - Called on well formed
5256  /// #pragma {STDC,OPENCL} FP_CONTRACT
5257  void ActOnPragmaFPContract(tok::OnOffSwitch OOS);
5258
5259  /// AddAlignmentAttributesForRecord - Adds any needed alignment attributes to
5260  /// a the record decl, to handle '#pragma pack' and '#pragma options align'.
5261  void AddAlignmentAttributesForRecord(RecordDecl *RD);
5262
5263  /// AddMsStructLayoutForRecord - Adds ms_struct layout attribute to record.
5264  void AddMsStructLayoutForRecord(RecordDecl *RD);
5265
5266  /// FreePackedContext - Deallocate and null out PackContext.
5267  void FreePackedContext();
5268
5269  /// PushNamespaceVisibilityAttr - Note that we've entered a
5270  /// namespace with a visibility attribute.
5271  void PushNamespaceVisibilityAttr(const VisibilityAttr *Attr);
5272
5273  /// AddPushedVisibilityAttribute - If '#pragma GCC visibility' was used,
5274  /// add an appropriate visibility attribute.
5275  void AddPushedVisibilityAttribute(Decl *RD);
5276
5277  /// PopPragmaVisibility - Pop the top element of the visibility stack; used
5278  /// for '#pragma GCC visibility' and visibility attributes on namespaces.
5279  void PopPragmaVisibility();
5280
5281  /// FreeVisContext - Deallocate and null out VisContext.
5282  void FreeVisContext();
5283
5284  /// AddAlignedAttr - Adds an aligned attribute to a particular declaration.
5285  void AddAlignedAttr(SourceLocation AttrLoc, Decl *D, Expr *E);
5286  void AddAlignedAttr(SourceLocation AttrLoc, Decl *D, TypeSourceInfo *T);
5287
5288  /// CastCategory - Get the correct forwarded implicit cast result category
5289  /// from the inner expression.
5290  ExprValueKind CastCategory(Expr *E);
5291
5292  /// \brief The kind of conversion being performed.
5293  enum CheckedConversionKind {
5294    /// \brief An implicit conversion.
5295    CCK_ImplicitConversion,
5296    /// \brief A C-style cast.
5297    CCK_CStyleCast,
5298    /// \brief A functional-style cast.
5299    CCK_FunctionalCast,
5300    /// \brief A cast other than a C-style cast.
5301    CCK_OtherCast
5302  };
5303
5304  /// ImpCastExprToType - If Expr is not of type 'Type', insert an implicit
5305  /// cast.  If there is already an implicit cast, merge into the existing one.
5306  /// If isLvalue, the result of the cast is an lvalue.
5307  ExprResult ImpCastExprToType(Expr *E, QualType Type, CastKind CK,
5308                               ExprValueKind VK = VK_RValue,
5309                               const CXXCastPath *BasePath = 0,
5310                               CheckedConversionKind CCK
5311                                  = CCK_ImplicitConversion);
5312
5313  /// ScalarTypeToBooleanCastKind - Returns the cast kind corresponding
5314  /// to the conversion from scalar type ScalarTy to the Boolean type.
5315  static CastKind ScalarTypeToBooleanCastKind(QualType ScalarTy);
5316
5317  /// IgnoredValueConversions - Given that an expression's result is
5318  /// syntactically ignored, perform any conversions that are
5319  /// required.
5320  ExprResult IgnoredValueConversions(Expr *E);
5321
5322  // UsualUnaryConversions - promotes integers (C99 6.3.1.1p2) and converts
5323  // functions and arrays to their respective pointers (C99 6.3.2.1).
5324  ExprResult UsualUnaryConversions(Expr *E);
5325
5326  // DefaultFunctionArrayConversion - converts functions and arrays
5327  // to their respective pointers (C99 6.3.2.1).
5328  ExprResult DefaultFunctionArrayConversion(Expr *E);
5329
5330  // DefaultFunctionArrayLvalueConversion - converts functions and
5331  // arrays to their respective pointers and performs the
5332  // lvalue-to-rvalue conversion.
5333  ExprResult DefaultFunctionArrayLvalueConversion(Expr *E);
5334
5335  // DefaultLvalueConversion - performs lvalue-to-rvalue conversion on
5336  // the operand.  This is DefaultFunctionArrayLvalueConversion,
5337  // except that it assumes the operand isn't of function or array
5338  // type.
5339  ExprResult DefaultLvalueConversion(Expr *E);
5340
5341  // DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
5342  // do not have a prototype. Integer promotions are performed on each
5343  // argument, and arguments that have type float are promoted to double.
5344  ExprResult DefaultArgumentPromotion(Expr *E);
5345
5346  // Used for emitting the right warning by DefaultVariadicArgumentPromotion
5347  enum VariadicCallType {
5348    VariadicFunction,
5349    VariadicBlock,
5350    VariadicMethod,
5351    VariadicConstructor,
5352    VariadicDoesNotApply
5353  };
5354
5355  /// GatherArgumentsForCall - Collector argument expressions for various
5356  /// form of call prototypes.
5357  bool GatherArgumentsForCall(SourceLocation CallLoc,
5358                              FunctionDecl *FDecl,
5359                              const FunctionProtoType *Proto,
5360                              unsigned FirstProtoArg,
5361                              Expr **Args, unsigned NumArgs,
5362                              SmallVector<Expr *, 8> &AllArgs,
5363                              VariadicCallType CallType = VariadicDoesNotApply);
5364
5365  // DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
5366  // will warn if the resulting type is not a POD type.
5367  ExprResult DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
5368                                              FunctionDecl *FDecl);
5369
5370  // UsualArithmeticConversions - performs the UsualUnaryConversions on it's
5371  // operands and then handles various conversions that are common to binary
5372  // operators (C99 6.3.1.8). If both operands aren't arithmetic, this
5373  // routine returns the first non-arithmetic type found. The client is
5374  // responsible for emitting appropriate error diagnostics.
5375  QualType UsualArithmeticConversions(ExprResult &lExpr, ExprResult &rExpr,
5376                                      bool isCompAssign = false);
5377
5378  /// AssignConvertType - All of the 'assignment' semantic checks return this
5379  /// enum to indicate whether the assignment was allowed.  These checks are
5380  /// done for simple assignments, as well as initialization, return from
5381  /// function, argument passing, etc.  The query is phrased in terms of a
5382  /// source and destination type.
5383  enum AssignConvertType {
5384    /// Compatible - the types are compatible according to the standard.
5385    Compatible,
5386
5387    /// PointerToInt - The assignment converts a pointer to an int, which we
5388    /// accept as an extension.
5389    PointerToInt,
5390
5391    /// IntToPointer - The assignment converts an int to a pointer, which we
5392    /// accept as an extension.
5393    IntToPointer,
5394
5395    /// FunctionVoidPointer - The assignment is between a function pointer and
5396    /// void*, which the standard doesn't allow, but we accept as an extension.
5397    FunctionVoidPointer,
5398
5399    /// IncompatiblePointer - The assignment is between two pointers types that
5400    /// are not compatible, but we accept them as an extension.
5401    IncompatiblePointer,
5402
5403    /// IncompatiblePointer - The assignment is between two pointers types which
5404    /// point to integers which have a different sign, but are otherwise identical.
5405    /// This is a subset of the above, but broken out because it's by far the most
5406    /// common case of incompatible pointers.
5407    IncompatiblePointerSign,
5408
5409    /// CompatiblePointerDiscardsQualifiers - The assignment discards
5410    /// c/v/r qualifiers, which we accept as an extension.
5411    CompatiblePointerDiscardsQualifiers,
5412
5413    /// IncompatiblePointerDiscardsQualifiers - The assignment
5414    /// discards qualifiers that we don't permit to be discarded,
5415    /// like address spaces.
5416    IncompatiblePointerDiscardsQualifiers,
5417
5418    /// IncompatibleNestedPointerQualifiers - The assignment is between two
5419    /// nested pointer types, and the qualifiers other than the first two
5420    /// levels differ e.g. char ** -> const char **, but we accept them as an
5421    /// extension.
5422    IncompatibleNestedPointerQualifiers,
5423
5424    /// IncompatibleVectors - The assignment is between two vector types that
5425    /// have the same size, which we accept as an extension.
5426    IncompatibleVectors,
5427
5428    /// IntToBlockPointer - The assignment converts an int to a block
5429    /// pointer. We disallow this.
5430    IntToBlockPointer,
5431
5432    /// IncompatibleBlockPointer - The assignment is between two block
5433    /// pointers types that are not compatible.
5434    IncompatibleBlockPointer,
5435
5436    /// IncompatibleObjCQualifiedId - The assignment is between a qualified
5437    /// id type and something else (that is incompatible with it). For example,
5438    /// "id <XXX>" = "Foo *", where "Foo *" doesn't implement the XXX protocol.
5439    IncompatibleObjCQualifiedId,
5440
5441    /// IncompatibleObjCWeakRef - Assigning a weak-unavailable object to an
5442    /// object with __weak qualifier.
5443    IncompatibleObjCWeakRef,
5444
5445    /// Incompatible - We reject this conversion outright, it is invalid to
5446    /// represent it in the AST.
5447    Incompatible
5448  };
5449
5450  /// DiagnoseAssignmentResult - Emit a diagnostic, if required, for the
5451  /// assignment conversion type specified by ConvTy.  This returns true if the
5452  /// conversion was invalid or false if the conversion was accepted.
5453  bool DiagnoseAssignmentResult(AssignConvertType ConvTy,
5454                                SourceLocation Loc,
5455                                QualType DstType, QualType SrcType,
5456                                Expr *SrcExpr, AssignmentAction Action,
5457                                bool *Complained = 0);
5458
5459  /// CheckAssignmentConstraints - Perform type checking for assignment,
5460  /// argument passing, variable initialization, and function return values.
5461  /// C99 6.5.16.
5462  AssignConvertType CheckAssignmentConstraints(SourceLocation Loc,
5463                                               QualType lhs, QualType rhs);
5464
5465  /// Check assignment constraints and prepare for a conversion of the
5466  /// RHS to the LHS type.
5467  AssignConvertType CheckAssignmentConstraints(QualType lhs, ExprResult &rhs,
5468                                               CastKind &Kind);
5469
5470  // CheckSingleAssignmentConstraints - Currently used by
5471  // CheckAssignmentOperands, and ActOnReturnStmt. Prior to type checking,
5472  // this routine performs the default function/array converions.
5473  AssignConvertType CheckSingleAssignmentConstraints(QualType lhs,
5474                                                     ExprResult &rExprRes);
5475
5476  // \brief If the lhs type is a transparent union, check whether we
5477  // can initialize the transparent union with the given expression.
5478  AssignConvertType CheckTransparentUnionArgumentConstraints(QualType lhs,
5479                                                             ExprResult &rExpr);
5480
5481  bool IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType);
5482
5483  bool CheckExceptionSpecCompatibility(Expr *From, QualType ToType);
5484
5485  ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
5486                                       AssignmentAction Action,
5487                                       bool AllowExplicit = false);
5488  ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
5489                                       AssignmentAction Action,
5490                                       bool AllowExplicit,
5491                                       ImplicitConversionSequence& ICS);
5492  ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
5493                                       const ImplicitConversionSequence& ICS,
5494                                       AssignmentAction Action,
5495                                       CheckedConversionKind CCK
5496                                          = CCK_ImplicitConversion);
5497  ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
5498                                       const StandardConversionSequence& SCS,
5499                                       AssignmentAction Action,
5500                                       CheckedConversionKind CCK);
5501
5502  /// the following "Check" methods will return a valid/converted QualType
5503  /// or a null QualType (indicating an error diagnostic was issued).
5504
5505  /// type checking binary operators (subroutines of CreateBuiltinBinOp).
5506  QualType InvalidOperands(SourceLocation l, ExprResult &lex, ExprResult &rex);
5507  QualType CheckPointerToMemberOperands( // C++ 5.5
5508    ExprResult &lex, ExprResult &rex, ExprValueKind &VK,
5509    SourceLocation OpLoc, bool isIndirect);
5510  QualType CheckMultiplyDivideOperands( // C99 6.5.5
5511    ExprResult &lex, ExprResult &rex, SourceLocation OpLoc, bool isCompAssign,
5512                                       bool isDivide);
5513  QualType CheckRemainderOperands( // C99 6.5.5
5514    ExprResult &lex, ExprResult &rex, SourceLocation OpLoc, bool isCompAssign = false);
5515  QualType CheckAdditionOperands( // C99 6.5.6
5516    ExprResult &lex, ExprResult &rex, SourceLocation OpLoc, QualType* CompLHSTy = 0);
5517  QualType CheckSubtractionOperands( // C99 6.5.6
5518    ExprResult &lex, ExprResult &rex, SourceLocation OpLoc, QualType* CompLHSTy = 0);
5519  QualType CheckShiftOperands( // C99 6.5.7
5520    ExprResult &lex, ExprResult &rex, SourceLocation OpLoc, unsigned Opc,
5521    bool isCompAssign = false);
5522  QualType CheckCompareOperands( // C99 6.5.8/9
5523    ExprResult &lex, ExprResult &rex, SourceLocation OpLoc, unsigned Opc,
5524                                bool isRelational);
5525  QualType CheckBitwiseOperands( // C99 6.5.[10...12]
5526    ExprResult &lex, ExprResult &rex, SourceLocation OpLoc, bool isCompAssign = false);
5527  QualType CheckLogicalOperands( // C99 6.5.[13,14]
5528    ExprResult &lex, ExprResult &rex, SourceLocation OpLoc, unsigned Opc);
5529  // CheckAssignmentOperands is used for both simple and compound assignment.
5530  // For simple assignment, pass both expressions and a null converted type.
5531  // For compound assignment, pass both expressions and the converted type.
5532  QualType CheckAssignmentOperands( // C99 6.5.16.[1,2]
5533    Expr *lex, ExprResult &rex, SourceLocation OpLoc, QualType convertedType);
5534
5535  void ConvertPropertyForLValue(ExprResult &LHS, ExprResult &RHS, QualType& LHSTy);
5536  ExprResult ConvertPropertyForRValue(Expr *E);
5537
5538  QualType CheckConditionalOperands( // C99 6.5.15
5539    ExprResult &cond, ExprResult &lhs, ExprResult &rhs,
5540    ExprValueKind &VK, ExprObjectKind &OK, SourceLocation questionLoc);
5541  QualType CXXCheckConditionalOperands( // C++ 5.16
5542    ExprResult &cond, ExprResult &lhs, ExprResult &rhs,
5543    ExprValueKind &VK, ExprObjectKind &OK, SourceLocation questionLoc);
5544  QualType FindCompositePointerType(SourceLocation Loc, Expr *&E1, Expr *&E2,
5545                                    bool *NonStandardCompositeType = 0);
5546  QualType FindCompositePointerType(SourceLocation Loc, ExprResult &E1, ExprResult &E2,
5547                                    bool *NonStandardCompositeType = 0) {
5548    Expr *E1Tmp = E1.take(), *E2Tmp = E2.take();
5549    QualType Composite = FindCompositePointerType(Loc, E1Tmp, E2Tmp, NonStandardCompositeType);
5550    E1 = Owned(E1Tmp);
5551    E2 = Owned(E2Tmp);
5552    return Composite;
5553  }
5554
5555  QualType FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
5556                                        SourceLocation questionLoc);
5557
5558  bool DiagnoseConditionalForNull(Expr *LHS, Expr *RHS,
5559                                  SourceLocation QuestionLoc);
5560
5561  /// type checking for vector binary operators.
5562  QualType CheckVectorOperands(ExprResult &lex, ExprResult &rex,
5563                               SourceLocation Loc, bool isCompAssign);
5564  QualType CheckVectorCompareOperands(ExprResult &lex, ExprResult &rx,
5565                                      SourceLocation l, bool isRel);
5566
5567  /// type checking declaration initializers (C99 6.7.8)
5568  bool CheckInitList(const InitializedEntity &Entity,
5569                     InitListExpr *&InitList, QualType &DeclType);
5570  bool CheckForConstantInitializer(Expr *e, QualType t);
5571
5572  // type checking C++ declaration initializers (C++ [dcl.init]).
5573
5574  /// ReferenceCompareResult - Expresses the result of comparing two
5575  /// types (cv1 T1 and cv2 T2) to determine their compatibility for the
5576  /// purposes of initialization by reference (C++ [dcl.init.ref]p4).
5577  enum ReferenceCompareResult {
5578    /// Ref_Incompatible - The two types are incompatible, so direct
5579    /// reference binding is not possible.
5580    Ref_Incompatible = 0,
5581    /// Ref_Related - The two types are reference-related, which means
5582    /// that their unqualified forms (T1 and T2) are either the same
5583    /// or T1 is a base class of T2.
5584    Ref_Related,
5585    /// Ref_Compatible_With_Added_Qualification - The two types are
5586    /// reference-compatible with added qualification, meaning that
5587    /// they are reference-compatible and the qualifiers on T1 (cv1)
5588    /// are greater than the qualifiers on T2 (cv2).
5589    Ref_Compatible_With_Added_Qualification,
5590    /// Ref_Compatible - The two types are reference-compatible and
5591    /// have equivalent qualifiers (cv1 == cv2).
5592    Ref_Compatible
5593  };
5594
5595  ReferenceCompareResult CompareReferenceRelationship(SourceLocation Loc,
5596                                                      QualType T1, QualType T2,
5597                                                      bool &DerivedToBase,
5598                                                      bool &ObjCConversion,
5599                                                bool &ObjCLifetimeConversion);
5600
5601  /// CheckCastTypes - Check type constraints for casting between types under
5602  /// C semantics, or forward to CXXCheckCStyleCast in C++.
5603  ExprResult CheckCastTypes(SourceLocation CastStartLoc, SourceRange TyRange,
5604                            QualType CastTy, Expr *CastExpr, CastKind &Kind,
5605                            ExprValueKind &VK, CXXCastPath &BasePath,
5606                            bool FunctionalStyle = false);
5607
5608  ExprResult checkUnknownAnyCast(SourceRange TyRange, QualType castType,
5609                                 Expr *castExpr, CastKind &castKind,
5610                                 ExprValueKind &valueKind, CXXCastPath &BasePath);
5611
5612  // CheckVectorCast - check type constraints for vectors.
5613  // Since vectors are an extension, there are no C standard reference for this.
5614  // We allow casting between vectors and integer datatypes of the same size.
5615  // returns true if the cast is invalid
5616  bool CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
5617                       CastKind &Kind);
5618
5619  // CheckExtVectorCast - check type constraints for extended vectors.
5620  // Since vectors are an extension, there are no C standard reference for this.
5621  // We allow casting between vectors and integer datatypes of the same size,
5622  // or vectors and the element type of that vector.
5623  // returns the cast expr
5624  ExprResult CheckExtVectorCast(SourceRange R, QualType VectorTy, Expr *CastExpr,
5625                                CastKind &Kind);
5626
5627  /// CXXCheckCStyleCast - Check constraints of a C-style or function-style
5628  /// cast under C++ semantics.
5629  ExprResult CXXCheckCStyleCast(SourceRange R, QualType CastTy, ExprValueKind &VK,
5630                                Expr *CastExpr, CastKind &Kind,
5631                                CXXCastPath &BasePath, bool FunctionalStyle);
5632
5633  /// \brief Checks for valid expressions which can be cast to an ObjC
5634  /// pointer without needing a bridge cast.
5635  bool ValidObjCARCNoBridgeCastExpr(Expr *&Exp, QualType castType);
5636
5637  /// \brief Checks for invalid conversions and casts between
5638  /// retainable pointers and other pointer kinds.
5639  void CheckObjCARCConversion(SourceRange castRange, QualType castType,
5640                              Expr *&op, CheckedConversionKind CCK);
5641
5642  bool CheckObjCARCUnavailableWeakConversion(QualType castType,
5643                                             QualType ExprType);
5644
5645  /// checkRetainCycles - Check whether an Objective-C message send
5646  /// might create an obvious retain cycle.
5647  void checkRetainCycles(ObjCMessageExpr *msg);
5648  void checkRetainCycles(Expr *receiver, Expr *argument);
5649
5650  /// checkUnsafeAssigns - Check whether +1 expr is being assigned
5651  /// to weak/__unsafe_unretained type.
5652  bool checkUnsafeAssigns(SourceLocation Loc, QualType LHS, Expr *RHS);
5653
5654  /// checkUnsafeExprAssigns - Check whether +1 expr is being assigned
5655  /// to weak/__unsafe_unretained expression.
5656  void checkUnsafeExprAssigns(SourceLocation Loc, Expr *LHS, Expr *RHS);
5657
5658  /// CheckMessageArgumentTypes - Check types in an Obj-C message send.
5659  /// \param Method - May be null.
5660  /// \param [out] ReturnType - The return type of the send.
5661  /// \return true iff there were any incompatible types.
5662  bool CheckMessageArgumentTypes(QualType ReceiverType,
5663                                 Expr **Args, unsigned NumArgs, Selector Sel,
5664                                 ObjCMethodDecl *Method, bool isClassMessage,
5665                                 bool isSuperMessage,
5666                                 SourceLocation lbrac, SourceLocation rbrac,
5667                                 QualType &ReturnType, ExprValueKind &VK);
5668
5669  /// \brief Determine the result of a message send expression based on
5670  /// the type of the receiver, the method expected to receive the message,
5671  /// and the form of the message send.
5672  QualType getMessageSendResultType(QualType ReceiverType,
5673                                    ObjCMethodDecl *Method,
5674                                    bool isClassMessage, bool isSuperMessage);
5675
5676  /// \brief If the given expression involves a message send to a method
5677  /// with a related result type, emit a note describing what happened.
5678  void EmitRelatedResultTypeNote(const Expr *E);
5679
5680  /// CheckBooleanCondition - Diagnose problems involving the use of
5681  /// the given expression as a boolean condition (e.g. in an if
5682  /// statement).  Also performs the standard function and array
5683  /// decays, possibly changing the input variable.
5684  ///
5685  /// \param Loc - A location associated with the condition, e.g. the
5686  /// 'if' keyword.
5687  /// \return true iff there were any errors
5688  ExprResult CheckBooleanCondition(Expr *CondExpr, SourceLocation Loc);
5689
5690  ExprResult ActOnBooleanCondition(Scope *S, SourceLocation Loc,
5691                                           Expr *SubExpr);
5692
5693  /// DiagnoseAssignmentAsCondition - Given that an expression is
5694  /// being used as a boolean condition, warn if it's an assignment.
5695  void DiagnoseAssignmentAsCondition(Expr *E);
5696
5697  /// \brief Redundant parentheses over an equality comparison can indicate
5698  /// that the user intended an assignment used as condition.
5699  void DiagnoseEqualityWithExtraParens(ParenExpr *parenE);
5700
5701  /// CheckCXXBooleanCondition - Returns true if conversion to bool is invalid.
5702  ExprResult CheckCXXBooleanCondition(Expr *CondExpr);
5703
5704  /// ConvertIntegerToTypeWarnOnOverflow - Convert the specified APInt to have
5705  /// the specified width and sign.  If an overflow occurs, detect it and emit
5706  /// the specified diagnostic.
5707  void ConvertIntegerToTypeWarnOnOverflow(llvm::APSInt &OldVal,
5708                                          unsigned NewWidth, bool NewSign,
5709                                          SourceLocation Loc, unsigned DiagID);
5710
5711  /// Checks that the Objective-C declaration is declared in the global scope.
5712  /// Emits an error and marks the declaration as invalid if it's not declared
5713  /// in the global scope.
5714  bool CheckObjCDeclScope(Decl *D);
5715
5716  /// VerifyIntegerConstantExpression - verifies that an expression is an ICE,
5717  /// and reports the appropriate diagnostics. Returns false on success.
5718  /// Can optionally return the value of the expression.
5719  bool VerifyIntegerConstantExpression(const Expr *E, llvm::APSInt *Result = 0);
5720
5721  /// VerifyBitField - verifies that a bit field expression is an ICE and has
5722  /// the correct width, and that the field type is valid.
5723  /// Returns false on success.
5724  /// Can optionally return whether the bit-field is of width 0
5725  bool VerifyBitField(SourceLocation FieldLoc, IdentifierInfo *FieldName,
5726                      QualType FieldTy, const Expr *BitWidth,
5727                      bool *ZeroWidth = 0);
5728
5729  /// \name Code completion
5730  //@{
5731  /// \brief Describes the context in which code completion occurs.
5732  enum ParserCompletionContext {
5733    /// \brief Code completion occurs at top-level or namespace context.
5734    PCC_Namespace,
5735    /// \brief Code completion occurs within a class, struct, or union.
5736    PCC_Class,
5737    /// \brief Code completion occurs within an Objective-C interface, protocol,
5738    /// or category.
5739    PCC_ObjCInterface,
5740    /// \brief Code completion occurs within an Objective-C implementation or
5741    /// category implementation
5742    PCC_ObjCImplementation,
5743    /// \brief Code completion occurs within the list of instance variables
5744    /// in an Objective-C interface, protocol, category, or implementation.
5745    PCC_ObjCInstanceVariableList,
5746    /// \brief Code completion occurs following one or more template
5747    /// headers.
5748    PCC_Template,
5749    /// \brief Code completion occurs following one or more template
5750    /// headers within a class.
5751    PCC_MemberTemplate,
5752    /// \brief Code completion occurs within an expression.
5753    PCC_Expression,
5754    /// \brief Code completion occurs within a statement, which may
5755    /// also be an expression or a declaration.
5756    PCC_Statement,
5757    /// \brief Code completion occurs at the beginning of the
5758    /// initialization statement (or expression) in a for loop.
5759    PCC_ForInit,
5760    /// \brief Code completion occurs within the condition of an if,
5761    /// while, switch, or for statement.
5762    PCC_Condition,
5763    /// \brief Code completion occurs within the body of a function on a
5764    /// recovery path, where we do not have a specific handle on our position
5765    /// in the grammar.
5766    PCC_RecoveryInFunction,
5767    /// \brief Code completion occurs where only a type is permitted.
5768    PCC_Type,
5769    /// \brief Code completion occurs in a parenthesized expression, which
5770    /// might also be a type cast.
5771    PCC_ParenthesizedExpression,
5772    /// \brief Code completion occurs within a sequence of declaration
5773    /// specifiers within a function, method, or block.
5774    PCC_LocalDeclarationSpecifiers
5775  };
5776
5777  void CodeCompleteOrdinaryName(Scope *S,
5778                                ParserCompletionContext CompletionContext);
5779  void CodeCompleteDeclSpec(Scope *S, DeclSpec &DS,
5780                            bool AllowNonIdentifiers,
5781                            bool AllowNestedNameSpecifiers);
5782
5783  struct CodeCompleteExpressionData;
5784  void CodeCompleteExpression(Scope *S,
5785                              const CodeCompleteExpressionData &Data);
5786  void CodeCompleteMemberReferenceExpr(Scope *S, Expr *Base,
5787                                       SourceLocation OpLoc,
5788                                       bool IsArrow);
5789  void CodeCompletePostfixExpression(Scope *S, ExprResult LHS);
5790  void CodeCompleteTag(Scope *S, unsigned TagSpec);
5791  void CodeCompleteTypeQualifiers(DeclSpec &DS);
5792  void CodeCompleteCase(Scope *S);
5793  void CodeCompleteCall(Scope *S, Expr *Fn, Expr **Args, unsigned NumArgs);
5794  void CodeCompleteInitializer(Scope *S, Decl *D);
5795  void CodeCompleteReturn(Scope *S);
5796  void CodeCompleteAssignmentRHS(Scope *S, Expr *LHS);
5797
5798  void CodeCompleteQualifiedId(Scope *S, CXXScopeSpec &SS,
5799                               bool EnteringContext);
5800  void CodeCompleteUsing(Scope *S);
5801  void CodeCompleteUsingDirective(Scope *S);
5802  void CodeCompleteNamespaceDecl(Scope *S);
5803  void CodeCompleteNamespaceAliasDecl(Scope *S);
5804  void CodeCompleteOperatorName(Scope *S);
5805  void CodeCompleteConstructorInitializer(Decl *Constructor,
5806                                          CXXCtorInitializer** Initializers,
5807                                          unsigned NumInitializers);
5808
5809  void CodeCompleteObjCAtDirective(Scope *S, Decl *ObjCImpDecl,
5810                                   bool InInterface);
5811  void CodeCompleteObjCAtVisibility(Scope *S);
5812  void CodeCompleteObjCAtStatement(Scope *S);
5813  void CodeCompleteObjCAtExpression(Scope *S);
5814  void CodeCompleteObjCPropertyFlags(Scope *S, ObjCDeclSpec &ODS);
5815  void CodeCompleteObjCPropertyGetter(Scope *S, Decl *ClassDecl);
5816  void CodeCompleteObjCPropertySetter(Scope *S, Decl *ClassDecl);
5817  void CodeCompleteObjCPassingType(Scope *S, ObjCDeclSpec &DS,
5818                                   bool IsParameter);
5819  void CodeCompleteObjCMessageReceiver(Scope *S);
5820  void CodeCompleteObjCSuperMessage(Scope *S, SourceLocation SuperLoc,
5821                                    IdentifierInfo **SelIdents,
5822                                    unsigned NumSelIdents,
5823                                    bool AtArgumentExpression);
5824  void CodeCompleteObjCClassMessage(Scope *S, ParsedType Receiver,
5825                                    IdentifierInfo **SelIdents,
5826                                    unsigned NumSelIdents,
5827                                    bool AtArgumentExpression,
5828                                    bool IsSuper = false);
5829  void CodeCompleteObjCInstanceMessage(Scope *S, ExprTy *Receiver,
5830                                       IdentifierInfo **SelIdents,
5831                                       unsigned NumSelIdents,
5832                                       bool AtArgumentExpression,
5833                                       ObjCInterfaceDecl *Super = 0);
5834  void CodeCompleteObjCForCollection(Scope *S,
5835                                     DeclGroupPtrTy IterationVar);
5836  void CodeCompleteObjCSelector(Scope *S,
5837                                IdentifierInfo **SelIdents,
5838                                unsigned NumSelIdents);
5839  void CodeCompleteObjCProtocolReferences(IdentifierLocPair *Protocols,
5840                                          unsigned NumProtocols);
5841  void CodeCompleteObjCProtocolDecl(Scope *S);
5842  void CodeCompleteObjCInterfaceDecl(Scope *S);
5843  void CodeCompleteObjCSuperclass(Scope *S,
5844                                  IdentifierInfo *ClassName,
5845                                  SourceLocation ClassNameLoc);
5846  void CodeCompleteObjCImplementationDecl(Scope *S);
5847  void CodeCompleteObjCInterfaceCategory(Scope *S,
5848                                         IdentifierInfo *ClassName,
5849                                         SourceLocation ClassNameLoc);
5850  void CodeCompleteObjCImplementationCategory(Scope *S,
5851                                              IdentifierInfo *ClassName,
5852                                              SourceLocation ClassNameLoc);
5853  void CodeCompleteObjCPropertyDefinition(Scope *S, Decl *ObjCImpDecl);
5854  void CodeCompleteObjCPropertySynthesizeIvar(Scope *S,
5855                                              IdentifierInfo *PropertyName,
5856                                              Decl *ObjCImpDecl);
5857  void CodeCompleteObjCMethodDecl(Scope *S,
5858                                  bool IsInstanceMethod,
5859                                  ParsedType ReturnType,
5860                                  Decl *IDecl);
5861  void CodeCompleteObjCMethodDeclSelector(Scope *S,
5862                                          bool IsInstanceMethod,
5863                                          bool AtParameterName,
5864                                          ParsedType ReturnType,
5865                                          IdentifierInfo **SelIdents,
5866                                          unsigned NumSelIdents);
5867  void CodeCompletePreprocessorDirective(bool InConditional);
5868  void CodeCompleteInPreprocessorConditionalExclusion(Scope *S);
5869  void CodeCompletePreprocessorMacroName(bool IsDefinition);
5870  void CodeCompletePreprocessorExpression();
5871  void CodeCompletePreprocessorMacroArgument(Scope *S,
5872                                             IdentifierInfo *Macro,
5873                                             MacroInfo *MacroInfo,
5874                                             unsigned Argument);
5875  void CodeCompleteNaturalLanguage();
5876  void GatherGlobalCodeCompletions(CodeCompletionAllocator &Allocator,
5877                  SmallVectorImpl<CodeCompletionResult> &Results);
5878  //@}
5879
5880  //===--------------------------------------------------------------------===//
5881  // Extra semantic analysis beyond the C type system
5882
5883public:
5884  SourceLocation getLocationOfStringLiteralByte(const StringLiteral *SL,
5885                                                unsigned ByteNo) const;
5886
5887private:
5888  void CheckArrayAccess(const Expr *E);
5889  bool CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall);
5890  bool CheckBlockCall(NamedDecl *NDecl, CallExpr *TheCall);
5891
5892  bool CheckablePrintfAttr(const FormatAttr *Format, CallExpr *TheCall);
5893  bool CheckObjCString(Expr *Arg);
5894
5895  ExprResult CheckBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
5896  bool CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
5897
5898  bool SemaBuiltinVAStart(CallExpr *TheCall);
5899  bool SemaBuiltinUnorderedCompare(CallExpr *TheCall);
5900  bool SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs);
5901
5902public:
5903  // Used by C++ template instantiation.
5904  ExprResult SemaBuiltinShuffleVector(CallExpr *TheCall);
5905
5906private:
5907  bool SemaBuiltinPrefetch(CallExpr *TheCall);
5908  bool SemaBuiltinObjectSize(CallExpr *TheCall);
5909  bool SemaBuiltinLongjmp(CallExpr *TheCall);
5910  ExprResult SemaBuiltinAtomicOverloaded(ExprResult TheCallResult);
5911  bool SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
5912                              llvm::APSInt &Result);
5913
5914  bool SemaCheckStringLiteral(const Expr *E, const CallExpr *TheCall,
5915                              bool HasVAListArg, unsigned format_idx,
5916                              unsigned firstDataArg, bool isPrintf);
5917
5918  void CheckFormatString(const StringLiteral *FExpr, const Expr *OrigFormatExpr,
5919                         const CallExpr *TheCall, bool HasVAListArg,
5920                         unsigned format_idx, unsigned firstDataArg,
5921                         bool isPrintf);
5922
5923  void CheckNonNullArguments(const NonNullAttr *NonNull,
5924                             const Expr * const *ExprArgs,
5925                             SourceLocation CallSiteLoc);
5926
5927  void CheckPrintfScanfArguments(const CallExpr *TheCall, bool HasVAListArg,
5928                                 unsigned format_idx, unsigned firstDataArg,
5929                                 bool isPrintf);
5930
5931  /// \brief Enumeration used to describe which of the memory setting or copying
5932  /// functions is being checked by \c CheckMemsetcpymoveArguments().
5933  enum CheckedMemoryFunction {
5934    CMF_Memset,
5935    CMF_Memcpy,
5936    CMF_Memmove
5937  };
5938
5939  void CheckMemsetcpymoveArguments(const CallExpr *Call,
5940                                   CheckedMemoryFunction CMF,
5941                                   IdentifierInfo *FnName);
5942
5943  void CheckReturnStackAddr(Expr *RetValExp, QualType lhsType,
5944                            SourceLocation ReturnLoc);
5945  void CheckFloatComparison(SourceLocation loc, Expr* lex, Expr* rex);
5946  void CheckImplicitConversions(Expr *E, SourceLocation CC = SourceLocation());
5947
5948  void CheckBitFieldInitialization(SourceLocation InitLoc, FieldDecl *Field,
5949                                   Expr *Init);
5950
5951  /// \brief The parser's current scope.
5952  ///
5953  /// The parser maintains this state here.
5954  Scope *CurScope;
5955
5956protected:
5957  friend class Parser;
5958  friend class InitializationSequence;
5959  friend class ASTReader;
5960  friend class ASTWriter;
5961
5962public:
5963  /// \brief Retrieve the parser's current scope.
5964  ///
5965  /// This routine must only be used when it is certain that semantic analysis
5966  /// and the parser are in precisely the same context, which is not the case
5967  /// when, e.g., we are performing any kind of template instantiation.
5968  /// Therefore, the only safe places to use this scope are in the parser
5969  /// itself and in routines directly invoked from the parser and *never* from
5970  /// template substitution or instantiation.
5971  Scope *getCurScope() const { return CurScope; }
5972};
5973
5974/// \brief RAII object that enters a new expression evaluation context.
5975class EnterExpressionEvaluationContext {
5976  Sema &Actions;
5977
5978public:
5979  EnterExpressionEvaluationContext(Sema &Actions,
5980                                   Sema::ExpressionEvaluationContext NewContext)
5981    : Actions(Actions) {
5982    Actions.PushExpressionEvaluationContext(NewContext);
5983  }
5984
5985  ~EnterExpressionEvaluationContext() {
5986    Actions.PopExpressionEvaluationContext();
5987  }
5988};
5989
5990}  // end namespace clang
5991
5992#endif
5993