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