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