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