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