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