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