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