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