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