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