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