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