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