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