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