Sema.h revision e761230ae3751b525cadd8066c74ec278ee4ef57
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
181  OpenCLOptions OpenCLFeatures;
182  FPOptions FPFeatures;
183
184  const LangOptions &LangOpts;
185  Preprocessor &PP;
186  ASTContext &Context;
187  ASTConsumer &Consumer;
188  Diagnostic &Diags;
189  SourceManager &SourceMgr;
190
191  /// \brief Flag indicating whether or not to collect detailed statistics.
192  bool CollectStats;
193
194  /// \brief Source of additional semantic information.
195  ExternalSemaSource *ExternalSource;
196
197  /// \brief Code-completion consumer.
198  CodeCompleteConsumer *CodeCompleter;
199
200  /// CurContext - This is the current declaration context of parsing.
201  DeclContext *CurContext;
202
203  /// VAListTagName - The declaration name corresponding to __va_list_tag.
204  /// This is used as part of a hack to omit that class from ADL results.
205  DeclarationName VAListTagName;
206
207  /// PackContext - Manages the stack for #pragma pack. An alignment
208  /// of 0 indicates default alignment.
209  void *PackContext; // Really a "PragmaPackStack*"
210
211  bool MSStructPragmaOn; // True when #pragma ms_struct on
212
213  /// VisContext - Manages the stack for #pragma GCC visibility.
214  void *VisContext; // Really a "PragmaVisStack*"
215
216  /// ExprNeedsCleanups - True if the current evaluation context
217  /// requires cleanups to be run at its conclusion.
218  bool ExprNeedsCleanups;
219
220  /// \brief Stack containing information about each of the nested
221  /// function, block, and method scopes that are currently active.
222  ///
223  /// This array is never empty.  Clients should ignore the first
224  /// element, which is used to cache a single FunctionScopeInfo
225  /// that's used to parse every top-level function.
226  SmallVector<sema::FunctionScopeInfo *, 4> FunctionScopes;
227
228  /// ExprTemporaries - This is the stack of temporaries that are created by
229  /// the current full expression.
230  SmallVector<CXXTemporary*, 8> ExprTemporaries;
231
232  typedef LazyVector<TypedefNameDecl *, ExternalSemaSource,
233                     &ExternalSemaSource::ReadExtVectorDecls, 2, 2>
234    ExtVectorDeclsType;
235
236  /// ExtVectorDecls - This is a list all the extended vector types. This allows
237  /// us to associate a raw vector type with one of the ext_vector type names.
238  /// This is only necessary for issuing pretty diagnostics.
239  ExtVectorDeclsType ExtVectorDecls;
240
241  /// FieldCollector - Collects CXXFieldDecls during parsing of C++ classes.
242  llvm::OwningPtr<CXXFieldCollector> FieldCollector;
243
244  typedef llvm::SmallPtrSet<const CXXRecordDecl*, 8> RecordDeclSetTy;
245
246  /// PureVirtualClassDiagSet - a set of class declarations which we have
247  /// emitted a list of pure virtual functions. Used to prevent emitting the
248  /// same list more than once.
249  llvm::OwningPtr<RecordDeclSetTy> PureVirtualClassDiagSet;
250
251  /// ParsingInitForAutoVars - a set of declarations with auto types for which
252  /// we are currently parsing the initializer.
253  llvm::SmallPtrSet<const Decl*, 4> ParsingInitForAutoVars;
254
255  /// \brief A mapping from external names to the most recent
256  /// locally-scoped external declaration with that name.
257  ///
258  /// This map contains external declarations introduced in local
259  /// scoped, e.g.,
260  ///
261  /// \code
262  /// void f() {
263  ///   void foo(int, int);
264  /// }
265  /// \endcode
266  ///
267  /// Here, the name "foo" will be associated with the declaration on
268  /// "foo" within f. This name is not visible outside of
269  /// "f". However, we still find it in two cases:
270  ///
271  ///   - If we are declaring another external with the name "foo", we
272  ///     can find "foo" as a previous declaration, so that the types
273  ///     of this external declaration can be checked for
274  ///     compatibility.
275  ///
276  ///   - If we would implicitly declare "foo" (e.g., due to a call to
277  ///     "foo" in C when no prototype or definition is visible), then
278  ///     we find this declaration of "foo" and complain that it is
279  ///     not visible.
280  llvm::DenseMap<DeclarationName, NamedDecl *> LocallyScopedExternalDecls;
281
282  /// \brief Look for a locally scoped external declaration by the given name.
283  llvm::DenseMap<DeclarationName, NamedDecl *>::iterator
284  findLocallyScopedExternalDecl(DeclarationName Name);
285
286  typedef LazyVector<VarDecl *, ExternalSemaSource,
287                     &ExternalSemaSource::ReadTentativeDefinitions, 2, 2>
288    TentativeDefinitionsType;
289
290  /// \brief All the tentative definitions encountered in the TU.
291  TentativeDefinitionsType TentativeDefinitions;
292
293  typedef LazyVector<const DeclaratorDecl *, ExternalSemaSource,
294                     &ExternalSemaSource::ReadUnusedFileScopedDecls, 2, 2>
295    UnusedFileScopedDeclsType;
296
297  /// \brief The set of file scoped decls seen so far that have not been used
298  /// and must warn if not used. Only contains the first declaration.
299  UnusedFileScopedDeclsType UnusedFileScopedDecls;
300
301  typedef LazyVector<CXXConstructorDecl *, ExternalSemaSource,
302                     &ExternalSemaSource::ReadDelegatingConstructors, 2, 2>
303    DelegatingCtorDeclsType;
304
305  /// \brief All the delegating constructors seen so far in the file, used for
306  /// cycle detection at the end of the TU.
307  DelegatingCtorDeclsType DelegatingCtorDecls;
308
309  /// \brief All the overriding destructors seen during a class definition
310  /// (there could be multiple due to nested classes) that had their exception
311  /// spec checks delayed, plus the overridden destructor.
312  SmallVector<std::pair<const CXXDestructorDecl*,
313                              const CXXDestructorDecl*>, 2>
314      DelayedDestructorExceptionSpecChecks;
315
316  /// \brief Callback to the parser to parse templated functions when needed.
317  typedef void LateTemplateParserCB(void *P, const FunctionDecl *FD);
318  LateTemplateParserCB *LateTemplateParser;
319  void *OpaqueParser;
320
321  void SetLateTemplateParser(LateTemplateParserCB *LTP, void *P) {
322    LateTemplateParser = LTP;
323    OpaqueParser = P;
324  }
325
326  class DelayedDiagnostics;
327
328  class ParsingDeclState {
329    unsigned SavedStackSize;
330    friend class Sema::DelayedDiagnostics;
331  };
332
333  class ProcessingContextState {
334    unsigned SavedParsingDepth;
335    unsigned SavedActiveStackBase;
336    friend class Sema::DelayedDiagnostics;
337  };
338
339  /// A class which encapsulates the logic for delaying diagnostics
340  /// during parsing and other processing.
341  class DelayedDiagnostics {
342    /// \brief The stack of diagnostics that were delayed due to being
343    /// produced during the parsing of a declaration.
344    sema::DelayedDiagnostic *Stack;
345
346    /// \brief The number of objects on the delayed-diagnostics stack.
347    unsigned StackSize;
348
349    /// \brief The current capacity of the delayed-diagnostics stack.
350    unsigned StackCapacity;
351
352    /// \brief The index of the first "active" delayed diagnostic in
353    /// the stack.  When parsing class definitions, we ignore active
354    /// delayed diagnostics from the surrounding context.
355    unsigned ActiveStackBase;
356
357    /// \brief The depth of the declarations we're currently parsing.
358    /// This gets saved and reset whenever we enter a class definition.
359    unsigned ParsingDepth;
360
361  public:
362    DelayedDiagnostics() : Stack(0), StackSize(0), StackCapacity(0),
363      ActiveStackBase(0), ParsingDepth(0) {}
364
365    ~DelayedDiagnostics() {
366      delete[] reinterpret_cast<char*>(Stack);
367    }
368
369    /// Adds a delayed diagnostic.
370    void add(const sema::DelayedDiagnostic &diag);
371
372    /// Determines whether diagnostics should be delayed.
373    bool shouldDelayDiagnostics() { return ParsingDepth > 0; }
374
375    /// Observe that we've started parsing a declaration.  Access and
376    /// deprecation diagnostics will be delayed; when the declaration
377    /// is completed, all active delayed diagnostics will be evaluated
378    /// in its context, and then active diagnostics stack will be
379    /// popped down to the saved depth.
380    ParsingDeclState pushParsingDecl() {
381      ParsingDepth++;
382
383      ParsingDeclState state;
384      state.SavedStackSize = StackSize;
385      return state;
386    }
387
388    /// Observe that we're completed parsing a declaration.
389    static void popParsingDecl(Sema &S, ParsingDeclState state, Decl *decl);
390
391    /// Observe that we've started processing a different context, the
392    /// contents of which are semantically separate from the
393    /// declarations it may lexically appear in.  This sets aside the
394    /// current stack of active diagnostics and starts afresh.
395    ProcessingContextState pushContext() {
396      assert(StackSize >= ActiveStackBase);
397
398      ProcessingContextState state;
399      state.SavedParsingDepth = ParsingDepth;
400      state.SavedActiveStackBase = ActiveStackBase;
401
402      ActiveStackBase = StackSize;
403      ParsingDepth = 0;
404
405      return state;
406    }
407
408    /// Observe that we've stopped processing a context.  This
409    /// restores the previous stack of active diagnostics.
410    void popContext(ProcessingContextState state) {
411      assert(ActiveStackBase == StackSize);
412      assert(ParsingDepth == 0);
413      ActiveStackBase = state.SavedActiveStackBase;
414      ParsingDepth = state.SavedParsingDepth;
415    }
416  } DelayedDiagnostics;
417
418  /// A RAII object to temporarily push a declaration context.
419  class ContextRAII {
420  private:
421    Sema &S;
422    DeclContext *SavedContext;
423    ProcessingContextState SavedContextState;
424
425  public:
426    ContextRAII(Sema &S, DeclContext *ContextToPush)
427      : S(S), SavedContext(S.CurContext),
428        SavedContextState(S.DelayedDiagnostics.pushContext())
429    {
430      assert(ContextToPush && "pushing null context");
431      S.CurContext = ContextToPush;
432    }
433
434    void pop() {
435      if (!SavedContext) return;
436      S.CurContext = SavedContext;
437      S.DelayedDiagnostics.popContext(SavedContextState);
438      SavedContext = 0;
439    }
440
441    ~ContextRAII() {
442      pop();
443    }
444  };
445
446  /// WeakUndeclaredIdentifiers - Identifiers contained in
447  /// #pragma weak before declared. rare. may alias another
448  /// identifier, declared or undeclared
449  llvm::DenseMap<IdentifierInfo*,WeakInfo> WeakUndeclaredIdentifiers;
450
451  /// \brief Load weak undeclared identifiers from the external source.
452  void LoadExternalWeakUndeclaredIdentifiers();
453
454  /// WeakTopLevelDecl - Translation-unit scoped declarations generated by
455  /// #pragma weak during processing of other Decls.
456  /// I couldn't figure out a clean way to generate these in-line, so
457  /// we store them here and handle separately -- which is a hack.
458  /// It would be best to refactor this.
459  SmallVector<Decl*,2> WeakTopLevelDecl;
460
461  IdentifierResolver IdResolver;
462
463  /// Translation Unit Scope - useful to Objective-C actions that need
464  /// to lookup file scope declarations in the "ordinary" C decl namespace.
465  /// For example, user-defined classes, built-in "id" type, etc.
466  Scope *TUScope;
467
468  /// \brief The C++ "std" namespace, where the standard library resides.
469  LazyDeclPtr StdNamespace;
470
471  /// \brief The C++ "std::bad_alloc" class, which is defined by the C++
472  /// standard library.
473  LazyDeclPtr StdBadAlloc;
474
475  /// \brief The C++ "type_info" declaration, which is defined in <typeinfo>.
476  RecordDecl *CXXTypeInfoDecl;
477
478  /// \brief The MSVC "_GUID" struct, which is defined in MSVC header files.
479  RecordDecl *MSVCGuidDecl;
480
481  /// A flag to remember whether the implicit forms of operator new and delete
482  /// have been declared.
483  bool GlobalNewDeleteDeclared;
484
485
486  /// A flag that is set when parsing a -dealloc method and no [super dealloc]
487  /// call was found yet.
488  bool ObjCShouldCallSuperDealloc;
489  /// A flag that is set when parsing a -finalize method and no [super finalize]
490  /// call was found yet.
491  bool ObjCShouldCallSuperFinalize;
492
493  /// \brief The set of declarations that have been referenced within
494  /// a potentially evaluated expression.
495  typedef SmallVector<std::pair<SourceLocation, Decl *>, 10>
496    PotentiallyReferencedDecls;
497
498  /// \brief A set of diagnostics that may be emitted.
499  typedef SmallVector<std::pair<SourceLocation, PartialDiagnostic>, 10>
500    PotentiallyEmittedDiagnostics;
501
502  /// \brief Describes how the expressions currently being parsed are
503  /// evaluated at run-time, if at all.
504  enum ExpressionEvaluationContext {
505    /// \brief The current expression and its subexpressions occur within an
506    /// unevaluated operand (C++0x [expr]p8), such as a constant expression
507    /// or the subexpression of \c sizeof, where the type or the value of the
508    /// expression may be significant but no code will be generated to evaluate
509    /// the value of the expression at run time.
510    Unevaluated,
511
512    /// \brief The current expression is potentially evaluated at run time,
513    /// which means that code may be generated to evaluate the value of the
514    /// expression at run time.
515    PotentiallyEvaluated,
516
517    /// \brief The current expression may be potentially evaluated or it may
518    /// be unevaluated, but it is impossible to tell from the lexical context.
519    /// This evaluation context is used primary for the operand of the C++
520    /// \c typeid expression, whose argument is potentially evaluated only when
521    /// it is an lvalue of polymorphic class type (C++ [basic.def.odr]p2).
522    PotentiallyPotentiallyEvaluated,
523
524    /// \brief The current expression is potentially evaluated, but any
525    /// declarations referenced inside that expression are only used if
526    /// in fact the current expression is used.
527    ///
528    /// This value is used when parsing default function arguments, for which
529    /// we would like to provide diagnostics (e.g., passing non-POD arguments
530    /// through varargs) but do not want to mark declarations as "referenced"
531    /// until the default argument is used.
532    PotentiallyEvaluatedIfUsed
533  };
534
535  /// \brief Data structure used to record current or nested
536  /// expression evaluation contexts.
537  struct ExpressionEvaluationContextRecord {
538    /// \brief The expression evaluation context.
539    ExpressionEvaluationContext Context;
540
541    /// \brief Whether the enclosing context needed a cleanup.
542    bool ParentNeedsCleanups;
543
544    /// \brief The number of temporaries that were active when we
545    /// entered this expression evaluation context.
546    unsigned NumTemporaries;
547
548    /// \brief The set of declarations referenced within a
549    /// potentially potentially-evaluated context.
550    ///
551    /// When leaving a potentially potentially-evaluated context, each
552    /// of these elements will be as referenced if the corresponding
553    /// potentially potentially evaluated expression is potentially
554    /// evaluated.
555    PotentiallyReferencedDecls *PotentiallyReferenced;
556
557    /// \brief The set of diagnostics to emit should this potentially
558    /// potentially-evaluated context become evaluated.
559    PotentiallyEmittedDiagnostics *PotentiallyDiagnosed;
560
561    ExpressionEvaluationContextRecord(ExpressionEvaluationContext Context,
562                                      unsigned NumTemporaries,
563                                      bool ParentNeedsCleanups)
564      : Context(Context), ParentNeedsCleanups(ParentNeedsCleanups),
565        NumTemporaries(NumTemporaries),
566        PotentiallyReferenced(0), PotentiallyDiagnosed(0) { }
567
568    void addReferencedDecl(SourceLocation Loc, Decl *Decl) {
569      if (!PotentiallyReferenced)
570        PotentiallyReferenced = new PotentiallyReferencedDecls;
571      PotentiallyReferenced->push_back(std::make_pair(Loc, Decl));
572    }
573
574    void addDiagnostic(SourceLocation Loc, const PartialDiagnostic &PD) {
575      if (!PotentiallyDiagnosed)
576        PotentiallyDiagnosed = new PotentiallyEmittedDiagnostics;
577      PotentiallyDiagnosed->push_back(std::make_pair(Loc, PD));
578    }
579
580    void Destroy() {
581      delete PotentiallyReferenced;
582      delete PotentiallyDiagnosed;
583      PotentiallyReferenced = 0;
584      PotentiallyDiagnosed = 0;
585    }
586  };
587
588  /// A stack of expression evaluation contexts.
589  SmallVector<ExpressionEvaluationContextRecord, 8> ExprEvalContexts;
590
591  /// SpecialMemberOverloadResult - The overloading result for a special member
592  /// function.
593  ///
594  /// This is basically a wrapper around PointerIntPair. The lowest bit of the
595  /// integer is used to determine whether we have a parameter qualification
596  /// match, the second-lowest is whether we had success in resolving the
597  /// overload to a unique non-deleted function.
598  ///
599  /// The ConstParamMatch bit represents whether, when looking up a copy
600  /// constructor or assignment operator, we found a potential copy
601  /// constructor/assignment operator whose first parameter is const-qualified.
602  /// This is used for determining parameter types of other objects and is
603  /// utterly meaningless on other types of special members.
604  class SpecialMemberOverloadResult : public llvm::FastFoldingSetNode {
605    llvm::PointerIntPair<CXXMethodDecl*, 2> Pair;
606  public:
607    SpecialMemberOverloadResult(const llvm::FoldingSetNodeID &ID)
608      : FastFoldingSetNode(ID)
609    {}
610
611    CXXMethodDecl *getMethod() const { return Pair.getPointer(); }
612    void setMethod(CXXMethodDecl *MD) { Pair.setPointer(MD); }
613
614    bool hasSuccess() const { return Pair.getInt() & 0x1; }
615    void setSuccess(bool B) {
616      Pair.setInt(unsigned(B) | hasConstParamMatch() << 1);
617    }
618
619    bool hasConstParamMatch() const { return Pair.getInt() & 0x2; }
620    void setConstParamMatch(bool B) {
621      Pair.setInt(B << 1 | unsigned(hasSuccess()));
622    }
623  };
624
625  /// \brief A cache of special member function overload resolution results
626  /// for C++ records.
627  llvm::FoldingSet<SpecialMemberOverloadResult> SpecialMemberCache;
628
629  /// \brief The kind of translation unit we are processing.
630  ///
631  /// When we're processing a complete translation unit, Sema will perform
632  /// end-of-translation-unit semantic tasks (such as creating
633  /// initializers for tentative definitions in C) once parsing has
634  /// completed. Modules and precompiled headers perform different kinds of
635  /// checks.
636  TranslationUnitKind TUKind;
637
638  llvm::BumpPtrAllocator BumpAlloc;
639
640  /// \brief The number of SFINAE diagnostics that have been trapped.
641  unsigned NumSFINAEErrors;
642
643  typedef llvm::DenseMap<ParmVarDecl *, SmallVector<ParmVarDecl *, 1> >
644    UnparsedDefaultArgInstantiationsMap;
645
646  /// \brief A mapping from parameters with unparsed default arguments to the
647  /// set of instantiations of each parameter.
648  ///
649  /// This mapping is a temporary data structure used when parsing
650  /// nested class templates or nested classes of class templates,
651  /// where we might end up instantiating an inner class before the
652  /// default arguments of its methods have been parsed.
653  UnparsedDefaultArgInstantiationsMap UnparsedDefaultArgInstantiations;
654
655  // Contains the locations of the beginning of unparsed default
656  // argument locations.
657  llvm::DenseMap<ParmVarDecl *,SourceLocation> UnparsedDefaultArgLocs;
658
659  /// UndefinedInternals - all the used, undefined objects with
660  /// internal linkage in this translation unit.
661  llvm::DenseMap<NamedDecl*, SourceLocation> UndefinedInternals;
662
663  typedef std::pair<ObjCMethodList, ObjCMethodList> GlobalMethods;
664  typedef llvm::DenseMap<Selector, GlobalMethods> GlobalMethodPool;
665
666  /// Method Pool - allows efficient lookup when typechecking messages to "id".
667  /// We need to maintain a list, since selectors can have differing signatures
668  /// across classes. In Cocoa, this happens to be extremely uncommon (only 1%
669  /// of selectors are "overloaded").
670  GlobalMethodPool MethodPool;
671
672  /// Method selectors used in a @selector expression. Used for implementation
673  /// of -Wselector.
674  llvm::DenseMap<Selector, SourceLocation> ReferencedSelectors;
675
676  GlobalMethodPool::iterator ReadMethodPool(Selector Sel);
677
678  /// Private Helper predicate to check for 'self'.
679  bool isSelfExpr(Expr *RExpr);
680public:
681  Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer,
682       TranslationUnitKind TUKind = TU_Complete,
683       CodeCompleteConsumer *CompletionConsumer = 0);
684  ~Sema();
685
686  /// \brief Perform initialization that occurs after the parser has been
687  /// initialized but before it parses anything.
688  void Initialize();
689
690  const LangOptions &getLangOptions() const { return LangOpts; }
691  OpenCLOptions &getOpenCLOptions() { return OpenCLFeatures; }
692  FPOptions     &getFPOptions() { return FPFeatures; }
693
694  Diagnostic &getDiagnostics() const { return Diags; }
695  SourceManager &getSourceManager() const { return SourceMgr; }
696  const TargetAttributesSema &getTargetAttributesSema() const;
697  Preprocessor &getPreprocessor() const { return PP; }
698  ASTContext &getASTContext() const { return Context; }
699  ASTConsumer &getASTConsumer() const { return Consumer; }
700  ASTMutationListener *getASTMutationListener() const;
701
702  void PrintStats() const;
703
704  /// \brief Helper class that creates diagnostics with optional
705  /// template instantiation stacks.
706  ///
707  /// This class provides a wrapper around the basic DiagnosticBuilder
708  /// class that emits diagnostics. SemaDiagnosticBuilder is
709  /// responsible for emitting the diagnostic (as DiagnosticBuilder
710  /// does) and, if the diagnostic comes from inside a template
711  /// instantiation, printing the template instantiation stack as
712  /// well.
713  class SemaDiagnosticBuilder : public DiagnosticBuilder {
714    Sema &SemaRef;
715    unsigned DiagID;
716
717  public:
718    SemaDiagnosticBuilder(DiagnosticBuilder &DB, Sema &SemaRef, unsigned DiagID)
719      : DiagnosticBuilder(DB), SemaRef(SemaRef), DiagID(DiagID) { }
720
721    explicit SemaDiagnosticBuilder(Sema &SemaRef)
722      : DiagnosticBuilder(DiagnosticBuilder::Suppress), SemaRef(SemaRef) { }
723
724    ~SemaDiagnosticBuilder();
725  };
726
727  /// \brief Emit a diagnostic.
728  SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID);
729
730  /// \brief Emit a partial diagnostic.
731  SemaDiagnosticBuilder Diag(SourceLocation Loc, const PartialDiagnostic& PD);
732
733  /// \brief Build a partial diagnostic.
734  PartialDiagnostic PDiag(unsigned DiagID = 0); // in SemaInternal.h
735
736  bool findMacroSpelling(SourceLocation &loc, StringRef name);
737
738  ExprResult Owned(Expr* E) { return E; }
739  ExprResult Owned(ExprResult R) { return R; }
740  StmtResult Owned(Stmt* S) { return S; }
741
742  void ActOnEndOfTranslationUnit();
743
744  void CheckDelegatingCtorCycles();
745
746  Scope *getScopeForContext(DeclContext *Ctx);
747
748  void PushFunctionScope();
749  void PushBlockScope(Scope *BlockScope, BlockDecl *Block);
750  void PopFunctionOrBlockScope(const sema::AnalysisBasedWarnings::Policy *WP =0,
751                               const Decl *D = 0, const BlockExpr *blkExpr = 0);
752
753  sema::FunctionScopeInfo *getCurFunction() const {
754    return FunctionScopes.back();
755  }
756
757  bool hasAnyUnrecoverableErrorsInThisFunction() const;
758
759  /// \brief Retrieve the current block, if any.
760  sema::BlockScopeInfo *getCurBlock();
761
762  /// WeakTopLevelDeclDecls - access to #pragma weak-generated Decls
763  SmallVector<Decl*,2> &WeakTopLevelDecls() { return WeakTopLevelDecl; }
764
765  //===--------------------------------------------------------------------===//
766  // Type Analysis / Processing: SemaType.cpp.
767  //
768
769  QualType BuildQualifiedType(QualType T, SourceLocation Loc, Qualifiers Qs);
770  QualType BuildQualifiedType(QualType T, SourceLocation Loc, unsigned CVR) {
771    return BuildQualifiedType(T, Loc, Qualifiers::fromCVRMask(CVR));
772  }
773  QualType BuildPointerType(QualType T,
774                            SourceLocation Loc, DeclarationName Entity);
775  QualType BuildReferenceType(QualType T, bool LValueRef,
776                              SourceLocation Loc, DeclarationName Entity);
777  QualType BuildArrayType(QualType T, ArrayType::ArraySizeModifier ASM,
778                          Expr *ArraySize, unsigned Quals,
779                          SourceRange Brackets, DeclarationName Entity);
780  QualType BuildExtVectorType(QualType T, Expr *ArraySize,
781                              SourceLocation AttrLoc);
782  QualType BuildFunctionType(QualType T,
783                             QualType *ParamTypes, unsigned NumParamTypes,
784                             bool Variadic, unsigned Quals,
785                             RefQualifierKind RefQualifier,
786                             SourceLocation Loc, DeclarationName Entity,
787                             FunctionType::ExtInfo Info);
788  QualType BuildMemberPointerType(QualType T, QualType Class,
789                                  SourceLocation Loc,
790                                  DeclarationName Entity);
791  QualType BuildBlockPointerType(QualType T,
792                                 SourceLocation Loc, DeclarationName Entity);
793  QualType BuildParenType(QualType T);
794
795  TypeSourceInfo *GetTypeForDeclarator(Declarator &D, Scope *S);
796  TypeSourceInfo *GetTypeForDeclaratorCast(Declarator &D, QualType FromTy);
797  TypeSourceInfo *GetTypeSourceInfoForDeclarator(Declarator &D, QualType T,
798                                               TypeSourceInfo *ReturnTypeInfo);
799  /// \brief Package the given type and TSI into a ParsedType.
800  ParsedType CreateParsedType(QualType T, TypeSourceInfo *TInfo);
801  DeclarationNameInfo GetNameForDeclarator(Declarator &D);
802  DeclarationNameInfo GetNameFromUnqualifiedId(const UnqualifiedId &Name);
803  static QualType GetTypeFromParser(ParsedType Ty, TypeSourceInfo **TInfo = 0);
804  bool CheckSpecifiedExceptionType(QualType T, const SourceRange &Range);
805  bool CheckDistantExceptionSpec(QualType T);
806  bool CheckEquivalentExceptionSpec(FunctionDecl *Old, FunctionDecl *New);
807  bool CheckEquivalentExceptionSpec(
808      const FunctionProtoType *Old, SourceLocation OldLoc,
809      const FunctionProtoType *New, SourceLocation NewLoc);
810  bool CheckEquivalentExceptionSpec(
811      const PartialDiagnostic &DiagID, const PartialDiagnostic & NoteID,
812      const FunctionProtoType *Old, SourceLocation OldLoc,
813      const FunctionProtoType *New, SourceLocation NewLoc,
814      bool *MissingExceptionSpecification = 0,
815      bool *MissingEmptyExceptionSpecification = 0,
816      bool AllowNoexceptAllMatchWithNoSpec = false,
817      bool IsOperatorNew = false);
818  bool CheckExceptionSpecSubset(
819      const PartialDiagnostic &DiagID, const PartialDiagnostic & NoteID,
820      const FunctionProtoType *Superset, SourceLocation SuperLoc,
821      const FunctionProtoType *Subset, SourceLocation SubLoc);
822  bool CheckParamExceptionSpec(const PartialDiagnostic & NoteID,
823      const FunctionProtoType *Target, SourceLocation TargetLoc,
824      const FunctionProtoType *Source, SourceLocation SourceLoc);
825
826  TypeResult ActOnTypeName(Scope *S, Declarator &D);
827
828  /// \brief The parser has parsed the context-sensitive type 'instancetype'
829  /// in an Objective-C message declaration. Return the appropriate type.
830  ParsedType ActOnObjCInstanceType(SourceLocation Loc);
831
832  bool RequireCompleteType(SourceLocation Loc, QualType T,
833                           const PartialDiagnostic &PD,
834                           std::pair<SourceLocation, PartialDiagnostic> Note);
835  bool RequireCompleteType(SourceLocation Loc, QualType T,
836                           const PartialDiagnostic &PD);
837  bool RequireCompleteType(SourceLocation Loc, QualType T,
838                           unsigned DiagID);
839  bool RequireCompleteExprType(Expr *E, const PartialDiagnostic &PD,
840                               std::pair<SourceLocation,
841                                         PartialDiagnostic> Note);
842
843
844  QualType getElaboratedType(ElaboratedTypeKeyword Keyword,
845                             const CXXScopeSpec &SS, QualType T);
846
847  QualType BuildTypeofExprType(Expr *E, SourceLocation Loc);
848  QualType BuildDecltypeType(Expr *E, SourceLocation Loc);
849  QualType BuildUnaryTransformType(QualType BaseType,
850                                   UnaryTransformType::UTTKind UKind,
851                                   SourceLocation Loc);
852
853  //===--------------------------------------------------------------------===//
854  // Symbol table / Decl tracking callbacks: SemaDecl.cpp.
855  //
856
857  DeclGroupPtrTy ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType = 0);
858
859  void DiagnoseUseOfUnimplementedSelectors();
860
861  ParsedType getTypeName(IdentifierInfo &II, SourceLocation NameLoc,
862                         Scope *S, CXXScopeSpec *SS = 0,
863                         bool isClassName = false,
864                         bool HasTrailingDot = false,
865                         ParsedType ObjectType = ParsedType(),
866                         bool WantNontrivialTypeSourceInfo = false);
867  TypeSpecifierType isTagName(IdentifierInfo &II, Scope *S);
868  bool isMicrosoftMissingTypename(const CXXScopeSpec *SS);
869  bool DiagnoseUnknownTypeName(const IdentifierInfo &II,
870                               SourceLocation IILoc,
871                               Scope *S,
872                               CXXScopeSpec *SS,
873                               ParsedType &SuggestedType);
874
875  /// \brief Describes the result of the name lookup and resolution performed
876  /// by \c ClassifyName().
877  enum NameClassificationKind {
878    NC_Unknown,
879    NC_Error,
880    NC_Keyword,
881    NC_Type,
882    NC_Expression,
883    NC_NestedNameSpecifier,
884    NC_TypeTemplate,
885    NC_FunctionTemplate
886  };
887
888  class NameClassification {
889    NameClassificationKind Kind;
890    ExprResult Expr;
891    TemplateName Template;
892    ParsedType Type;
893    const IdentifierInfo *Keyword;
894
895    explicit NameClassification(NameClassificationKind Kind) : Kind(Kind) {}
896
897  public:
898    NameClassification(ExprResult Expr) : Kind(NC_Expression), Expr(Expr) {}
899
900    NameClassification(ParsedType Type) : Kind(NC_Type), Type(Type) {}
901
902    NameClassification(const IdentifierInfo *Keyword)
903      : Kind(NC_Keyword), Keyword(Keyword) { }
904
905    static NameClassification Error() {
906      return NameClassification(NC_Error);
907    }
908
909    static NameClassification Unknown() {
910      return NameClassification(NC_Unknown);
911    }
912
913    static NameClassification NestedNameSpecifier() {
914      return NameClassification(NC_NestedNameSpecifier);
915    }
916
917    static NameClassification TypeTemplate(TemplateName Name) {
918      NameClassification Result(NC_TypeTemplate);
919      Result.Template = Name;
920      return Result;
921    }
922
923    static NameClassification FunctionTemplate(TemplateName Name) {
924      NameClassification Result(NC_FunctionTemplate);
925      Result.Template = Name;
926      return Result;
927    }
928
929    NameClassificationKind getKind() const { return Kind; }
930
931    ParsedType getType() const {
932      assert(Kind == NC_Type);
933      return Type;
934    }
935
936    ExprResult getExpression() const {
937      assert(Kind == NC_Expression);
938      return Expr;
939    }
940
941    TemplateName getTemplateName() const {
942      assert(Kind == NC_TypeTemplate || Kind == NC_FunctionTemplate);
943      return Template;
944    }
945
946    TemplateNameKind getTemplateNameKind() const {
947      assert(Kind == NC_TypeTemplate || Kind == NC_FunctionTemplate);
948      return Kind == NC_TypeTemplate? TNK_Type_template : TNK_Function_template;
949    }
950};
951
952  /// \brief Perform name lookup on the given name, classifying it based on
953  /// the results of name lookup and the following token.
954  ///
955  /// This routine is used by the parser to resolve identifiers and help direct
956  /// parsing. When the identifier cannot be found, this routine will attempt
957  /// to correct the typo and classify based on the resulting name.
958  ///
959  /// \param S The scope in which we're performing name lookup.
960  ///
961  /// \param SS The nested-name-specifier that precedes the name.
962  ///
963  /// \param Name The identifier. If typo correction finds an alternative name,
964  /// this pointer parameter will be updated accordingly.
965  ///
966  /// \param NameLoc The location of the identifier.
967  ///
968  /// \param NextToken The token following the identifier. Used to help
969  /// disambiguate the name.
970  NameClassification ClassifyName(Scope *S,
971                                  CXXScopeSpec &SS,
972                                  IdentifierInfo *&Name,
973                                  SourceLocation NameLoc,
974                                  const Token &NextToken);
975
976  Decl *ActOnDeclarator(Scope *S, Declarator &D);
977
978  Decl *HandleDeclarator(Scope *S, Declarator &D,
979                         MultiTemplateParamsArg TemplateParameterLists,
980                         bool IsFunctionDefinition);
981  void RegisterLocallyScopedExternCDecl(NamedDecl *ND,
982                                        const LookupResult &Previous,
983                                        Scope *S);
984  bool DiagnoseClassNameShadow(DeclContext *DC, DeclarationNameInfo Info);
985  void DiagnoseFunctionSpecifiers(Declarator& D);
986  void CheckShadow(Scope *S, VarDecl *D, const LookupResult& R);
987  void CheckShadow(Scope *S, VarDecl *D);
988  void CheckCastAlign(Expr *Op, QualType T, SourceRange TRange);
989  void CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *D);
990  NamedDecl* ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
991                                    QualType R, TypeSourceInfo *TInfo,
992                                    LookupResult &Previous, bool &Redeclaration);
993  NamedDecl* ActOnTypedefNameDecl(Scope* S, DeclContext* DC, TypedefNameDecl *D,
994                                  LookupResult &Previous, bool &Redeclaration);
995  NamedDecl* ActOnVariableDeclarator(Scope* S, Declarator& D, DeclContext* DC,
996                                     QualType R, TypeSourceInfo *TInfo,
997                                     LookupResult &Previous,
998                                     MultiTemplateParamsArg TemplateParamLists,
999                                     bool &Redeclaration);
1000  void CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous,
1001                                bool &Redeclaration);
1002  void CheckCompleteVariableDeclaration(VarDecl *var);
1003  NamedDecl* ActOnFunctionDeclarator(Scope* S, Declarator& D, DeclContext* DC,
1004                                     QualType R, TypeSourceInfo *TInfo,
1005                                     LookupResult &Previous,
1006                                     MultiTemplateParamsArg TemplateParamLists,
1007                                     bool IsFunctionDefinition,
1008                                     bool &Redeclaration,
1009                                     bool &AddToScope);
1010  bool AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD);
1011  void DiagnoseHiddenVirtualMethods(CXXRecordDecl *DC, CXXMethodDecl *MD);
1012  void CheckFunctionDeclaration(Scope *S,
1013                                FunctionDecl *NewFD, LookupResult &Previous,
1014                                bool IsExplicitSpecialization,
1015                                bool &Redeclaration);
1016  void CheckMain(FunctionDecl *FD, const DeclSpec &D);
1017  Decl *ActOnParamDeclarator(Scope *S, Declarator &D);
1018  ParmVarDecl *BuildParmVarDeclForTypedef(DeclContext *DC,
1019                                          SourceLocation Loc,
1020                                          QualType T);
1021  ParmVarDecl *CheckParameter(DeclContext *DC, SourceLocation StartLoc,
1022                              SourceLocation NameLoc, IdentifierInfo *Name,
1023                              QualType T, TypeSourceInfo *TSInfo,
1024                              StorageClass SC, StorageClass SCAsWritten);
1025  void ActOnParamDefaultArgument(Decl *param,
1026                                 SourceLocation EqualLoc,
1027                                 Expr *defarg);
1028  void ActOnParamUnparsedDefaultArgument(Decl *param,
1029                                         SourceLocation EqualLoc,
1030                                         SourceLocation ArgLoc);
1031  void ActOnParamDefaultArgumentError(Decl *param);
1032  bool SetParamDefaultArgument(ParmVarDecl *Param, Expr *DefaultArg,
1033                               SourceLocation EqualLoc);
1034
1035  void CheckSelfReference(Decl *OrigDecl, Expr *E);
1036  void AddInitializerToDecl(Decl *dcl, Expr *init, bool DirectInit,
1037                            bool TypeMayContainAuto);
1038  void ActOnUninitializedDecl(Decl *dcl, bool TypeMayContainAuto);
1039  void ActOnInitializerError(Decl *Dcl);
1040  void ActOnCXXForRangeDecl(Decl *D);
1041  void SetDeclDeleted(Decl *dcl, SourceLocation DelLoc);
1042  void SetDeclDefaulted(Decl *dcl, SourceLocation DefaultLoc);
1043  void FinalizeDeclaration(Decl *D);
1044  DeclGroupPtrTy FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
1045                                         Decl **Group,
1046                                         unsigned NumDecls);
1047  DeclGroupPtrTy BuildDeclaratorGroup(Decl **Group, unsigned NumDecls,
1048                                      bool TypeMayContainAuto = true);
1049  void ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
1050                                       SourceLocation LocAfterDecls);
1051  void CheckForFunctionRedefinition(FunctionDecl *FD);
1052  Decl *ActOnStartOfFunctionDef(Scope *S, Declarator &D);
1053  Decl *ActOnStartOfFunctionDef(Scope *S, Decl *D);
1054  void ActOnStartOfObjCMethodDef(Scope *S, Decl *D);
1055
1056  void computeNRVO(Stmt *Body, sema::FunctionScopeInfo *Scope);
1057  Decl *ActOnFinishFunctionBody(Decl *Decl, Stmt *Body);
1058  Decl *ActOnFinishFunctionBody(Decl *Decl, Stmt *Body, bool IsInstantiation);
1059
1060  /// ActOnFinishDelayedAttribute - Invoked when we have finished parsing an
1061  /// attribute for which parsing is delayed.
1062  void ActOnFinishDelayedAttribute(Scope *S, Decl *D, ParsedAttributes &Attrs);
1063
1064  /// \brief Diagnose any unused parameters in the given sequence of
1065  /// ParmVarDecl pointers.
1066  void DiagnoseUnusedParameters(ParmVarDecl * const *Begin,
1067                                ParmVarDecl * const *End);
1068
1069  /// \brief Diagnose whether the size of parameters or return value of a
1070  /// function or obj-c method definition is pass-by-value and larger than a
1071  /// specified threshold.
1072  void DiagnoseSizeOfParametersAndReturnValue(ParmVarDecl * const *Begin,
1073                                              ParmVarDecl * const *End,
1074                                              QualType ReturnTy,
1075                                              NamedDecl *D);
1076
1077  void DiagnoseInvalidJumps(Stmt *Body);
1078  Decl *ActOnFileScopeAsmDecl(Expr *expr,
1079                              SourceLocation AsmLoc,
1080                              SourceLocation RParenLoc);
1081
1082  /// \brief The parser has processed a module import declaration.
1083  ///
1084  /// \param ImportLoc The location of the '__import_module__' keyword.
1085  ///
1086  /// \param ModuleName The name of the module.
1087  ///
1088  /// \param ModuleNameLoc The location of the module name.
1089  DeclResult ActOnModuleImport(SourceLocation ImportLoc,
1090                               IdentifierInfo &ModuleName,
1091                               SourceLocation ModuleNameLoc);
1092
1093  /// \brief Diagnose that \p New is a module-private redeclaration of
1094  /// \p Old.
1095  void diagnoseModulePrivateRedeclaration(NamedDecl *New, NamedDecl *Old,
1096                                          SourceLocation ModulePrivateKeyword
1097                                            = SourceLocation());
1098
1099  /// Scope actions.
1100  void ActOnPopScope(SourceLocation Loc, Scope *S);
1101  void ActOnTranslationUnitScope(Scope *S);
1102
1103  Decl *ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS,
1104                                   DeclSpec &DS);
1105  Decl *ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS,
1106                                   DeclSpec &DS,
1107                                   MultiTemplateParamsArg TemplateParams);
1108
1109  StmtResult ActOnVlaStmt(const DeclSpec &DS);
1110
1111  Decl *BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
1112                                    AccessSpecifier AS,
1113                                    RecordDecl *Record);
1114
1115  Decl *BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
1116                                       RecordDecl *Record);
1117
1118  bool isAcceptableTagRedeclaration(const TagDecl *Previous,
1119                                    TagTypeKind NewTag, bool isDefinition,
1120                                    SourceLocation NewTagLoc,
1121                                    const IdentifierInfo &Name);
1122
1123  enum TagUseKind {
1124    TUK_Reference,   // Reference to a tag:  'struct foo *X;'
1125    TUK_Declaration, // Fwd decl of a tag:   'struct foo;'
1126    TUK_Definition,  // Definition of a tag: 'struct foo { int X; } Y;'
1127    TUK_Friend       // Friend declaration:  'friend struct foo;'
1128  };
1129
1130  Decl *ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
1131                 SourceLocation KWLoc, CXXScopeSpec &SS,
1132                 IdentifierInfo *Name, SourceLocation NameLoc,
1133                 AttributeList *Attr, AccessSpecifier AS,
1134                 SourceLocation ModulePrivateLoc,
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 PerformContextuallyConvertToObjCPointer(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      Expr *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                            CXXCtorInitializer **MemInits,
3481                            unsigned NumMemInits,
3482                            bool AnyErrors);
3483
3484  void CheckCompletedCXXClass(CXXRecordDecl *Record);
3485  void ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
3486                                         Decl *TagDecl,
3487                                         SourceLocation LBrac,
3488                                         SourceLocation RBrac,
3489                                         AttributeList *AttrList);
3490
3491  void ActOnReenterTemplateScope(Scope *S, Decl *Template);
3492  void ActOnReenterDeclaratorTemplateScope(Scope *S, DeclaratorDecl *D);
3493  void ActOnStartDelayedMemberDeclarations(Scope *S, Decl *Record);
3494  void ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *Method);
3495  void ActOnDelayedCXXMethodParameter(Scope *S, Decl *Param);
3496  void ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *Record);
3497  void ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *Method);
3498  void ActOnFinishDelayedMemberInitializers(Decl *Record);
3499  void MarkAsLateParsedTemplate(FunctionDecl *FD, bool Flag = true);
3500  bool IsInsideALocalClassWithinATemplateFunction();
3501
3502  Decl *ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
3503                                     Expr *AssertExpr,
3504                                     Expr *AssertMessageExpr,
3505                                     SourceLocation RParenLoc);
3506
3507  FriendDecl *CheckFriendTypeDecl(SourceLocation FriendLoc,
3508                                  TypeSourceInfo *TSInfo);
3509  Decl *ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
3510                                MultiTemplateParamsArg TemplateParams);
3511  Decl *ActOnFriendFunctionDecl(Scope *S, Declarator &D, bool IsDefinition,
3512                                    MultiTemplateParamsArg TemplateParams);
3513
3514  QualType CheckConstructorDeclarator(Declarator &D, QualType R,
3515                                      StorageClass& SC);
3516  void CheckConstructor(CXXConstructorDecl *Constructor);
3517  QualType CheckDestructorDeclarator(Declarator &D, QualType R,
3518                                     StorageClass& SC);
3519  bool CheckDestructor(CXXDestructorDecl *Destructor);
3520  void CheckConversionDeclarator(Declarator &D, QualType &R,
3521                                 StorageClass& SC);
3522  Decl *ActOnConversionDeclarator(CXXConversionDecl *Conversion);
3523
3524  void CheckExplicitlyDefaultedMethods(CXXRecordDecl *Record);
3525  void CheckExplicitlyDefaultedDefaultConstructor(CXXConstructorDecl *Ctor);
3526  void CheckExplicitlyDefaultedCopyConstructor(CXXConstructorDecl *Ctor);
3527  void CheckExplicitlyDefaultedCopyAssignment(CXXMethodDecl *Method);
3528  void CheckExplicitlyDefaultedMoveConstructor(CXXConstructorDecl *Ctor);
3529  void CheckExplicitlyDefaultedMoveAssignment(CXXMethodDecl *Method);
3530  void CheckExplicitlyDefaultedDestructor(CXXDestructorDecl *Dtor);
3531
3532  //===--------------------------------------------------------------------===//
3533  // C++ Derived Classes
3534  //
3535
3536  /// ActOnBaseSpecifier - Parsed a base specifier
3537  CXXBaseSpecifier *CheckBaseSpecifier(CXXRecordDecl *Class,
3538                                       SourceRange SpecifierRange,
3539                                       bool Virtual, AccessSpecifier Access,
3540                                       TypeSourceInfo *TInfo,
3541                                       SourceLocation EllipsisLoc);
3542
3543  BaseResult ActOnBaseSpecifier(Decl *classdecl,
3544                                SourceRange SpecifierRange,
3545                                bool Virtual, AccessSpecifier Access,
3546                                ParsedType basetype,
3547                                SourceLocation BaseLoc,
3548                                SourceLocation EllipsisLoc);
3549
3550  bool AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
3551                            unsigned NumBases);
3552  void ActOnBaseSpecifiers(Decl *ClassDecl, CXXBaseSpecifier **Bases,
3553                           unsigned NumBases);
3554
3555  bool IsDerivedFrom(QualType Derived, QualType Base);
3556  bool IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths);
3557
3558  // FIXME: I don't like this name.
3559  void BuildBasePathArray(const CXXBasePaths &Paths, CXXCastPath &BasePath);
3560
3561  bool BasePathInvolvesVirtualBase(const CXXCastPath &BasePath);
3562
3563  bool CheckDerivedToBaseConversion(QualType Derived, QualType Base,
3564                                    SourceLocation Loc, SourceRange Range,
3565                                    CXXCastPath *BasePath = 0,
3566                                    bool IgnoreAccess = false);
3567  bool CheckDerivedToBaseConversion(QualType Derived, QualType Base,
3568                                    unsigned InaccessibleBaseID,
3569                                    unsigned AmbigiousBaseConvID,
3570                                    SourceLocation Loc, SourceRange Range,
3571                                    DeclarationName Name,
3572                                    CXXCastPath *BasePath);
3573
3574  std::string getAmbiguousPathsDisplayString(CXXBasePaths &Paths);
3575
3576  /// CheckOverridingFunctionReturnType - Checks whether the return types are
3577  /// covariant, according to C++ [class.virtual]p5.
3578  bool CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
3579                                         const CXXMethodDecl *Old);
3580
3581  /// CheckOverridingFunctionExceptionSpec - Checks whether the exception
3582  /// spec is a subset of base spec.
3583  bool CheckOverridingFunctionExceptionSpec(const CXXMethodDecl *New,
3584                                            const CXXMethodDecl *Old);
3585
3586  bool CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange);
3587
3588  /// CheckOverrideControl - Check C++0x override control semantics.
3589  void CheckOverrideControl(const Decl *D);
3590
3591  /// CheckForFunctionMarkedFinal - Checks whether a virtual member function
3592  /// overrides a virtual member function marked 'final', according to
3593  /// C++0x [class.virtual]p3.
3594  bool CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
3595                                              const CXXMethodDecl *Old);
3596
3597
3598  //===--------------------------------------------------------------------===//
3599  // C++ Access Control
3600  //
3601
3602  enum AccessResult {
3603    AR_accessible,
3604    AR_inaccessible,
3605    AR_dependent,
3606    AR_delayed
3607  };
3608
3609  bool SetMemberAccessSpecifier(NamedDecl *MemberDecl,
3610                                NamedDecl *PrevMemberDecl,
3611                                AccessSpecifier LexicalAS);
3612
3613  AccessResult CheckUnresolvedMemberAccess(UnresolvedMemberExpr *E,
3614                                           DeclAccessPair FoundDecl);
3615  AccessResult CheckUnresolvedLookupAccess(UnresolvedLookupExpr *E,
3616                                           DeclAccessPair FoundDecl);
3617  AccessResult CheckAllocationAccess(SourceLocation OperatorLoc,
3618                                     SourceRange PlacementRange,
3619                                     CXXRecordDecl *NamingClass,
3620                                     DeclAccessPair FoundDecl,
3621                                     bool Diagnose = true);
3622  AccessResult CheckConstructorAccess(SourceLocation Loc,
3623                                      CXXConstructorDecl *D,
3624                                      const InitializedEntity &Entity,
3625                                      AccessSpecifier Access,
3626                                      bool IsCopyBindingRefToTemp = false);
3627  AccessResult CheckConstructorAccess(SourceLocation Loc,
3628                                      CXXConstructorDecl *D,
3629                                      AccessSpecifier Access,
3630                                      PartialDiagnostic PD);
3631  AccessResult CheckDestructorAccess(SourceLocation Loc,
3632                                     CXXDestructorDecl *Dtor,
3633                                     const PartialDiagnostic &PDiag);
3634  AccessResult CheckDirectMemberAccess(SourceLocation Loc,
3635                                       NamedDecl *D,
3636                                       const PartialDiagnostic &PDiag);
3637  AccessResult CheckMemberOperatorAccess(SourceLocation Loc,
3638                                         Expr *ObjectExpr,
3639                                         Expr *ArgExpr,
3640                                         DeclAccessPair FoundDecl);
3641  AccessResult CheckAddressOfMemberAccess(Expr *OvlExpr,
3642                                          DeclAccessPair FoundDecl);
3643  AccessResult CheckBaseClassAccess(SourceLocation AccessLoc,
3644                                    QualType Base, QualType Derived,
3645                                    const CXXBasePath &Path,
3646                                    unsigned DiagID,
3647                                    bool ForceCheck = false,
3648                                    bool ForceUnprivileged = false);
3649  void CheckLookupAccess(const LookupResult &R);
3650
3651  void HandleDependentAccessCheck(const DependentDiagnostic &DD,
3652                         const MultiLevelTemplateArgumentList &TemplateArgs);
3653  void PerformDependentDiagnostics(const DeclContext *Pattern,
3654                        const MultiLevelTemplateArgumentList &TemplateArgs);
3655
3656  void HandleDelayedAccessCheck(sema::DelayedDiagnostic &DD, Decl *Ctx);
3657
3658  /// A flag to suppress access checking.
3659  bool SuppressAccessChecking;
3660
3661  /// \brief When true, access checking violations are treated as SFINAE
3662  /// failures rather than hard errors.
3663  bool AccessCheckingSFINAE;
3664
3665  void ActOnStartSuppressingAccessChecks();
3666  void ActOnStopSuppressingAccessChecks();
3667
3668  enum AbstractDiagSelID {
3669    AbstractNone = -1,
3670    AbstractReturnType,
3671    AbstractParamType,
3672    AbstractVariableType,
3673    AbstractFieldType,
3674    AbstractArrayType
3675  };
3676
3677  bool RequireNonAbstractType(SourceLocation Loc, QualType T,
3678                              const PartialDiagnostic &PD);
3679  void DiagnoseAbstractType(const CXXRecordDecl *RD);
3680
3681  bool RequireNonAbstractType(SourceLocation Loc, QualType T, unsigned DiagID,
3682                              AbstractDiagSelID SelID = AbstractNone);
3683
3684  //===--------------------------------------------------------------------===//
3685  // C++ Overloaded Operators [C++ 13.5]
3686  //
3687
3688  bool CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl);
3689
3690  bool CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl);
3691
3692  //===--------------------------------------------------------------------===//
3693  // C++ Templates [C++ 14]
3694  //
3695  void FilterAcceptableTemplateNames(LookupResult &R);
3696  bool hasAnyAcceptableTemplateNames(LookupResult &R);
3697
3698  void LookupTemplateName(LookupResult &R, Scope *S, CXXScopeSpec &SS,
3699                          QualType ObjectType, bool EnteringContext,
3700                          bool &MemberOfUnknownSpecialization);
3701
3702  TemplateNameKind isTemplateName(Scope *S,
3703                                  CXXScopeSpec &SS,
3704                                  bool hasTemplateKeyword,
3705                                  UnqualifiedId &Name,
3706                                  ParsedType ObjectType,
3707                                  bool EnteringContext,
3708                                  TemplateTy &Template,
3709                                  bool &MemberOfUnknownSpecialization);
3710
3711  bool DiagnoseUnknownTemplateName(const IdentifierInfo &II,
3712                                   SourceLocation IILoc,
3713                                   Scope *S,
3714                                   const CXXScopeSpec *SS,
3715                                   TemplateTy &SuggestedTemplate,
3716                                   TemplateNameKind &SuggestedKind);
3717
3718  bool DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl);
3719  TemplateDecl *AdjustDeclIfTemplate(Decl *&Decl);
3720
3721  Decl *ActOnTypeParameter(Scope *S, bool Typename, bool Ellipsis,
3722                           SourceLocation EllipsisLoc,
3723                           SourceLocation KeyLoc,
3724                           IdentifierInfo *ParamName,
3725                           SourceLocation ParamNameLoc,
3726                           unsigned Depth, unsigned Position,
3727                           SourceLocation EqualLoc,
3728                           ParsedType DefaultArg);
3729
3730  QualType CheckNonTypeTemplateParameterType(QualType T, SourceLocation Loc);
3731  Decl *ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
3732                                      unsigned Depth,
3733                                      unsigned Position,
3734                                      SourceLocation EqualLoc,
3735                                      Expr *DefaultArg);
3736  Decl *ActOnTemplateTemplateParameter(Scope *S,
3737                                       SourceLocation TmpLoc,
3738                                       TemplateParameterList *Params,
3739                                       SourceLocation EllipsisLoc,
3740                                       IdentifierInfo *ParamName,
3741                                       SourceLocation ParamNameLoc,
3742                                       unsigned Depth,
3743                                       unsigned Position,
3744                                       SourceLocation EqualLoc,
3745                                       ParsedTemplateArgument DefaultArg);
3746
3747  TemplateParameterList *
3748  ActOnTemplateParameterList(unsigned Depth,
3749                             SourceLocation ExportLoc,
3750                             SourceLocation TemplateLoc,
3751                             SourceLocation LAngleLoc,
3752                             Decl **Params, unsigned NumParams,
3753                             SourceLocation RAngleLoc);
3754
3755  /// \brief The context in which we are checking a template parameter
3756  /// list.
3757  enum TemplateParamListContext {
3758    TPC_ClassTemplate,
3759    TPC_FunctionTemplate,
3760    TPC_ClassTemplateMember,
3761    TPC_FriendFunctionTemplate,
3762    TPC_FriendFunctionTemplateDefinition,
3763    TPC_TypeAliasTemplate
3764  };
3765
3766  bool CheckTemplateParameterList(TemplateParameterList *NewParams,
3767                                  TemplateParameterList *OldParams,
3768                                  TemplateParamListContext TPC);
3769  TemplateParameterList *
3770  MatchTemplateParametersToScopeSpecifier(SourceLocation DeclStartLoc,
3771                                          SourceLocation DeclLoc,
3772                                          const CXXScopeSpec &SS,
3773                                          TemplateParameterList **ParamLists,
3774                                          unsigned NumParamLists,
3775                                          bool IsFriend,
3776                                          bool &IsExplicitSpecialization,
3777                                          bool &Invalid);
3778
3779  DeclResult CheckClassTemplate(Scope *S, unsigned TagSpec, TagUseKind TUK,
3780                                SourceLocation KWLoc, CXXScopeSpec &SS,
3781                                IdentifierInfo *Name, SourceLocation NameLoc,
3782                                AttributeList *Attr,
3783                                TemplateParameterList *TemplateParams,
3784                                AccessSpecifier AS,
3785                                SourceLocation ModulePrivateLoc,
3786                                unsigned NumOuterTemplateParamLists,
3787                            TemplateParameterList **OuterTemplateParamLists);
3788
3789  void translateTemplateArguments(const ASTTemplateArgsPtr &In,
3790                                  TemplateArgumentListInfo &Out);
3791
3792  void NoteAllFoundTemplates(TemplateName Name);
3793
3794  QualType CheckTemplateIdType(TemplateName Template,
3795                               SourceLocation TemplateLoc,
3796                              TemplateArgumentListInfo &TemplateArgs);
3797
3798  TypeResult
3799  ActOnTemplateIdType(CXXScopeSpec &SS,
3800                      TemplateTy Template, SourceLocation TemplateLoc,
3801                      SourceLocation LAngleLoc,
3802                      ASTTemplateArgsPtr TemplateArgs,
3803                      SourceLocation RAngleLoc);
3804
3805  /// \brief Parsed an elaborated-type-specifier that refers to a template-id,
3806  /// such as \c class T::template apply<U>.
3807  ///
3808  /// \param TUK
3809  TypeResult ActOnTagTemplateIdType(TagUseKind TUK,
3810                                    TypeSpecifierType TagSpec,
3811                                    SourceLocation TagLoc,
3812                                    CXXScopeSpec &SS,
3813                                    TemplateTy TemplateD,
3814                                    SourceLocation TemplateLoc,
3815                                    SourceLocation LAngleLoc,
3816                                    ASTTemplateArgsPtr TemplateArgsIn,
3817                                    SourceLocation RAngleLoc);
3818
3819
3820  ExprResult BuildTemplateIdExpr(const CXXScopeSpec &SS,
3821                                 LookupResult &R,
3822                                 bool RequiresADL,
3823                               const TemplateArgumentListInfo &TemplateArgs);
3824  ExprResult BuildQualifiedTemplateIdExpr(CXXScopeSpec &SS,
3825                               const DeclarationNameInfo &NameInfo,
3826                               const TemplateArgumentListInfo &TemplateArgs);
3827
3828  TemplateNameKind ActOnDependentTemplateName(Scope *S,
3829                                              SourceLocation TemplateKWLoc,
3830                                              CXXScopeSpec &SS,
3831                                              UnqualifiedId &Name,
3832                                              ParsedType ObjectType,
3833                                              bool EnteringContext,
3834                                              TemplateTy &Template);
3835
3836  DeclResult
3837  ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec, TagUseKind TUK,
3838                                   SourceLocation KWLoc,
3839                                   CXXScopeSpec &SS,
3840                                   TemplateTy Template,
3841                                   SourceLocation TemplateNameLoc,
3842                                   SourceLocation LAngleLoc,
3843                                   ASTTemplateArgsPtr TemplateArgs,
3844                                   SourceLocation RAngleLoc,
3845                                   AttributeList *Attr,
3846                                 MultiTemplateParamsArg TemplateParameterLists);
3847
3848  Decl *ActOnTemplateDeclarator(Scope *S,
3849                                MultiTemplateParamsArg TemplateParameterLists,
3850                                Declarator &D);
3851
3852  Decl *ActOnStartOfFunctionTemplateDef(Scope *FnBodyScope,
3853                                  MultiTemplateParamsArg TemplateParameterLists,
3854                                        Declarator &D);
3855
3856  bool
3857  CheckSpecializationInstantiationRedecl(SourceLocation NewLoc,
3858                                         TemplateSpecializationKind NewTSK,
3859                                         NamedDecl *PrevDecl,
3860                                         TemplateSpecializationKind PrevTSK,
3861                                         SourceLocation PrevPtOfInstantiation,
3862                                         bool &SuppressNew);
3863
3864  bool CheckDependentFunctionTemplateSpecialization(FunctionDecl *FD,
3865                    const TemplateArgumentListInfo &ExplicitTemplateArgs,
3866                                                    LookupResult &Previous);
3867
3868  bool CheckFunctionTemplateSpecialization(FunctionDecl *FD,
3869                         TemplateArgumentListInfo *ExplicitTemplateArgs,
3870                                           LookupResult &Previous);
3871  bool CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous);
3872
3873  DeclResult
3874  ActOnExplicitInstantiation(Scope *S,
3875                             SourceLocation ExternLoc,
3876                             SourceLocation TemplateLoc,
3877                             unsigned TagSpec,
3878                             SourceLocation KWLoc,
3879                             const CXXScopeSpec &SS,
3880                             TemplateTy Template,
3881                             SourceLocation TemplateNameLoc,
3882                             SourceLocation LAngleLoc,
3883                             ASTTemplateArgsPtr TemplateArgs,
3884                             SourceLocation RAngleLoc,
3885                             AttributeList *Attr);
3886
3887  DeclResult
3888  ActOnExplicitInstantiation(Scope *S,
3889                             SourceLocation ExternLoc,
3890                             SourceLocation TemplateLoc,
3891                             unsigned TagSpec,
3892                             SourceLocation KWLoc,
3893                             CXXScopeSpec &SS,
3894                             IdentifierInfo *Name,
3895                             SourceLocation NameLoc,
3896                             AttributeList *Attr);
3897
3898  DeclResult ActOnExplicitInstantiation(Scope *S,
3899                                        SourceLocation ExternLoc,
3900                                        SourceLocation TemplateLoc,
3901                                        Declarator &D);
3902
3903  TemplateArgumentLoc
3904  SubstDefaultTemplateArgumentIfAvailable(TemplateDecl *Template,
3905                                          SourceLocation TemplateLoc,
3906                                          SourceLocation RAngleLoc,
3907                                          Decl *Param,
3908                          SmallVectorImpl<TemplateArgument> &Converted);
3909
3910  /// \brief Specifies the context in which a particular template
3911  /// argument is being checked.
3912  enum CheckTemplateArgumentKind {
3913    /// \brief The template argument was specified in the code or was
3914    /// instantiated with some deduced template arguments.
3915    CTAK_Specified,
3916
3917    /// \brief The template argument was deduced via template argument
3918    /// deduction.
3919    CTAK_Deduced,
3920
3921    /// \brief The template argument was deduced from an array bound
3922    /// via template argument deduction.
3923    CTAK_DeducedFromArrayBound
3924  };
3925
3926  bool CheckTemplateArgument(NamedDecl *Param,
3927                             const TemplateArgumentLoc &Arg,
3928                             NamedDecl *Template,
3929                             SourceLocation TemplateLoc,
3930                             SourceLocation RAngleLoc,
3931                             unsigned ArgumentPackIndex,
3932                           SmallVectorImpl<TemplateArgument> &Converted,
3933                             CheckTemplateArgumentKind CTAK = CTAK_Specified);
3934
3935  /// \brief Check that the given template arguments can be be provided to
3936  /// the given template, converting the arguments along the way.
3937  ///
3938  /// \param Template The template to which the template arguments are being
3939  /// provided.
3940  ///
3941  /// \param TemplateLoc The location of the template name in the source.
3942  ///
3943  /// \param TemplateArgs The list of template arguments. If the template is
3944  /// a template template parameter, this function may extend the set of
3945  /// template arguments to also include substituted, defaulted template
3946  /// arguments.
3947  ///
3948  /// \param PartialTemplateArgs True if the list of template arguments is
3949  /// intentionally partial, e.g., because we're checking just the initial
3950  /// set of template arguments.
3951  ///
3952  /// \param Converted Will receive the converted, canonicalized template
3953  /// arguments.
3954  ///
3955  /// \returns True if an error occurred, false otherwise.
3956  bool CheckTemplateArgumentList(TemplateDecl *Template,
3957                                 SourceLocation TemplateLoc,
3958                                 TemplateArgumentListInfo &TemplateArgs,
3959                                 bool PartialTemplateArgs,
3960                           SmallVectorImpl<TemplateArgument> &Converted);
3961
3962  bool CheckTemplateTypeArgument(TemplateTypeParmDecl *Param,
3963                                 const TemplateArgumentLoc &Arg,
3964                           SmallVectorImpl<TemplateArgument> &Converted);
3965
3966  bool CheckTemplateArgument(TemplateTypeParmDecl *Param,
3967                             TypeSourceInfo *Arg);
3968  bool CheckTemplateArgumentPointerToMember(Expr *Arg,
3969                                            TemplateArgument &Converted);
3970  ExprResult CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
3971                                   QualType InstantiatedParamType, Expr *Arg,
3972                                   TemplateArgument &Converted,
3973                                   CheckTemplateArgumentKind CTAK = CTAK_Specified);
3974  bool CheckTemplateArgument(TemplateTemplateParmDecl *Param,
3975                             const TemplateArgumentLoc &Arg);
3976
3977  ExprResult
3978  BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg,
3979                                          QualType ParamType,
3980                                          SourceLocation Loc);
3981  ExprResult
3982  BuildExpressionFromIntegralTemplateArgument(const TemplateArgument &Arg,
3983                                              SourceLocation Loc);
3984
3985  /// \brief Enumeration describing how template parameter lists are compared
3986  /// for equality.
3987  enum TemplateParameterListEqualKind {
3988    /// \brief We are matching the template parameter lists of two templates
3989    /// that might be redeclarations.
3990    ///
3991    /// \code
3992    /// template<typename T> struct X;
3993    /// template<typename T> struct X;
3994    /// \endcode
3995    TPL_TemplateMatch,
3996
3997    /// \brief We are matching the template parameter lists of two template
3998    /// template parameters as part of matching the template parameter lists
3999    /// of two templates that might be redeclarations.
4000    ///
4001    /// \code
4002    /// template<template<int I> class TT> struct X;
4003    /// template<template<int Value> class Other> struct X;
4004    /// \endcode
4005    TPL_TemplateTemplateParmMatch,
4006
4007    /// \brief We are matching the template parameter lists of a template
4008    /// template argument against the template parameter lists of a template
4009    /// template parameter.
4010    ///
4011    /// \code
4012    /// template<template<int Value> class Metafun> struct X;
4013    /// template<int Value> struct integer_c;
4014    /// X<integer_c> xic;
4015    /// \endcode
4016    TPL_TemplateTemplateArgumentMatch
4017  };
4018
4019  bool TemplateParameterListsAreEqual(TemplateParameterList *New,
4020                                      TemplateParameterList *Old,
4021                                      bool Complain,
4022                                      TemplateParameterListEqualKind Kind,
4023                                      SourceLocation TemplateArgLoc
4024                                        = SourceLocation());
4025
4026  bool CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams);
4027
4028  /// \brief Called when the parser has parsed a C++ typename
4029  /// specifier, e.g., "typename T::type".
4030  ///
4031  /// \param S The scope in which this typename type occurs.
4032  /// \param TypenameLoc the location of the 'typename' keyword
4033  /// \param SS the nested-name-specifier following the typename (e.g., 'T::').
4034  /// \param II the identifier we're retrieving (e.g., 'type' in the example).
4035  /// \param IdLoc the location of the identifier.
4036  TypeResult
4037  ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
4038                    const CXXScopeSpec &SS, const IdentifierInfo &II,
4039                    SourceLocation IdLoc);
4040
4041  /// \brief Called when the parser has parsed a C++ typename
4042  /// specifier that ends in a template-id, e.g.,
4043  /// "typename MetaFun::template apply<T1, T2>".
4044  ///
4045  /// \param S The scope in which this typename type occurs.
4046  /// \param TypenameLoc the location of the 'typename' keyword
4047  /// \param SS the nested-name-specifier following the typename (e.g., 'T::').
4048  /// \param TemplateLoc the location of the 'template' keyword, if any.
4049  /// \param TemplateName The template name.
4050  /// \param TemplateNameLoc The location of the template name.
4051  /// \param LAngleLoc The location of the opening angle bracket  ('<').
4052  /// \param TemplateArgs The template arguments.
4053  /// \param RAngleLoc The location of the closing angle bracket  ('>').
4054  TypeResult
4055  ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
4056                    const CXXScopeSpec &SS,
4057                    SourceLocation TemplateLoc,
4058                    TemplateTy Template,
4059                    SourceLocation TemplateNameLoc,
4060                    SourceLocation LAngleLoc,
4061                    ASTTemplateArgsPtr TemplateArgs,
4062                    SourceLocation RAngleLoc);
4063
4064  QualType CheckTypenameType(ElaboratedTypeKeyword Keyword,
4065                             SourceLocation KeywordLoc,
4066                             NestedNameSpecifierLoc QualifierLoc,
4067                             const IdentifierInfo &II,
4068                             SourceLocation IILoc);
4069
4070  TypeSourceInfo *RebuildTypeInCurrentInstantiation(TypeSourceInfo *T,
4071                                                    SourceLocation Loc,
4072                                                    DeclarationName Name);
4073  bool RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS);
4074
4075  ExprResult RebuildExprInCurrentInstantiation(Expr *E);
4076
4077  std::string
4078  getTemplateArgumentBindingsText(const TemplateParameterList *Params,
4079                                  const TemplateArgumentList &Args);
4080
4081  std::string
4082  getTemplateArgumentBindingsText(const TemplateParameterList *Params,
4083                                  const TemplateArgument *Args,
4084                                  unsigned NumArgs);
4085
4086  //===--------------------------------------------------------------------===//
4087  // C++ Variadic Templates (C++0x [temp.variadic])
4088  //===--------------------------------------------------------------------===//
4089
4090  /// \brief The context in which an unexpanded parameter pack is
4091  /// being diagnosed.
4092  ///
4093  /// Note that the values of this enumeration line up with the first
4094  /// argument to the \c err_unexpanded_parameter_pack diagnostic.
4095  enum UnexpandedParameterPackContext {
4096    /// \brief An arbitrary expression.
4097    UPPC_Expression = 0,
4098
4099    /// \brief The base type of a class type.
4100    UPPC_BaseType,
4101
4102    /// \brief The type of an arbitrary declaration.
4103    UPPC_DeclarationType,
4104
4105    /// \brief The type of a data member.
4106    UPPC_DataMemberType,
4107
4108    /// \brief The size of a bit-field.
4109    UPPC_BitFieldWidth,
4110
4111    /// \brief The expression in a static assertion.
4112    UPPC_StaticAssertExpression,
4113
4114    /// \brief The fixed underlying type of an enumeration.
4115    UPPC_FixedUnderlyingType,
4116
4117    /// \brief The enumerator value.
4118    UPPC_EnumeratorValue,
4119
4120    /// \brief A using declaration.
4121    UPPC_UsingDeclaration,
4122
4123    /// \brief A friend declaration.
4124    UPPC_FriendDeclaration,
4125
4126    /// \brief A declaration qualifier.
4127    UPPC_DeclarationQualifier,
4128
4129    /// \brief An initializer.
4130    UPPC_Initializer,
4131
4132    /// \brief A default argument.
4133    UPPC_DefaultArgument,
4134
4135    /// \brief The type of a non-type template parameter.
4136    UPPC_NonTypeTemplateParameterType,
4137
4138    /// \brief The type of an exception.
4139    UPPC_ExceptionType,
4140
4141    /// \brief Partial specialization.
4142    UPPC_PartialSpecialization
4143  };
4144
4145  /// \brief If the given type contains an unexpanded parameter pack,
4146  /// diagnose the error.
4147  ///
4148  /// \param Loc The source location where a diagnostc should be emitted.
4149  ///
4150  /// \param T The type that is being checked for unexpanded parameter
4151  /// packs.
4152  ///
4153  /// \returns true if an error occurred, false otherwise.
4154  bool DiagnoseUnexpandedParameterPack(SourceLocation Loc, TypeSourceInfo *T,
4155                                       UnexpandedParameterPackContext UPPC);
4156
4157  /// \brief If the given expression contains an unexpanded parameter
4158  /// pack, diagnose the error.
4159  ///
4160  /// \param E The expression that is being checked for unexpanded
4161  /// parameter packs.
4162  ///
4163  /// \returns true if an error occurred, false otherwise.
4164  bool DiagnoseUnexpandedParameterPack(Expr *E,
4165                       UnexpandedParameterPackContext UPPC = UPPC_Expression);
4166
4167  /// \brief If the given nested-name-specifier contains an unexpanded
4168  /// parameter pack, diagnose the error.
4169  ///
4170  /// \param SS The nested-name-specifier that is being checked for
4171  /// unexpanded parameter packs.
4172  ///
4173  /// \returns true if an error occurred, false otherwise.
4174  bool DiagnoseUnexpandedParameterPack(const CXXScopeSpec &SS,
4175                                       UnexpandedParameterPackContext UPPC);
4176
4177  /// \brief If the given name contains an unexpanded parameter pack,
4178  /// diagnose the error.
4179  ///
4180  /// \param NameInfo The name (with source location information) that
4181  /// is being checked for unexpanded parameter packs.
4182  ///
4183  /// \returns true if an error occurred, false otherwise.
4184  bool DiagnoseUnexpandedParameterPack(const DeclarationNameInfo &NameInfo,
4185                                       UnexpandedParameterPackContext UPPC);
4186
4187  /// \brief If the given template name contains an unexpanded parameter pack,
4188  /// diagnose the error.
4189  ///
4190  /// \param Loc The location of the template name.
4191  ///
4192  /// \param Template The template name that is being checked for unexpanded
4193  /// parameter packs.
4194  ///
4195  /// \returns true if an error occurred, false otherwise.
4196  bool DiagnoseUnexpandedParameterPack(SourceLocation Loc,
4197                                       TemplateName Template,
4198                                       UnexpandedParameterPackContext UPPC);
4199
4200  /// \brief If the given template argument contains an unexpanded parameter
4201  /// pack, diagnose the error.
4202  ///
4203  /// \param Arg The template argument that is being checked for unexpanded
4204  /// parameter packs.
4205  ///
4206  /// \returns true if an error occurred, false otherwise.
4207  bool DiagnoseUnexpandedParameterPack(TemplateArgumentLoc Arg,
4208                                       UnexpandedParameterPackContext UPPC);
4209
4210  /// \brief Collect the set of unexpanded parameter packs within the given
4211  /// template argument.
4212  ///
4213  /// \param Arg The template argument that will be traversed to find
4214  /// unexpanded parameter packs.
4215  void collectUnexpandedParameterPacks(TemplateArgument Arg,
4216                   SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
4217
4218  /// \brief Collect the set of unexpanded parameter packs within the given
4219  /// template argument.
4220  ///
4221  /// \param Arg The template argument that will be traversed to find
4222  /// unexpanded parameter packs.
4223  void collectUnexpandedParameterPacks(TemplateArgumentLoc Arg,
4224                    SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
4225
4226  /// \brief Collect the set of unexpanded parameter packs within the given
4227  /// type.
4228  ///
4229  /// \param T The type that will be traversed to find
4230  /// unexpanded parameter packs.
4231  void collectUnexpandedParameterPacks(QualType T,
4232                   SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
4233
4234  /// \brief Collect the set of unexpanded parameter packs within the given
4235  /// type.
4236  ///
4237  /// \param TL The type that will be traversed to find
4238  /// unexpanded parameter packs.
4239  void collectUnexpandedParameterPacks(TypeLoc TL,
4240                   SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
4241
4242  /// \brief Invoked when parsing a template argument followed by an
4243  /// ellipsis, which creates a pack expansion.
4244  ///
4245  /// \param Arg The template argument preceding the ellipsis, which
4246  /// may already be invalid.
4247  ///
4248  /// \param EllipsisLoc The location of the ellipsis.
4249  ParsedTemplateArgument ActOnPackExpansion(const ParsedTemplateArgument &Arg,
4250                                            SourceLocation EllipsisLoc);
4251
4252  /// \brief Invoked when parsing a type followed by an ellipsis, which
4253  /// creates a pack expansion.
4254  ///
4255  /// \param Type The type preceding the ellipsis, which will become
4256  /// the pattern of the pack expansion.
4257  ///
4258  /// \param EllipsisLoc The location of the ellipsis.
4259  TypeResult ActOnPackExpansion(ParsedType Type, SourceLocation EllipsisLoc);
4260
4261  /// \brief Construct a pack expansion type from the pattern of the pack
4262  /// expansion.
4263  TypeSourceInfo *CheckPackExpansion(TypeSourceInfo *Pattern,
4264                                     SourceLocation EllipsisLoc,
4265                                     llvm::Optional<unsigned> NumExpansions);
4266
4267  /// \brief Construct a pack expansion type from the pattern of the pack
4268  /// expansion.
4269  QualType CheckPackExpansion(QualType Pattern,
4270                              SourceRange PatternRange,
4271                              SourceLocation EllipsisLoc,
4272                              llvm::Optional<unsigned> NumExpansions);
4273
4274  /// \brief Invoked when parsing an expression followed by an ellipsis, which
4275  /// creates a pack expansion.
4276  ///
4277  /// \param Pattern The expression preceding the ellipsis, which will become
4278  /// the pattern of the pack expansion.
4279  ///
4280  /// \param EllipsisLoc The location of the ellipsis.
4281  ExprResult ActOnPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc);
4282
4283  /// \brief Invoked when parsing an expression followed by an ellipsis, which
4284  /// creates a pack expansion.
4285  ///
4286  /// \param Pattern The expression preceding the ellipsis, which will become
4287  /// the pattern of the pack expansion.
4288  ///
4289  /// \param EllipsisLoc The location of the ellipsis.
4290  ExprResult CheckPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc,
4291                                llvm::Optional<unsigned> NumExpansions);
4292
4293  /// \brief Determine whether we could expand a pack expansion with the
4294  /// given set of parameter packs into separate arguments by repeatedly
4295  /// transforming the pattern.
4296  ///
4297  /// \param EllipsisLoc The location of the ellipsis that identifies the
4298  /// pack expansion.
4299  ///
4300  /// \param PatternRange The source range that covers the entire pattern of
4301  /// the pack expansion.
4302  ///
4303  /// \param Unexpanded The set of unexpanded parameter packs within the
4304  /// pattern.
4305  ///
4306  /// \param NumUnexpanded The number of unexpanded parameter packs in
4307  /// \p Unexpanded.
4308  ///
4309  /// \param ShouldExpand Will be set to \c true if the transformer should
4310  /// expand the corresponding pack expansions into separate arguments. When
4311  /// set, \c NumExpansions must also be set.
4312  ///
4313  /// \param RetainExpansion Whether the caller should add an unexpanded
4314  /// pack expansion after all of the expanded arguments. This is used
4315  /// when extending explicitly-specified template argument packs per
4316  /// C++0x [temp.arg.explicit]p9.
4317  ///
4318  /// \param NumExpansions The number of separate arguments that will be in
4319  /// the expanded form of the corresponding pack expansion. This is both an
4320  /// input and an output parameter, which can be set by the caller if the
4321  /// number of expansions is known a priori (e.g., due to a prior substitution)
4322  /// and will be set by the callee when the number of expansions is known.
4323  /// The callee must set this value when \c ShouldExpand is \c true; it may
4324  /// set this value in other cases.
4325  ///
4326  /// \returns true if an error occurred (e.g., because the parameter packs
4327  /// are to be instantiated with arguments of different lengths), false
4328  /// otherwise. If false, \c ShouldExpand (and possibly \c NumExpansions)
4329  /// must be set.
4330  bool CheckParameterPacksForExpansion(SourceLocation EllipsisLoc,
4331                                       SourceRange PatternRange,
4332                                     const UnexpandedParameterPack *Unexpanded,
4333                                       unsigned NumUnexpanded,
4334                             const MultiLevelTemplateArgumentList &TemplateArgs,
4335                                       bool &ShouldExpand,
4336                                       bool &RetainExpansion,
4337                                       llvm::Optional<unsigned> &NumExpansions);
4338
4339  /// \brief Determine the number of arguments in the given pack expansion
4340  /// type.
4341  ///
4342  /// This routine already assumes that the pack expansion type can be
4343  /// expanded and that the number of arguments in the expansion is
4344  /// consistent across all of the unexpanded parameter packs in its pattern.
4345  unsigned getNumArgumentsInExpansion(QualType T,
4346                            const MultiLevelTemplateArgumentList &TemplateArgs);
4347
4348  /// \brief Determine whether the given declarator contains any unexpanded
4349  /// parameter packs.
4350  ///
4351  /// This routine is used by the parser to disambiguate function declarators
4352  /// with an ellipsis prior to the ')', e.g.,
4353  ///
4354  /// \code
4355  ///   void f(T...);
4356  /// \endcode
4357  ///
4358  /// To determine whether we have an (unnamed) function parameter pack or
4359  /// a variadic function.
4360  ///
4361  /// \returns true if the declarator contains any unexpanded parameter packs,
4362  /// false otherwise.
4363  bool containsUnexpandedParameterPacks(Declarator &D);
4364
4365  //===--------------------------------------------------------------------===//
4366  // C++ Template Argument Deduction (C++ [temp.deduct])
4367  //===--------------------------------------------------------------------===//
4368
4369  /// \brief Describes the result of template argument deduction.
4370  ///
4371  /// The TemplateDeductionResult enumeration describes the result of
4372  /// template argument deduction, as returned from
4373  /// DeduceTemplateArguments(). The separate TemplateDeductionInfo
4374  /// structure provides additional information about the results of
4375  /// template argument deduction, e.g., the deduced template argument
4376  /// list (if successful) or the specific template parameters or
4377  /// deduced arguments that were involved in the failure.
4378  enum TemplateDeductionResult {
4379    /// \brief Template argument deduction was successful.
4380    TDK_Success = 0,
4381    /// \brief Template argument deduction exceeded the maximum template
4382    /// instantiation depth (which has already been diagnosed).
4383    TDK_InstantiationDepth,
4384    /// \brief Template argument deduction did not deduce a value
4385    /// for every template parameter.
4386    TDK_Incomplete,
4387    /// \brief Template argument deduction produced inconsistent
4388    /// deduced values for the given template parameter.
4389    TDK_Inconsistent,
4390    /// \brief Template argument deduction failed due to inconsistent
4391    /// cv-qualifiers on a template parameter type that would
4392    /// otherwise be deduced, e.g., we tried to deduce T in "const T"
4393    /// but were given a non-const "X".
4394    TDK_Underqualified,
4395    /// \brief Substitution of the deduced template argument values
4396    /// resulted in an error.
4397    TDK_SubstitutionFailure,
4398    /// \brief Substitution of the deduced template argument values
4399    /// into a non-deduced context produced a type or value that
4400    /// produces a type that does not match the original template
4401    /// arguments provided.
4402    TDK_NonDeducedMismatch,
4403    /// \brief When performing template argument deduction for a function
4404    /// template, there were too many call arguments.
4405    TDK_TooManyArguments,
4406    /// \brief When performing template argument deduction for a function
4407    /// template, there were too few call arguments.
4408    TDK_TooFewArguments,
4409    /// \brief The explicitly-specified template arguments were not valid
4410    /// template arguments for the given template.
4411    TDK_InvalidExplicitArguments,
4412    /// \brief The arguments included an overloaded function name that could
4413    /// not be resolved to a suitable function.
4414    TDK_FailedOverloadResolution
4415  };
4416
4417  TemplateDeductionResult
4418  DeduceTemplateArguments(ClassTemplatePartialSpecializationDecl *Partial,
4419                          const TemplateArgumentList &TemplateArgs,
4420                          sema::TemplateDeductionInfo &Info);
4421
4422  TemplateDeductionResult
4423  SubstituteExplicitTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
4424                              TemplateArgumentListInfo &ExplicitTemplateArgs,
4425                      SmallVectorImpl<DeducedTemplateArgument> &Deduced,
4426                                 SmallVectorImpl<QualType> &ParamTypes,
4427                                      QualType *FunctionType,
4428                                      sema::TemplateDeductionInfo &Info);
4429
4430  /// brief A function argument from which we performed template argument
4431  // deduction for a call.
4432  struct OriginalCallArg {
4433    OriginalCallArg(QualType OriginalParamType,
4434                    unsigned ArgIdx,
4435                    QualType OriginalArgType)
4436      : OriginalParamType(OriginalParamType), ArgIdx(ArgIdx),
4437        OriginalArgType(OriginalArgType) { }
4438
4439    QualType OriginalParamType;
4440    unsigned ArgIdx;
4441    QualType OriginalArgType;
4442  };
4443
4444  TemplateDeductionResult
4445  FinishTemplateArgumentDeduction(FunctionTemplateDecl *FunctionTemplate,
4446                      SmallVectorImpl<DeducedTemplateArgument> &Deduced,
4447                                  unsigned NumExplicitlySpecified,
4448                                  FunctionDecl *&Specialization,
4449                                  sema::TemplateDeductionInfo &Info,
4450           SmallVectorImpl<OriginalCallArg> const *OriginalCallArgs = 0);
4451
4452  TemplateDeductionResult
4453  DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
4454                          TemplateArgumentListInfo *ExplicitTemplateArgs,
4455                          Expr **Args, unsigned NumArgs,
4456                          FunctionDecl *&Specialization,
4457                          sema::TemplateDeductionInfo &Info);
4458
4459  TemplateDeductionResult
4460  DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
4461                          TemplateArgumentListInfo *ExplicitTemplateArgs,
4462                          QualType ArgFunctionType,
4463                          FunctionDecl *&Specialization,
4464                          sema::TemplateDeductionInfo &Info);
4465
4466  TemplateDeductionResult
4467  DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
4468                          QualType ToType,
4469                          CXXConversionDecl *&Specialization,
4470                          sema::TemplateDeductionInfo &Info);
4471
4472  TemplateDeductionResult
4473  DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
4474                          TemplateArgumentListInfo *ExplicitTemplateArgs,
4475                          FunctionDecl *&Specialization,
4476                          sema::TemplateDeductionInfo &Info);
4477
4478  bool DeduceAutoType(TypeSourceInfo *AutoType, Expr *Initializer,
4479                      TypeSourceInfo *&Result);
4480
4481  FunctionTemplateDecl *getMoreSpecializedTemplate(FunctionTemplateDecl *FT1,
4482                                                   FunctionTemplateDecl *FT2,
4483                                                   SourceLocation Loc,
4484                                           TemplatePartialOrderingContext TPOC,
4485                                                   unsigned NumCallArguments);
4486  UnresolvedSetIterator getMostSpecialized(UnresolvedSetIterator SBegin,
4487                                           UnresolvedSetIterator SEnd,
4488                                           TemplatePartialOrderingContext TPOC,
4489                                           unsigned NumCallArguments,
4490                                           SourceLocation Loc,
4491                                           const PartialDiagnostic &NoneDiag,
4492                                           const PartialDiagnostic &AmbigDiag,
4493                                        const PartialDiagnostic &CandidateDiag,
4494                                        bool Complain = true);
4495
4496  ClassTemplatePartialSpecializationDecl *
4497  getMoreSpecializedPartialSpecialization(
4498                                  ClassTemplatePartialSpecializationDecl *PS1,
4499                                  ClassTemplatePartialSpecializationDecl *PS2,
4500                                  SourceLocation Loc);
4501
4502  void MarkUsedTemplateParameters(const TemplateArgumentList &TemplateArgs,
4503                                  bool OnlyDeduced,
4504                                  unsigned Depth,
4505                                  SmallVectorImpl<bool> &Used);
4506  void MarkDeducedTemplateParameters(FunctionTemplateDecl *FunctionTemplate,
4507                                     SmallVectorImpl<bool> &Deduced);
4508
4509  //===--------------------------------------------------------------------===//
4510  // C++ Template Instantiation
4511  //
4512
4513  MultiLevelTemplateArgumentList getTemplateInstantiationArgs(NamedDecl *D,
4514                                     const TemplateArgumentList *Innermost = 0,
4515                                                bool RelativeToPrimary = false,
4516                                               const FunctionDecl *Pattern = 0);
4517
4518  /// \brief A template instantiation that is currently in progress.
4519  struct ActiveTemplateInstantiation {
4520    /// \brief The kind of template instantiation we are performing
4521    enum InstantiationKind {
4522      /// We are instantiating a template declaration. The entity is
4523      /// the declaration we're instantiating (e.g., a CXXRecordDecl).
4524      TemplateInstantiation,
4525
4526      /// We are instantiating a default argument for a template
4527      /// parameter. The Entity is the template, and
4528      /// TemplateArgs/NumTemplateArguments provides the template
4529      /// arguments as specified.
4530      /// FIXME: Use a TemplateArgumentList
4531      DefaultTemplateArgumentInstantiation,
4532
4533      /// We are instantiating a default argument for a function.
4534      /// The Entity is the ParmVarDecl, and TemplateArgs/NumTemplateArgs
4535      /// provides the template arguments as specified.
4536      DefaultFunctionArgumentInstantiation,
4537
4538      /// We are substituting explicit template arguments provided for
4539      /// a function template. The entity is a FunctionTemplateDecl.
4540      ExplicitTemplateArgumentSubstitution,
4541
4542      /// We are substituting template argument determined as part of
4543      /// template argument deduction for either a class template
4544      /// partial specialization or a function template. The
4545      /// Entity is either a ClassTemplatePartialSpecializationDecl or
4546      /// a FunctionTemplateDecl.
4547      DeducedTemplateArgumentSubstitution,
4548
4549      /// We are substituting prior template arguments into a new
4550      /// template parameter. The template parameter itself is either a
4551      /// NonTypeTemplateParmDecl or a TemplateTemplateParmDecl.
4552      PriorTemplateArgumentSubstitution,
4553
4554      /// We are checking the validity of a default template argument that
4555      /// has been used when naming a template-id.
4556      DefaultTemplateArgumentChecking
4557    } Kind;
4558
4559    /// \brief The point of instantiation within the source code.
4560    SourceLocation PointOfInstantiation;
4561
4562    /// \brief The template (or partial specialization) in which we are
4563    /// performing the instantiation, for substitutions of prior template
4564    /// arguments.
4565    NamedDecl *Template;
4566
4567    /// \brief The entity that is being instantiated.
4568    uintptr_t Entity;
4569
4570    /// \brief The list of template arguments we are substituting, if they
4571    /// are not part of the entity.
4572    const TemplateArgument *TemplateArgs;
4573
4574    /// \brief The number of template arguments in TemplateArgs.
4575    unsigned NumTemplateArgs;
4576
4577    /// \brief The template deduction info object associated with the
4578    /// substitution or checking of explicit or deduced template arguments.
4579    sema::TemplateDeductionInfo *DeductionInfo;
4580
4581    /// \brief The source range that covers the construct that cause
4582    /// the instantiation, e.g., the template-id that causes a class
4583    /// template instantiation.
4584    SourceRange InstantiationRange;
4585
4586    ActiveTemplateInstantiation()
4587      : Kind(TemplateInstantiation), Template(0), Entity(0), TemplateArgs(0),
4588        NumTemplateArgs(0), DeductionInfo(0) {}
4589
4590    /// \brief Determines whether this template is an actual instantiation
4591    /// that should be counted toward the maximum instantiation depth.
4592    bool isInstantiationRecord() const;
4593
4594    friend bool operator==(const ActiveTemplateInstantiation &X,
4595                           const ActiveTemplateInstantiation &Y) {
4596      if (X.Kind != Y.Kind)
4597        return false;
4598
4599      if (X.Entity != Y.Entity)
4600        return false;
4601
4602      switch (X.Kind) {
4603      case TemplateInstantiation:
4604        return true;
4605
4606      case PriorTemplateArgumentSubstitution:
4607      case DefaultTemplateArgumentChecking:
4608        if (X.Template != Y.Template)
4609          return false;
4610
4611        // Fall through
4612
4613      case DefaultTemplateArgumentInstantiation:
4614      case ExplicitTemplateArgumentSubstitution:
4615      case DeducedTemplateArgumentSubstitution:
4616      case DefaultFunctionArgumentInstantiation:
4617        return X.TemplateArgs == Y.TemplateArgs;
4618
4619      }
4620
4621      return true;
4622    }
4623
4624    friend bool operator!=(const ActiveTemplateInstantiation &X,
4625                           const ActiveTemplateInstantiation &Y) {
4626      return !(X == Y);
4627    }
4628  };
4629
4630  /// \brief List of active template instantiations.
4631  ///
4632  /// This vector is treated as a stack. As one template instantiation
4633  /// requires another template instantiation, additional
4634  /// instantiations are pushed onto the stack up to a
4635  /// user-configurable limit LangOptions::InstantiationDepth.
4636  SmallVector<ActiveTemplateInstantiation, 16>
4637    ActiveTemplateInstantiations;
4638
4639  /// \brief Whether we are in a SFINAE context that is not associated with
4640  /// template instantiation.
4641  ///
4642  /// This is used when setting up a SFINAE trap (\c see SFINAETrap) outside
4643  /// of a template instantiation or template argument deduction.
4644  bool InNonInstantiationSFINAEContext;
4645
4646  /// \brief The number of ActiveTemplateInstantiation entries in
4647  /// \c ActiveTemplateInstantiations that are not actual instantiations and,
4648  /// therefore, should not be counted as part of the instantiation depth.
4649  unsigned NonInstantiationEntries;
4650
4651  /// \brief The last template from which a template instantiation
4652  /// error or warning was produced.
4653  ///
4654  /// This value is used to suppress printing of redundant template
4655  /// instantiation backtraces when there are multiple errors in the
4656  /// same instantiation. FIXME: Does this belong in Sema? It's tough
4657  /// to implement it anywhere else.
4658  ActiveTemplateInstantiation LastTemplateInstantiationErrorContext;
4659
4660  /// \brief The current index into pack expansion arguments that will be
4661  /// used for substitution of parameter packs.
4662  ///
4663  /// The pack expansion index will be -1 to indicate that parameter packs
4664  /// should be instantiated as themselves. Otherwise, the index specifies
4665  /// which argument within the parameter pack will be used for substitution.
4666  int ArgumentPackSubstitutionIndex;
4667
4668  /// \brief RAII object used to change the argument pack substitution index
4669  /// within a \c Sema object.
4670  ///
4671  /// See \c ArgumentPackSubstitutionIndex for more information.
4672  class ArgumentPackSubstitutionIndexRAII {
4673    Sema &Self;
4674    int OldSubstitutionIndex;
4675
4676  public:
4677    ArgumentPackSubstitutionIndexRAII(Sema &Self, int NewSubstitutionIndex)
4678      : Self(Self), OldSubstitutionIndex(Self.ArgumentPackSubstitutionIndex) {
4679      Self.ArgumentPackSubstitutionIndex = NewSubstitutionIndex;
4680    }
4681
4682    ~ArgumentPackSubstitutionIndexRAII() {
4683      Self.ArgumentPackSubstitutionIndex = OldSubstitutionIndex;
4684    }
4685  };
4686
4687  friend class ArgumentPackSubstitutionRAII;
4688
4689  /// \brief The stack of calls expression undergoing template instantiation.
4690  ///
4691  /// The top of this stack is used by a fixit instantiating unresolved
4692  /// function calls to fix the AST to match the textual change it prints.
4693  SmallVector<CallExpr *, 8> CallsUndergoingInstantiation;
4694
4695  /// \brief For each declaration that involved template argument deduction, the
4696  /// set of diagnostics that were suppressed during that template argument
4697  /// deduction.
4698  ///
4699  /// FIXME: Serialize this structure to the AST file.
4700  llvm::DenseMap<Decl *, SmallVector<PartialDiagnosticAt, 1> >
4701    SuppressedDiagnostics;
4702
4703  /// \brief A stack object to be created when performing template
4704  /// instantiation.
4705  ///
4706  /// Construction of an object of type \c InstantiatingTemplate
4707  /// pushes the current instantiation onto the stack of active
4708  /// instantiations. If the size of this stack exceeds the maximum
4709  /// number of recursive template instantiations, construction
4710  /// produces an error and evaluates true.
4711  ///
4712  /// Destruction of this object will pop the named instantiation off
4713  /// the stack.
4714  struct InstantiatingTemplate {
4715    /// \brief Note that we are instantiating a class template,
4716    /// function template, or a member thereof.
4717    InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
4718                          Decl *Entity,
4719                          SourceRange InstantiationRange = SourceRange());
4720
4721    /// \brief Note that we are instantiating a default argument in a
4722    /// template-id.
4723    InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
4724                          TemplateDecl *Template,
4725                          const TemplateArgument *TemplateArgs,
4726                          unsigned NumTemplateArgs,
4727                          SourceRange InstantiationRange = SourceRange());
4728
4729    /// \brief Note that we are instantiating a default argument in a
4730    /// template-id.
4731    InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
4732                          FunctionTemplateDecl *FunctionTemplate,
4733                          const TemplateArgument *TemplateArgs,
4734                          unsigned NumTemplateArgs,
4735                          ActiveTemplateInstantiation::InstantiationKind Kind,
4736                          sema::TemplateDeductionInfo &DeductionInfo,
4737                          SourceRange InstantiationRange = SourceRange());
4738
4739    /// \brief Note that we are instantiating as part of template
4740    /// argument deduction for a class template partial
4741    /// specialization.
4742    InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
4743                          ClassTemplatePartialSpecializationDecl *PartialSpec,
4744                          const TemplateArgument *TemplateArgs,
4745                          unsigned NumTemplateArgs,
4746                          sema::TemplateDeductionInfo &DeductionInfo,
4747                          SourceRange InstantiationRange = SourceRange());
4748
4749    InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
4750                          ParmVarDecl *Param,
4751                          const TemplateArgument *TemplateArgs,
4752                          unsigned NumTemplateArgs,
4753                          SourceRange InstantiationRange = SourceRange());
4754
4755    /// \brief Note that we are substituting prior template arguments into a
4756    /// non-type or template template parameter.
4757    InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
4758                          NamedDecl *Template,
4759                          NonTypeTemplateParmDecl *Param,
4760                          const TemplateArgument *TemplateArgs,
4761                          unsigned NumTemplateArgs,
4762                          SourceRange InstantiationRange);
4763
4764    InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
4765                          NamedDecl *Template,
4766                          TemplateTemplateParmDecl *Param,
4767                          const TemplateArgument *TemplateArgs,
4768                          unsigned NumTemplateArgs,
4769                          SourceRange InstantiationRange);
4770
4771    /// \brief Note that we are checking the default template argument
4772    /// against the template parameter for a given template-id.
4773    InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
4774                          TemplateDecl *Template,
4775                          NamedDecl *Param,
4776                          const TemplateArgument *TemplateArgs,
4777                          unsigned NumTemplateArgs,
4778                          SourceRange InstantiationRange);
4779
4780
4781    /// \brief Note that we have finished instantiating this template.
4782    void Clear();
4783
4784    ~InstantiatingTemplate() { Clear(); }
4785
4786    /// \brief Determines whether we have exceeded the maximum
4787    /// recursive template instantiations.
4788    operator bool() const { return Invalid; }
4789
4790  private:
4791    Sema &SemaRef;
4792    bool Invalid;
4793    bool SavedInNonInstantiationSFINAEContext;
4794    bool CheckInstantiationDepth(SourceLocation PointOfInstantiation,
4795                                 SourceRange InstantiationRange);
4796
4797    InstantiatingTemplate(const InstantiatingTemplate&); // not implemented
4798
4799    InstantiatingTemplate&
4800    operator=(const InstantiatingTemplate&); // not implemented
4801  };
4802
4803  void PrintInstantiationStack();
4804
4805  /// \brief Determines whether we are currently in a context where
4806  /// template argument substitution failures are not considered
4807  /// errors.
4808  ///
4809  /// \returns An empty \c llvm::Optional if we're not in a SFINAE context.
4810  /// Otherwise, contains a pointer that, if non-NULL, contains the nearest
4811  /// template-deduction context object, which can be used to capture
4812  /// diagnostics that will be suppressed.
4813  llvm::Optional<sema::TemplateDeductionInfo *> isSFINAEContext() const;
4814
4815  /// \brief RAII class used to determine whether SFINAE has
4816  /// trapped any errors that occur during template argument
4817  /// deduction.`
4818  class SFINAETrap {
4819    Sema &SemaRef;
4820    unsigned PrevSFINAEErrors;
4821    bool PrevInNonInstantiationSFINAEContext;
4822    bool PrevAccessCheckingSFINAE;
4823
4824  public:
4825    explicit SFINAETrap(Sema &SemaRef, bool AccessCheckingSFINAE = false)
4826      : SemaRef(SemaRef), PrevSFINAEErrors(SemaRef.NumSFINAEErrors),
4827        PrevInNonInstantiationSFINAEContext(
4828                                      SemaRef.InNonInstantiationSFINAEContext),
4829        PrevAccessCheckingSFINAE(SemaRef.AccessCheckingSFINAE)
4830    {
4831      if (!SemaRef.isSFINAEContext())
4832        SemaRef.InNonInstantiationSFINAEContext = true;
4833      SemaRef.AccessCheckingSFINAE = AccessCheckingSFINAE;
4834    }
4835
4836    ~SFINAETrap() {
4837      SemaRef.NumSFINAEErrors = PrevSFINAEErrors;
4838      SemaRef.InNonInstantiationSFINAEContext
4839        = PrevInNonInstantiationSFINAEContext;
4840      SemaRef.AccessCheckingSFINAE = PrevAccessCheckingSFINAE;
4841    }
4842
4843    /// \brief Determine whether any SFINAE errors have been trapped.
4844    bool hasErrorOccurred() const {
4845      return SemaRef.NumSFINAEErrors > PrevSFINAEErrors;
4846    }
4847  };
4848
4849  /// \brief The current instantiation scope used to store local
4850  /// variables.
4851  LocalInstantiationScope *CurrentInstantiationScope;
4852
4853  /// \brief The number of typos corrected by CorrectTypo.
4854  unsigned TyposCorrected;
4855
4856  typedef llvm::DenseMap<IdentifierInfo *, TypoCorrection>
4857    UnqualifiedTyposCorrectedMap;
4858
4859  /// \brief A cache containing the results of typo correction for unqualified
4860  /// name lookup.
4861  ///
4862  /// The string is the string that we corrected to (which may be empty, if
4863  /// there was no correction), while the boolean will be true when the
4864  /// string represents a keyword.
4865  UnqualifiedTyposCorrectedMap UnqualifiedTyposCorrected;
4866
4867  /// \brief Worker object for performing CFG-based warnings.
4868  sema::AnalysisBasedWarnings AnalysisWarnings;
4869
4870  /// \brief An entity for which implicit template instantiation is required.
4871  ///
4872  /// The source location associated with the declaration is the first place in
4873  /// the source code where the declaration was "used". It is not necessarily
4874  /// the point of instantiation (which will be either before or after the
4875  /// namespace-scope declaration that triggered this implicit instantiation),
4876  /// However, it is the location that diagnostics should generally refer to,
4877  /// because users will need to know what code triggered the instantiation.
4878  typedef std::pair<ValueDecl *, SourceLocation> PendingImplicitInstantiation;
4879
4880  /// \brief The queue of implicit template instantiations that are required
4881  /// but have not yet been performed.
4882  std::deque<PendingImplicitInstantiation> PendingInstantiations;
4883
4884  /// \brief The queue of implicit template instantiations that are required
4885  /// and must be performed within the current local scope.
4886  ///
4887  /// This queue is only used for member functions of local classes in
4888  /// templates, which must be instantiated in the same scope as their
4889  /// enclosing function, so that they can reference function-local
4890  /// types, static variables, enumerators, etc.
4891  std::deque<PendingImplicitInstantiation> PendingLocalImplicitInstantiations;
4892
4893  void PerformPendingInstantiations(bool LocalOnly = false);
4894
4895  TypeSourceInfo *SubstType(TypeSourceInfo *T,
4896                            const MultiLevelTemplateArgumentList &TemplateArgs,
4897                            SourceLocation Loc, DeclarationName Entity);
4898
4899  QualType SubstType(QualType T,
4900                     const MultiLevelTemplateArgumentList &TemplateArgs,
4901                     SourceLocation Loc, DeclarationName Entity);
4902
4903  TypeSourceInfo *SubstType(TypeLoc TL,
4904                            const MultiLevelTemplateArgumentList &TemplateArgs,
4905                            SourceLocation Loc, DeclarationName Entity);
4906
4907  TypeSourceInfo *SubstFunctionDeclType(TypeSourceInfo *T,
4908                            const MultiLevelTemplateArgumentList &TemplateArgs,
4909                                        SourceLocation Loc,
4910                                        DeclarationName Entity);
4911  ParmVarDecl *SubstParmVarDecl(ParmVarDecl *D,
4912                            const MultiLevelTemplateArgumentList &TemplateArgs,
4913                                int indexAdjustment,
4914                                llvm::Optional<unsigned> NumExpansions);
4915  bool SubstParmTypes(SourceLocation Loc,
4916                      ParmVarDecl **Params, unsigned NumParams,
4917                      const MultiLevelTemplateArgumentList &TemplateArgs,
4918                      SmallVectorImpl<QualType> &ParamTypes,
4919                      SmallVectorImpl<ParmVarDecl *> *OutParams = 0);
4920  ExprResult SubstExpr(Expr *E,
4921                       const MultiLevelTemplateArgumentList &TemplateArgs);
4922
4923  /// \brief Substitute the given template arguments into a list of
4924  /// expressions, expanding pack expansions if required.
4925  ///
4926  /// \param Exprs The list of expressions to substitute into.
4927  ///
4928  /// \param NumExprs The number of expressions in \p Exprs.
4929  ///
4930  /// \param IsCall Whether this is some form of call, in which case
4931  /// default arguments will be dropped.
4932  ///
4933  /// \param TemplateArgs The set of template arguments to substitute.
4934  ///
4935  /// \param Outputs Will receive all of the substituted arguments.
4936  ///
4937  /// \returns true if an error occurred, false otherwise.
4938  bool SubstExprs(Expr **Exprs, unsigned NumExprs, bool IsCall,
4939                  const MultiLevelTemplateArgumentList &TemplateArgs,
4940                  SmallVectorImpl<Expr *> &Outputs);
4941
4942  StmtResult SubstStmt(Stmt *S,
4943                       const MultiLevelTemplateArgumentList &TemplateArgs);
4944
4945  Decl *SubstDecl(Decl *D, DeclContext *Owner,
4946                  const MultiLevelTemplateArgumentList &TemplateArgs);
4947
4948  bool
4949  SubstBaseSpecifiers(CXXRecordDecl *Instantiation,
4950                      CXXRecordDecl *Pattern,
4951                      const MultiLevelTemplateArgumentList &TemplateArgs);
4952
4953  bool
4954  InstantiateClass(SourceLocation PointOfInstantiation,
4955                   CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern,
4956                   const MultiLevelTemplateArgumentList &TemplateArgs,
4957                   TemplateSpecializationKind TSK,
4958                   bool Complain = true);
4959
4960  void InstantiateAttrs(const MultiLevelTemplateArgumentList &TemplateArgs,
4961                        const Decl *Pattern, Decl *Inst);
4962
4963  bool
4964  InstantiateClassTemplateSpecialization(SourceLocation PointOfInstantiation,
4965                           ClassTemplateSpecializationDecl *ClassTemplateSpec,
4966                           TemplateSpecializationKind TSK,
4967                           bool Complain = true);
4968
4969  void InstantiateClassMembers(SourceLocation PointOfInstantiation,
4970                               CXXRecordDecl *Instantiation,
4971                            const MultiLevelTemplateArgumentList &TemplateArgs,
4972                               TemplateSpecializationKind TSK);
4973
4974  void InstantiateClassTemplateSpecializationMembers(
4975                                          SourceLocation PointOfInstantiation,
4976                           ClassTemplateSpecializationDecl *ClassTemplateSpec,
4977                                                TemplateSpecializationKind TSK);
4978
4979  NestedNameSpecifierLoc
4980  SubstNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS,
4981                           const MultiLevelTemplateArgumentList &TemplateArgs);
4982
4983  DeclarationNameInfo
4984  SubstDeclarationNameInfo(const DeclarationNameInfo &NameInfo,
4985                           const MultiLevelTemplateArgumentList &TemplateArgs);
4986  TemplateName
4987  SubstTemplateName(NestedNameSpecifierLoc QualifierLoc, TemplateName Name,
4988                    SourceLocation Loc,
4989                    const MultiLevelTemplateArgumentList &TemplateArgs);
4990  bool Subst(const TemplateArgumentLoc *Args, unsigned NumArgs,
4991             TemplateArgumentListInfo &Result,
4992             const MultiLevelTemplateArgumentList &TemplateArgs);
4993
4994  void InstantiateFunctionDefinition(SourceLocation PointOfInstantiation,
4995                                     FunctionDecl *Function,
4996                                     bool Recursive = false,
4997                                     bool DefinitionRequired = false);
4998  void InstantiateStaticDataMemberDefinition(
4999                                     SourceLocation PointOfInstantiation,
5000                                     VarDecl *Var,
5001                                     bool Recursive = false,
5002                                     bool DefinitionRequired = false);
5003
5004  void InstantiateMemInitializers(CXXConstructorDecl *New,
5005                                  const CXXConstructorDecl *Tmpl,
5006                            const MultiLevelTemplateArgumentList &TemplateArgs);
5007  bool InstantiateInitializer(Expr *Init,
5008                            const MultiLevelTemplateArgumentList &TemplateArgs,
5009                              SourceLocation &LParenLoc,
5010                              ASTOwningVector<Expr*> &NewArgs,
5011                              SourceLocation &RParenLoc);
5012
5013  NamedDecl *FindInstantiatedDecl(SourceLocation Loc, NamedDecl *D,
5014                          const MultiLevelTemplateArgumentList &TemplateArgs);
5015  DeclContext *FindInstantiatedContext(SourceLocation Loc, DeclContext *DC,
5016                          const MultiLevelTemplateArgumentList &TemplateArgs);
5017
5018  // Objective-C declarations.
5019  Decl *ActOnStartClassInterface(SourceLocation AtInterfaceLoc,
5020                                 IdentifierInfo *ClassName,
5021                                 SourceLocation ClassLoc,
5022                                 IdentifierInfo *SuperName,
5023                                 SourceLocation SuperLoc,
5024                                 Decl * const *ProtoRefs,
5025                                 unsigned NumProtoRefs,
5026                                 const SourceLocation *ProtoLocs,
5027                                 SourceLocation EndProtoLoc,
5028                                 AttributeList *AttrList);
5029
5030  Decl *ActOnCompatiblityAlias(
5031                    SourceLocation AtCompatibilityAliasLoc,
5032                    IdentifierInfo *AliasName,  SourceLocation AliasLocation,
5033                    IdentifierInfo *ClassName, SourceLocation ClassLocation);
5034
5035  bool CheckForwardProtocolDeclarationForCircularDependency(
5036    IdentifierInfo *PName,
5037    SourceLocation &PLoc, SourceLocation PrevLoc,
5038    const ObjCList<ObjCProtocolDecl> &PList);
5039
5040  Decl *ActOnStartProtocolInterface(
5041                    SourceLocation AtProtoInterfaceLoc,
5042                    IdentifierInfo *ProtocolName, SourceLocation ProtocolLoc,
5043                    Decl * const *ProtoRefNames, unsigned NumProtoRefs,
5044                    const SourceLocation *ProtoLocs,
5045                    SourceLocation EndProtoLoc,
5046                    AttributeList *AttrList);
5047
5048  Decl *ActOnStartCategoryInterface(SourceLocation AtInterfaceLoc,
5049                                    IdentifierInfo *ClassName,
5050                                    SourceLocation ClassLoc,
5051                                    IdentifierInfo *CategoryName,
5052                                    SourceLocation CategoryLoc,
5053                                    Decl * const *ProtoRefs,
5054                                    unsigned NumProtoRefs,
5055                                    const SourceLocation *ProtoLocs,
5056                                    SourceLocation EndProtoLoc);
5057
5058  Decl *ActOnStartClassImplementation(
5059                    SourceLocation AtClassImplLoc,
5060                    IdentifierInfo *ClassName, SourceLocation ClassLoc,
5061                    IdentifierInfo *SuperClassname,
5062                    SourceLocation SuperClassLoc);
5063
5064  Decl *ActOnStartCategoryImplementation(SourceLocation AtCatImplLoc,
5065                                         IdentifierInfo *ClassName,
5066                                         SourceLocation ClassLoc,
5067                                         IdentifierInfo *CatName,
5068                                         SourceLocation CatLoc);
5069
5070  DeclGroupPtrTy ActOnForwardClassDeclaration(SourceLocation Loc,
5071                                     IdentifierInfo **IdentList,
5072                                     SourceLocation *IdentLocs,
5073                                     unsigned NumElts);
5074
5075  Decl *ActOnForwardProtocolDeclaration(SourceLocation AtProtoclLoc,
5076                                        const IdentifierLocPair *IdentList,
5077                                        unsigned NumElts,
5078                                        AttributeList *attrList);
5079
5080  void FindProtocolDeclaration(bool WarnOnDeclarations,
5081                               const IdentifierLocPair *ProtocolId,
5082                               unsigned NumProtocols,
5083                               SmallVectorImpl<Decl *> &Protocols);
5084
5085  /// Ensure attributes are consistent with type.
5086  /// \param [in, out] Attributes The attributes to check; they will
5087  /// be modified to be consistent with \arg PropertyTy.
5088  void CheckObjCPropertyAttributes(Decl *PropertyPtrTy,
5089                                   SourceLocation Loc,
5090                                   unsigned &Attributes);
5091
5092  /// Process the specified property declaration and create decls for the
5093  /// setters and getters as needed.
5094  /// \param property The property declaration being processed
5095  /// \param DC The semantic container for the property
5096  /// \param redeclaredProperty Declaration for property if redeclared
5097  ///        in class extension.
5098  /// \param lexicalDC Container for redeclaredProperty.
5099  void ProcessPropertyDecl(ObjCPropertyDecl *property,
5100                           ObjCContainerDecl *DC,
5101                           ObjCPropertyDecl *redeclaredProperty = 0,
5102                           ObjCContainerDecl *lexicalDC = 0);
5103
5104  void DiagnosePropertyMismatch(ObjCPropertyDecl *Property,
5105                                ObjCPropertyDecl *SuperProperty,
5106                                const IdentifierInfo *Name);
5107  void ComparePropertiesInBaseAndSuper(ObjCInterfaceDecl *IDecl);
5108
5109  void CompareMethodParamsInBaseAndSuper(Decl *IDecl,
5110                                         ObjCMethodDecl *MethodDecl,
5111                                         bool IsInstance);
5112
5113  void CompareProperties(Decl *CDecl, Decl *MergeProtocols);
5114
5115  void DiagnoseClassExtensionDupMethods(ObjCCategoryDecl *CAT,
5116                                        ObjCInterfaceDecl *ID);
5117
5118  void MatchOneProtocolPropertiesInClass(Decl *CDecl,
5119                                         ObjCProtocolDecl *PDecl);
5120
5121  void ActOnAtEnd(Scope *S, SourceRange AtEnd,
5122                  Decl **allMethods = 0, unsigned allNum = 0,
5123                  Decl **allProperties = 0, unsigned pNum = 0,
5124                  DeclGroupPtrTy *allTUVars = 0, unsigned tuvNum = 0);
5125
5126  Decl *ActOnProperty(Scope *S, SourceLocation AtLoc,
5127                      FieldDeclarator &FD, ObjCDeclSpec &ODS,
5128                      Selector GetterSel, Selector SetterSel,
5129                      bool *OverridingProperty,
5130                      tok::ObjCKeywordKind MethodImplKind,
5131                      DeclContext *lexicalDC = 0);
5132
5133  Decl *ActOnPropertyImplDecl(Scope *S,
5134                              SourceLocation AtLoc,
5135                              SourceLocation PropertyLoc,
5136                              bool ImplKind,
5137                              IdentifierInfo *PropertyId,
5138                              IdentifierInfo *PropertyIvar,
5139                              SourceLocation PropertyIvarLoc);
5140
5141  enum ObjCSpecialMethodKind {
5142    OSMK_None,
5143    OSMK_Alloc,
5144    OSMK_New,
5145    OSMK_Copy,
5146    OSMK_RetainingInit,
5147    OSMK_NonRetainingInit
5148  };
5149
5150  struct ObjCArgInfo {
5151    IdentifierInfo *Name;
5152    SourceLocation NameLoc;
5153    // The Type is null if no type was specified, and the DeclSpec is invalid
5154    // in this case.
5155    ParsedType Type;
5156    ObjCDeclSpec DeclSpec;
5157
5158    /// ArgAttrs - Attribute list for this argument.
5159    AttributeList *ArgAttrs;
5160  };
5161
5162  Decl *ActOnMethodDeclaration(
5163    Scope *S,
5164    SourceLocation BeginLoc, // location of the + or -.
5165    SourceLocation EndLoc,   // location of the ; or {.
5166    tok::TokenKind MethodType,
5167    ObjCDeclSpec &ReturnQT, ParsedType ReturnType,
5168    SourceLocation SelectorStartLoc, Selector Sel,
5169    // optional arguments. The number of types/arguments is obtained
5170    // from the Sel.getNumArgs().
5171    ObjCArgInfo *ArgInfo,
5172    DeclaratorChunk::ParamInfo *CParamInfo, unsigned CNumArgs, // c-style args
5173    AttributeList *AttrList, tok::ObjCKeywordKind MethodImplKind,
5174    bool isVariadic, bool MethodDefinition);
5175
5176  // Helper method for ActOnClassMethod/ActOnInstanceMethod.
5177  // Will search "local" class/category implementations for a method decl.
5178  // Will also search in class's root looking for instance method.
5179  // Returns 0 if no method is found.
5180  ObjCMethodDecl *LookupPrivateClassMethod(Selector Sel,
5181                                           ObjCInterfaceDecl *CDecl);
5182  ObjCMethodDecl *LookupPrivateInstanceMethod(Selector Sel,
5183                                              ObjCInterfaceDecl *ClassDecl);
5184  ObjCMethodDecl *LookupMethodInQualifiedType(Selector Sel,
5185                                              const ObjCObjectPointerType *OPT,
5186                                              bool IsInstance);
5187
5188  bool inferObjCARCLifetime(ValueDecl *decl);
5189
5190  ExprResult
5191  HandleExprPropertyRefExpr(const ObjCObjectPointerType *OPT,
5192                            Expr *BaseExpr,
5193                            SourceLocation OpLoc,
5194                            DeclarationName MemberName,
5195                            SourceLocation MemberLoc,
5196                            SourceLocation SuperLoc, QualType SuperType,
5197                            bool Super);
5198
5199  ExprResult
5200  ActOnClassPropertyRefExpr(IdentifierInfo &receiverName,
5201                            IdentifierInfo &propertyName,
5202                            SourceLocation receiverNameLoc,
5203                            SourceLocation propertyNameLoc);
5204
5205  ObjCMethodDecl *tryCaptureObjCSelf();
5206
5207  /// \brief Describes the kind of message expression indicated by a message
5208  /// send that starts with an identifier.
5209  enum ObjCMessageKind {
5210    /// \brief The message is sent to 'super'.
5211    ObjCSuperMessage,
5212    /// \brief The message is an instance message.
5213    ObjCInstanceMessage,
5214    /// \brief The message is a class message, and the identifier is a type
5215    /// name.
5216    ObjCClassMessage
5217  };
5218
5219  ObjCMessageKind getObjCMessageKind(Scope *S,
5220                                     IdentifierInfo *Name,
5221                                     SourceLocation NameLoc,
5222                                     bool IsSuper,
5223                                     bool HasTrailingDot,
5224                                     ParsedType &ReceiverType);
5225
5226  ExprResult ActOnSuperMessage(Scope *S, SourceLocation SuperLoc,
5227                               Selector Sel,
5228                               SourceLocation LBracLoc,
5229                               SourceLocation SelectorLoc,
5230                               SourceLocation RBracLoc,
5231                               MultiExprArg Args);
5232
5233  ExprResult BuildClassMessage(TypeSourceInfo *ReceiverTypeInfo,
5234                               QualType ReceiverType,
5235                               SourceLocation SuperLoc,
5236                               Selector Sel,
5237                               ObjCMethodDecl *Method,
5238                               SourceLocation LBracLoc,
5239                               SourceLocation SelectorLoc,
5240                               SourceLocation RBracLoc,
5241                               MultiExprArg Args);
5242
5243  ExprResult ActOnClassMessage(Scope *S,
5244                               ParsedType Receiver,
5245                               Selector Sel,
5246                               SourceLocation LBracLoc,
5247                               SourceLocation SelectorLoc,
5248                               SourceLocation RBracLoc,
5249                               MultiExprArg Args);
5250
5251  ExprResult BuildInstanceMessage(Expr *Receiver,
5252                                  QualType ReceiverType,
5253                                  SourceLocation SuperLoc,
5254                                  Selector Sel,
5255                                  ObjCMethodDecl *Method,
5256                                  SourceLocation LBracLoc,
5257                                  SourceLocation SelectorLoc,
5258                                  SourceLocation RBracLoc,
5259                                  MultiExprArg Args);
5260
5261  ExprResult ActOnInstanceMessage(Scope *S,
5262                                  Expr *Receiver,
5263                                  Selector Sel,
5264                                  SourceLocation LBracLoc,
5265                                  SourceLocation SelectorLoc,
5266                                  SourceLocation RBracLoc,
5267                                  MultiExprArg Args);
5268
5269  ExprResult BuildObjCBridgedCast(SourceLocation LParenLoc,
5270                                  ObjCBridgeCastKind Kind,
5271                                  SourceLocation BridgeKeywordLoc,
5272                                  TypeSourceInfo *TSInfo,
5273                                  Expr *SubExpr);
5274
5275  ExprResult ActOnObjCBridgedCast(Scope *S,
5276                                  SourceLocation LParenLoc,
5277                                  ObjCBridgeCastKind Kind,
5278                                  SourceLocation BridgeKeywordLoc,
5279                                  ParsedType Type,
5280                                  SourceLocation RParenLoc,
5281                                  Expr *SubExpr);
5282
5283  bool checkInitMethod(ObjCMethodDecl *method, QualType receiverTypeIfCall);
5284
5285  /// \brief Check whether the given new method is a valid override of the
5286  /// given overridden method, and set any properties that should be inherited.
5287  ///
5288  /// \returns True if an error occurred.
5289  bool CheckObjCMethodOverride(ObjCMethodDecl *NewMethod,
5290                               const ObjCMethodDecl *Overridden,
5291                               bool IsImplementation);
5292
5293  /// \brief Check whether the given method overrides any methods in its class,
5294  /// calling \c CheckObjCMethodOverride for each overridden method.
5295  bool CheckObjCMethodOverrides(ObjCMethodDecl *NewMethod, DeclContext *DC);
5296
5297  enum PragmaOptionsAlignKind {
5298    POAK_Native,  // #pragma options align=native
5299    POAK_Natural, // #pragma options align=natural
5300    POAK_Packed,  // #pragma options align=packed
5301    POAK_Power,   // #pragma options align=power
5302    POAK_Mac68k,  // #pragma options align=mac68k
5303    POAK_Reset    // #pragma options align=reset
5304  };
5305
5306  /// ActOnPragmaOptionsAlign - Called on well formed #pragma options align.
5307  void ActOnPragmaOptionsAlign(PragmaOptionsAlignKind Kind,
5308                               SourceLocation PragmaLoc,
5309                               SourceLocation KindLoc);
5310
5311  enum PragmaPackKind {
5312    PPK_Default, // #pragma pack([n])
5313    PPK_Show,    // #pragma pack(show), only supported by MSVC.
5314    PPK_Push,    // #pragma pack(push, [identifier], [n])
5315    PPK_Pop      // #pragma pack(pop, [identifier], [n])
5316  };
5317
5318  enum PragmaMSStructKind {
5319    PMSST_OFF,  // #pragms ms_struct off
5320    PMSST_ON    // #pragms ms_struct on
5321  };
5322
5323  /// ActOnPragmaPack - Called on well formed #pragma pack(...).
5324  void ActOnPragmaPack(PragmaPackKind Kind,
5325                       IdentifierInfo *Name,
5326                       Expr *Alignment,
5327                       SourceLocation PragmaLoc,
5328                       SourceLocation LParenLoc,
5329                       SourceLocation RParenLoc);
5330
5331  /// ActOnPragmaMSStruct - Called on well formed #pragms ms_struct [on|off].
5332  void ActOnPragmaMSStruct(PragmaMSStructKind Kind);
5333
5334  /// ActOnPragmaUnused - Called on well-formed '#pragma unused'.
5335  void ActOnPragmaUnused(const Token &Identifier,
5336                         Scope *curScope,
5337                         SourceLocation PragmaLoc);
5338
5339  /// ActOnPragmaVisibility - Called on well formed #pragma GCC visibility... .
5340  void ActOnPragmaVisibility(bool IsPush, const IdentifierInfo* VisType,
5341                             SourceLocation PragmaLoc);
5342
5343  NamedDecl *DeclClonePragmaWeak(NamedDecl *ND, IdentifierInfo *II,
5344                                 SourceLocation Loc);
5345  void DeclApplyPragmaWeak(Scope *S, NamedDecl *ND, WeakInfo &W);
5346
5347  /// ActOnPragmaWeakID - Called on well formed #pragma weak ident.
5348  void ActOnPragmaWeakID(IdentifierInfo* WeakName,
5349                         SourceLocation PragmaLoc,
5350                         SourceLocation WeakNameLoc);
5351
5352  /// ActOnPragmaWeakAlias - Called on well formed #pragma weak ident = ident.
5353  void ActOnPragmaWeakAlias(IdentifierInfo* WeakName,
5354                            IdentifierInfo* AliasName,
5355                            SourceLocation PragmaLoc,
5356                            SourceLocation WeakNameLoc,
5357                            SourceLocation AliasNameLoc);
5358
5359  /// ActOnPragmaFPContract - Called on well formed
5360  /// #pragma {STDC,OPENCL} FP_CONTRACT
5361  void ActOnPragmaFPContract(tok::OnOffSwitch OOS);
5362
5363  /// AddAlignmentAttributesForRecord - Adds any needed alignment attributes to
5364  /// a the record decl, to handle '#pragma pack' and '#pragma options align'.
5365  void AddAlignmentAttributesForRecord(RecordDecl *RD);
5366
5367  /// AddMsStructLayoutForRecord - Adds ms_struct layout attribute to record.
5368  void AddMsStructLayoutForRecord(RecordDecl *RD);
5369
5370  /// FreePackedContext - Deallocate and null out PackContext.
5371  void FreePackedContext();
5372
5373  /// PushNamespaceVisibilityAttr - Note that we've entered a
5374  /// namespace with a visibility attribute.
5375  void PushNamespaceVisibilityAttr(const VisibilityAttr *Attr);
5376
5377  /// AddPushedVisibilityAttribute - If '#pragma GCC visibility' was used,
5378  /// add an appropriate visibility attribute.
5379  void AddPushedVisibilityAttribute(Decl *RD);
5380
5381  /// PopPragmaVisibility - Pop the top element of the visibility stack; used
5382  /// for '#pragma GCC visibility' and visibility attributes on namespaces.
5383  void PopPragmaVisibility();
5384
5385  /// FreeVisContext - Deallocate and null out VisContext.
5386  void FreeVisContext();
5387
5388  /// AddAlignedAttr - Adds an aligned attribute to a particular declaration.
5389  void AddAlignedAttr(SourceLocation AttrLoc, Decl *D, Expr *E);
5390  void AddAlignedAttr(SourceLocation AttrLoc, Decl *D, TypeSourceInfo *T);
5391
5392  /// CastCategory - Get the correct forwarded implicit cast result category
5393  /// from the inner expression.
5394  ExprValueKind CastCategory(Expr *E);
5395
5396  /// \brief The kind of conversion being performed.
5397  enum CheckedConversionKind {
5398    /// \brief An implicit conversion.
5399    CCK_ImplicitConversion,
5400    /// \brief A C-style cast.
5401    CCK_CStyleCast,
5402    /// \brief A functional-style cast.
5403    CCK_FunctionalCast,
5404    /// \brief A cast other than a C-style cast.
5405    CCK_OtherCast
5406  };
5407
5408  /// ImpCastExprToType - If Expr is not of type 'Type', insert an implicit
5409  /// cast.  If there is already an implicit cast, merge into the existing one.
5410  /// If isLvalue, the result of the cast is an lvalue.
5411  ExprResult ImpCastExprToType(Expr *E, QualType Type, CastKind CK,
5412                               ExprValueKind VK = VK_RValue,
5413                               const CXXCastPath *BasePath = 0,
5414                               CheckedConversionKind CCK
5415                                  = CCK_ImplicitConversion);
5416
5417  /// ScalarTypeToBooleanCastKind - Returns the cast kind corresponding
5418  /// to the conversion from scalar type ScalarTy to the Boolean type.
5419  static CastKind ScalarTypeToBooleanCastKind(QualType ScalarTy);
5420
5421  /// IgnoredValueConversions - Given that an expression's result is
5422  /// syntactically ignored, perform any conversions that are
5423  /// required.
5424  ExprResult IgnoredValueConversions(Expr *E);
5425
5426  // UsualUnaryConversions - promotes integers (C99 6.3.1.1p2) and converts
5427  // functions and arrays to their respective pointers (C99 6.3.2.1).
5428  ExprResult UsualUnaryConversions(Expr *E);
5429
5430  // DefaultFunctionArrayConversion - converts functions and arrays
5431  // to their respective pointers (C99 6.3.2.1).
5432  ExprResult DefaultFunctionArrayConversion(Expr *E);
5433
5434  // DefaultFunctionArrayLvalueConversion - converts functions and
5435  // arrays to their respective pointers and performs the
5436  // lvalue-to-rvalue conversion.
5437  ExprResult DefaultFunctionArrayLvalueConversion(Expr *E);
5438
5439  // DefaultLvalueConversion - performs lvalue-to-rvalue conversion on
5440  // the operand.  This is DefaultFunctionArrayLvalueConversion,
5441  // except that it assumes the operand isn't of function or array
5442  // type.
5443  ExprResult DefaultLvalueConversion(Expr *E);
5444
5445  // DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
5446  // do not have a prototype. Integer promotions are performed on each
5447  // argument, and arguments that have type float are promoted to double.
5448  ExprResult DefaultArgumentPromotion(Expr *E);
5449
5450  // Used for emitting the right warning by DefaultVariadicArgumentPromotion
5451  enum VariadicCallType {
5452    VariadicFunction,
5453    VariadicBlock,
5454    VariadicMethod,
5455    VariadicConstructor,
5456    VariadicDoesNotApply
5457  };
5458
5459  /// GatherArgumentsForCall - Collector argument expressions for various
5460  /// form of call prototypes.
5461  bool GatherArgumentsForCall(SourceLocation CallLoc,
5462                              FunctionDecl *FDecl,
5463                              const FunctionProtoType *Proto,
5464                              unsigned FirstProtoArg,
5465                              Expr **Args, unsigned NumArgs,
5466                              SmallVector<Expr *, 8> &AllArgs,
5467                              VariadicCallType CallType = VariadicDoesNotApply);
5468
5469  // DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
5470  // will warn if the resulting type is not a POD type.
5471  ExprResult DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
5472                                              FunctionDecl *FDecl);
5473
5474  // UsualArithmeticConversions - performs the UsualUnaryConversions on it's
5475  // operands and then handles various conversions that are common to binary
5476  // operators (C99 6.3.1.8). If both operands aren't arithmetic, this
5477  // routine returns the first non-arithmetic type found. The client is
5478  // responsible for emitting appropriate error diagnostics.
5479  QualType UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
5480                                      bool IsCompAssign = false);
5481
5482  /// AssignConvertType - All of the 'assignment' semantic checks return this
5483  /// enum to indicate whether the assignment was allowed.  These checks are
5484  /// done for simple assignments, as well as initialization, return from
5485  /// function, argument passing, etc.  The query is phrased in terms of a
5486  /// source and destination type.
5487  enum AssignConvertType {
5488    /// Compatible - the types are compatible according to the standard.
5489    Compatible,
5490
5491    /// PointerToInt - The assignment converts a pointer to an int, which we
5492    /// accept as an extension.
5493    PointerToInt,
5494
5495    /// IntToPointer - The assignment converts an int to a pointer, which we
5496    /// accept as an extension.
5497    IntToPointer,
5498
5499    /// FunctionVoidPointer - The assignment is between a function pointer and
5500    /// void*, which the standard doesn't allow, but we accept as an extension.
5501    FunctionVoidPointer,
5502
5503    /// IncompatiblePointer - The assignment is between two pointers types that
5504    /// are not compatible, but we accept them as an extension.
5505    IncompatiblePointer,
5506
5507    /// IncompatiblePointer - The assignment is between two pointers types which
5508    /// point to integers which have a different sign, but are otherwise identical.
5509    /// This is a subset of the above, but broken out because it's by far the most
5510    /// common case of incompatible pointers.
5511    IncompatiblePointerSign,
5512
5513    /// CompatiblePointerDiscardsQualifiers - The assignment discards
5514    /// c/v/r qualifiers, which we accept as an extension.
5515    CompatiblePointerDiscardsQualifiers,
5516
5517    /// IncompatiblePointerDiscardsQualifiers - The assignment
5518    /// discards qualifiers that we don't permit to be discarded,
5519    /// like address spaces.
5520    IncompatiblePointerDiscardsQualifiers,
5521
5522    /// IncompatibleNestedPointerQualifiers - The assignment is between two
5523    /// nested pointer types, and the qualifiers other than the first two
5524    /// levels differ e.g. char ** -> const char **, but we accept them as an
5525    /// extension.
5526    IncompatibleNestedPointerQualifiers,
5527
5528    /// IncompatibleVectors - The assignment is between two vector types that
5529    /// have the same size, which we accept as an extension.
5530    IncompatibleVectors,
5531
5532    /// IntToBlockPointer - The assignment converts an int to a block
5533    /// pointer. We disallow this.
5534    IntToBlockPointer,
5535
5536    /// IncompatibleBlockPointer - The assignment is between two block
5537    /// pointers types that are not compatible.
5538    IncompatibleBlockPointer,
5539
5540    /// IncompatibleObjCQualifiedId - The assignment is between a qualified
5541    /// id type and something else (that is incompatible with it). For example,
5542    /// "id <XXX>" = "Foo *", where "Foo *" doesn't implement the XXX protocol.
5543    IncompatibleObjCQualifiedId,
5544
5545    /// IncompatibleObjCWeakRef - Assigning a weak-unavailable object to an
5546    /// object with __weak qualifier.
5547    IncompatibleObjCWeakRef,
5548
5549    /// Incompatible - We reject this conversion outright, it is invalid to
5550    /// represent it in the AST.
5551    Incompatible
5552  };
5553
5554  /// DiagnoseAssignmentResult - Emit a diagnostic, if required, for the
5555  /// assignment conversion type specified by ConvTy.  This returns true if the
5556  /// conversion was invalid or false if the conversion was accepted.
5557  bool DiagnoseAssignmentResult(AssignConvertType ConvTy,
5558                                SourceLocation Loc,
5559                                QualType DstType, QualType SrcType,
5560                                Expr *SrcExpr, AssignmentAction Action,
5561                                bool *Complained = 0);
5562
5563  /// CheckAssignmentConstraints - Perform type checking for assignment,
5564  /// argument passing, variable initialization, and function return values.
5565  /// C99 6.5.16.
5566  AssignConvertType CheckAssignmentConstraints(SourceLocation Loc,
5567                                               QualType LHSType,
5568                                               QualType RHSType);
5569
5570  /// Check assignment constraints and prepare for a conversion of the
5571  /// RHS to the LHS type.
5572  AssignConvertType CheckAssignmentConstraints(QualType LHSType,
5573                                               ExprResult &RHS,
5574                                               CastKind &Kind);
5575
5576  // CheckSingleAssignmentConstraints - Currently used by
5577  // CheckAssignmentOperands, and ActOnReturnStmt. Prior to type checking,
5578  // this routine performs the default function/array converions.
5579  AssignConvertType CheckSingleAssignmentConstraints(QualType LHSType,
5580                                                     ExprResult &RHS);
5581
5582  // \brief If the lhs type is a transparent union, check whether we
5583  // can initialize the transparent union with the given expression.
5584  AssignConvertType CheckTransparentUnionArgumentConstraints(QualType ArgType,
5585                                                             ExprResult &RHS);
5586
5587  bool IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType);
5588
5589  bool CheckExceptionSpecCompatibility(Expr *From, QualType ToType);
5590
5591  ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
5592                                       AssignmentAction Action,
5593                                       bool AllowExplicit = false);
5594  ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
5595                                       AssignmentAction Action,
5596                                       bool AllowExplicit,
5597                                       ImplicitConversionSequence& ICS);
5598  ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
5599                                       const ImplicitConversionSequence& ICS,
5600                                       AssignmentAction Action,
5601                                       CheckedConversionKind CCK
5602                                          = CCK_ImplicitConversion);
5603  ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
5604                                       const StandardConversionSequence& SCS,
5605                                       AssignmentAction Action,
5606                                       CheckedConversionKind CCK);
5607
5608  /// the following "Check" methods will return a valid/converted QualType
5609  /// or a null QualType (indicating an error diagnostic was issued).
5610
5611  /// type checking binary operators (subroutines of CreateBuiltinBinOp).
5612  QualType InvalidOperands(SourceLocation Loc, ExprResult &LHS,
5613                           ExprResult &RHS);
5614  QualType CheckPointerToMemberOperands( // C++ 5.5
5615    ExprResult &lex, ExprResult &rex, ExprValueKind &VK,
5616    SourceLocation OpLoc, bool isIndirect);
5617  QualType CheckMultiplyDivideOperands( // C99 6.5.5
5618    ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign,
5619    bool IsDivide);
5620  QualType CheckRemainderOperands( // C99 6.5.5
5621    ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
5622    bool IsCompAssign = false);
5623  QualType CheckAdditionOperands( // C99 6.5.6
5624    ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
5625    QualType* CompLHSTy = 0);
5626  QualType CheckSubtractionOperands( // C99 6.5.6
5627    ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
5628    QualType* CompLHSTy = 0);
5629  QualType CheckShiftOperands( // C99 6.5.7
5630    ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc,
5631    bool IsCompAssign = false);
5632  QualType CheckCompareOperands( // C99 6.5.8/9
5633    ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned OpaqueOpc,
5634                                bool isRelational);
5635  QualType CheckBitwiseOperands( // C99 6.5.[10...12]
5636    ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
5637    bool IsCompAssign = false);
5638  QualType CheckLogicalOperands( // C99 6.5.[13,14]
5639    ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc);
5640  // CheckAssignmentOperands is used for both simple and compound assignment.
5641  // For simple assignment, pass both expressions and a null converted type.
5642  // For compound assignment, pass both expressions and the converted type.
5643  QualType CheckAssignmentOperands( // C99 6.5.16.[1,2]
5644    Expr *LHSExpr, ExprResult &RHS, SourceLocation Loc, QualType CompoundType);
5645
5646  void ConvertPropertyForLValue(ExprResult &LHS, ExprResult &RHS,
5647                                QualType& LHSTy);
5648  ExprResult ConvertPropertyForRValue(Expr *E);
5649
5650  QualType CheckConditionalOperands( // C99 6.5.15
5651    ExprResult &Cond, ExprResult &LHS, ExprResult &RHS,
5652    ExprValueKind &VK, ExprObjectKind &OK, SourceLocation QuestionLoc);
5653  QualType CXXCheckConditionalOperands( // C++ 5.16
5654    ExprResult &cond, ExprResult &lhs, ExprResult &rhs,
5655    ExprValueKind &VK, ExprObjectKind &OK, SourceLocation questionLoc);
5656  QualType FindCompositePointerType(SourceLocation Loc, Expr *&E1, Expr *&E2,
5657                                    bool *NonStandardCompositeType = 0);
5658  QualType FindCompositePointerType(SourceLocation Loc, ExprResult &E1, ExprResult &E2,
5659                                    bool *NonStandardCompositeType = 0) {
5660    Expr *E1Tmp = E1.take(), *E2Tmp = E2.take();
5661    QualType Composite = FindCompositePointerType(Loc, E1Tmp, E2Tmp, NonStandardCompositeType);
5662    E1 = Owned(E1Tmp);
5663    E2 = Owned(E2Tmp);
5664    return Composite;
5665  }
5666
5667  QualType FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
5668                                        SourceLocation QuestionLoc);
5669
5670  bool DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
5671                                  SourceLocation QuestionLoc);
5672
5673  /// type checking for vector binary operators.
5674  QualType CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
5675                               SourceLocation Loc, bool IsCompAssign);
5676  QualType CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
5677                                      SourceLocation Loc, bool isRelational);
5678
5679  /// type checking declaration initializers (C99 6.7.8)
5680  bool CheckInitList(const InitializedEntity &Entity,
5681                     InitListExpr *&InitList, QualType &DeclType);
5682  bool CheckForConstantInitializer(Expr *e, QualType t);
5683
5684  // type checking C++ declaration initializers (C++ [dcl.init]).
5685
5686  /// ReferenceCompareResult - Expresses the result of comparing two
5687  /// types (cv1 T1 and cv2 T2) to determine their compatibility for the
5688  /// purposes of initialization by reference (C++ [dcl.init.ref]p4).
5689  enum ReferenceCompareResult {
5690    /// Ref_Incompatible - The two types are incompatible, so direct
5691    /// reference binding is not possible.
5692    Ref_Incompatible = 0,
5693    /// Ref_Related - The two types are reference-related, which means
5694    /// that their unqualified forms (T1 and T2) are either the same
5695    /// or T1 is a base class of T2.
5696    Ref_Related,
5697    /// Ref_Compatible_With_Added_Qualification - The two types are
5698    /// reference-compatible with added qualification, meaning that
5699    /// they are reference-compatible and the qualifiers on T1 (cv1)
5700    /// are greater than the qualifiers on T2 (cv2).
5701    Ref_Compatible_With_Added_Qualification,
5702    /// Ref_Compatible - The two types are reference-compatible and
5703    /// have equivalent qualifiers (cv1 == cv2).
5704    Ref_Compatible
5705  };
5706
5707  ReferenceCompareResult CompareReferenceRelationship(SourceLocation Loc,
5708                                                      QualType T1, QualType T2,
5709                                                      bool &DerivedToBase,
5710                                                      bool &ObjCConversion,
5711                                                bool &ObjCLifetimeConversion);
5712
5713  /// CheckCastTypes - Check type constraints for casting between types under
5714  /// C semantics, or forward to CXXCheckCStyleCast in C++.
5715  ExprResult CheckCastTypes(SourceLocation CastStartLoc, SourceRange TypeRange,
5716                            QualType CastType, Expr *CastExpr, CastKind &Kind,
5717                            ExprValueKind &VK, CXXCastPath &BasePath,
5718                            bool FunctionalStyle = false);
5719
5720  ExprResult checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
5721                                 Expr *CastExpr, CastKind &CastKind,
5722                                 ExprValueKind &VK, CXXCastPath &Path);
5723
5724  // CheckVectorCast - check type constraints for vectors.
5725  // Since vectors are an extension, there are no C standard reference for this.
5726  // We allow casting between vectors and integer datatypes of the same size.
5727  // returns true if the cast is invalid
5728  bool CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
5729                       CastKind &Kind);
5730
5731  // CheckExtVectorCast - check type constraints for extended vectors.
5732  // Since vectors are an extension, there are no C standard reference for this.
5733  // We allow casting between vectors and integer datatypes of the same size,
5734  // or vectors and the element type of that vector.
5735  // returns the cast expr
5736  ExprResult CheckExtVectorCast(SourceRange R, QualType DestTy, Expr *CastExpr,
5737                                CastKind &Kind);
5738
5739  /// CXXCheckCStyleCast - Check constraints of a C-style or function-style
5740  /// cast under C++ semantics.
5741  ExprResult CXXCheckCStyleCast(SourceRange R, QualType CastTy, ExprValueKind &VK,
5742                                Expr *CastExpr, CastKind &Kind,
5743                                CXXCastPath &BasePath, bool FunctionalStyle);
5744
5745  /// \brief Checks for valid expressions which can be cast to an ObjC
5746  /// pointer without needing a bridge cast.
5747  bool ValidObjCARCNoBridgeCastExpr(Expr *&Exp, QualType castType);
5748
5749  /// \brief Checks for invalid conversions and casts between
5750  /// retainable pointers and other pointer kinds.
5751  void CheckObjCARCConversion(SourceRange castRange, QualType castType,
5752                              Expr *&op, CheckedConversionKind CCK);
5753
5754  bool CheckObjCARCUnavailableWeakConversion(QualType castType,
5755                                             QualType ExprType);
5756
5757  /// checkRetainCycles - Check whether an Objective-C message send
5758  /// might create an obvious retain cycle.
5759  void checkRetainCycles(ObjCMessageExpr *msg);
5760  void checkRetainCycles(Expr *receiver, Expr *argument);
5761
5762  /// checkUnsafeAssigns - Check whether +1 expr is being assigned
5763  /// to weak/__unsafe_unretained type.
5764  bool checkUnsafeAssigns(SourceLocation Loc, QualType LHS, Expr *RHS);
5765
5766  /// checkUnsafeExprAssigns - Check whether +1 expr is being assigned
5767  /// to weak/__unsafe_unretained expression.
5768  void checkUnsafeExprAssigns(SourceLocation Loc, Expr *LHS, Expr *RHS);
5769
5770  /// CheckMessageArgumentTypes - Check types in an Obj-C message send.
5771  /// \param Method - May be null.
5772  /// \param [out] ReturnType - The return type of the send.
5773  /// \return true iff there were any incompatible types.
5774  bool CheckMessageArgumentTypes(QualType ReceiverType,
5775                                 Expr **Args, unsigned NumArgs, Selector Sel,
5776                                 ObjCMethodDecl *Method, bool isClassMessage,
5777                                 bool isSuperMessage,
5778                                 SourceLocation lbrac, SourceLocation rbrac,
5779                                 QualType &ReturnType, ExprValueKind &VK);
5780
5781  /// \brief Determine the result of a message send expression based on
5782  /// the type of the receiver, the method expected to receive the message,
5783  /// and the form of the message send.
5784  QualType getMessageSendResultType(QualType ReceiverType,
5785                                    ObjCMethodDecl *Method,
5786                                    bool isClassMessage, bool isSuperMessage);
5787
5788  /// \brief If the given expression involves a message send to a method
5789  /// with a related result type, emit a note describing what happened.
5790  void EmitRelatedResultTypeNote(const Expr *E);
5791
5792  /// CheckBooleanCondition - Diagnose problems involving the use of
5793  /// the given expression as a boolean condition (e.g. in an if
5794  /// statement).  Also performs the standard function and array
5795  /// decays, possibly changing the input variable.
5796  ///
5797  /// \param Loc - A location associated with the condition, e.g. the
5798  /// 'if' keyword.
5799  /// \return true iff there were any errors
5800  ExprResult CheckBooleanCondition(Expr *E, SourceLocation Loc);
5801
5802  ExprResult ActOnBooleanCondition(Scope *S, SourceLocation Loc,
5803                                   Expr *SubExpr);
5804
5805  /// DiagnoseAssignmentAsCondition - Given that an expression is
5806  /// being used as a boolean condition, warn if it's an assignment.
5807  void DiagnoseAssignmentAsCondition(Expr *E);
5808
5809  /// \brief Redundant parentheses over an equality comparison can indicate
5810  /// that the user intended an assignment used as condition.
5811  void DiagnoseEqualityWithExtraParens(ParenExpr *ParenE);
5812
5813  /// CheckCXXBooleanCondition - Returns true if conversion to bool is invalid.
5814  ExprResult CheckCXXBooleanCondition(Expr *CondExpr);
5815
5816  /// ConvertIntegerToTypeWarnOnOverflow - Convert the specified APInt to have
5817  /// the specified width and sign.  If an overflow occurs, detect it and emit
5818  /// the specified diagnostic.
5819  void ConvertIntegerToTypeWarnOnOverflow(llvm::APSInt &OldVal,
5820                                          unsigned NewWidth, bool NewSign,
5821                                          SourceLocation Loc, unsigned DiagID);
5822
5823  /// Checks that the Objective-C declaration is declared in the global scope.
5824  /// Emits an error and marks the declaration as invalid if it's not declared
5825  /// in the global scope.
5826  bool CheckObjCDeclScope(Decl *D);
5827
5828  /// VerifyIntegerConstantExpression - verifies that an expression is an ICE,
5829  /// and reports the appropriate diagnostics. Returns false on success.
5830  /// Can optionally return the value of the expression.
5831  bool VerifyIntegerConstantExpression(const Expr *E, llvm::APSInt *Result = 0);
5832
5833  /// VerifyBitField - verifies that a bit field expression is an ICE and has
5834  /// the correct width, and that the field type is valid.
5835  /// Returns false on success.
5836  /// Can optionally return whether the bit-field is of width 0
5837  bool VerifyBitField(SourceLocation FieldLoc, IdentifierInfo *FieldName,
5838                      QualType FieldTy, const Expr *BitWidth,
5839                      bool *ZeroWidth = 0);
5840
5841  /// \name Code completion
5842  //@{
5843  /// \brief Describes the context in which code completion occurs.
5844  enum ParserCompletionContext {
5845    /// \brief Code completion occurs at top-level or namespace context.
5846    PCC_Namespace,
5847    /// \brief Code completion occurs within a class, struct, or union.
5848    PCC_Class,
5849    /// \brief Code completion occurs within an Objective-C interface, protocol,
5850    /// or category.
5851    PCC_ObjCInterface,
5852    /// \brief Code completion occurs within an Objective-C implementation or
5853    /// category implementation
5854    PCC_ObjCImplementation,
5855    /// \brief Code completion occurs within the list of instance variables
5856    /// in an Objective-C interface, protocol, category, or implementation.
5857    PCC_ObjCInstanceVariableList,
5858    /// \brief Code completion occurs following one or more template
5859    /// headers.
5860    PCC_Template,
5861    /// \brief Code completion occurs following one or more template
5862    /// headers within a class.
5863    PCC_MemberTemplate,
5864    /// \brief Code completion occurs within an expression.
5865    PCC_Expression,
5866    /// \brief Code completion occurs within a statement, which may
5867    /// also be an expression or a declaration.
5868    PCC_Statement,
5869    /// \brief Code completion occurs at the beginning of the
5870    /// initialization statement (or expression) in a for loop.
5871    PCC_ForInit,
5872    /// \brief Code completion occurs within the condition of an if,
5873    /// while, switch, or for statement.
5874    PCC_Condition,
5875    /// \brief Code completion occurs within the body of a function on a
5876    /// recovery path, where we do not have a specific handle on our position
5877    /// in the grammar.
5878    PCC_RecoveryInFunction,
5879    /// \brief Code completion occurs where only a type is permitted.
5880    PCC_Type,
5881    /// \brief Code completion occurs in a parenthesized expression, which
5882    /// might also be a type cast.
5883    PCC_ParenthesizedExpression,
5884    /// \brief Code completion occurs within a sequence of declaration
5885    /// specifiers within a function, method, or block.
5886    PCC_LocalDeclarationSpecifiers
5887  };
5888
5889  void CodeCompleteOrdinaryName(Scope *S,
5890                                ParserCompletionContext CompletionContext);
5891  void CodeCompleteDeclSpec(Scope *S, DeclSpec &DS,
5892                            bool AllowNonIdentifiers,
5893                            bool AllowNestedNameSpecifiers);
5894
5895  struct CodeCompleteExpressionData;
5896  void CodeCompleteExpression(Scope *S,
5897                              const CodeCompleteExpressionData &Data);
5898  void CodeCompleteMemberReferenceExpr(Scope *S, Expr *Base,
5899                                       SourceLocation OpLoc,
5900                                       bool IsArrow);
5901  void CodeCompletePostfixExpression(Scope *S, ExprResult LHS);
5902  void CodeCompleteTag(Scope *S, unsigned TagSpec);
5903  void CodeCompleteTypeQualifiers(DeclSpec &DS);
5904  void CodeCompleteCase(Scope *S);
5905  void CodeCompleteCall(Scope *S, Expr *Fn, Expr **Args, unsigned NumArgs);
5906  void CodeCompleteInitializer(Scope *S, Decl *D);
5907  void CodeCompleteReturn(Scope *S);
5908  void CodeCompleteAfterIf(Scope *S);
5909  void CodeCompleteAssignmentRHS(Scope *S, Expr *LHS);
5910
5911  void CodeCompleteQualifiedId(Scope *S, CXXScopeSpec &SS,
5912                               bool EnteringContext);
5913  void CodeCompleteUsing(Scope *S);
5914  void CodeCompleteUsingDirective(Scope *S);
5915  void CodeCompleteNamespaceDecl(Scope *S);
5916  void CodeCompleteNamespaceAliasDecl(Scope *S);
5917  void CodeCompleteOperatorName(Scope *S);
5918  void CodeCompleteConstructorInitializer(Decl *Constructor,
5919                                          CXXCtorInitializer** Initializers,
5920                                          unsigned NumInitializers);
5921
5922  void CodeCompleteObjCAtDirective(Scope *S);
5923  void CodeCompleteObjCAtVisibility(Scope *S);
5924  void CodeCompleteObjCAtStatement(Scope *S);
5925  void CodeCompleteObjCAtExpression(Scope *S);
5926  void CodeCompleteObjCPropertyFlags(Scope *S, ObjCDeclSpec &ODS);
5927  void CodeCompleteObjCPropertyGetter(Scope *S);
5928  void CodeCompleteObjCPropertySetter(Scope *S);
5929  void CodeCompleteObjCPassingType(Scope *S, ObjCDeclSpec &DS,
5930                                   bool IsParameter);
5931  void CodeCompleteObjCMessageReceiver(Scope *S);
5932  void CodeCompleteObjCSuperMessage(Scope *S, SourceLocation SuperLoc,
5933                                    IdentifierInfo **SelIdents,
5934                                    unsigned NumSelIdents,
5935                                    bool AtArgumentExpression);
5936  void CodeCompleteObjCClassMessage(Scope *S, ParsedType Receiver,
5937                                    IdentifierInfo **SelIdents,
5938                                    unsigned NumSelIdents,
5939                                    bool AtArgumentExpression,
5940                                    bool IsSuper = false);
5941  void CodeCompleteObjCInstanceMessage(Scope *S, Expr *Receiver,
5942                                       IdentifierInfo **SelIdents,
5943                                       unsigned NumSelIdents,
5944                                       bool AtArgumentExpression,
5945                                       ObjCInterfaceDecl *Super = 0);
5946  void CodeCompleteObjCForCollection(Scope *S,
5947                                     DeclGroupPtrTy IterationVar);
5948  void CodeCompleteObjCSelector(Scope *S,
5949                                IdentifierInfo **SelIdents,
5950                                unsigned NumSelIdents);
5951  void CodeCompleteObjCProtocolReferences(IdentifierLocPair *Protocols,
5952                                          unsigned NumProtocols);
5953  void CodeCompleteObjCProtocolDecl(Scope *S);
5954  void CodeCompleteObjCInterfaceDecl(Scope *S);
5955  void CodeCompleteObjCSuperclass(Scope *S,
5956                                  IdentifierInfo *ClassName,
5957                                  SourceLocation ClassNameLoc);
5958  void CodeCompleteObjCImplementationDecl(Scope *S);
5959  void CodeCompleteObjCInterfaceCategory(Scope *S,
5960                                         IdentifierInfo *ClassName,
5961                                         SourceLocation ClassNameLoc);
5962  void CodeCompleteObjCImplementationCategory(Scope *S,
5963                                              IdentifierInfo *ClassName,
5964                                              SourceLocation ClassNameLoc);
5965  void CodeCompleteObjCPropertyDefinition(Scope *S);
5966  void CodeCompleteObjCPropertySynthesizeIvar(Scope *S,
5967                                              IdentifierInfo *PropertyName);
5968  void CodeCompleteObjCMethodDecl(Scope *S,
5969                                  bool IsInstanceMethod,
5970                                  ParsedType ReturnType);
5971  void CodeCompleteObjCMethodDeclSelector(Scope *S,
5972                                          bool IsInstanceMethod,
5973                                          bool AtParameterName,
5974                                          ParsedType ReturnType,
5975                                          IdentifierInfo **SelIdents,
5976                                          unsigned NumSelIdents);
5977  void CodeCompletePreprocessorDirective(bool InConditional);
5978  void CodeCompleteInPreprocessorConditionalExclusion(Scope *S);
5979  void CodeCompletePreprocessorMacroName(bool IsDefinition);
5980  void CodeCompletePreprocessorExpression();
5981  void CodeCompletePreprocessorMacroArgument(Scope *S,
5982                                             IdentifierInfo *Macro,
5983                                             MacroInfo *MacroInfo,
5984                                             unsigned Argument);
5985  void CodeCompleteNaturalLanguage();
5986  void GatherGlobalCodeCompletions(CodeCompletionAllocator &Allocator,
5987                  SmallVectorImpl<CodeCompletionResult> &Results);
5988  //@}
5989
5990  //===--------------------------------------------------------------------===//
5991  // Extra semantic analysis beyond the C type system
5992
5993public:
5994  SourceLocation getLocationOfStringLiteralByte(const StringLiteral *SL,
5995                                                unsigned ByteNo) const;
5996
5997private:
5998  void CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
5999                        bool isSubscript=false, bool AllowOnePastEnd=true);
6000  void CheckArrayAccess(const Expr *E);
6001  bool CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall);
6002  bool CheckBlockCall(NamedDecl *NDecl, CallExpr *TheCall);
6003
6004  bool CheckablePrintfAttr(const FormatAttr *Format, CallExpr *TheCall);
6005  bool CheckObjCString(Expr *Arg);
6006
6007  ExprResult CheckBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
6008  bool CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
6009
6010  bool SemaBuiltinVAStart(CallExpr *TheCall);
6011  bool SemaBuiltinUnorderedCompare(CallExpr *TheCall);
6012  bool SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs);
6013
6014public:
6015  // Used by C++ template instantiation.
6016  ExprResult SemaBuiltinShuffleVector(CallExpr *TheCall);
6017
6018private:
6019  bool SemaBuiltinPrefetch(CallExpr *TheCall);
6020  bool SemaBuiltinObjectSize(CallExpr *TheCall);
6021  bool SemaBuiltinLongjmp(CallExpr *TheCall);
6022  ExprResult SemaBuiltinAtomicOverloaded(ExprResult TheCallResult);
6023  bool SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
6024                              llvm::APSInt &Result);
6025
6026  bool SemaCheckStringLiteral(const Expr *E, const CallExpr *TheCall,
6027                              bool HasVAListArg, unsigned format_idx,
6028                              unsigned firstDataArg, bool isPrintf);
6029
6030  void CheckFormatString(const StringLiteral *FExpr, const Expr *OrigFormatExpr,
6031                         const CallExpr *TheCall, bool HasVAListArg,
6032                         unsigned format_idx, unsigned firstDataArg,
6033                         bool isPrintf);
6034
6035  void CheckNonNullArguments(const NonNullAttr *NonNull,
6036                             const Expr * const *ExprArgs,
6037                             SourceLocation CallSiteLoc);
6038
6039  void CheckPrintfScanfArguments(const CallExpr *TheCall, bool HasVAListArg,
6040                                 unsigned format_idx, unsigned firstDataArg,
6041                                 bool isPrintf);
6042
6043  /// \brief Enumeration used to describe which of the memory setting or copying
6044  /// functions is being checked by \c CheckMemaccessArguments().
6045  enum CheckedMemoryFunction {
6046    CMF_Memset,
6047    CMF_Memcpy,
6048    CMF_Memmove,
6049    CMF_Memcmp
6050  };
6051
6052  void CheckMemaccessArguments(const CallExpr *Call, CheckedMemoryFunction CMF,
6053                               IdentifierInfo *FnName);
6054
6055  void CheckStrlcpycatArguments(const CallExpr *Call,
6056                                IdentifierInfo *FnName);
6057
6058  void CheckReturnStackAddr(Expr *RetValExp, QualType lhsType,
6059                            SourceLocation ReturnLoc);
6060  void CheckFloatComparison(SourceLocation loc, Expr* lex, Expr* rex);
6061  void CheckImplicitConversions(Expr *E, SourceLocation CC = SourceLocation());
6062
6063  void CheckBitFieldInitialization(SourceLocation InitLoc, FieldDecl *Field,
6064                                   Expr *Init);
6065
6066  /// \brief The parser's current scope.
6067  ///
6068  /// The parser maintains this state here.
6069  Scope *CurScope;
6070
6071protected:
6072  friend class Parser;
6073  friend class InitializationSequence;
6074  friend class ASTReader;
6075  friend class ASTWriter;
6076
6077public:
6078  /// \brief Retrieve the parser's current scope.
6079  ///
6080  /// This routine must only be used when it is certain that semantic analysis
6081  /// and the parser are in precisely the same context, which is not the case
6082  /// when, e.g., we are performing any kind of template instantiation.
6083  /// Therefore, the only safe places to use this scope are in the parser
6084  /// itself and in routines directly invoked from the parser and *never* from
6085  /// template substitution or instantiation.
6086  Scope *getCurScope() const { return CurScope; }
6087
6088  Decl *getObjCDeclContext() const;
6089};
6090
6091/// \brief RAII object that enters a new expression evaluation context.
6092class EnterExpressionEvaluationContext {
6093  Sema &Actions;
6094
6095public:
6096  EnterExpressionEvaluationContext(Sema &Actions,
6097                                   Sema::ExpressionEvaluationContext NewContext)
6098    : Actions(Actions) {
6099    Actions.PushExpressionEvaluationContext(NewContext);
6100  }
6101
6102  ~EnterExpressionEvaluationContext() {
6103    Actions.PopExpressionEvaluationContext();
6104  }
6105};
6106
6107}  // end namespace clang
6108
6109#endif
6110