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