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