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