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