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/MangleNumberingContext.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/Module.h"
30#include "clang/Basic/OpenMPKinds.h"
31#include "clang/Basic/Specifiers.h"
32#include "clang/Basic/TemplateKinds.h"
33#include "clang/Basic/TypeTraits.h"
34#include "clang/Sema/AnalysisBasedWarnings.h"
35#include "clang/Sema/DeclSpec.h"
36#include "clang/Sema/ExternalSemaSource.h"
37#include "clang/Sema/IdentifierResolver.h"
38#include "clang/Sema/LocInfoType.h"
39#include "clang/Sema/ObjCMethodList.h"
40#include "clang/Sema/Ownership.h"
41#include "clang/Sema/Scope.h"
42#include "clang/Sema/ScopeInfo.h"
43#include "clang/Sema/TypoCorrection.h"
44#include "clang/Sema/Weak.h"
45#include "llvm/ADT/ArrayRef.h"
46#include "llvm/ADT/Optional.h"
47#include "llvm/ADT/SetVector.h"
48#include "llvm/ADT/SmallPtrSet.h"
49#include "llvm/ADT/SmallVector.h"
50#include "llvm/ADT/TinyPtrVector.h"
51#include <deque>
52#include <memory>
53#include <string>
54#include <vector>
55
56namespace llvm {
57  class APSInt;
58  template <typename ValueT> struct DenseMapInfo;
59  template <typename ValueT, typename ValueInfoT> class DenseSet;
60  class SmallBitVector;
61  class InlineAsmIdentifierInfo;
62}
63
64namespace clang {
65  class ADLResult;
66  class ASTConsumer;
67  class ASTContext;
68  class ASTMutationListener;
69  class ASTReader;
70  class ASTWriter;
71  class ArrayType;
72  class AttributeList;
73  class BlockDecl;
74  class CapturedDecl;
75  class CXXBasePath;
76  class CXXBasePaths;
77  class CXXBindTemporaryExpr;
78  typedef SmallVector<CXXBaseSpecifier*, 4> CXXCastPath;
79  class CXXConstructorDecl;
80  class CXXConversionDecl;
81  class CXXDestructorDecl;
82  class CXXFieldCollector;
83  class CXXMemberCallExpr;
84  class CXXMethodDecl;
85  class CXXScopeSpec;
86  class CXXTemporary;
87  class CXXTryStmt;
88  class CallExpr;
89  class ClassTemplateDecl;
90  class ClassTemplatePartialSpecializationDecl;
91  class ClassTemplateSpecializationDecl;
92  class VarTemplatePartialSpecializationDecl;
93  class CodeCompleteConsumer;
94  class CodeCompletionAllocator;
95  class CodeCompletionTUInfo;
96  class CodeCompletionResult;
97  class Decl;
98  class DeclAccessPair;
99  class DeclContext;
100  class DeclRefExpr;
101  class DeclaratorDecl;
102  class DeducedTemplateArgument;
103  class DependentDiagnostic;
104  class DesignatedInitExpr;
105  class Designation;
106  class EnableIfAttr;
107  class EnumConstantDecl;
108  class Expr;
109  class ExtVectorType;
110  class ExternalSemaSource;
111  class FormatAttr;
112  class FriendDecl;
113  class FunctionDecl;
114  class FunctionProtoType;
115  class FunctionTemplateDecl;
116  class ImplicitConversionSequence;
117  class InitListExpr;
118  class InitializationKind;
119  class InitializationSequence;
120  class InitializedEntity;
121  class IntegerLiteral;
122  class LabelStmt;
123  class LambdaExpr;
124  class LangOptions;
125  class LocalInstantiationScope;
126  class LookupResult;
127  class MacroInfo;
128  typedef ArrayRef<std::pair<IdentifierInfo *, SourceLocation>> ModuleIdPath;
129  class ModuleLoader;
130  class MultiLevelTemplateArgumentList;
131  class NamedDecl;
132  class NonNullAttr;
133  class ObjCCategoryDecl;
134  class ObjCCategoryImplDecl;
135  class ObjCCompatibleAliasDecl;
136  class ObjCContainerDecl;
137  class ObjCImplDecl;
138  class ObjCImplementationDecl;
139  class ObjCInterfaceDecl;
140  class ObjCIvarDecl;
141  template <class T> class ObjCList;
142  class ObjCMessageExpr;
143  class ObjCMethodDecl;
144  class ObjCPropertyDecl;
145  class ObjCProtocolDecl;
146  class OMPThreadPrivateDecl;
147  class OMPClause;
148  class OverloadCandidateSet;
149  class OverloadExpr;
150  class ParenListExpr;
151  class ParmVarDecl;
152  class Preprocessor;
153  class PseudoDestructorTypeStorage;
154  class PseudoObjectExpr;
155  class QualType;
156  class StandardConversionSequence;
157  class Stmt;
158  class StringLiteral;
159  class SwitchStmt;
160  class TemplateArgument;
161  class TemplateArgumentList;
162  class TemplateArgumentLoc;
163  class TemplateDecl;
164  class TemplateParameterList;
165  class TemplatePartialOrderingContext;
166  class TemplateTemplateParmDecl;
167  class Token;
168  class TypeAliasDecl;
169  class TypedefDecl;
170  class TypedefNameDecl;
171  class TypeLoc;
172  class UnqualifiedId;
173  class UnresolvedLookupExpr;
174  class UnresolvedMemberExpr;
175  class UnresolvedSetImpl;
176  class UnresolvedSetIterator;
177  class UsingDecl;
178  class UsingShadowDecl;
179  class ValueDecl;
180  class VarDecl;
181  class VarTemplateSpecializationDecl;
182  class VisibilityAttr;
183  class VisibleDeclConsumer;
184  class IndirectFieldDecl;
185  struct DeductionFailureInfo;
186  class TemplateSpecCandidateSet;
187
188namespace sema {
189  class AccessedEntity;
190  class BlockScopeInfo;
191  class CapturedRegionScopeInfo;
192  class CapturingScopeInfo;
193  class CompoundScopeInfo;
194  class DelayedDiagnostic;
195  class DelayedDiagnosticPool;
196  class FunctionScopeInfo;
197  class LambdaScopeInfo;
198  class PossiblyUnreachableDiag;
199  class TemplateDeductionInfo;
200}
201
202// FIXME: No way to easily map from TemplateTypeParmTypes to
203// TemplateTypeParmDecls, so we have this horrible PointerUnion.
204typedef std::pair<llvm::PointerUnion<const TemplateTypeParmType*, NamedDecl*>,
205                  SourceLocation> UnexpandedParameterPack;
206
207/// Sema - This implements semantic analysis and AST building for C.
208class Sema {
209  Sema(const Sema &) LLVM_DELETED_FUNCTION;
210  void operator=(const Sema &) LLVM_DELETED_FUNCTION;
211
212  ///\brief Source of additional semantic information.
213  ExternalSemaSource *ExternalSource;
214
215  ///\brief Whether Sema has generated a multiplexer and has to delete it.
216  bool isMultiplexExternalSource;
217
218  static bool mightHaveNonExternalLinkage(const DeclaratorDecl *FD);
219
220  static bool
221  shouldLinkPossiblyHiddenDecl(const NamedDecl *Old, const NamedDecl *New) {
222    // We are about to link these. It is now safe to compute the linkage of
223    // the new decl. If the new decl has external linkage, we will
224    // link it with the hidden decl (which also has external linkage) and
225    // it will keep having external linkage. If it has internal linkage, we
226    // will not link it. Since it has no previous decls, it will remain
227    // with internal linkage.
228    return !Old->isHidden() || New->isExternallyVisible();
229  }
230
231public:
232  typedef OpaquePtr<DeclGroupRef> DeclGroupPtrTy;
233  typedef OpaquePtr<TemplateName> TemplateTy;
234  typedef OpaquePtr<QualType> TypeTy;
235
236  OpenCLOptions OpenCLFeatures;
237  FPOptions FPFeatures;
238
239  const LangOptions &LangOpts;
240  Preprocessor &PP;
241  ASTContext &Context;
242  ASTConsumer &Consumer;
243  DiagnosticsEngine &Diags;
244  SourceManager &SourceMgr;
245
246  /// \brief Flag indicating whether or not to collect detailed statistics.
247  bool CollectStats;
248
249  /// \brief Code-completion consumer.
250  CodeCompleteConsumer *CodeCompleter;
251
252  /// CurContext - This is the current declaration context of parsing.
253  DeclContext *CurContext;
254
255  /// \brief Generally null except when we temporarily switch decl contexts,
256  /// like in \see ActOnObjCTemporaryExitContainerContext.
257  DeclContext *OriginalLexicalContext;
258
259  /// VAListTagName - The declaration name corresponding to __va_list_tag.
260  /// This is used as part of a hack to omit that class from ADL results.
261  DeclarationName VAListTagName;
262
263  /// PackContext - Manages the stack for \#pragma pack. An alignment
264  /// of 0 indicates default alignment.
265  void *PackContext; // Really a "PragmaPackStack*"
266
267  bool MSStructPragmaOn; // True when \#pragma ms_struct on
268
269  /// \brief Controls member pointer representation format under the MS ABI.
270  LangOptions::PragmaMSPointersToMembersKind
271      MSPointerToMemberRepresentationMethod;
272
273  enum PragmaVtorDispKind {
274    PVDK_Push,          ///< #pragma vtordisp(push, mode)
275    PVDK_Set,           ///< #pragma vtordisp(mode)
276    PVDK_Pop,           ///< #pragma vtordisp(pop)
277    PVDK_Reset          ///< #pragma vtordisp()
278  };
279
280  enum PragmaMsStackAction {
281    PSK_Reset,    // #pragma ()
282    PSK_Set,      // #pragma ("name")
283    PSK_Push,     // #pragma (push[, id])
284    PSK_Push_Set, // #pragma (push[, id], "name")
285    PSK_Pop,      // #pragma (pop[, id])
286    PSK_Pop_Set,  // #pragma (pop[, id], "name")
287  };
288
289  /// \brief Whether to insert vtordisps prior to virtual bases in the Microsoft
290  /// C++ ABI.  Possible values are 0, 1, and 2, which mean:
291  ///
292  /// 0: Suppress all vtordisps
293  /// 1: Insert vtordisps in the presence of vbase overrides and non-trivial
294  ///    structors
295  /// 2: Always insert vtordisps to support RTTI on partially constructed
296  ///    objects
297  ///
298  /// The stack always has at least one element in it.
299  SmallVector<MSVtorDispAttr::Mode, 2> VtorDispModeStack;
300
301  /// \brief Source location for newly created implicit MSInheritanceAttrs
302  SourceLocation ImplicitMSInheritanceAttrLoc;
303
304  template<typename ValueType>
305  struct PragmaStack {
306    struct Slot {
307      llvm::StringRef StackSlotLabel;
308      ValueType Value;
309      SourceLocation PragmaLocation;
310      Slot(llvm::StringRef StackSlotLabel,
311           ValueType Value,
312           SourceLocation PragmaLocation)
313        : StackSlotLabel(StackSlotLabel), Value(Value),
314          PragmaLocation(PragmaLocation) {}
315    };
316    void Act(SourceLocation PragmaLocation,
317             PragmaMsStackAction Action,
318             llvm::StringRef StackSlotLabel,
319             ValueType Value);
320    explicit PragmaStack(const ValueType &Value)
321      : CurrentValue(Value) {}
322    SmallVector<Slot, 2> Stack;
323    ValueType CurrentValue;
324    SourceLocation CurrentPragmaLocation;
325  };
326  // FIXME: We should serialize / deserialize these if they occur in a PCH (but
327  // we shouldn't do so if they're in a module).
328  PragmaStack<StringLiteral *> DataSegStack;
329  PragmaStack<StringLiteral *> BSSSegStack;
330  PragmaStack<StringLiteral *> ConstSegStack;
331  PragmaStack<StringLiteral *> CodeSegStack;
332
333  /// VisContext - Manages the stack for \#pragma GCC visibility.
334  void *VisContext; // Really a "PragmaVisStack*"
335
336  /// \brief This represents the last location of a "#pragma clang optimize off"
337  /// directive if such a directive has not been closed by an "on" yet. If
338  /// optimizations are currently "on", this is set to an invalid location.
339  SourceLocation OptimizeOffPragmaLocation;
340
341  /// \brief Flag indicating if Sema is building a recovery call expression.
342  ///
343  /// This flag is used to avoid building recovery call expressions
344  /// if Sema is already doing so, which would cause infinite recursions.
345  bool IsBuildingRecoveryCallExpr;
346
347  /// ExprNeedsCleanups - True if the current evaluation context
348  /// requires cleanups to be run at its conclusion.
349  bool ExprNeedsCleanups;
350
351  /// ExprCleanupObjects - This is the stack of objects requiring
352  /// cleanup that are created by the current full expression.  The
353  /// element type here is ExprWithCleanups::Object.
354  SmallVector<BlockDecl*, 8> ExprCleanupObjects;
355
356  /// \brief Store a list of either DeclRefExprs or MemberExprs
357  ///  that contain a reference to a variable (constant) that may or may not
358  ///  be odr-used in this Expr, and we won't know until all lvalue-to-rvalue
359  ///  and discarded value conversions have been applied to all subexpressions
360  ///  of the enclosing full expression.  This is cleared at the end of each
361  ///  full expression.
362  llvm::SmallPtrSet<Expr*, 2> MaybeODRUseExprs;
363
364  /// \brief Stack containing information about each of the nested
365  /// function, block, and method scopes that are currently active.
366  ///
367  /// This array is never empty.  Clients should ignore the first
368  /// element, which is used to cache a single FunctionScopeInfo
369  /// that's used to parse every top-level function.
370  SmallVector<sema::FunctionScopeInfo *, 4> FunctionScopes;
371
372  typedef LazyVector<TypedefNameDecl *, ExternalSemaSource,
373                     &ExternalSemaSource::ReadExtVectorDecls, 2, 2>
374    ExtVectorDeclsType;
375
376  /// ExtVectorDecls - This is a list all the extended vector types. This allows
377  /// us to associate a raw vector type with one of the ext_vector type names.
378  /// This is only necessary for issuing pretty diagnostics.
379  ExtVectorDeclsType ExtVectorDecls;
380
381  /// FieldCollector - Collects CXXFieldDecls during parsing of C++ classes.
382  std::unique_ptr<CXXFieldCollector> FieldCollector;
383
384  typedef llvm::SmallSetVector<const NamedDecl*, 16> NamedDeclSetType;
385
386  /// \brief Set containing all declared private fields that are not used.
387  NamedDeclSetType UnusedPrivateFields;
388
389  typedef llvm::SmallPtrSet<const CXXRecordDecl*, 8> RecordDeclSetTy;
390
391  /// PureVirtualClassDiagSet - a set of class declarations which we have
392  /// emitted a list of pure virtual functions. Used to prevent emitting the
393  /// same list more than once.
394  std::unique_ptr<RecordDeclSetTy> PureVirtualClassDiagSet;
395
396  /// ParsingInitForAutoVars - a set of declarations with auto types for which
397  /// we are currently parsing the initializer.
398  llvm::SmallPtrSet<const Decl*, 4> ParsingInitForAutoVars;
399
400  /// \brief A mapping from external names to the most recent
401  /// locally-scoped extern "C" declaration with that name.
402  ///
403  /// This map contains external declarations introduced in local
404  /// scopes, e.g.,
405  ///
406  /// \code
407  /// extern "C" void f() {
408  ///   void foo(int, int);
409  /// }
410  /// \endcode
411  ///
412  /// Here, the name "foo" will be associated with the declaration of
413  /// "foo" within f. This name is not visible outside of
414  /// "f". However, we still find it in two cases:
415  ///
416  ///   - If we are declaring another global or extern "C" entity with
417  ///     the name "foo", we can find "foo" as a previous declaration,
418  ///     so that the types of this external declaration can be checked
419  ///     for compatibility.
420  ///
421  ///   - If we would implicitly declare "foo" (e.g., due to a call to
422  ///     "foo" in C when no prototype or definition is visible), then
423  ///     we find this declaration of "foo" and complain that it is
424  ///     not visible.
425  llvm::DenseMap<DeclarationName, NamedDecl *> LocallyScopedExternCDecls;
426
427  /// \brief Look for a locally scoped extern "C" declaration by the given name.
428  NamedDecl *findLocallyScopedExternCDecl(DeclarationName Name);
429
430  typedef LazyVector<VarDecl *, ExternalSemaSource,
431                     &ExternalSemaSource::ReadTentativeDefinitions, 2, 2>
432    TentativeDefinitionsType;
433
434  /// \brief All the tentative definitions encountered in the TU.
435  TentativeDefinitionsType TentativeDefinitions;
436
437  typedef LazyVector<const DeclaratorDecl *, ExternalSemaSource,
438                     &ExternalSemaSource::ReadUnusedFileScopedDecls, 2, 2>
439    UnusedFileScopedDeclsType;
440
441  /// \brief The set of file scoped decls seen so far that have not been used
442  /// and must warn if not used. Only contains the first declaration.
443  UnusedFileScopedDeclsType UnusedFileScopedDecls;
444
445  typedef LazyVector<CXXConstructorDecl *, ExternalSemaSource,
446                     &ExternalSemaSource::ReadDelegatingConstructors, 2, 2>
447    DelegatingCtorDeclsType;
448
449  /// \brief All the delegating constructors seen so far in the file, used for
450  /// cycle detection at the end of the TU.
451  DelegatingCtorDeclsType DelegatingCtorDecls;
452
453  /// \brief All the overriding destructors seen during a class definition
454  /// (there could be multiple due to nested classes) that had their exception
455  /// spec checks delayed, plus the overridden destructor.
456  SmallVector<std::pair<const CXXDestructorDecl*,
457                              const CXXDestructorDecl*>, 2>
458      DelayedDestructorExceptionSpecChecks;
459
460  /// \brief All the members seen during a class definition which were both
461  /// explicitly defaulted and had explicitly-specified exception
462  /// specifications, along with the function type containing their
463  /// user-specified exception specification. Those exception specifications
464  /// were overridden with the default specifications, but we still need to
465  /// check whether they are compatible with the default specification, and
466  /// we can't do that until the nesting set of class definitions is complete.
467  SmallVector<std::pair<CXXMethodDecl*, const FunctionProtoType*>, 2>
468    DelayedDefaultedMemberExceptionSpecs;
469
470  typedef llvm::DenseMap<const FunctionDecl *, LateParsedTemplate *>
471  LateParsedTemplateMapT;
472  LateParsedTemplateMapT LateParsedTemplateMap;
473
474  /// \brief Callback to the parser to parse templated functions when needed.
475  typedef void LateTemplateParserCB(void *P, LateParsedTemplate &LPT);
476  LateTemplateParserCB *LateTemplateParser;
477  void *OpaqueParser;
478
479  void SetLateTemplateParser(LateTemplateParserCB *LTP, void *P) {
480    LateTemplateParser = LTP;
481    OpaqueParser = P;
482  }
483
484  class DelayedDiagnostics;
485
486  class DelayedDiagnosticsState {
487    sema::DelayedDiagnosticPool *SavedPool;
488    friend class Sema::DelayedDiagnostics;
489  };
490  typedef DelayedDiagnosticsState ParsingDeclState;
491  typedef DelayedDiagnosticsState ProcessingContextState;
492
493  /// A class which encapsulates the logic for delaying diagnostics
494  /// during parsing and other processing.
495  class DelayedDiagnostics {
496    /// \brief The current pool of diagnostics into which delayed
497    /// diagnostics should go.
498    sema::DelayedDiagnosticPool *CurPool;
499
500  public:
501    DelayedDiagnostics() : CurPool(nullptr) {}
502
503    /// Adds a delayed diagnostic.
504    void add(const sema::DelayedDiagnostic &diag); // in DelayedDiagnostic.h
505
506    /// Determines whether diagnostics should be delayed.
507    bool shouldDelayDiagnostics() { return CurPool != nullptr; }
508
509    /// Returns the current delayed-diagnostics pool.
510    sema::DelayedDiagnosticPool *getCurrentPool() const {
511      return CurPool;
512    }
513
514    /// Enter a new scope.  Access and deprecation diagnostics will be
515    /// collected in this pool.
516    DelayedDiagnosticsState push(sema::DelayedDiagnosticPool &pool) {
517      DelayedDiagnosticsState state;
518      state.SavedPool = CurPool;
519      CurPool = &pool;
520      return state;
521    }
522
523    /// Leave a delayed-diagnostic state that was previously pushed.
524    /// Do not emit any of the diagnostics.  This is performed as part
525    /// of the bookkeeping of popping a pool "properly".
526    void popWithoutEmitting(DelayedDiagnosticsState state) {
527      CurPool = state.SavedPool;
528    }
529
530    /// Enter a new scope where access and deprecation diagnostics are
531    /// not delayed.
532    DelayedDiagnosticsState pushUndelayed() {
533      DelayedDiagnosticsState state;
534      state.SavedPool = CurPool;
535      CurPool = nullptr;
536      return state;
537    }
538
539    /// Undo a previous pushUndelayed().
540    void popUndelayed(DelayedDiagnosticsState state) {
541      assert(CurPool == nullptr);
542      CurPool = state.SavedPool;
543    }
544  } DelayedDiagnostics;
545
546  /// A RAII object to temporarily push a declaration context.
547  class ContextRAII {
548  private:
549    Sema &S;
550    DeclContext *SavedContext;
551    ProcessingContextState SavedContextState;
552    QualType SavedCXXThisTypeOverride;
553
554  public:
555    ContextRAII(Sema &S, DeclContext *ContextToPush, bool NewThisContext = true)
556      : S(S), SavedContext(S.CurContext),
557        SavedContextState(S.DelayedDiagnostics.pushUndelayed()),
558        SavedCXXThisTypeOverride(S.CXXThisTypeOverride)
559    {
560      assert(ContextToPush && "pushing null context");
561      S.CurContext = ContextToPush;
562      if (NewThisContext)
563        S.CXXThisTypeOverride = QualType();
564    }
565
566    void pop() {
567      if (!SavedContext) return;
568      S.CurContext = SavedContext;
569      S.DelayedDiagnostics.popUndelayed(SavedContextState);
570      S.CXXThisTypeOverride = SavedCXXThisTypeOverride;
571      SavedContext = nullptr;
572    }
573
574    ~ContextRAII() {
575      pop();
576    }
577  };
578
579  /// \brief RAII object to handle the state changes required to synthesize
580  /// a function body.
581  class SynthesizedFunctionScope {
582    Sema &S;
583    Sema::ContextRAII SavedContext;
584
585  public:
586    SynthesizedFunctionScope(Sema &S, DeclContext *DC)
587      : S(S), SavedContext(S, DC)
588    {
589      S.PushFunctionScope();
590      S.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated);
591    }
592
593    ~SynthesizedFunctionScope() {
594      S.PopExpressionEvaluationContext();
595      S.PopFunctionScopeInfo();
596    }
597  };
598
599  /// WeakUndeclaredIdentifiers - Identifiers contained in
600  /// \#pragma weak before declared. rare. may alias another
601  /// identifier, declared or undeclared
602  llvm::DenseMap<IdentifierInfo*,WeakInfo> WeakUndeclaredIdentifiers;
603
604  /// ExtnameUndeclaredIdentifiers - Identifiers contained in
605  /// \#pragma redefine_extname before declared.  Used in Solaris system headers
606  /// to define functions that occur in multiple standards to call the version
607  /// in the currently selected standard.
608  llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*> ExtnameUndeclaredIdentifiers;
609
610
611  /// \brief Load weak undeclared identifiers from the external source.
612  void LoadExternalWeakUndeclaredIdentifiers();
613
614  /// WeakTopLevelDecl - Translation-unit scoped declarations generated by
615  /// \#pragma weak during processing of other Decls.
616  /// I couldn't figure out a clean way to generate these in-line, so
617  /// we store them here and handle separately -- which is a hack.
618  /// It would be best to refactor this.
619  SmallVector<Decl*,2> WeakTopLevelDecl;
620
621  IdentifierResolver IdResolver;
622
623  /// Translation Unit Scope - useful to Objective-C actions that need
624  /// to lookup file scope declarations in the "ordinary" C decl namespace.
625  /// For example, user-defined classes, built-in "id" type, etc.
626  Scope *TUScope;
627
628  /// \brief The C++ "std" namespace, where the standard library resides.
629  LazyDeclPtr StdNamespace;
630
631  /// \brief The C++ "std::bad_alloc" class, which is defined by the C++
632  /// standard library.
633  LazyDeclPtr StdBadAlloc;
634
635  /// \brief The C++ "std::initializer_list" template, which is defined in
636  /// \<initializer_list>.
637  ClassTemplateDecl *StdInitializerList;
638
639  /// \brief The C++ "type_info" declaration, which is defined in \<typeinfo>.
640  RecordDecl *CXXTypeInfoDecl;
641
642  /// \brief The MSVC "_GUID" struct, which is defined in MSVC header files.
643  RecordDecl *MSVCGuidDecl;
644
645  /// \brief Caches identifiers/selectors for NSFoundation APIs.
646  std::unique_ptr<NSAPI> NSAPIObj;
647
648  /// \brief The declaration of the Objective-C NSNumber class.
649  ObjCInterfaceDecl *NSNumberDecl;
650
651  /// \brief Pointer to NSNumber type (NSNumber *).
652  QualType NSNumberPointer;
653
654  /// \brief The Objective-C NSNumber methods used to create NSNumber literals.
655  ObjCMethodDecl *NSNumberLiteralMethods[NSAPI::NumNSNumberLiteralMethods];
656
657  /// \brief The declaration of the Objective-C NSString class.
658  ObjCInterfaceDecl *NSStringDecl;
659
660  /// \brief Pointer to NSString type (NSString *).
661  QualType NSStringPointer;
662
663  /// \brief The declaration of the stringWithUTF8String: method.
664  ObjCMethodDecl *StringWithUTF8StringMethod;
665
666  /// \brief The declaration of the Objective-C NSArray class.
667  ObjCInterfaceDecl *NSArrayDecl;
668
669  /// \brief The declaration of the arrayWithObjects:count: method.
670  ObjCMethodDecl *ArrayWithObjectsMethod;
671
672  /// \brief The declaration of the Objective-C NSDictionary class.
673  ObjCInterfaceDecl *NSDictionaryDecl;
674
675  /// \brief The declaration of the dictionaryWithObjects:forKeys:count: method.
676  ObjCMethodDecl *DictionaryWithObjectsMethod;
677
678  /// \brief id<NSCopying> type.
679  QualType QIDNSCopying;
680
681  /// \brief will hold 'respondsToSelector:'
682  Selector RespondsToSelectorSel;
683
684  /// A flag to remember whether the implicit forms of operator new and delete
685  /// have been declared.
686  bool GlobalNewDeleteDeclared;
687
688  /// A flag to indicate that we're in a context that permits abstract
689  /// references to fields.  This is really a
690  bool AllowAbstractFieldReference;
691
692  /// \brief Describes how the expressions currently being parsed are
693  /// evaluated at run-time, if at all.
694  enum ExpressionEvaluationContext {
695    /// \brief The current expression and its subexpressions occur within an
696    /// unevaluated operand (C++11 [expr]p7), such as the subexpression of
697    /// \c sizeof, where the type of the expression may be significant but
698    /// no code will be generated to evaluate the value of the expression at
699    /// run time.
700    Unevaluated,
701
702    /// \brief The current expression occurs within an unevaluated
703    /// operand that unconditionally permits abstract references to
704    /// fields, such as a SIZE operator in MS-style inline assembly.
705    UnevaluatedAbstract,
706
707    /// \brief The current context is "potentially evaluated" in C++11 terms,
708    /// but the expression is evaluated at compile-time (like the values of
709    /// cases in a switch statement).
710    ConstantEvaluated,
711
712    /// \brief The current expression is potentially evaluated at run time,
713    /// which means that code may be generated to evaluate the value of the
714    /// expression at run time.
715    PotentiallyEvaluated,
716
717    /// \brief The current expression is potentially evaluated, but any
718    /// declarations referenced inside that expression are only used if
719    /// in fact the current expression is used.
720    ///
721    /// This value is used when parsing default function arguments, for which
722    /// we would like to provide diagnostics (e.g., passing non-POD arguments
723    /// through varargs) but do not want to mark declarations as "referenced"
724    /// until the default argument is used.
725    PotentiallyEvaluatedIfUsed
726  };
727
728  /// \brief Data structure used to record current or nested
729  /// expression evaluation contexts.
730  struct ExpressionEvaluationContextRecord {
731    /// \brief The expression evaluation context.
732    ExpressionEvaluationContext Context;
733
734    /// \brief Whether the enclosing context needed a cleanup.
735    bool ParentNeedsCleanups;
736
737    /// \brief Whether we are in a decltype expression.
738    bool IsDecltype;
739
740    /// \brief The number of active cleanup objects when we entered
741    /// this expression evaluation context.
742    unsigned NumCleanupObjects;
743
744    llvm::SmallPtrSet<Expr*, 2> SavedMaybeODRUseExprs;
745
746    /// \brief The lambdas that are present within this context, if it
747    /// is indeed an unevaluated context.
748    SmallVector<LambdaExpr *, 2> Lambdas;
749
750    /// \brief The declaration that provides context for lambda expressions
751    /// and block literals if the normal declaration context does not
752    /// suffice, e.g., in a default function argument.
753    Decl *ManglingContextDecl;
754
755    /// \brief The context information used to mangle lambda expressions
756    /// and block literals within this context.
757    ///
758    /// This mangling information is allocated lazily, since most contexts
759    /// do not have lambda expressions or block literals.
760    IntrusiveRefCntPtr<MangleNumberingContext> MangleNumbering;
761
762    /// \brief If we are processing a decltype type, a set of call expressions
763    /// for which we have deferred checking the completeness of the return type.
764    SmallVector<CallExpr *, 8> DelayedDecltypeCalls;
765
766    /// \brief If we are processing a decltype type, a set of temporary binding
767    /// expressions for which we have deferred checking the destructor.
768    SmallVector<CXXBindTemporaryExpr *, 8> DelayedDecltypeBinds;
769
770    ExpressionEvaluationContextRecord(ExpressionEvaluationContext Context,
771                                      unsigned NumCleanupObjects,
772                                      bool ParentNeedsCleanups,
773                                      Decl *ManglingContextDecl,
774                                      bool IsDecltype)
775      : Context(Context), ParentNeedsCleanups(ParentNeedsCleanups),
776        IsDecltype(IsDecltype), NumCleanupObjects(NumCleanupObjects),
777        ManglingContextDecl(ManglingContextDecl), MangleNumbering() { }
778
779    /// \brief Retrieve the mangling numbering context, used to consistently
780    /// number constructs like lambdas for mangling.
781    MangleNumberingContext &getMangleNumberingContext(ASTContext &Ctx);
782
783    bool isUnevaluated() const {
784      return Context == Unevaluated || Context == UnevaluatedAbstract;
785    }
786  };
787
788  /// A stack of expression evaluation contexts.
789  SmallVector<ExpressionEvaluationContextRecord, 8> ExprEvalContexts;
790
791  /// \brief Compute the mangling number context for a lambda expression or
792  /// block literal.
793  ///
794  /// \param DC - The DeclContext containing the lambda expression or
795  /// block literal.
796  /// \param[out] ManglingContextDecl - Returns the ManglingContextDecl
797  /// associated with the context, if relevant.
798  MangleNumberingContext *getCurrentMangleNumberContext(
799    const DeclContext *DC,
800    Decl *&ManglingContextDecl);
801
802
803  /// SpecialMemberOverloadResult - The overloading result for a special member
804  /// function.
805  ///
806  /// This is basically a wrapper around PointerIntPair. The lowest bits of the
807  /// integer are used to determine whether overload resolution succeeded.
808  class SpecialMemberOverloadResult : public llvm::FastFoldingSetNode {
809  public:
810    enum Kind {
811      NoMemberOrDeleted,
812      Ambiguous,
813      Success
814    };
815
816  private:
817    llvm::PointerIntPair<CXXMethodDecl*, 2> Pair;
818
819  public:
820    SpecialMemberOverloadResult(const llvm::FoldingSetNodeID &ID)
821      : FastFoldingSetNode(ID)
822    {}
823
824    CXXMethodDecl *getMethod() const { return Pair.getPointer(); }
825    void setMethod(CXXMethodDecl *MD) { Pair.setPointer(MD); }
826
827    Kind getKind() const { return static_cast<Kind>(Pair.getInt()); }
828    void setKind(Kind K) { Pair.setInt(K); }
829  };
830
831  /// \brief A cache of special member function overload resolution results
832  /// for C++ records.
833  llvm::FoldingSet<SpecialMemberOverloadResult> SpecialMemberCache;
834
835  /// \brief The kind of translation unit we are processing.
836  ///
837  /// When we're processing a complete translation unit, Sema will perform
838  /// end-of-translation-unit semantic tasks (such as creating
839  /// initializers for tentative definitions in C) once parsing has
840  /// completed. Modules and precompiled headers perform different kinds of
841  /// checks.
842  TranslationUnitKind TUKind;
843
844  llvm::BumpPtrAllocator BumpAlloc;
845
846  /// \brief The number of SFINAE diagnostics that have been trapped.
847  unsigned NumSFINAEErrors;
848
849  typedef llvm::DenseMap<ParmVarDecl *, llvm::TinyPtrVector<ParmVarDecl *>>
850    UnparsedDefaultArgInstantiationsMap;
851
852  /// \brief A mapping from parameters with unparsed default arguments to the
853  /// set of instantiations of each parameter.
854  ///
855  /// This mapping is a temporary data structure used when parsing
856  /// nested class templates or nested classes of class templates,
857  /// where we might end up instantiating an inner class before the
858  /// default arguments of its methods have been parsed.
859  UnparsedDefaultArgInstantiationsMap UnparsedDefaultArgInstantiations;
860
861  // Contains the locations of the beginning of unparsed default
862  // argument locations.
863  llvm::DenseMap<ParmVarDecl *, SourceLocation> UnparsedDefaultArgLocs;
864
865  /// UndefinedInternals - all the used, undefined objects which require a
866  /// definition in this translation unit.
867  llvm::DenseMap<NamedDecl *, SourceLocation> UndefinedButUsed;
868
869  /// Obtain a sorted list of functions that are undefined but ODR-used.
870  void getUndefinedButUsed(
871      SmallVectorImpl<std::pair<NamedDecl *, SourceLocation> > &Undefined);
872
873  typedef std::pair<ObjCMethodList, ObjCMethodList> GlobalMethods;
874  typedef llvm::DenseMap<Selector, GlobalMethods> GlobalMethodPool;
875
876  /// Method Pool - allows efficient lookup when typechecking messages to "id".
877  /// We need to maintain a list, since selectors can have differing signatures
878  /// across classes. In Cocoa, this happens to be extremely uncommon (only 1%
879  /// of selectors are "overloaded").
880  /// At the head of the list it is recorded whether there were 0, 1, or >= 2
881  /// methods inside categories with a particular selector.
882  GlobalMethodPool MethodPool;
883
884  /// Method selectors used in a \@selector expression. Used for implementation
885  /// of -Wselector.
886  llvm::DenseMap<Selector, SourceLocation> ReferencedSelectors;
887
888  /// Kinds of C++ special members.
889  enum CXXSpecialMember {
890    CXXDefaultConstructor,
891    CXXCopyConstructor,
892    CXXMoveConstructor,
893    CXXCopyAssignment,
894    CXXMoveAssignment,
895    CXXDestructor,
896    CXXInvalid
897  };
898
899  typedef std::pair<CXXRecordDecl*, CXXSpecialMember> SpecialMemberDecl;
900
901  /// The C++ special members which we are currently in the process of
902  /// declaring. If this process recursively triggers the declaration of the
903  /// same special member, we should act as if it is not yet declared.
904  llvm::SmallSet<SpecialMemberDecl, 4> SpecialMembersBeingDeclared;
905
906  void ReadMethodPool(Selector Sel);
907
908  /// Private Helper predicate to check for 'self'.
909  bool isSelfExpr(Expr *RExpr);
910  bool isSelfExpr(Expr *RExpr, const ObjCMethodDecl *Method);
911
912  /// \brief Cause the active diagnostic on the DiagosticsEngine to be
913  /// emitted. This is closely coupled to the SemaDiagnosticBuilder class and
914  /// should not be used elsewhere.
915  void EmitCurrentDiagnostic(unsigned DiagID);
916
917  /// Records and restores the FP_CONTRACT state on entry/exit of compound
918  /// statements.
919  class FPContractStateRAII {
920  public:
921    FPContractStateRAII(Sema& S)
922      : S(S), OldFPContractState(S.FPFeatures.fp_contract) {}
923    ~FPContractStateRAII() {
924      S.FPFeatures.fp_contract = OldFPContractState;
925    }
926  private:
927    Sema& S;
928    bool OldFPContractState : 1;
929  };
930
931  void addImplicitTypedef(StringRef Name, QualType T);
932
933public:
934  Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer,
935       TranslationUnitKind TUKind = TU_Complete,
936       CodeCompleteConsumer *CompletionConsumer = nullptr);
937  ~Sema();
938
939  /// \brief Perform initialization that occurs after the parser has been
940  /// initialized but before it parses anything.
941  void Initialize();
942
943  const LangOptions &getLangOpts() const { return LangOpts; }
944  OpenCLOptions &getOpenCLOptions() { return OpenCLFeatures; }
945  FPOptions     &getFPOptions() { return FPFeatures; }
946
947  DiagnosticsEngine &getDiagnostics() const { return Diags; }
948  SourceManager &getSourceManager() const { return SourceMgr; }
949  Preprocessor &getPreprocessor() const { return PP; }
950  ASTContext &getASTContext() const { return Context; }
951  ASTConsumer &getASTConsumer() const { return Consumer; }
952  ASTMutationListener *getASTMutationListener() const;
953  ExternalSemaSource* getExternalSource() const { return ExternalSource; }
954
955  ///\brief Registers an external source. If an external source already exists,
956  /// creates a multiplex external source and appends to it.
957  ///
958  ///\param[in] E - A non-null external sema source.
959  ///
960  void addExternalSource(ExternalSemaSource *E);
961
962  void PrintStats() const;
963
964  /// \brief Helper class that creates diagnostics with optional
965  /// template instantiation stacks.
966  ///
967  /// This class provides a wrapper around the basic DiagnosticBuilder
968  /// class that emits diagnostics. SemaDiagnosticBuilder is
969  /// responsible for emitting the diagnostic (as DiagnosticBuilder
970  /// does) and, if the diagnostic comes from inside a template
971  /// instantiation, printing the template instantiation stack as
972  /// well.
973  class SemaDiagnosticBuilder : public DiagnosticBuilder {
974    Sema &SemaRef;
975    unsigned DiagID;
976
977  public:
978    SemaDiagnosticBuilder(DiagnosticBuilder &DB, Sema &SemaRef, unsigned DiagID)
979      : DiagnosticBuilder(DB), SemaRef(SemaRef), DiagID(DiagID) { }
980
981    ~SemaDiagnosticBuilder() {
982      // If we aren't active, there is nothing to do.
983      if (!isActive()) return;
984
985      // Otherwise, we need to emit the diagnostic. First flush the underlying
986      // DiagnosticBuilder data, and clear the diagnostic builder itself so it
987      // won't emit the diagnostic in its own destructor.
988      //
989      // This seems wasteful, in that as written the DiagnosticBuilder dtor will
990      // do its own needless checks to see if the diagnostic needs to be
991      // emitted. However, because we take care to ensure that the builder
992      // objects never escape, a sufficiently smart compiler will be able to
993      // eliminate that code.
994      FlushCounts();
995      Clear();
996
997      // Dispatch to Sema to emit the diagnostic.
998      SemaRef.EmitCurrentDiagnostic(DiagID);
999    }
1000
1001    /// Teach operator<< to produce an object of the correct type.
1002    template<typename T>
1003    friend const SemaDiagnosticBuilder &operator<<(
1004        const SemaDiagnosticBuilder &Diag, const T &Value) {
1005      const DiagnosticBuilder &BaseDiag = Diag;
1006      BaseDiag << Value;
1007      return Diag;
1008    }
1009  };
1010
1011  /// \brief Emit a diagnostic.
1012  SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID) {
1013    DiagnosticBuilder DB = Diags.Report(Loc, DiagID);
1014    return SemaDiagnosticBuilder(DB, *this, DiagID);
1015  }
1016
1017  /// \brief Emit a partial diagnostic.
1018  SemaDiagnosticBuilder Diag(SourceLocation Loc, const PartialDiagnostic& PD);
1019
1020  /// \brief Build a partial diagnostic.
1021  PartialDiagnostic PDiag(unsigned DiagID = 0); // in SemaInternal.h
1022
1023  bool findMacroSpelling(SourceLocation &loc, StringRef name);
1024
1025  /// \brief Get a string to suggest for zero-initialization of a type.
1026  std::string
1027  getFixItZeroInitializerForType(QualType T, SourceLocation Loc) const;
1028  std::string getFixItZeroLiteralForType(QualType T, SourceLocation Loc) const;
1029
1030  /// \brief Calls \c Lexer::getLocForEndOfToken()
1031  SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset = 0);
1032
1033  /// \brief Retrieve the module loader associated with the preprocessor.
1034  ModuleLoader &getModuleLoader() const;
1035
1036  void ActOnEndOfTranslationUnit();
1037
1038  void CheckDelegatingCtorCycles();
1039
1040  Scope *getScopeForContext(DeclContext *Ctx);
1041
1042  void PushFunctionScope();
1043  void PushBlockScope(Scope *BlockScope, BlockDecl *Block);
1044  sema::LambdaScopeInfo *PushLambdaScope();
1045
1046  /// \brief This is used to inform Sema what the current TemplateParameterDepth
1047  /// is during Parsing.  Currently it is used to pass on the depth
1048  /// when parsing generic lambda 'auto' parameters.
1049  void RecordParsingTemplateParameterDepth(unsigned Depth);
1050
1051  void PushCapturedRegionScope(Scope *RegionScope, CapturedDecl *CD,
1052                               RecordDecl *RD,
1053                               CapturedRegionKind K);
1054  void
1055  PopFunctionScopeInfo(const sema::AnalysisBasedWarnings::Policy *WP = nullptr,
1056                       const Decl *D = nullptr,
1057                       const BlockExpr *blkExpr = nullptr);
1058
1059  sema::FunctionScopeInfo *getCurFunction() const {
1060    return FunctionScopes.back();
1061  }
1062
1063  sema::FunctionScopeInfo *getEnclosingFunction() const {
1064    if (FunctionScopes.empty())
1065      return nullptr;
1066
1067    for (int e = FunctionScopes.size()-1; e >= 0; --e) {
1068      if (isa<sema::BlockScopeInfo>(FunctionScopes[e]))
1069        continue;
1070      return FunctionScopes[e];
1071    }
1072    return nullptr;
1073  }
1074
1075  template <typename ExprT>
1076  void recordUseOfEvaluatedWeak(const ExprT *E, bool IsRead=true) {
1077    if (!isUnevaluatedContext())
1078      getCurFunction()->recordUseOfWeak(E, IsRead);
1079  }
1080
1081  void PushCompoundScope();
1082  void PopCompoundScope();
1083
1084  sema::CompoundScopeInfo &getCurCompoundScope() const;
1085
1086  bool hasAnyUnrecoverableErrorsInThisFunction() const;
1087
1088  /// \brief Retrieve the current block, if any.
1089  sema::BlockScopeInfo *getCurBlock();
1090
1091  /// \brief Retrieve the current lambda scope info, if any.
1092  sema::LambdaScopeInfo *getCurLambda();
1093
1094  /// \brief Retrieve the current generic lambda info, if any.
1095  sema::LambdaScopeInfo *getCurGenericLambda();
1096
1097  /// \brief Retrieve the current captured region, if any.
1098  sema::CapturedRegionScopeInfo *getCurCapturedRegion();
1099
1100  /// WeakTopLevelDeclDecls - access to \#pragma weak-generated Decls
1101  SmallVectorImpl<Decl *> &WeakTopLevelDecls() { return WeakTopLevelDecl; }
1102
1103  void ActOnComment(SourceRange Comment);
1104
1105  //===--------------------------------------------------------------------===//
1106  // Type Analysis / Processing: SemaType.cpp.
1107  //
1108
1109  QualType BuildQualifiedType(QualType T, SourceLocation Loc, Qualifiers Qs,
1110                              const DeclSpec *DS = nullptr);
1111  QualType BuildQualifiedType(QualType T, SourceLocation Loc, unsigned CVRA,
1112                              const DeclSpec *DS = nullptr);
1113  QualType BuildPointerType(QualType T,
1114                            SourceLocation Loc, DeclarationName Entity);
1115  QualType BuildReferenceType(QualType T, bool LValueRef,
1116                              SourceLocation Loc, DeclarationName Entity);
1117  QualType BuildArrayType(QualType T, ArrayType::ArraySizeModifier ASM,
1118                          Expr *ArraySize, unsigned Quals,
1119                          SourceRange Brackets, DeclarationName Entity);
1120  QualType BuildExtVectorType(QualType T, Expr *ArraySize,
1121                              SourceLocation AttrLoc);
1122
1123  bool CheckFunctionReturnType(QualType T, SourceLocation Loc);
1124
1125  /// \brief Build a function type.
1126  ///
1127  /// This routine checks the function type according to C++ rules and
1128  /// under the assumption that the result type and parameter types have
1129  /// just been instantiated from a template. It therefore duplicates
1130  /// some of the behavior of GetTypeForDeclarator, but in a much
1131  /// simpler form that is only suitable for this narrow use case.
1132  ///
1133  /// \param T The return type of the function.
1134  ///
1135  /// \param ParamTypes The parameter types of the function. This array
1136  /// will be modified to account for adjustments to the types of the
1137  /// function parameters.
1138  ///
1139  /// \param Loc The location of the entity whose type involves this
1140  /// function type or, if there is no such entity, the location of the
1141  /// type that will have function type.
1142  ///
1143  /// \param Entity The name of the entity that involves the function
1144  /// type, if known.
1145  ///
1146  /// \param EPI Extra information about the function type. Usually this will
1147  /// be taken from an existing function with the same prototype.
1148  ///
1149  /// \returns A suitable function type, if there are no errors. The
1150  /// unqualified type will always be a FunctionProtoType.
1151  /// Otherwise, returns a NULL type.
1152  QualType BuildFunctionType(QualType T,
1153                             MutableArrayRef<QualType> ParamTypes,
1154                             SourceLocation Loc, DeclarationName Entity,
1155                             const FunctionProtoType::ExtProtoInfo &EPI);
1156
1157  QualType BuildMemberPointerType(QualType T, QualType Class,
1158                                  SourceLocation Loc,
1159                                  DeclarationName Entity);
1160  QualType BuildBlockPointerType(QualType T,
1161                                 SourceLocation Loc, DeclarationName Entity);
1162  QualType BuildParenType(QualType T);
1163  QualType BuildAtomicType(QualType T, SourceLocation Loc);
1164
1165  TypeSourceInfo *GetTypeForDeclarator(Declarator &D, Scope *S);
1166  TypeSourceInfo *GetTypeForDeclaratorCast(Declarator &D, QualType FromTy);
1167  TypeSourceInfo *GetTypeSourceInfoForDeclarator(Declarator &D, QualType T,
1168                                               TypeSourceInfo *ReturnTypeInfo);
1169
1170  /// \brief Package the given type and TSI into a ParsedType.
1171  ParsedType CreateParsedType(QualType T, TypeSourceInfo *TInfo);
1172  DeclarationNameInfo GetNameForDeclarator(Declarator &D);
1173  DeclarationNameInfo GetNameFromUnqualifiedId(const UnqualifiedId &Name);
1174  static QualType GetTypeFromParser(ParsedType Ty,
1175                                    TypeSourceInfo **TInfo = nullptr);
1176  CanThrowResult canThrow(const Expr *E);
1177  const FunctionProtoType *ResolveExceptionSpec(SourceLocation Loc,
1178                                                const FunctionProtoType *FPT);
1179  void UpdateExceptionSpec(FunctionDecl *FD,
1180                           const FunctionProtoType::ExtProtoInfo &EPI);
1181  bool CheckSpecifiedExceptionType(QualType &T, const SourceRange &Range);
1182  bool CheckDistantExceptionSpec(QualType T);
1183  bool CheckEquivalentExceptionSpec(FunctionDecl *Old, FunctionDecl *New);
1184  bool CheckEquivalentExceptionSpec(
1185      const FunctionProtoType *Old, SourceLocation OldLoc,
1186      const FunctionProtoType *New, SourceLocation NewLoc);
1187  bool CheckEquivalentExceptionSpec(
1188      const PartialDiagnostic &DiagID, const PartialDiagnostic & NoteID,
1189      const FunctionProtoType *Old, SourceLocation OldLoc,
1190      const FunctionProtoType *New, SourceLocation NewLoc,
1191      bool *MissingExceptionSpecification = nullptr,
1192      bool *MissingEmptyExceptionSpecification = nullptr,
1193      bool AllowNoexceptAllMatchWithNoSpec = false,
1194      bool IsOperatorNew = false);
1195  bool CheckExceptionSpecSubset(
1196      const PartialDiagnostic &DiagID, const PartialDiagnostic & NoteID,
1197      const FunctionProtoType *Superset, SourceLocation SuperLoc,
1198      const FunctionProtoType *Subset, SourceLocation SubLoc);
1199  bool CheckParamExceptionSpec(const PartialDiagnostic & NoteID,
1200      const FunctionProtoType *Target, SourceLocation TargetLoc,
1201      const FunctionProtoType *Source, SourceLocation SourceLoc);
1202
1203  TypeResult ActOnTypeName(Scope *S, Declarator &D);
1204
1205  /// \brief The parser has parsed the context-sensitive type 'instancetype'
1206  /// in an Objective-C message declaration. Return the appropriate type.
1207  ParsedType ActOnObjCInstanceType(SourceLocation Loc);
1208
1209  /// \brief Abstract class used to diagnose incomplete types.
1210  struct TypeDiagnoser {
1211    bool Suppressed;
1212
1213    TypeDiagnoser(bool Suppressed = false) : Suppressed(Suppressed) { }
1214
1215    virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) = 0;
1216    virtual ~TypeDiagnoser() {}
1217  };
1218
1219  static int getPrintable(int I) { return I; }
1220  static unsigned getPrintable(unsigned I) { return I; }
1221  static bool getPrintable(bool B) { return B; }
1222  static const char * getPrintable(const char *S) { return S; }
1223  static StringRef getPrintable(StringRef S) { return S; }
1224  static const std::string &getPrintable(const std::string &S) { return S; }
1225  static const IdentifierInfo *getPrintable(const IdentifierInfo *II) {
1226    return II;
1227  }
1228  static DeclarationName getPrintable(DeclarationName N) { return N; }
1229  static QualType getPrintable(QualType T) { return T; }
1230  static SourceRange getPrintable(SourceRange R) { return R; }
1231  static SourceRange getPrintable(SourceLocation L) { return L; }
1232  static SourceRange getPrintable(Expr *E) { return E->getSourceRange(); }
1233  static SourceRange getPrintable(TypeLoc TL) { return TL.getSourceRange();}
1234
1235  template<typename T1>
1236  class BoundTypeDiagnoser1 : public TypeDiagnoser {
1237    unsigned DiagID;
1238    const T1 &Arg1;
1239
1240  public:
1241    BoundTypeDiagnoser1(unsigned DiagID, const T1 &Arg1)
1242      : TypeDiagnoser(DiagID == 0), DiagID(DiagID), Arg1(Arg1) { }
1243    void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
1244      if (Suppressed) return;
1245      S.Diag(Loc, DiagID) << getPrintable(Arg1) << T;
1246    }
1247
1248    virtual ~BoundTypeDiagnoser1() { }
1249  };
1250
1251  template<typename T1, typename T2>
1252  class BoundTypeDiagnoser2 : public TypeDiagnoser {
1253    unsigned DiagID;
1254    const T1 &Arg1;
1255    const T2 &Arg2;
1256
1257  public:
1258    BoundTypeDiagnoser2(unsigned DiagID, const T1 &Arg1,
1259                                  const T2 &Arg2)
1260      : TypeDiagnoser(DiagID == 0), DiagID(DiagID), Arg1(Arg1),
1261        Arg2(Arg2) { }
1262
1263    void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
1264      if (Suppressed) return;
1265      S.Diag(Loc, DiagID) << getPrintable(Arg1) << getPrintable(Arg2) << T;
1266    }
1267
1268    virtual ~BoundTypeDiagnoser2() { }
1269  };
1270
1271  template<typename T1, typename T2, typename T3>
1272  class BoundTypeDiagnoser3 : public TypeDiagnoser {
1273    unsigned DiagID;
1274    const T1 &Arg1;
1275    const T2 &Arg2;
1276    const T3 &Arg3;
1277
1278  public:
1279    BoundTypeDiagnoser3(unsigned DiagID, const T1 &Arg1,
1280                                  const T2 &Arg2, const T3 &Arg3)
1281    : TypeDiagnoser(DiagID == 0), DiagID(DiagID), Arg1(Arg1),
1282      Arg2(Arg2), Arg3(Arg3) { }
1283
1284    void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
1285      if (Suppressed) return;
1286      S.Diag(Loc, DiagID)
1287        << getPrintable(Arg1) << getPrintable(Arg2) << getPrintable(Arg3) << T;
1288    }
1289
1290    virtual ~BoundTypeDiagnoser3() { }
1291  };
1292
1293private:
1294  bool RequireCompleteTypeImpl(SourceLocation Loc, QualType T,
1295                           TypeDiagnoser &Diagnoser);
1296public:
1297  bool RequireCompleteType(SourceLocation Loc, QualType T,
1298                           TypeDiagnoser &Diagnoser);
1299  bool RequireCompleteType(SourceLocation Loc, QualType T,
1300                           unsigned DiagID);
1301
1302  template<typename T1>
1303  bool RequireCompleteType(SourceLocation Loc, QualType T,
1304                           unsigned DiagID, const T1 &Arg1) {
1305    BoundTypeDiagnoser1<T1> Diagnoser(DiagID, Arg1);
1306    return RequireCompleteType(Loc, T, Diagnoser);
1307  }
1308
1309  template<typename T1, typename T2>
1310  bool RequireCompleteType(SourceLocation Loc, QualType T,
1311                           unsigned DiagID, const T1 &Arg1, const T2 &Arg2) {
1312    BoundTypeDiagnoser2<T1, T2> Diagnoser(DiagID, Arg1, Arg2);
1313    return RequireCompleteType(Loc, T, Diagnoser);
1314  }
1315
1316  template<typename T1, typename T2, typename T3>
1317  bool RequireCompleteType(SourceLocation Loc, QualType T,
1318                           unsigned DiagID, const T1 &Arg1, const T2 &Arg2,
1319                           const T3 &Arg3) {
1320    BoundTypeDiagnoser3<T1, T2, T3> Diagnoser(DiagID, Arg1, Arg2,
1321                                                        Arg3);
1322    return RequireCompleteType(Loc, T, Diagnoser);
1323  }
1324
1325  bool RequireCompleteExprType(Expr *E, TypeDiagnoser &Diagnoser);
1326  bool RequireCompleteExprType(Expr *E, unsigned DiagID);
1327
1328  template<typename T1>
1329  bool RequireCompleteExprType(Expr *E, unsigned DiagID, const T1 &Arg1) {
1330    BoundTypeDiagnoser1<T1> Diagnoser(DiagID, Arg1);
1331    return RequireCompleteExprType(E, Diagnoser);
1332  }
1333
1334  template<typename T1, typename T2>
1335  bool RequireCompleteExprType(Expr *E, unsigned DiagID, const T1 &Arg1,
1336                               const T2 &Arg2) {
1337    BoundTypeDiagnoser2<T1, T2> Diagnoser(DiagID, Arg1, Arg2);
1338    return RequireCompleteExprType(E, Diagnoser);
1339  }
1340
1341  template<typename T1, typename T2, typename T3>
1342  bool RequireCompleteExprType(Expr *E, unsigned DiagID, const T1 &Arg1,
1343                               const T2 &Arg2, const T3 &Arg3) {
1344    BoundTypeDiagnoser3<T1, T2, T3> Diagnoser(DiagID, Arg1, Arg2,
1345                                                        Arg3);
1346    return RequireCompleteExprType(E, Diagnoser);
1347  }
1348
1349  bool RequireLiteralType(SourceLocation Loc, QualType T,
1350                          TypeDiagnoser &Diagnoser);
1351  bool RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID);
1352
1353  template<typename T1>
1354  bool RequireLiteralType(SourceLocation Loc, QualType T,
1355                          unsigned DiagID, const T1 &Arg1) {
1356    BoundTypeDiagnoser1<T1> Diagnoser(DiagID, Arg1);
1357    return RequireLiteralType(Loc, T, Diagnoser);
1358  }
1359
1360  template<typename T1, typename T2>
1361  bool RequireLiteralType(SourceLocation Loc, QualType T,
1362                          unsigned DiagID, const T1 &Arg1, const T2 &Arg2) {
1363    BoundTypeDiagnoser2<T1, T2> Diagnoser(DiagID, Arg1, Arg2);
1364    return RequireLiteralType(Loc, T, Diagnoser);
1365  }
1366
1367  template<typename T1, typename T2, typename T3>
1368  bool RequireLiteralType(SourceLocation Loc, QualType T,
1369                          unsigned DiagID, const T1 &Arg1, const T2 &Arg2,
1370                          const T3 &Arg3) {
1371    BoundTypeDiagnoser3<T1, T2, T3> Diagnoser(DiagID, Arg1, Arg2,
1372                                                        Arg3);
1373    return RequireLiteralType(Loc, T, Diagnoser);
1374  }
1375
1376  QualType getElaboratedType(ElaboratedTypeKeyword Keyword,
1377                             const CXXScopeSpec &SS, QualType T);
1378
1379  QualType BuildTypeofExprType(Expr *E, SourceLocation Loc);
1380  QualType BuildDecltypeType(Expr *E, SourceLocation Loc);
1381  QualType BuildUnaryTransformType(QualType BaseType,
1382                                   UnaryTransformType::UTTKind UKind,
1383                                   SourceLocation Loc);
1384
1385  //===--------------------------------------------------------------------===//
1386  // Symbol table / Decl tracking callbacks: SemaDecl.cpp.
1387  //
1388
1389  /// List of decls defined in a function prototype. This contains EnumConstants
1390  /// that incorrectly end up in translation unit scope because there is no
1391  /// function to pin them on. ActOnFunctionDeclarator reads this list and patches
1392  /// them into the FunctionDecl.
1393  std::vector<NamedDecl*> DeclsInPrototypeScope;
1394
1395  DeclGroupPtrTy ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType = nullptr);
1396
1397  void DiagnoseUseOfUnimplementedSelectors();
1398
1399  bool isSimpleTypeSpecifier(tok::TokenKind Kind) const;
1400
1401  ParsedType getTypeName(const IdentifierInfo &II, SourceLocation NameLoc,
1402                         Scope *S, CXXScopeSpec *SS = nullptr,
1403                         bool isClassName = false,
1404                         bool HasTrailingDot = false,
1405                         ParsedType ObjectType = ParsedType(),
1406                         bool IsCtorOrDtorName = false,
1407                         bool WantNontrivialTypeSourceInfo = false,
1408                         IdentifierInfo **CorrectedII = nullptr);
1409  TypeSpecifierType isTagName(IdentifierInfo &II, Scope *S);
1410  bool isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S);
1411  void DiagnoseUnknownTypeName(IdentifierInfo *&II,
1412                               SourceLocation IILoc,
1413                               Scope *S,
1414                               CXXScopeSpec *SS,
1415                               ParsedType &SuggestedType,
1416                               bool AllowClassTemplates = false);
1417
1418  /// \brief For compatibility with MSVC, we delay parsing of some default
1419  /// template type arguments until instantiation time.  Emits a warning and
1420  /// returns a synthesized DependentNameType that isn't really dependent on any
1421  /// other template arguments.
1422  ParsedType ActOnDelayedDefaultTemplateArg(const IdentifierInfo &II,
1423                                            SourceLocation NameLoc);
1424
1425  /// \brief Describes the result of the name lookup and resolution performed
1426  /// by \c ClassifyName().
1427  enum NameClassificationKind {
1428    NC_Unknown,
1429    NC_Error,
1430    NC_Keyword,
1431    NC_Type,
1432    NC_Expression,
1433    NC_NestedNameSpecifier,
1434    NC_TypeTemplate,
1435    NC_VarTemplate,
1436    NC_FunctionTemplate
1437  };
1438
1439  class NameClassification {
1440    NameClassificationKind Kind;
1441    ExprResult Expr;
1442    TemplateName Template;
1443    ParsedType Type;
1444    const IdentifierInfo *Keyword;
1445
1446    explicit NameClassification(NameClassificationKind Kind) : Kind(Kind) {}
1447
1448  public:
1449    NameClassification(ExprResult Expr) : Kind(NC_Expression), Expr(Expr) {}
1450
1451    NameClassification(ParsedType Type) : Kind(NC_Type), Type(Type) {}
1452
1453    NameClassification(const IdentifierInfo *Keyword)
1454      : Kind(NC_Keyword), Keyword(Keyword) { }
1455
1456    static NameClassification Error() {
1457      return NameClassification(NC_Error);
1458    }
1459
1460    static NameClassification Unknown() {
1461      return NameClassification(NC_Unknown);
1462    }
1463
1464    static NameClassification NestedNameSpecifier() {
1465      return NameClassification(NC_NestedNameSpecifier);
1466    }
1467
1468    static NameClassification TypeTemplate(TemplateName Name) {
1469      NameClassification Result(NC_TypeTemplate);
1470      Result.Template = Name;
1471      return Result;
1472    }
1473
1474    static NameClassification VarTemplate(TemplateName Name) {
1475      NameClassification Result(NC_VarTemplate);
1476      Result.Template = Name;
1477      return Result;
1478    }
1479
1480    static NameClassification FunctionTemplate(TemplateName Name) {
1481      NameClassification Result(NC_FunctionTemplate);
1482      Result.Template = Name;
1483      return Result;
1484    }
1485
1486    NameClassificationKind getKind() const { return Kind; }
1487
1488    ParsedType getType() const {
1489      assert(Kind == NC_Type);
1490      return Type;
1491    }
1492
1493    ExprResult getExpression() const {
1494      assert(Kind == NC_Expression);
1495      return Expr;
1496    }
1497
1498    TemplateName getTemplateName() const {
1499      assert(Kind == NC_TypeTemplate || Kind == NC_FunctionTemplate ||
1500             Kind == NC_VarTemplate);
1501      return Template;
1502    }
1503
1504    TemplateNameKind getTemplateNameKind() const {
1505      switch (Kind) {
1506      case NC_TypeTemplate:
1507        return TNK_Type_template;
1508      case NC_FunctionTemplate:
1509        return TNK_Function_template;
1510      case NC_VarTemplate:
1511        return TNK_Var_template;
1512      default:
1513        llvm_unreachable("unsupported name classification.");
1514      }
1515    }
1516  };
1517
1518  /// \brief Perform name lookup on the given name, classifying it based on
1519  /// the results of name lookup and the following token.
1520  ///
1521  /// This routine is used by the parser to resolve identifiers and help direct
1522  /// parsing. When the identifier cannot be found, this routine will attempt
1523  /// to correct the typo and classify based on the resulting name.
1524  ///
1525  /// \param S The scope in which we're performing name lookup.
1526  ///
1527  /// \param SS The nested-name-specifier that precedes the name.
1528  ///
1529  /// \param Name The identifier. If typo correction finds an alternative name,
1530  /// this pointer parameter will be updated accordingly.
1531  ///
1532  /// \param NameLoc The location of the identifier.
1533  ///
1534  /// \param NextToken The token following the identifier. Used to help
1535  /// disambiguate the name.
1536  ///
1537  /// \param IsAddressOfOperand True if this name is the operand of a unary
1538  ///        address of ('&') expression, assuming it is classified as an
1539  ///        expression.
1540  ///
1541  /// \param CCC The correction callback, if typo correction is desired.
1542  NameClassification ClassifyName(Scope *S,
1543                                  CXXScopeSpec &SS,
1544                                  IdentifierInfo *&Name,
1545                                  SourceLocation NameLoc,
1546                                  const Token &NextToken,
1547                                  bool IsAddressOfOperand,
1548                                  CorrectionCandidateCallback *CCC = nullptr);
1549
1550  Decl *ActOnDeclarator(Scope *S, Declarator &D);
1551
1552  NamedDecl *HandleDeclarator(Scope *S, Declarator &D,
1553                              MultiTemplateParamsArg TemplateParameterLists);
1554  void RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S);
1555  bool DiagnoseClassNameShadow(DeclContext *DC, DeclarationNameInfo Info);
1556  bool diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
1557                                    DeclarationName Name,
1558                                    SourceLocation Loc);
1559  void
1560  diagnoseIgnoredQualifiers(unsigned DiagID, unsigned Quals,
1561                            SourceLocation FallbackLoc,
1562                            SourceLocation ConstQualLoc = SourceLocation(),
1563                            SourceLocation VolatileQualLoc = SourceLocation(),
1564                            SourceLocation RestrictQualLoc = SourceLocation(),
1565                            SourceLocation AtomicQualLoc = SourceLocation());
1566
1567  static bool adjustContextForLocalExternDecl(DeclContext *&DC);
1568  void DiagnoseFunctionSpecifiers(const DeclSpec &DS);
1569  void CheckShadow(Scope *S, VarDecl *D, const LookupResult& R);
1570  void CheckShadow(Scope *S, VarDecl *D);
1571  void CheckCastAlign(Expr *Op, QualType T, SourceRange TRange);
1572  void CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *D);
1573  NamedDecl* ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
1574                                    TypeSourceInfo *TInfo,
1575                                    LookupResult &Previous);
1576  NamedDecl* ActOnTypedefNameDecl(Scope* S, DeclContext* DC, TypedefNameDecl *D,
1577                                  LookupResult &Previous, bool &Redeclaration);
1578  NamedDecl *ActOnVariableDeclarator(Scope *S, Declarator &D, DeclContext *DC,
1579                                     TypeSourceInfo *TInfo,
1580                                     LookupResult &Previous,
1581                                     MultiTemplateParamsArg TemplateParamLists,
1582                                     bool &AddToScope);
1583  // Returns true if the variable declaration is a redeclaration
1584  bool CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous);
1585  void CheckVariableDeclarationType(VarDecl *NewVD);
1586  void CheckCompleteVariableDeclaration(VarDecl *var);
1587  void MaybeSuggestAddingStaticToDecl(const FunctionDecl *D);
1588
1589  NamedDecl* ActOnFunctionDeclarator(Scope* S, Declarator& D, DeclContext* DC,
1590                                     TypeSourceInfo *TInfo,
1591                                     LookupResult &Previous,
1592                                     MultiTemplateParamsArg TemplateParamLists,
1593                                     bool &AddToScope);
1594  bool AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD);
1595
1596  bool CheckConstexprFunctionDecl(const FunctionDecl *FD);
1597  bool CheckConstexprFunctionBody(const FunctionDecl *FD, Stmt *Body);
1598
1599  void DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD);
1600  void FindHiddenVirtualMethods(CXXMethodDecl *MD,
1601                          SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods);
1602  void NoteHiddenVirtualMethods(CXXMethodDecl *MD,
1603                          SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods);
1604  // Returns true if the function declaration is a redeclaration
1605  bool CheckFunctionDeclaration(Scope *S,
1606                                FunctionDecl *NewFD, LookupResult &Previous,
1607                                bool IsExplicitSpecialization);
1608  void CheckMain(FunctionDecl *FD, const DeclSpec &D);
1609  void CheckMSVCRTEntryPoint(FunctionDecl *FD);
1610  Decl *ActOnParamDeclarator(Scope *S, Declarator &D);
1611  ParmVarDecl *BuildParmVarDeclForTypedef(DeclContext *DC,
1612                                          SourceLocation Loc,
1613                                          QualType T);
1614  ParmVarDecl *CheckParameter(DeclContext *DC, SourceLocation StartLoc,
1615                              SourceLocation NameLoc, IdentifierInfo *Name,
1616                              QualType T, TypeSourceInfo *TSInfo,
1617                              StorageClass SC);
1618  void ActOnParamDefaultArgument(Decl *param,
1619                                 SourceLocation EqualLoc,
1620                                 Expr *defarg);
1621  void ActOnParamUnparsedDefaultArgument(Decl *param,
1622                                         SourceLocation EqualLoc,
1623                                         SourceLocation ArgLoc);
1624  void ActOnParamDefaultArgumentError(Decl *param);
1625  bool SetParamDefaultArgument(ParmVarDecl *Param, Expr *DefaultArg,
1626                               SourceLocation EqualLoc);
1627
1628  void AddInitializerToDecl(Decl *dcl, Expr *init, bool DirectInit,
1629                            bool TypeMayContainAuto);
1630  void ActOnUninitializedDecl(Decl *dcl, bool TypeMayContainAuto);
1631  void ActOnInitializerError(Decl *Dcl);
1632  void ActOnCXXForRangeDecl(Decl *D);
1633  StmtResult ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc,
1634                                        IdentifierInfo *Ident,
1635                                        ParsedAttributes &Attrs,
1636                                        SourceLocation AttrEnd);
1637  void SetDeclDeleted(Decl *dcl, SourceLocation DelLoc);
1638  void SetDeclDefaulted(Decl *dcl, SourceLocation DefaultLoc);
1639  void FinalizeDeclaration(Decl *D);
1640  DeclGroupPtrTy FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
1641                                         ArrayRef<Decl *> Group);
1642  DeclGroupPtrTy BuildDeclaratorGroup(MutableArrayRef<Decl *> Group,
1643                                      bool TypeMayContainAuto = true);
1644
1645  /// Should be called on all declarations that might have attached
1646  /// documentation comments.
1647  void ActOnDocumentableDecl(Decl *D);
1648  void ActOnDocumentableDecls(ArrayRef<Decl *> Group);
1649
1650  void ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
1651                                       SourceLocation LocAfterDecls);
1652  void CheckForFunctionRedefinition(FunctionDecl *FD,
1653                                    const FunctionDecl *EffectiveDefinition =
1654                                        nullptr);
1655  Decl *ActOnStartOfFunctionDef(Scope *S, Declarator &D);
1656  Decl *ActOnStartOfFunctionDef(Scope *S, Decl *D);
1657  void ActOnStartOfObjCMethodDef(Scope *S, Decl *D);
1658  bool isObjCMethodDecl(Decl *D) {
1659    return D && isa<ObjCMethodDecl>(D);
1660  }
1661
1662  /// \brief Determine whether we can delay parsing the body of a function or
1663  /// function template until it is used, assuming we don't care about emitting
1664  /// code for that function.
1665  ///
1666  /// This will be \c false if we may need the body of the function in the
1667  /// middle of parsing an expression (where it's impractical to switch to
1668  /// parsing a different function), for instance, if it's constexpr in C++11
1669  /// or has an 'auto' return type in C++14. These cases are essentially bugs.
1670  bool canDelayFunctionBody(const Declarator &D);
1671
1672  /// \brief Determine whether we can skip parsing the body of a function
1673  /// definition, assuming we don't care about analyzing its body or emitting
1674  /// code for that function.
1675  ///
1676  /// This will be \c false only if we may need the body of the function in
1677  /// order to parse the rest of the program (for instance, if it is
1678  /// \c constexpr in C++11 or has an 'auto' return type in C++14).
1679  bool canSkipFunctionBody(Decl *D);
1680
1681  void computeNRVO(Stmt *Body, sema::FunctionScopeInfo *Scope);
1682  Decl *ActOnFinishFunctionBody(Decl *Decl, Stmt *Body);
1683  Decl *ActOnFinishFunctionBody(Decl *Decl, Stmt *Body, bool IsInstantiation);
1684  Decl *ActOnSkippedFunctionBody(Decl *Decl);
1685  void ActOnFinishInlineMethodDef(CXXMethodDecl *D);
1686
1687  /// ActOnFinishDelayedAttribute - Invoked when we have finished parsing an
1688  /// attribute for which parsing is delayed.
1689  void ActOnFinishDelayedAttribute(Scope *S, Decl *D, ParsedAttributes &Attrs);
1690
1691  /// \brief Diagnose any unused parameters in the given sequence of
1692  /// ParmVarDecl pointers.
1693  void DiagnoseUnusedParameters(ParmVarDecl * const *Begin,
1694                                ParmVarDecl * const *End);
1695
1696  /// \brief Diagnose whether the size of parameters or return value of a
1697  /// function or obj-c method definition is pass-by-value and larger than a
1698  /// specified threshold.
1699  void DiagnoseSizeOfParametersAndReturnValue(ParmVarDecl * const *Begin,
1700                                              ParmVarDecl * const *End,
1701                                              QualType ReturnTy,
1702                                              NamedDecl *D);
1703
1704  void DiagnoseInvalidJumps(Stmt *Body);
1705  Decl *ActOnFileScopeAsmDecl(Expr *expr,
1706                              SourceLocation AsmLoc,
1707                              SourceLocation RParenLoc);
1708
1709  /// \brief Handle a C++11 empty-declaration and attribute-declaration.
1710  Decl *ActOnEmptyDeclaration(Scope *S,
1711                              AttributeList *AttrList,
1712                              SourceLocation SemiLoc);
1713
1714  /// \brief The parser has processed a module import declaration.
1715  ///
1716  /// \param AtLoc The location of the '@' symbol, if any.
1717  ///
1718  /// \param ImportLoc The location of the 'import' keyword.
1719  ///
1720  /// \param Path The module access path.
1721  DeclResult ActOnModuleImport(SourceLocation AtLoc, SourceLocation ImportLoc,
1722                               ModuleIdPath Path);
1723
1724  /// \brief The parser has processed a module import translated from a
1725  /// #include or similar preprocessing directive.
1726  void ActOnModuleInclude(SourceLocation DirectiveLoc, Module *Mod);
1727
1728  /// \brief Create an implicit import of the given module at the given
1729  /// source location, for error recovery, if possible.
1730  ///
1731  /// This routine is typically used when an entity found by name lookup
1732  /// is actually hidden within a module that we know about but the user
1733  /// has forgotten to import.
1734  void createImplicitModuleImportForErrorRecovery(SourceLocation Loc,
1735                                                  Module *Mod);
1736
1737  /// \brief Retrieve a suitable printing policy.
1738  PrintingPolicy getPrintingPolicy() const {
1739    return getPrintingPolicy(Context, PP);
1740  }
1741
1742  /// \brief Retrieve a suitable printing policy.
1743  static PrintingPolicy getPrintingPolicy(const ASTContext &Ctx,
1744                                          const Preprocessor &PP);
1745
1746  /// Scope actions.
1747  void ActOnPopScope(SourceLocation Loc, Scope *S);
1748  void ActOnTranslationUnitScope(Scope *S);
1749
1750  Decl *ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS,
1751                                   DeclSpec &DS);
1752  Decl *ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS,
1753                                   DeclSpec &DS,
1754                                   MultiTemplateParamsArg TemplateParams,
1755                                   bool IsExplicitInstantiation = false);
1756
1757  Decl *BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
1758                                    AccessSpecifier AS,
1759                                    RecordDecl *Record,
1760                                    const PrintingPolicy &Policy);
1761
1762  Decl *BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
1763                                       RecordDecl *Record);
1764
1765  bool isAcceptableTagRedeclaration(const TagDecl *Previous,
1766                                    TagTypeKind NewTag, bool isDefinition,
1767                                    SourceLocation NewTagLoc,
1768                                    const IdentifierInfo &Name);
1769
1770  enum TagUseKind {
1771    TUK_Reference,   // Reference to a tag:  'struct foo *X;'
1772    TUK_Declaration, // Fwd decl of a tag:   'struct foo;'
1773    TUK_Definition,  // Definition of a tag: 'struct foo { int X; } Y;'
1774    TUK_Friend       // Friend declaration:  'friend struct foo;'
1775  };
1776
1777  Decl *ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
1778                 SourceLocation KWLoc, CXXScopeSpec &SS,
1779                 IdentifierInfo *Name, SourceLocation NameLoc,
1780                 AttributeList *Attr, AccessSpecifier AS,
1781                 SourceLocation ModulePrivateLoc,
1782                 MultiTemplateParamsArg TemplateParameterLists,
1783                 bool &OwnedDecl, bool &IsDependent,
1784                 SourceLocation ScopedEnumKWLoc,
1785                 bool ScopedEnumUsesClassTag, TypeResult UnderlyingType,
1786                 bool IsTypeSpecifier);
1787
1788  Decl *ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
1789                                unsigned TagSpec, SourceLocation TagLoc,
1790                                CXXScopeSpec &SS,
1791                                IdentifierInfo *Name, SourceLocation NameLoc,
1792                                AttributeList *Attr,
1793                                MultiTemplateParamsArg TempParamLists);
1794
1795  TypeResult ActOnDependentTag(Scope *S,
1796                               unsigned TagSpec,
1797                               TagUseKind TUK,
1798                               const CXXScopeSpec &SS,
1799                               IdentifierInfo *Name,
1800                               SourceLocation TagLoc,
1801                               SourceLocation NameLoc);
1802
1803  void ActOnDefs(Scope *S, Decl *TagD, SourceLocation DeclStart,
1804                 IdentifierInfo *ClassName,
1805                 SmallVectorImpl<Decl *> &Decls);
1806  Decl *ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
1807                   Declarator &D, Expr *BitfieldWidth);
1808
1809  FieldDecl *HandleField(Scope *S, RecordDecl *TagD, SourceLocation DeclStart,
1810                         Declarator &D, Expr *BitfieldWidth,
1811                         InClassInitStyle InitStyle,
1812                         AccessSpecifier AS);
1813  MSPropertyDecl *HandleMSProperty(Scope *S, RecordDecl *TagD,
1814                                   SourceLocation DeclStart,
1815                                   Declarator &D, Expr *BitfieldWidth,
1816                                   InClassInitStyle InitStyle,
1817                                   AccessSpecifier AS,
1818                                   AttributeList *MSPropertyAttr);
1819
1820  FieldDecl *CheckFieldDecl(DeclarationName Name, QualType T,
1821                            TypeSourceInfo *TInfo,
1822                            RecordDecl *Record, SourceLocation Loc,
1823                            bool Mutable, Expr *BitfieldWidth,
1824                            InClassInitStyle InitStyle,
1825                            SourceLocation TSSL,
1826                            AccessSpecifier AS, NamedDecl *PrevDecl,
1827                            Declarator *D = nullptr);
1828
1829  bool CheckNontrivialField(FieldDecl *FD);
1830  void DiagnoseNontrivial(const CXXRecordDecl *Record, CXXSpecialMember CSM);
1831  bool SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
1832                              bool Diagnose = false);
1833  CXXSpecialMember getSpecialMember(const CXXMethodDecl *MD);
1834  void ActOnLastBitfield(SourceLocation DeclStart,
1835                         SmallVectorImpl<Decl *> &AllIvarDecls);
1836  Decl *ActOnIvar(Scope *S, SourceLocation DeclStart,
1837                  Declarator &D, Expr *BitfieldWidth,
1838                  tok::ObjCKeywordKind visibility);
1839
1840  // This is used for both record definitions and ObjC interface declarations.
1841  void ActOnFields(Scope* S, SourceLocation RecLoc, Decl *TagDecl,
1842                   ArrayRef<Decl *> Fields,
1843                   SourceLocation LBrac, SourceLocation RBrac,
1844                   AttributeList *AttrList);
1845
1846  /// ActOnTagStartDefinition - Invoked when we have entered the
1847  /// scope of a tag's definition (e.g., for an enumeration, class,
1848  /// struct, or union).
1849  void ActOnTagStartDefinition(Scope *S, Decl *TagDecl);
1850
1851  Decl *ActOnObjCContainerStartDefinition(Decl *IDecl);
1852
1853  /// ActOnStartCXXMemberDeclarations - Invoked when we have parsed a
1854  /// C++ record definition's base-specifiers clause and are starting its
1855  /// member declarations.
1856  void ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagDecl,
1857                                       SourceLocation FinalLoc,
1858                                       bool IsFinalSpelledSealed,
1859                                       SourceLocation LBraceLoc);
1860
1861  /// ActOnTagFinishDefinition - Invoked once we have finished parsing
1862  /// the definition of a tag (enumeration, class, struct, or union).
1863  void ActOnTagFinishDefinition(Scope *S, Decl *TagDecl,
1864                                SourceLocation RBraceLoc);
1865
1866  void ActOnObjCContainerFinishDefinition();
1867
1868  /// \brief Invoked when we must temporarily exit the objective-c container
1869  /// scope for parsing/looking-up C constructs.
1870  ///
1871  /// Must be followed by a call to \see ActOnObjCReenterContainerContext
1872  void ActOnObjCTemporaryExitContainerContext(DeclContext *DC);
1873  void ActOnObjCReenterContainerContext(DeclContext *DC);
1874
1875  /// ActOnTagDefinitionError - Invoked when there was an unrecoverable
1876  /// error parsing the definition of a tag.
1877  void ActOnTagDefinitionError(Scope *S, Decl *TagDecl);
1878
1879  EnumConstantDecl *CheckEnumConstant(EnumDecl *Enum,
1880                                      EnumConstantDecl *LastEnumConst,
1881                                      SourceLocation IdLoc,
1882                                      IdentifierInfo *Id,
1883                                      Expr *val);
1884  bool CheckEnumUnderlyingType(TypeSourceInfo *TI);
1885  bool CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
1886                              QualType EnumUnderlyingTy, const EnumDecl *Prev);
1887
1888  Decl *ActOnEnumConstant(Scope *S, Decl *EnumDecl, Decl *LastEnumConstant,
1889                          SourceLocation IdLoc, IdentifierInfo *Id,
1890                          AttributeList *Attrs,
1891                          SourceLocation EqualLoc, Expr *Val);
1892  void ActOnEnumBody(SourceLocation EnumLoc, SourceLocation LBraceLoc,
1893                     SourceLocation RBraceLoc, Decl *EnumDecl,
1894                     ArrayRef<Decl *> Elements,
1895                     Scope *S, AttributeList *Attr);
1896
1897  DeclContext *getContainingDC(DeclContext *DC);
1898
1899  /// Set the current declaration context until it gets popped.
1900  void PushDeclContext(Scope *S, DeclContext *DC);
1901  void PopDeclContext();
1902
1903  /// EnterDeclaratorContext - Used when we must lookup names in the context
1904  /// of a declarator's nested name specifier.
1905  void EnterDeclaratorContext(Scope *S, DeclContext *DC);
1906  void ExitDeclaratorContext(Scope *S);
1907
1908  /// Push the parameters of D, which must be a function, into scope.
1909  void ActOnReenterFunctionContext(Scope* S, Decl* D);
1910  void ActOnExitFunctionContext();
1911
1912  DeclContext *getFunctionLevelDeclContext();
1913
1914  /// getCurFunctionDecl - If inside of a function body, this returns a pointer
1915  /// to the function decl for the function being parsed.  If we're currently
1916  /// in a 'block', this returns the containing context.
1917  FunctionDecl *getCurFunctionDecl();
1918
1919  /// getCurMethodDecl - If inside of a method body, this returns a pointer to
1920  /// the method decl for the method being parsed.  If we're currently
1921  /// in a 'block', this returns the containing context.
1922  ObjCMethodDecl *getCurMethodDecl();
1923
1924  /// getCurFunctionOrMethodDecl - Return the Decl for the current ObjC method
1925  /// or C function we're in, otherwise return null.  If we're currently
1926  /// in a 'block', this returns the containing context.
1927  NamedDecl *getCurFunctionOrMethodDecl();
1928
1929  /// Add this decl to the scope shadowed decl chains.
1930  void PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext = true);
1931
1932  /// \brief Make the given externally-produced declaration visible at the
1933  /// top level scope.
1934  ///
1935  /// \param D The externally-produced declaration to push.
1936  ///
1937  /// \param Name The name of the externally-produced declaration.
1938  void pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name);
1939
1940  /// isDeclInScope - If 'Ctx' is a function/method, isDeclInScope returns true
1941  /// if 'D' is in Scope 'S', otherwise 'S' is ignored and isDeclInScope returns
1942  /// true if 'D' belongs to the given declaration context.
1943  ///
1944  /// \param AllowInlineNamespace If \c true, allow the declaration to be in the
1945  ///        enclosing namespace set of the context, rather than contained
1946  ///        directly within it.
1947  bool isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S = nullptr,
1948                     bool AllowInlineNamespace = false);
1949
1950  /// Finds the scope corresponding to the given decl context, if it
1951  /// happens to be an enclosing scope.  Otherwise return NULL.
1952  static Scope *getScopeForDeclContext(Scope *S, DeclContext *DC);
1953
1954  /// Subroutines of ActOnDeclarator().
1955  TypedefDecl *ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
1956                                TypeSourceInfo *TInfo);
1957  bool isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New);
1958
1959  /// Attribute merging methods. Return true if a new attribute was added.
1960  AvailabilityAttr *mergeAvailabilityAttr(NamedDecl *D, SourceRange Range,
1961                                          IdentifierInfo *Platform,
1962                                          VersionTuple Introduced,
1963                                          VersionTuple Deprecated,
1964                                          VersionTuple Obsoleted,
1965                                          bool IsUnavailable,
1966                                          StringRef Message,
1967                                          bool Override,
1968                                          unsigned AttrSpellingListIndex);
1969  TypeVisibilityAttr *mergeTypeVisibilityAttr(Decl *D, SourceRange Range,
1970                                       TypeVisibilityAttr::VisibilityType Vis,
1971                                              unsigned AttrSpellingListIndex);
1972  VisibilityAttr *mergeVisibilityAttr(Decl *D, SourceRange Range,
1973                                      VisibilityAttr::VisibilityType Vis,
1974                                      unsigned AttrSpellingListIndex);
1975  DLLImportAttr *mergeDLLImportAttr(Decl *D, SourceRange Range,
1976                                    unsigned AttrSpellingListIndex);
1977  DLLExportAttr *mergeDLLExportAttr(Decl *D, SourceRange Range,
1978                                    unsigned AttrSpellingListIndex);
1979  MSInheritanceAttr *
1980  mergeMSInheritanceAttr(Decl *D, SourceRange Range, bool BestCase,
1981                         unsigned AttrSpellingListIndex,
1982                         MSInheritanceAttr::Spelling SemanticSpelling);
1983  FormatAttr *mergeFormatAttr(Decl *D, SourceRange Range,
1984                              IdentifierInfo *Format, int FormatIdx,
1985                              int FirstArg, unsigned AttrSpellingListIndex);
1986  SectionAttr *mergeSectionAttr(Decl *D, SourceRange Range, StringRef Name,
1987                                unsigned AttrSpellingListIndex);
1988
1989  /// \brief Describes the kind of merge to perform for availability
1990  /// attributes (including "deprecated", "unavailable", and "availability").
1991  enum AvailabilityMergeKind {
1992    /// \brief Don't merge availability attributes at all.
1993    AMK_None,
1994    /// \brief Merge availability attributes for a redeclaration, which requires
1995    /// an exact match.
1996    AMK_Redeclaration,
1997    /// \brief Merge availability attributes for an override, which requires
1998    /// an exact match or a weakening of constraints.
1999    AMK_Override
2000  };
2001
2002  void mergeDeclAttributes(NamedDecl *New, Decl *Old,
2003                           AvailabilityMergeKind AMK = AMK_Redeclaration);
2004  void MergeTypedefNameDecl(TypedefNameDecl *New, LookupResult &OldDecls);
2005  bool MergeFunctionDecl(FunctionDecl *New, NamedDecl *&Old, Scope *S,
2006                         bool MergeTypeWithOld);
2007  bool MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
2008                                    Scope *S, bool MergeTypeWithOld);
2009  void mergeObjCMethodDecls(ObjCMethodDecl *New, ObjCMethodDecl *Old);
2010  void MergeVarDecl(VarDecl *New, LookupResult &Previous);
2011  void MergeVarDeclTypes(VarDecl *New, VarDecl *Old, bool MergeTypeWithOld);
2012  void MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old);
2013  bool MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old, Scope *S);
2014
2015  // AssignmentAction - This is used by all the assignment diagnostic functions
2016  // to represent what is actually causing the operation
2017  enum AssignmentAction {
2018    AA_Assigning,
2019    AA_Passing,
2020    AA_Returning,
2021    AA_Converting,
2022    AA_Initializing,
2023    AA_Sending,
2024    AA_Casting,
2025    AA_Passing_CFAudited
2026  };
2027
2028  /// C++ Overloading.
2029  enum OverloadKind {
2030    /// This is a legitimate overload: the existing declarations are
2031    /// functions or function templates with different signatures.
2032    Ovl_Overload,
2033
2034    /// This is not an overload because the signature exactly matches
2035    /// an existing declaration.
2036    Ovl_Match,
2037
2038    /// This is not an overload because the lookup results contain a
2039    /// non-function.
2040    Ovl_NonFunction
2041  };
2042  OverloadKind CheckOverload(Scope *S,
2043                             FunctionDecl *New,
2044                             const LookupResult &OldDecls,
2045                             NamedDecl *&OldDecl,
2046                             bool IsForUsingDecl);
2047  bool IsOverload(FunctionDecl *New, FunctionDecl *Old, bool IsForUsingDecl);
2048
2049  /// \brief Checks availability of the function depending on the current
2050  /// function context.Inside an unavailable function,unavailability is ignored.
2051  ///
2052  /// \returns true if \p FD is unavailable and current context is inside
2053  /// an available function, false otherwise.
2054  bool isFunctionConsideredUnavailable(FunctionDecl *FD);
2055
2056  ImplicitConversionSequence
2057  TryImplicitConversion(Expr *From, QualType ToType,
2058                        bool SuppressUserConversions,
2059                        bool AllowExplicit,
2060                        bool InOverloadResolution,
2061                        bool CStyle,
2062                        bool AllowObjCWritebackConversion);
2063
2064  bool IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType);
2065  bool IsFloatingPointPromotion(QualType FromType, QualType ToType);
2066  bool IsComplexPromotion(QualType FromType, QualType ToType);
2067  bool IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
2068                           bool InOverloadResolution,
2069                           QualType& ConvertedType, bool &IncompatibleObjC);
2070  bool isObjCPointerConversion(QualType FromType, QualType ToType,
2071                               QualType& ConvertedType, bool &IncompatibleObjC);
2072  bool isObjCWritebackConversion(QualType FromType, QualType ToType,
2073                                 QualType &ConvertedType);
2074  bool IsBlockPointerConversion(QualType FromType, QualType ToType,
2075                                QualType& ConvertedType);
2076  bool FunctionParamTypesAreEqual(const FunctionProtoType *OldType,
2077                                  const FunctionProtoType *NewType,
2078                                  unsigned *ArgPos = nullptr);
2079  void HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
2080                                  QualType FromType, QualType ToType);
2081
2082  CastKind PrepareCastToObjCObjectPointer(ExprResult &E);
2083  bool CheckPointerConversion(Expr *From, QualType ToType,
2084                              CastKind &Kind,
2085                              CXXCastPath& BasePath,
2086                              bool IgnoreBaseAccess);
2087  bool IsMemberPointerConversion(Expr *From, QualType FromType, QualType ToType,
2088                                 bool InOverloadResolution,
2089                                 QualType &ConvertedType);
2090  bool CheckMemberPointerConversion(Expr *From, QualType ToType,
2091                                    CastKind &Kind,
2092                                    CXXCastPath &BasePath,
2093                                    bool IgnoreBaseAccess);
2094  bool IsQualificationConversion(QualType FromType, QualType ToType,
2095                                 bool CStyle, bool &ObjCLifetimeConversion);
2096  bool IsNoReturnConversion(QualType FromType, QualType ToType,
2097                            QualType &ResultTy);
2098  bool DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType);
2099  bool isSameOrCompatibleFunctionType(CanQualType Param, CanQualType Arg);
2100
2101  ExprResult PerformMoveOrCopyInitialization(const InitializedEntity &Entity,
2102                                             const VarDecl *NRVOCandidate,
2103                                             QualType ResultType,
2104                                             Expr *Value,
2105                                             bool AllowNRVO = true);
2106
2107  bool CanPerformCopyInitialization(const InitializedEntity &Entity,
2108                                    ExprResult Init);
2109  ExprResult PerformCopyInitialization(const InitializedEntity &Entity,
2110                                       SourceLocation EqualLoc,
2111                                       ExprResult Init,
2112                                       bool TopLevelOfInitList = false,
2113                                       bool AllowExplicit = false);
2114  ExprResult PerformObjectArgumentInitialization(Expr *From,
2115                                                 NestedNameSpecifier *Qualifier,
2116                                                 NamedDecl *FoundDecl,
2117                                                 CXXMethodDecl *Method);
2118
2119  ExprResult PerformContextuallyConvertToBool(Expr *From);
2120  ExprResult PerformContextuallyConvertToObjCPointer(Expr *From);
2121
2122  /// Contexts in which a converted constant expression is required.
2123  enum CCEKind {
2124    CCEK_CaseValue,   ///< Expression in a case label.
2125    CCEK_Enumerator,  ///< Enumerator value with fixed underlying type.
2126    CCEK_TemplateArg, ///< Value of a non-type template parameter.
2127    CCEK_NewExpr      ///< Constant expression in a noptr-new-declarator.
2128  };
2129  ExprResult CheckConvertedConstantExpression(Expr *From, QualType T,
2130                                              llvm::APSInt &Value, CCEKind CCE);
2131
2132  /// \brief Abstract base class used to perform a contextual implicit
2133  /// conversion from an expression to any type passing a filter.
2134  class ContextualImplicitConverter {
2135  public:
2136    bool Suppress;
2137    bool SuppressConversion;
2138
2139    ContextualImplicitConverter(bool Suppress = false,
2140                                bool SuppressConversion = false)
2141        : Suppress(Suppress), SuppressConversion(SuppressConversion) {}
2142
2143    /// \brief Determine whether the specified type is a valid destination type
2144    /// for this conversion.
2145    virtual bool match(QualType T) = 0;
2146
2147    /// \brief Emits a diagnostic complaining that the expression does not have
2148    /// integral or enumeration type.
2149    virtual SemaDiagnosticBuilder
2150    diagnoseNoMatch(Sema &S, SourceLocation Loc, QualType T) = 0;
2151
2152    /// \brief Emits a diagnostic when the expression has incomplete class type.
2153    virtual SemaDiagnosticBuilder
2154    diagnoseIncomplete(Sema &S, SourceLocation Loc, QualType T) = 0;
2155
2156    /// \brief Emits a diagnostic when the only matching conversion function
2157    /// is explicit.
2158    virtual SemaDiagnosticBuilder diagnoseExplicitConv(
2159        Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) = 0;
2160
2161    /// \brief Emits a note for the explicit conversion function.
2162    virtual SemaDiagnosticBuilder
2163    noteExplicitConv(Sema &S, CXXConversionDecl *Conv, QualType ConvTy) = 0;
2164
2165    /// \brief Emits a diagnostic when there are multiple possible conversion
2166    /// functions.
2167    virtual SemaDiagnosticBuilder
2168    diagnoseAmbiguous(Sema &S, SourceLocation Loc, QualType T) = 0;
2169
2170    /// \brief Emits a note for one of the candidate conversions.
2171    virtual SemaDiagnosticBuilder
2172    noteAmbiguous(Sema &S, CXXConversionDecl *Conv, QualType ConvTy) = 0;
2173
2174    /// \brief Emits a diagnostic when we picked a conversion function
2175    /// (for cases when we are not allowed to pick a conversion function).
2176    virtual SemaDiagnosticBuilder diagnoseConversion(
2177        Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) = 0;
2178
2179    virtual ~ContextualImplicitConverter() {}
2180  };
2181
2182  class ICEConvertDiagnoser : public ContextualImplicitConverter {
2183    bool AllowScopedEnumerations;
2184
2185  public:
2186    ICEConvertDiagnoser(bool AllowScopedEnumerations,
2187                        bool Suppress, bool SuppressConversion)
2188        : ContextualImplicitConverter(Suppress, SuppressConversion),
2189          AllowScopedEnumerations(AllowScopedEnumerations) {}
2190
2191    /// Match an integral or (possibly scoped) enumeration type.
2192    bool match(QualType T) override;
2193
2194    SemaDiagnosticBuilder
2195    diagnoseNoMatch(Sema &S, SourceLocation Loc, QualType T) override {
2196      return diagnoseNotInt(S, Loc, T);
2197    }
2198
2199    /// \brief Emits a diagnostic complaining that the expression does not have
2200    /// integral or enumeration type.
2201    virtual SemaDiagnosticBuilder
2202    diagnoseNotInt(Sema &S, SourceLocation Loc, QualType T) = 0;
2203  };
2204
2205  /// Perform a contextual implicit conversion.
2206  ExprResult PerformContextualImplicitConversion(
2207      SourceLocation Loc, Expr *FromE, ContextualImplicitConverter &Converter);
2208
2209
2210  enum ObjCSubscriptKind {
2211    OS_Array,
2212    OS_Dictionary,
2213    OS_Error
2214  };
2215  ObjCSubscriptKind CheckSubscriptingKind(Expr *FromE);
2216
2217  // Note that LK_String is intentionally after the other literals, as
2218  // this is used for diagnostics logic.
2219  enum ObjCLiteralKind {
2220    LK_Array,
2221    LK_Dictionary,
2222    LK_Numeric,
2223    LK_Boxed,
2224    LK_String,
2225    LK_Block,
2226    LK_None
2227  };
2228  ObjCLiteralKind CheckLiteralKind(Expr *FromE);
2229
2230  ExprResult PerformObjectMemberConversion(Expr *From,
2231                                           NestedNameSpecifier *Qualifier,
2232                                           NamedDecl *FoundDecl,
2233                                           NamedDecl *Member);
2234
2235  // Members have to be NamespaceDecl* or TranslationUnitDecl*.
2236  // TODO: make this is a typesafe union.
2237  typedef llvm::SmallPtrSet<DeclContext   *, 16> AssociatedNamespaceSet;
2238  typedef llvm::SmallPtrSet<CXXRecordDecl *, 16> AssociatedClassSet;
2239
2240  void AddOverloadCandidate(FunctionDecl *Function,
2241                            DeclAccessPair FoundDecl,
2242                            ArrayRef<Expr *> Args,
2243                            OverloadCandidateSet& CandidateSet,
2244                            bool SuppressUserConversions = false,
2245                            bool PartialOverloading = false,
2246                            bool AllowExplicit = false);
2247  void AddFunctionCandidates(const UnresolvedSetImpl &Functions,
2248                      ArrayRef<Expr *> Args,
2249                      OverloadCandidateSet &CandidateSet,
2250                      bool SuppressUserConversions = false,
2251                      TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr);
2252  void AddMethodCandidate(DeclAccessPair FoundDecl,
2253                          QualType ObjectType,
2254                          Expr::Classification ObjectClassification,
2255                          ArrayRef<Expr *> Args,
2256                          OverloadCandidateSet& CandidateSet,
2257                          bool SuppressUserConversion = false);
2258  void AddMethodCandidate(CXXMethodDecl *Method,
2259                          DeclAccessPair FoundDecl,
2260                          CXXRecordDecl *ActingContext, QualType ObjectType,
2261                          Expr::Classification ObjectClassification,
2262                          ArrayRef<Expr *> Args,
2263                          OverloadCandidateSet& CandidateSet,
2264                          bool SuppressUserConversions = false);
2265  void AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
2266                                  DeclAccessPair FoundDecl,
2267                                  CXXRecordDecl *ActingContext,
2268                                 TemplateArgumentListInfo *ExplicitTemplateArgs,
2269                                  QualType ObjectType,
2270                                  Expr::Classification ObjectClassification,
2271                                  ArrayRef<Expr *> Args,
2272                                  OverloadCandidateSet& CandidateSet,
2273                                  bool SuppressUserConversions = false);
2274  void AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
2275                                    DeclAccessPair FoundDecl,
2276                                 TemplateArgumentListInfo *ExplicitTemplateArgs,
2277                                    ArrayRef<Expr *> Args,
2278                                    OverloadCandidateSet& CandidateSet,
2279                                    bool SuppressUserConversions = false);
2280  void AddConversionCandidate(CXXConversionDecl *Conversion,
2281                              DeclAccessPair FoundDecl,
2282                              CXXRecordDecl *ActingContext,
2283                              Expr *From, QualType ToType,
2284                              OverloadCandidateSet& CandidateSet,
2285                              bool AllowObjCConversionOnExplicit);
2286  void AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
2287                                      DeclAccessPair FoundDecl,
2288                                      CXXRecordDecl *ActingContext,
2289                                      Expr *From, QualType ToType,
2290                                      OverloadCandidateSet &CandidateSet,
2291                                      bool AllowObjCConversionOnExplicit);
2292  void AddSurrogateCandidate(CXXConversionDecl *Conversion,
2293                             DeclAccessPair FoundDecl,
2294                             CXXRecordDecl *ActingContext,
2295                             const FunctionProtoType *Proto,
2296                             Expr *Object, ArrayRef<Expr *> Args,
2297                             OverloadCandidateSet& CandidateSet);
2298  void AddMemberOperatorCandidates(OverloadedOperatorKind Op,
2299                                   SourceLocation OpLoc, ArrayRef<Expr *> Args,
2300                                   OverloadCandidateSet& CandidateSet,
2301                                   SourceRange OpRange = SourceRange());
2302  void AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
2303                           ArrayRef<Expr *> Args,
2304                           OverloadCandidateSet& CandidateSet,
2305                           bool IsAssignmentOperator = false,
2306                           unsigned NumContextualBoolArguments = 0);
2307  void AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
2308                                    SourceLocation OpLoc, ArrayRef<Expr *> Args,
2309                                    OverloadCandidateSet& CandidateSet);
2310  void AddArgumentDependentLookupCandidates(DeclarationName Name,
2311                                            SourceLocation Loc,
2312                                            ArrayRef<Expr *> Args,
2313                                TemplateArgumentListInfo *ExplicitTemplateArgs,
2314                                            OverloadCandidateSet& CandidateSet,
2315                                            bool PartialOverloading = false);
2316
2317  // Emit as a 'note' the specific overload candidate
2318  void NoteOverloadCandidate(FunctionDecl *Fn, QualType DestType = QualType());
2319
2320  // Emit as a series of 'note's all template and non-templates
2321  // identified by the expression Expr
2322  void NoteAllOverloadCandidates(Expr* E, QualType DestType = QualType());
2323
2324  /// Check the enable_if expressions on the given function. Returns the first
2325  /// failing attribute, or NULL if they were all successful.
2326  EnableIfAttr *CheckEnableIf(FunctionDecl *Function, ArrayRef<Expr *> Args,
2327                              bool MissingImplicitThis = false);
2328
2329  // [PossiblyAFunctionType]  -->   [Return]
2330  // NonFunctionType --> NonFunctionType
2331  // R (A) --> R(A)
2332  // R (*)(A) --> R (A)
2333  // R (&)(A) --> R (A)
2334  // R (S::*)(A) --> R (A)
2335  QualType ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType);
2336
2337  FunctionDecl *
2338  ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
2339                                     QualType TargetType,
2340                                     bool Complain,
2341                                     DeclAccessPair &Found,
2342                                     bool *pHadMultipleCandidates = nullptr);
2343
2344  FunctionDecl *
2345  ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
2346                                              bool Complain = false,
2347                                              DeclAccessPair *Found = nullptr);
2348
2349  bool ResolveAndFixSingleFunctionTemplateSpecialization(
2350                      ExprResult &SrcExpr,
2351                      bool DoFunctionPointerConverion = false,
2352                      bool Complain = false,
2353                      const SourceRange& OpRangeForComplaining = SourceRange(),
2354                      QualType DestTypeForComplaining = QualType(),
2355                      unsigned DiagIDForComplaining = 0);
2356
2357
2358  Expr *FixOverloadedFunctionReference(Expr *E,
2359                                       DeclAccessPair FoundDecl,
2360                                       FunctionDecl *Fn);
2361  ExprResult FixOverloadedFunctionReference(ExprResult,
2362                                            DeclAccessPair FoundDecl,
2363                                            FunctionDecl *Fn);
2364
2365  void AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
2366                                   ArrayRef<Expr *> Args,
2367                                   OverloadCandidateSet &CandidateSet,
2368                                   bool PartialOverloading = false);
2369
2370  // An enum used to represent the different possible results of building a
2371  // range-based for loop.
2372  enum ForRangeStatus {
2373    FRS_Success,
2374    FRS_NoViableFunction,
2375    FRS_DiagnosticIssued
2376  };
2377
2378  // An enum to represent whether something is dealing with a call to begin()
2379  // or a call to end() in a range-based for loop.
2380  enum BeginEndFunction {
2381    BEF_begin,
2382    BEF_end
2383  };
2384
2385  ForRangeStatus BuildForRangeBeginEndCall(Scope *S, SourceLocation Loc,
2386                                           SourceLocation RangeLoc,
2387                                           VarDecl *Decl,
2388                                           BeginEndFunction BEF,
2389                                           const DeclarationNameInfo &NameInfo,
2390                                           LookupResult &MemberLookup,
2391                                           OverloadCandidateSet *CandidateSet,
2392                                           Expr *Range, ExprResult *CallExpr);
2393
2394  ExprResult BuildOverloadedCallExpr(Scope *S, Expr *Fn,
2395                                     UnresolvedLookupExpr *ULE,
2396                                     SourceLocation LParenLoc,
2397                                     MultiExprArg Args,
2398                                     SourceLocation RParenLoc,
2399                                     Expr *ExecConfig,
2400                                     bool AllowTypoCorrection=true);
2401
2402  bool buildOverloadedCallSet(Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE,
2403                              MultiExprArg Args, SourceLocation RParenLoc,
2404                              OverloadCandidateSet *CandidateSet,
2405                              ExprResult *Result);
2406
2407  ExprResult CreateOverloadedUnaryOp(SourceLocation OpLoc,
2408                                     unsigned Opc,
2409                                     const UnresolvedSetImpl &Fns,
2410                                     Expr *input);
2411
2412  ExprResult CreateOverloadedBinOp(SourceLocation OpLoc,
2413                                   unsigned Opc,
2414                                   const UnresolvedSetImpl &Fns,
2415                                   Expr *LHS, Expr *RHS);
2416
2417  ExprResult CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
2418                                                SourceLocation RLoc,
2419                                                Expr *Base,Expr *Idx);
2420
2421  ExprResult
2422  BuildCallToMemberFunction(Scope *S, Expr *MemExpr,
2423                            SourceLocation LParenLoc,
2424                            MultiExprArg Args,
2425                            SourceLocation RParenLoc);
2426  ExprResult
2427  BuildCallToObjectOfClassType(Scope *S, Expr *Object, SourceLocation LParenLoc,
2428                               MultiExprArg Args,
2429                               SourceLocation RParenLoc);
2430
2431  ExprResult BuildOverloadedArrowExpr(Scope *S, Expr *Base,
2432                                      SourceLocation OpLoc,
2433                                      bool *NoArrowOperatorFound = nullptr);
2434
2435  /// CheckCallReturnType - Checks that a call expression's return type is
2436  /// complete. Returns true on failure. The location passed in is the location
2437  /// that best represents the call.
2438  bool CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
2439                           CallExpr *CE, FunctionDecl *FD);
2440
2441  /// Helpers for dealing with blocks and functions.
2442  bool CheckParmsForFunctionDef(ParmVarDecl *const *Param,
2443                                ParmVarDecl *const *ParamEnd,
2444                                bool CheckParameterNames);
2445  void CheckCXXDefaultArguments(FunctionDecl *FD);
2446  void CheckExtraCXXDefaultArguments(Declarator &D);
2447  Scope *getNonFieldDeclScope(Scope *S);
2448
2449  /// \name Name lookup
2450  ///
2451  /// These routines provide name lookup that is used during semantic
2452  /// analysis to resolve the various kinds of names (identifiers,
2453  /// overloaded operator names, constructor names, etc.) into zero or
2454  /// more declarations within a particular scope. The major entry
2455  /// points are LookupName, which performs unqualified name lookup,
2456  /// and LookupQualifiedName, which performs qualified name lookup.
2457  ///
2458  /// All name lookup is performed based on some specific criteria,
2459  /// which specify what names will be visible to name lookup and how
2460  /// far name lookup should work. These criteria are important both
2461  /// for capturing language semantics (certain lookups will ignore
2462  /// certain names, for example) and for performance, since name
2463  /// lookup is often a bottleneck in the compilation of C++. Name
2464  /// lookup criteria is specified via the LookupCriteria enumeration.
2465  ///
2466  /// The results of name lookup can vary based on the kind of name
2467  /// lookup performed, the current language, and the translation
2468  /// unit. In C, for example, name lookup will either return nothing
2469  /// (no entity found) or a single declaration. In C++, name lookup
2470  /// can additionally refer to a set of overloaded functions or
2471  /// result in an ambiguity. All of the possible results of name
2472  /// lookup are captured by the LookupResult class, which provides
2473  /// the ability to distinguish among them.
2474  //@{
2475
2476  /// @brief Describes the kind of name lookup to perform.
2477  enum LookupNameKind {
2478    /// Ordinary name lookup, which finds ordinary names (functions,
2479    /// variables, typedefs, etc.) in C and most kinds of names
2480    /// (functions, variables, members, types, etc.) in C++.
2481    LookupOrdinaryName = 0,
2482    /// Tag name lookup, which finds the names of enums, classes,
2483    /// structs, and unions.
2484    LookupTagName,
2485    /// Label name lookup.
2486    LookupLabel,
2487    /// Member name lookup, which finds the names of
2488    /// class/struct/union members.
2489    LookupMemberName,
2490    /// Look up of an operator name (e.g., operator+) for use with
2491    /// operator overloading. This lookup is similar to ordinary name
2492    /// lookup, but will ignore any declarations that are class members.
2493    LookupOperatorName,
2494    /// Look up of a name that precedes the '::' scope resolution
2495    /// operator in C++. This lookup completely ignores operator, object,
2496    /// function, and enumerator names (C++ [basic.lookup.qual]p1).
2497    LookupNestedNameSpecifierName,
2498    /// Look up a namespace name within a C++ using directive or
2499    /// namespace alias definition, ignoring non-namespace names (C++
2500    /// [basic.lookup.udir]p1).
2501    LookupNamespaceName,
2502    /// Look up all declarations in a scope with the given name,
2503    /// including resolved using declarations.  This is appropriate
2504    /// for checking redeclarations for a using declaration.
2505    LookupUsingDeclName,
2506    /// Look up an ordinary name that is going to be redeclared as a
2507    /// name with linkage. This lookup ignores any declarations that
2508    /// are outside of the current scope unless they have linkage. See
2509    /// C99 6.2.2p4-5 and C++ [basic.link]p6.
2510    LookupRedeclarationWithLinkage,
2511    /// Look up a friend of a local class. This lookup does not look
2512    /// outside the innermost non-class scope. See C++11 [class.friend]p11.
2513    LookupLocalFriendName,
2514    /// Look up the name of an Objective-C protocol.
2515    LookupObjCProtocolName,
2516    /// Look up implicit 'self' parameter of an objective-c method.
2517    LookupObjCImplicitSelfParam,
2518    /// \brief Look up any declaration with any name.
2519    LookupAnyName
2520  };
2521
2522  /// \brief Specifies whether (or how) name lookup is being performed for a
2523  /// redeclaration (vs. a reference).
2524  enum RedeclarationKind {
2525    /// \brief The lookup is a reference to this name that is not for the
2526    /// purpose of redeclaring the name.
2527    NotForRedeclaration = 0,
2528    /// \brief The lookup results will be used for redeclaration of a name,
2529    /// if an entity by that name already exists.
2530    ForRedeclaration
2531  };
2532
2533  /// \brief The possible outcomes of name lookup for a literal operator.
2534  enum LiteralOperatorLookupResult {
2535    /// \brief The lookup resulted in an error.
2536    LOLR_Error,
2537    /// \brief The lookup found a single 'cooked' literal operator, which
2538    /// expects a normal literal to be built and passed to it.
2539    LOLR_Cooked,
2540    /// \brief The lookup found a single 'raw' literal operator, which expects
2541    /// a string literal containing the spelling of the literal token.
2542    LOLR_Raw,
2543    /// \brief The lookup found an overload set of literal operator templates,
2544    /// which expect the characters of the spelling of the literal token to be
2545    /// passed as a non-type template argument pack.
2546    LOLR_Template,
2547    /// \brief The lookup found an overload set of literal operator templates,
2548    /// which expect the character type and characters of the spelling of the
2549    /// string literal token to be passed as template arguments.
2550    LOLR_StringTemplate
2551  };
2552
2553  SpecialMemberOverloadResult *LookupSpecialMember(CXXRecordDecl *D,
2554                                                   CXXSpecialMember SM,
2555                                                   bool ConstArg,
2556                                                   bool VolatileArg,
2557                                                   bool RValueThis,
2558                                                   bool ConstThis,
2559                                                   bool VolatileThis);
2560
2561private:
2562  bool CppLookupName(LookupResult &R, Scope *S);
2563
2564  // \brief The set of known/encountered (unique, canonicalized) NamespaceDecls.
2565  //
2566  // The boolean value will be true to indicate that the namespace was loaded
2567  // from an AST/PCH file, or false otherwise.
2568  llvm::MapVector<NamespaceDecl*, bool> KnownNamespaces;
2569
2570  /// \brief Whether we have already loaded known namespaces from an extenal
2571  /// source.
2572  bool LoadedExternalKnownNamespaces;
2573
2574public:
2575  /// \brief Look up a name, looking for a single declaration.  Return
2576  /// null if the results were absent, ambiguous, or overloaded.
2577  ///
2578  /// It is preferable to use the elaborated form and explicitly handle
2579  /// ambiguity and overloaded.
2580  NamedDecl *LookupSingleName(Scope *S, DeclarationName Name,
2581                              SourceLocation Loc,
2582                              LookupNameKind NameKind,
2583                              RedeclarationKind Redecl
2584                                = NotForRedeclaration);
2585  bool LookupName(LookupResult &R, Scope *S,
2586                  bool AllowBuiltinCreation = false);
2587  bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
2588                           bool InUnqualifiedLookup = false);
2589  bool LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS,
2590                        bool AllowBuiltinCreation = false,
2591                        bool EnteringContext = false);
2592  ObjCProtocolDecl *LookupProtocol(IdentifierInfo *II, SourceLocation IdLoc,
2593                                   RedeclarationKind Redecl
2594                                     = NotForRedeclaration);
2595
2596  void LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S,
2597                                    QualType T1, QualType T2,
2598                                    UnresolvedSetImpl &Functions);
2599  void addOverloadedOperatorToUnresolvedSet(UnresolvedSetImpl &Functions,
2600                                            DeclAccessPair Operator,
2601                                            QualType T1, QualType T2);
2602
2603  LabelDecl *LookupOrCreateLabel(IdentifierInfo *II, SourceLocation IdentLoc,
2604                                 SourceLocation GnuLabelLoc = SourceLocation());
2605
2606  DeclContextLookupResult LookupConstructors(CXXRecordDecl *Class);
2607  CXXConstructorDecl *LookupDefaultConstructor(CXXRecordDecl *Class);
2608  CXXConstructorDecl *LookupCopyingConstructor(CXXRecordDecl *Class,
2609                                               unsigned Quals);
2610  CXXMethodDecl *LookupCopyingAssignment(CXXRecordDecl *Class, unsigned Quals,
2611                                         bool RValueThis, unsigned ThisQuals);
2612  CXXConstructorDecl *LookupMovingConstructor(CXXRecordDecl *Class,
2613                                              unsigned Quals);
2614  CXXMethodDecl *LookupMovingAssignment(CXXRecordDecl *Class, unsigned Quals,
2615                                        bool RValueThis, unsigned ThisQuals);
2616  CXXDestructorDecl *LookupDestructor(CXXRecordDecl *Class);
2617
2618  bool checkLiteralOperatorId(const CXXScopeSpec &SS, const UnqualifiedId &Id);
2619  LiteralOperatorLookupResult LookupLiteralOperator(Scope *S, LookupResult &R,
2620                                                    ArrayRef<QualType> ArgTys,
2621                                                    bool AllowRaw,
2622                                                    bool AllowTemplate,
2623                                                    bool AllowStringTemplate);
2624  bool isKnownName(StringRef name);
2625
2626  void ArgumentDependentLookup(DeclarationName Name, SourceLocation Loc,
2627                               ArrayRef<Expr *> Args, ADLResult &Functions);
2628
2629  void LookupVisibleDecls(Scope *S, LookupNameKind Kind,
2630                          VisibleDeclConsumer &Consumer,
2631                          bool IncludeGlobalScope = true);
2632  void LookupVisibleDecls(DeclContext *Ctx, LookupNameKind Kind,
2633                          VisibleDeclConsumer &Consumer,
2634                          bool IncludeGlobalScope = true);
2635
2636  enum CorrectTypoKind {
2637    CTK_NonError,     // CorrectTypo used in a non error recovery situation.
2638    CTK_ErrorRecovery // CorrectTypo used in normal error recovery.
2639  };
2640
2641  TypoCorrection CorrectTypo(const DeclarationNameInfo &Typo,
2642                             Sema::LookupNameKind LookupKind,
2643                             Scope *S, CXXScopeSpec *SS,
2644                             CorrectionCandidateCallback &CCC,
2645                             CorrectTypoKind Mode,
2646                             DeclContext *MemberContext = nullptr,
2647                             bool EnteringContext = false,
2648                             const ObjCObjectPointerType *OPT = nullptr,
2649                             bool RecordFailure = true);
2650
2651  void diagnoseTypo(const TypoCorrection &Correction,
2652                    const PartialDiagnostic &TypoDiag,
2653                    bool ErrorRecovery = true);
2654
2655  void diagnoseTypo(const TypoCorrection &Correction,
2656                    const PartialDiagnostic &TypoDiag,
2657                    const PartialDiagnostic &PrevNote,
2658                    bool ErrorRecovery = true);
2659
2660  void FindAssociatedClassesAndNamespaces(SourceLocation InstantiationLoc,
2661                                          ArrayRef<Expr *> Args,
2662                                   AssociatedNamespaceSet &AssociatedNamespaces,
2663                                   AssociatedClassSet &AssociatedClasses);
2664
2665  void FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S,
2666                            bool ConsiderLinkage, bool AllowInlineNamespace);
2667
2668  void DiagnoseAmbiguousLookup(LookupResult &Result);
2669  //@}
2670
2671  ObjCInterfaceDecl *getObjCInterfaceDecl(IdentifierInfo *&Id,
2672                                          SourceLocation IdLoc,
2673                                          bool TypoCorrection = false);
2674  NamedDecl *LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID,
2675                                 Scope *S, bool ForRedeclaration,
2676                                 SourceLocation Loc);
2677  NamedDecl *ImplicitlyDefineFunction(SourceLocation Loc, IdentifierInfo &II,
2678                                      Scope *S);
2679  void AddKnownFunctionAttributes(FunctionDecl *FD);
2680
2681  // More parsing and symbol table subroutines.
2682
2683  void ProcessPragmaWeak(Scope *S, Decl *D);
2684  // Decl attributes - this routine is the top level dispatcher.
2685  void ProcessDeclAttributes(Scope *S, Decl *D, const Declarator &PD);
2686  void ProcessDeclAttributeList(Scope *S, Decl *D, const AttributeList *AL,
2687                                bool IncludeCXX11Attributes = true);
2688  bool ProcessAccessDeclAttributeList(AccessSpecDecl *ASDecl,
2689                                      const AttributeList *AttrList);
2690
2691  void checkUnusedDeclAttributes(Declarator &D);
2692
2693  bool CheckRegparmAttr(const AttributeList &attr, unsigned &value);
2694  bool CheckCallingConvAttr(const AttributeList &attr, CallingConv &CC,
2695                            const FunctionDecl *FD = nullptr);
2696  bool CheckNoReturnAttr(const AttributeList &attr);
2697  bool checkStringLiteralArgumentAttr(const AttributeList &Attr,
2698                                      unsigned ArgNum, StringRef &Str,
2699                                      SourceLocation *ArgLocation = nullptr);
2700  bool checkMSInheritanceAttrOnDefinition(
2701      CXXRecordDecl *RD, SourceRange Range, bool BestCase,
2702      MSInheritanceAttr::Spelling SemanticSpelling);
2703
2704  void CheckAlignasUnderalignment(Decl *D);
2705
2706  /// Adjust the calling convention of a method to be the ABI default if it
2707  /// wasn't specified explicitly.  This handles method types formed from
2708  /// function type typedefs and typename template arguments.
2709  void adjustMemberFunctionCC(QualType &T, bool IsStatic);
2710
2711  // Check if there is an explicit attribute, but only look through parens.
2712  // The intent is to look for an attribute on the current declarator, but not
2713  // one that came from a typedef.
2714  bool hasExplicitCallingConv(QualType &T);
2715
2716  /// Get the outermost AttributedType node that sets a calling convention.
2717  /// Valid types should not have multiple attributes with different CCs.
2718  const AttributedType *getCallingConvAttributedType(QualType T) const;
2719
2720  /// \brief Stmt attributes - this routine is the top level dispatcher.
2721  StmtResult ProcessStmtAttributes(Stmt *Stmt, AttributeList *Attrs,
2722                                   SourceRange Range);
2723
2724  void WarnConflictingTypedMethods(ObjCMethodDecl *Method,
2725                                   ObjCMethodDecl *MethodDecl,
2726                                   bool IsProtocolMethodDecl);
2727
2728  void CheckConflictingOverridingMethod(ObjCMethodDecl *Method,
2729                                   ObjCMethodDecl *Overridden,
2730                                   bool IsProtocolMethodDecl);
2731
2732  /// WarnExactTypedMethods - This routine issues a warning if method
2733  /// implementation declaration matches exactly that of its declaration.
2734  void WarnExactTypedMethods(ObjCMethodDecl *Method,
2735                             ObjCMethodDecl *MethodDecl,
2736                             bool IsProtocolMethodDecl);
2737
2738  typedef llvm::SmallPtrSet<Selector, 8> SelectorSet;
2739  typedef llvm::DenseMap<Selector, ObjCMethodDecl*> ProtocolsMethodsMap;
2740
2741  /// CheckImplementationIvars - This routine checks if the instance variables
2742  /// listed in the implelementation match those listed in the interface.
2743  void CheckImplementationIvars(ObjCImplementationDecl *ImpDecl,
2744                                ObjCIvarDecl **Fields, unsigned nIvars,
2745                                SourceLocation Loc);
2746
2747  /// ImplMethodsVsClassMethods - This is main routine to warn if any method
2748  /// remains unimplemented in the class or category \@implementation.
2749  void ImplMethodsVsClassMethods(Scope *S, ObjCImplDecl* IMPDecl,
2750                                 ObjCContainerDecl* IDecl,
2751                                 bool IncompleteImpl = false);
2752
2753  /// DiagnoseUnimplementedProperties - This routine warns on those properties
2754  /// which must be implemented by this implementation.
2755  void DiagnoseUnimplementedProperties(Scope *S, ObjCImplDecl* IMPDecl,
2756                                       ObjCContainerDecl *CDecl,
2757                                       bool SynthesizeProperties);
2758
2759  /// DefaultSynthesizeProperties - This routine default synthesizes all
2760  /// properties which must be synthesized in the class's \@implementation.
2761  void DefaultSynthesizeProperties (Scope *S, ObjCImplDecl* IMPDecl,
2762                                    ObjCInterfaceDecl *IDecl);
2763  void DefaultSynthesizeProperties(Scope *S, Decl *D);
2764
2765  /// IvarBacksCurrentMethodAccessor - This routine returns 'true' if 'IV' is
2766  /// an ivar synthesized for 'Method' and 'Method' is a property accessor
2767  /// declared in class 'IFace'.
2768  bool IvarBacksCurrentMethodAccessor(ObjCInterfaceDecl *IFace,
2769                                      ObjCMethodDecl *Method, ObjCIvarDecl *IV);
2770
2771  /// DiagnoseUnusedBackingIvarInAccessor - Issue an 'unused' warning if ivar which
2772  /// backs the property is not used in the property's accessor.
2773  void DiagnoseUnusedBackingIvarInAccessor(Scope *S,
2774                                           const ObjCImplementationDecl *ImplD);
2775
2776  /// GetIvarBackingPropertyAccessor - If method is a property setter/getter and
2777  /// it property has a backing ivar, returns this ivar; otherwise, returns NULL.
2778  /// It also returns ivar's property on success.
2779  ObjCIvarDecl *GetIvarBackingPropertyAccessor(const ObjCMethodDecl *Method,
2780                                               const ObjCPropertyDecl *&PDecl) const;
2781
2782  /// Called by ActOnProperty to handle \@property declarations in
2783  /// class extensions.
2784  ObjCPropertyDecl *HandlePropertyInClassExtension(Scope *S,
2785                      SourceLocation AtLoc,
2786                      SourceLocation LParenLoc,
2787                      FieldDeclarator &FD,
2788                      Selector GetterSel,
2789                      Selector SetterSel,
2790                      const bool isAssign,
2791                      const bool isReadWrite,
2792                      const unsigned Attributes,
2793                      const unsigned AttributesAsWritten,
2794                      bool *isOverridingProperty,
2795                      TypeSourceInfo *T,
2796                      tok::ObjCKeywordKind MethodImplKind);
2797
2798  /// Called by ActOnProperty and HandlePropertyInClassExtension to
2799  /// handle creating the ObjcPropertyDecl for a category or \@interface.
2800  ObjCPropertyDecl *CreatePropertyDecl(Scope *S,
2801                                       ObjCContainerDecl *CDecl,
2802                                       SourceLocation AtLoc,
2803                                       SourceLocation LParenLoc,
2804                                       FieldDeclarator &FD,
2805                                       Selector GetterSel,
2806                                       Selector SetterSel,
2807                                       const bool isAssign,
2808                                       const bool isReadWrite,
2809                                       const unsigned Attributes,
2810                                       const unsigned AttributesAsWritten,
2811                                       TypeSourceInfo *T,
2812                                       tok::ObjCKeywordKind MethodImplKind,
2813                                       DeclContext *lexicalDC = nullptr);
2814
2815  /// AtomicPropertySetterGetterRules - This routine enforces the rule (via
2816  /// warning) when atomic property has one but not the other user-declared
2817  /// setter or getter.
2818  void AtomicPropertySetterGetterRules(ObjCImplDecl* IMPDecl,
2819                                       ObjCContainerDecl* IDecl);
2820
2821  void DiagnoseOwningPropertyGetterSynthesis(const ObjCImplementationDecl *D);
2822
2823  void DiagnoseMissingDesignatedInitOverrides(
2824                                          const ObjCImplementationDecl *ImplD,
2825                                          const ObjCInterfaceDecl *IFD);
2826
2827  void DiagnoseDuplicateIvars(ObjCInterfaceDecl *ID, ObjCInterfaceDecl *SID);
2828
2829  enum MethodMatchStrategy {
2830    MMS_loose,
2831    MMS_strict
2832  };
2833
2834  /// MatchTwoMethodDeclarations - Checks if two methods' type match and returns
2835  /// true, or false, accordingly.
2836  bool MatchTwoMethodDeclarations(const ObjCMethodDecl *Method,
2837                                  const ObjCMethodDecl *PrevMethod,
2838                                  MethodMatchStrategy strategy = MMS_strict);
2839
2840  /// MatchAllMethodDeclarations - Check methods declaraed in interface or
2841  /// or protocol against those declared in their implementations.
2842  void MatchAllMethodDeclarations(const SelectorSet &InsMap,
2843                                  const SelectorSet &ClsMap,
2844                                  SelectorSet &InsMapSeen,
2845                                  SelectorSet &ClsMapSeen,
2846                                  ObjCImplDecl* IMPDecl,
2847                                  ObjCContainerDecl* IDecl,
2848                                  bool &IncompleteImpl,
2849                                  bool ImmediateClass,
2850                                  bool WarnCategoryMethodImpl=false);
2851
2852  /// CheckCategoryVsClassMethodMatches - Checks that methods implemented in
2853  /// category matches with those implemented in its primary class and
2854  /// warns each time an exact match is found.
2855  void CheckCategoryVsClassMethodMatches(ObjCCategoryImplDecl *CatIMP);
2856
2857  /// \brief Add the given method to the list of globally-known methods.
2858  void addMethodToGlobalList(ObjCMethodList *List, ObjCMethodDecl *Method);
2859
2860private:
2861  /// AddMethodToGlobalPool - Add an instance or factory method to the global
2862  /// pool. See descriptoin of AddInstanceMethodToGlobalPool.
2863  void AddMethodToGlobalPool(ObjCMethodDecl *Method, bool impl, bool instance);
2864
2865  /// LookupMethodInGlobalPool - Returns the instance or factory method and
2866  /// optionally warns if there are multiple signatures.
2867  ObjCMethodDecl *LookupMethodInGlobalPool(Selector Sel, SourceRange R,
2868                                           bool receiverIdOrClass,
2869                                           bool warn, bool instance);
2870
2871  /// \brief Record the typo correction failure and return an empty correction.
2872  TypoCorrection FailedCorrection(IdentifierInfo *Typo, SourceLocation TypoLoc,
2873                                  bool RecordFailure = true,
2874                                  bool IsUnqualifiedLookup = false) {
2875    if (IsUnqualifiedLookup)
2876      (void)UnqualifiedTyposCorrected[Typo];
2877    if (RecordFailure)
2878      TypoCorrectionFailures[Typo].insert(TypoLoc);
2879    return TypoCorrection();
2880  }
2881
2882public:
2883  /// AddInstanceMethodToGlobalPool - All instance methods in a translation
2884  /// unit are added to a global pool. This allows us to efficiently associate
2885  /// a selector with a method declaraation for purposes of typechecking
2886  /// messages sent to "id" (where the class of the object is unknown).
2887  void AddInstanceMethodToGlobalPool(ObjCMethodDecl *Method, bool impl=false) {
2888    AddMethodToGlobalPool(Method, impl, /*instance*/true);
2889  }
2890
2891  /// AddFactoryMethodToGlobalPool - Same as above, but for factory methods.
2892  void AddFactoryMethodToGlobalPool(ObjCMethodDecl *Method, bool impl=false) {
2893    AddMethodToGlobalPool(Method, impl, /*instance*/false);
2894  }
2895
2896  /// AddAnyMethodToGlobalPool - Add any method, instance or factory to global
2897  /// pool.
2898  void AddAnyMethodToGlobalPool(Decl *D);
2899
2900  /// LookupInstanceMethodInGlobalPool - Returns the method and warns if
2901  /// there are multiple signatures.
2902  ObjCMethodDecl *LookupInstanceMethodInGlobalPool(Selector Sel, SourceRange R,
2903                                                   bool receiverIdOrClass=false,
2904                                                   bool warn=true) {
2905    return LookupMethodInGlobalPool(Sel, R, receiverIdOrClass,
2906                                    warn, /*instance*/true);
2907  }
2908
2909  /// LookupFactoryMethodInGlobalPool - Returns the method and warns if
2910  /// there are multiple signatures.
2911  ObjCMethodDecl *LookupFactoryMethodInGlobalPool(Selector Sel, SourceRange R,
2912                                                  bool receiverIdOrClass=false,
2913                                                  bool warn=true) {
2914    return LookupMethodInGlobalPool(Sel, R, receiverIdOrClass,
2915                                    warn, /*instance*/false);
2916  }
2917
2918  const ObjCMethodDecl *SelectorsForTypoCorrection(Selector Sel,
2919                              QualType ObjectType=QualType());
2920  /// LookupImplementedMethodInGlobalPool - Returns the method which has an
2921  /// implementation.
2922  ObjCMethodDecl *LookupImplementedMethodInGlobalPool(Selector Sel);
2923
2924  /// CollectIvarsToConstructOrDestruct - Collect those ivars which require
2925  /// initialization.
2926  void CollectIvarsToConstructOrDestruct(ObjCInterfaceDecl *OI,
2927                                  SmallVectorImpl<ObjCIvarDecl*> &Ivars);
2928
2929  //===--------------------------------------------------------------------===//
2930  // Statement Parsing Callbacks: SemaStmt.cpp.
2931public:
2932  class FullExprArg {
2933  public:
2934    FullExprArg(Sema &actions) : E(nullptr) { }
2935
2936    // FIXME: The const_cast here is ugly. RValue references would make this
2937    // much nicer (or we could duplicate a bunch of the move semantics
2938    // emulation code from Ownership.h).
2939    FullExprArg(const FullExprArg& Other) : E(Other.E) {}
2940
2941    ExprResult release() {
2942      return E;
2943    }
2944
2945    Expr *get() const { return E; }
2946
2947    Expr *operator->() {
2948      return E;
2949    }
2950
2951  private:
2952    // FIXME: No need to make the entire Sema class a friend when it's just
2953    // Sema::MakeFullExpr that needs access to the constructor below.
2954    friend class Sema;
2955
2956    explicit FullExprArg(Expr *expr) : E(expr) {}
2957
2958    Expr *E;
2959  };
2960
2961  FullExprArg MakeFullExpr(Expr *Arg) {
2962    return MakeFullExpr(Arg, Arg ? Arg->getExprLoc() : SourceLocation());
2963  }
2964  FullExprArg MakeFullExpr(Expr *Arg, SourceLocation CC) {
2965    return FullExprArg(ActOnFinishFullExpr(Arg, CC).get());
2966  }
2967  FullExprArg MakeFullDiscardedValueExpr(Expr *Arg) {
2968    ExprResult FE =
2969      ActOnFinishFullExpr(Arg, Arg ? Arg->getExprLoc() : SourceLocation(),
2970                          /*DiscardedValue*/ true);
2971    return FullExprArg(FE.get());
2972  }
2973
2974  StmtResult ActOnExprStmt(ExprResult Arg);
2975  StmtResult ActOnExprStmtError();
2976
2977  StmtResult ActOnNullStmt(SourceLocation SemiLoc,
2978                           bool HasLeadingEmptyMacro = false);
2979
2980  void ActOnStartOfCompoundStmt();
2981  void ActOnFinishOfCompoundStmt();
2982  StmtResult ActOnCompoundStmt(SourceLocation L, SourceLocation R,
2983                               ArrayRef<Stmt *> Elts, bool isStmtExpr);
2984
2985  /// \brief A RAII object to enter scope of a compound statement.
2986  class CompoundScopeRAII {
2987  public:
2988    CompoundScopeRAII(Sema &S): S(S) {
2989      S.ActOnStartOfCompoundStmt();
2990    }
2991
2992    ~CompoundScopeRAII() {
2993      S.ActOnFinishOfCompoundStmt();
2994    }
2995
2996  private:
2997    Sema &S;
2998  };
2999
3000  StmtResult ActOnDeclStmt(DeclGroupPtrTy Decl,
3001                                   SourceLocation StartLoc,
3002                                   SourceLocation EndLoc);
3003  void ActOnForEachDeclStmt(DeclGroupPtrTy Decl);
3004  StmtResult ActOnForEachLValueExpr(Expr *E);
3005  StmtResult ActOnCaseStmt(SourceLocation CaseLoc, Expr *LHSVal,
3006                                   SourceLocation DotDotDotLoc, Expr *RHSVal,
3007                                   SourceLocation ColonLoc);
3008  void ActOnCaseStmtBody(Stmt *CaseStmt, Stmt *SubStmt);
3009
3010  StmtResult ActOnDefaultStmt(SourceLocation DefaultLoc,
3011                                      SourceLocation ColonLoc,
3012                                      Stmt *SubStmt, Scope *CurScope);
3013  StmtResult ActOnLabelStmt(SourceLocation IdentLoc, LabelDecl *TheDecl,
3014                            SourceLocation ColonLoc, Stmt *SubStmt);
3015
3016  StmtResult ActOnAttributedStmt(SourceLocation AttrLoc,
3017                                 ArrayRef<const Attr*> Attrs,
3018                                 Stmt *SubStmt);
3019
3020  StmtResult ActOnIfStmt(SourceLocation IfLoc,
3021                         FullExprArg CondVal, Decl *CondVar,
3022                         Stmt *ThenVal,
3023                         SourceLocation ElseLoc, Stmt *ElseVal);
3024  StmtResult ActOnStartOfSwitchStmt(SourceLocation SwitchLoc,
3025                                            Expr *Cond,
3026                                            Decl *CondVar);
3027  StmtResult ActOnFinishSwitchStmt(SourceLocation SwitchLoc,
3028                                           Stmt *Switch, Stmt *Body);
3029  StmtResult ActOnWhileStmt(SourceLocation WhileLoc,
3030                            FullExprArg Cond,
3031                            Decl *CondVar, Stmt *Body);
3032  StmtResult ActOnDoStmt(SourceLocation DoLoc, Stmt *Body,
3033                                 SourceLocation WhileLoc,
3034                                 SourceLocation CondLParen, Expr *Cond,
3035                                 SourceLocation CondRParen);
3036
3037  StmtResult ActOnForStmt(SourceLocation ForLoc,
3038                          SourceLocation LParenLoc,
3039                          Stmt *First, FullExprArg Second,
3040                          Decl *SecondVar,
3041                          FullExprArg Third,
3042                          SourceLocation RParenLoc,
3043                          Stmt *Body);
3044  ExprResult CheckObjCForCollectionOperand(SourceLocation forLoc,
3045                                           Expr *collection);
3046  StmtResult ActOnObjCForCollectionStmt(SourceLocation ForColLoc,
3047                                        Stmt *First, Expr *collection,
3048                                        SourceLocation RParenLoc);
3049  StmtResult FinishObjCForCollectionStmt(Stmt *ForCollection, Stmt *Body);
3050
3051  enum BuildForRangeKind {
3052    /// Initial building of a for-range statement.
3053    BFRK_Build,
3054    /// Instantiation or recovery rebuild of a for-range statement. Don't
3055    /// attempt any typo-correction.
3056    BFRK_Rebuild,
3057    /// Determining whether a for-range statement could be built. Avoid any
3058    /// unnecessary or irreversible actions.
3059    BFRK_Check
3060  };
3061
3062  StmtResult ActOnCXXForRangeStmt(SourceLocation ForLoc, Stmt *LoopVar,
3063                                  SourceLocation ColonLoc, Expr *Collection,
3064                                  SourceLocation RParenLoc,
3065                                  BuildForRangeKind Kind);
3066  StmtResult BuildCXXForRangeStmt(SourceLocation ForLoc,
3067                                  SourceLocation ColonLoc,
3068                                  Stmt *RangeDecl, Stmt *BeginEndDecl,
3069                                  Expr *Cond, Expr *Inc,
3070                                  Stmt *LoopVarDecl,
3071                                  SourceLocation RParenLoc,
3072                                  BuildForRangeKind Kind);
3073  StmtResult FinishCXXForRangeStmt(Stmt *ForRange, Stmt *Body);
3074
3075  StmtResult ActOnGotoStmt(SourceLocation GotoLoc,
3076                           SourceLocation LabelLoc,
3077                           LabelDecl *TheDecl);
3078  StmtResult ActOnIndirectGotoStmt(SourceLocation GotoLoc,
3079                                   SourceLocation StarLoc,
3080                                   Expr *DestExp);
3081  StmtResult ActOnContinueStmt(SourceLocation ContinueLoc, Scope *CurScope);
3082  StmtResult ActOnBreakStmt(SourceLocation BreakLoc, Scope *CurScope);
3083
3084  void ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope,
3085                                CapturedRegionKind Kind, unsigned NumParams);
3086  typedef std::pair<StringRef, QualType> CapturedParamNameType;
3087  void ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope,
3088                                CapturedRegionKind Kind,
3089                                ArrayRef<CapturedParamNameType> Params);
3090  StmtResult ActOnCapturedRegionEnd(Stmt *S);
3091  void ActOnCapturedRegionError();
3092  RecordDecl *CreateCapturedStmtRecordDecl(CapturedDecl *&CD,
3093                                           SourceLocation Loc,
3094                                           unsigned NumParams);
3095  VarDecl *getCopyElisionCandidate(QualType ReturnType, Expr *E,
3096                                   bool AllowFunctionParameters);
3097  bool isCopyElisionCandidate(QualType ReturnType, const VarDecl *VD,
3098                              bool AllowFunctionParameters);
3099
3100  StmtResult ActOnReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp,
3101                             Scope *CurScope);
3102  StmtResult BuildReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp);
3103  StmtResult ActOnCapScopeReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp);
3104
3105  StmtResult ActOnGCCAsmStmt(SourceLocation AsmLoc, bool IsSimple,
3106                             bool IsVolatile, unsigned NumOutputs,
3107                             unsigned NumInputs, IdentifierInfo **Names,
3108                             MultiExprArg Constraints, MultiExprArg Exprs,
3109                             Expr *AsmString, MultiExprArg Clobbers,
3110                             SourceLocation RParenLoc);
3111
3112  ExprResult LookupInlineAsmIdentifier(CXXScopeSpec &SS,
3113                                       SourceLocation TemplateKWLoc,
3114                                       UnqualifiedId &Id,
3115                                       llvm::InlineAsmIdentifierInfo &Info,
3116                                       bool IsUnevaluatedContext);
3117  bool LookupInlineAsmField(StringRef Base, StringRef Member,
3118                            unsigned &Offset, SourceLocation AsmLoc);
3119  StmtResult ActOnMSAsmStmt(SourceLocation AsmLoc, SourceLocation LBraceLoc,
3120                            ArrayRef<Token> AsmToks,
3121                            StringRef AsmString,
3122                            unsigned NumOutputs, unsigned NumInputs,
3123                            ArrayRef<StringRef> Constraints,
3124                            ArrayRef<StringRef> Clobbers,
3125                            ArrayRef<Expr*> Exprs,
3126                            SourceLocation EndLoc);
3127
3128  VarDecl *BuildObjCExceptionDecl(TypeSourceInfo *TInfo, QualType ExceptionType,
3129                                  SourceLocation StartLoc,
3130                                  SourceLocation IdLoc, IdentifierInfo *Id,
3131                                  bool Invalid = false);
3132
3133  Decl *ActOnObjCExceptionDecl(Scope *S, Declarator &D);
3134
3135  StmtResult ActOnObjCAtCatchStmt(SourceLocation AtLoc, SourceLocation RParen,
3136                                  Decl *Parm, Stmt *Body);
3137
3138  StmtResult ActOnObjCAtFinallyStmt(SourceLocation AtLoc, Stmt *Body);
3139
3140  StmtResult ActOnObjCAtTryStmt(SourceLocation AtLoc, Stmt *Try,
3141                                MultiStmtArg Catch, Stmt *Finally);
3142
3143  StmtResult BuildObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw);
3144  StmtResult ActOnObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw,
3145                                  Scope *CurScope);
3146  ExprResult ActOnObjCAtSynchronizedOperand(SourceLocation atLoc,
3147                                            Expr *operand);
3148  StmtResult ActOnObjCAtSynchronizedStmt(SourceLocation AtLoc,
3149                                         Expr *SynchExpr,
3150                                         Stmt *SynchBody);
3151
3152  StmtResult ActOnObjCAutoreleasePoolStmt(SourceLocation AtLoc, Stmt *Body);
3153
3154  VarDecl *BuildExceptionDeclaration(Scope *S, TypeSourceInfo *TInfo,
3155                                     SourceLocation StartLoc,
3156                                     SourceLocation IdLoc,
3157                                     IdentifierInfo *Id);
3158
3159  Decl *ActOnExceptionDeclarator(Scope *S, Declarator &D);
3160
3161  StmtResult ActOnCXXCatchBlock(SourceLocation CatchLoc,
3162                                Decl *ExDecl, Stmt *HandlerBlock);
3163  StmtResult ActOnCXXTryBlock(SourceLocation TryLoc, Stmt *TryBlock,
3164                              ArrayRef<Stmt *> Handlers);
3165
3166  StmtResult ActOnSEHTryBlock(bool IsCXXTry, // try (true) or __try (false) ?
3167                              SourceLocation TryLoc, Stmt *TryBlock,
3168                              Stmt *Handler);
3169  StmtResult ActOnSEHExceptBlock(SourceLocation Loc,
3170                                 Expr *FilterExpr,
3171                                 Stmt *Block);
3172  StmtResult ActOnSEHFinallyBlock(SourceLocation Loc, Stmt *Block);
3173  StmtResult ActOnSEHLeaveStmt(SourceLocation Loc, Scope *CurScope);
3174
3175  void DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock);
3176
3177  bool ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const;
3178
3179  /// \brief If it's a file scoped decl that must warn if not used, keep track
3180  /// of it.
3181  void MarkUnusedFileScopedDecl(const DeclaratorDecl *D);
3182
3183  /// DiagnoseUnusedExprResult - If the statement passed in is an expression
3184  /// whose result is unused, warn.
3185  void DiagnoseUnusedExprResult(const Stmt *S);
3186  void DiagnoseUnusedDecl(const NamedDecl *ND);
3187
3188  /// Emit \p DiagID if statement located on \p StmtLoc has a suspicious null
3189  /// statement as a \p Body, and it is located on the same line.
3190  ///
3191  /// This helps prevent bugs due to typos, such as:
3192  ///     if (condition);
3193  ///       do_stuff();
3194  void DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
3195                             const Stmt *Body,
3196                             unsigned DiagID);
3197
3198  /// Warn if a for/while loop statement \p S, which is followed by
3199  /// \p PossibleBody, has a suspicious null statement as a body.
3200  void DiagnoseEmptyLoopBody(const Stmt *S,
3201                             const Stmt *PossibleBody);
3202
3203  ParsingDeclState PushParsingDeclaration(sema::DelayedDiagnosticPool &pool) {
3204    return DelayedDiagnostics.push(pool);
3205  }
3206  void PopParsingDeclaration(ParsingDeclState state, Decl *decl);
3207
3208  typedef ProcessingContextState ParsingClassState;
3209  ParsingClassState PushParsingClass() {
3210    return DelayedDiagnostics.pushUndelayed();
3211  }
3212  void PopParsingClass(ParsingClassState state) {
3213    DelayedDiagnostics.popUndelayed(state);
3214  }
3215
3216  void redelayDiagnostics(sema::DelayedDiagnosticPool &pool);
3217
3218  enum AvailabilityDiagnostic { AD_Deprecation, AD_Unavailable };
3219
3220  void EmitAvailabilityWarning(AvailabilityDiagnostic AD,
3221                               NamedDecl *D, StringRef Message,
3222                               SourceLocation Loc,
3223                               const ObjCInterfaceDecl *UnknownObjCClass,
3224                               const ObjCPropertyDecl  *ObjCProperty,
3225                               bool ObjCPropertyAccess);
3226
3227  void HandleDelayedAvailabilityCheck(sema::DelayedDiagnostic &DD, Decl *Ctx);
3228
3229  bool makeUnavailableInSystemHeader(SourceLocation loc,
3230                                     StringRef message);
3231
3232  //===--------------------------------------------------------------------===//
3233  // Expression Parsing Callbacks: SemaExpr.cpp.
3234
3235  bool CanUseDecl(NamedDecl *D);
3236  bool DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc,
3237                         const ObjCInterfaceDecl *UnknownObjCClass=nullptr,
3238                         bool ObjCPropertyAccess=false);
3239  void NoteDeletedFunction(FunctionDecl *FD);
3240  std::string getDeletedOrUnavailableSuffix(const FunctionDecl *FD);
3241  bool DiagnosePropertyAccessorMismatch(ObjCPropertyDecl *PD,
3242                                        ObjCMethodDecl *Getter,
3243                                        SourceLocation Loc);
3244  void DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
3245                             ArrayRef<Expr *> Args);
3246
3247  void PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
3248                                       Decl *LambdaContextDecl = nullptr,
3249                                       bool IsDecltype = false);
3250  enum ReuseLambdaContextDecl_t { ReuseLambdaContextDecl };
3251  void PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
3252                                       ReuseLambdaContextDecl_t,
3253                                       bool IsDecltype = false);
3254  void PopExpressionEvaluationContext();
3255
3256  void DiscardCleanupsInEvaluationContext();
3257
3258  ExprResult TransformToPotentiallyEvaluated(Expr *E);
3259  ExprResult HandleExprEvaluationContextForTypeof(Expr *E);
3260
3261  ExprResult ActOnConstantExpression(ExprResult Res);
3262
3263  // Functions for marking a declaration referenced.  These functions also
3264  // contain the relevant logic for marking if a reference to a function or
3265  // variable is an odr-use (in the C++11 sense).  There are separate variants
3266  // for expressions referring to a decl; these exist because odr-use marking
3267  // needs to be delayed for some constant variables when we build one of the
3268  // named expressions.
3269  void MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, bool OdrUse);
3270  void MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func);
3271  void MarkVariableReferenced(SourceLocation Loc, VarDecl *Var);
3272  void MarkDeclRefReferenced(DeclRefExpr *E);
3273  void MarkMemberReferenced(MemberExpr *E);
3274
3275  void UpdateMarkingForLValueToRValue(Expr *E);
3276  void CleanupVarDeclMarking();
3277
3278  enum TryCaptureKind {
3279    TryCapture_Implicit, TryCapture_ExplicitByVal, TryCapture_ExplicitByRef
3280  };
3281
3282  /// \brief Try to capture the given variable.
3283  ///
3284  /// \param Var The variable to capture.
3285  ///
3286  /// \param Loc The location at which the capture occurs.
3287  ///
3288  /// \param Kind The kind of capture, which may be implicit (for either a
3289  /// block or a lambda), or explicit by-value or by-reference (for a lambda).
3290  ///
3291  /// \param EllipsisLoc The location of the ellipsis, if one is provided in
3292  /// an explicit lambda capture.
3293  ///
3294  /// \param BuildAndDiagnose Whether we are actually supposed to add the
3295  /// captures or diagnose errors. If false, this routine merely check whether
3296  /// the capture can occur without performing the capture itself or complaining
3297  /// if the variable cannot be captured.
3298  ///
3299  /// \param CaptureType Will be set to the type of the field used to capture
3300  /// this variable in the innermost block or lambda. Only valid when the
3301  /// variable can be captured.
3302  ///
3303  /// \param DeclRefType Will be set to the type of a reference to the capture
3304  /// from within the current scope. Only valid when the variable can be
3305  /// captured.
3306  ///
3307  /// \param FunctionScopeIndexToStopAt If non-null, it points to the index
3308  /// of the FunctionScopeInfo stack beyond which we do not attempt to capture.
3309  /// This is useful when enclosing lambdas must speculatively capture
3310  /// variables that may or may not be used in certain specializations of
3311  /// a nested generic lambda.
3312  ///
3313  /// \returns true if an error occurred (i.e., the variable cannot be
3314  /// captured) and false if the capture succeeded.
3315  bool tryCaptureVariable(VarDecl *Var, SourceLocation Loc, TryCaptureKind Kind,
3316                          SourceLocation EllipsisLoc, bool BuildAndDiagnose,
3317                          QualType &CaptureType,
3318                          QualType &DeclRefType,
3319                          const unsigned *const FunctionScopeIndexToStopAt);
3320
3321  /// \brief Try to capture the given variable.
3322  bool tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
3323                          TryCaptureKind Kind = TryCapture_Implicit,
3324                          SourceLocation EllipsisLoc = SourceLocation());
3325
3326  /// \brief Given a variable, determine the type that a reference to that
3327  /// variable will have in the given scope.
3328  QualType getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc);
3329
3330  void MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T);
3331  void MarkDeclarationsReferencedInExpr(Expr *E,
3332                                        bool SkipLocalVariables = false);
3333
3334  /// \brief Try to recover by turning the given expression into a
3335  /// call.  Returns true if recovery was attempted or an error was
3336  /// emitted; this may also leave the ExprResult invalid.
3337  bool tryToRecoverWithCall(ExprResult &E, const PartialDiagnostic &PD,
3338                            bool ForceComplain = false,
3339                            bool (*IsPlausibleResult)(QualType) = nullptr);
3340
3341  /// \brief Figure out if an expression could be turned into a call.
3342  bool tryExprAsCall(Expr &E, QualType &ZeroArgCallReturnTy,
3343                     UnresolvedSetImpl &NonTemplateOverloads);
3344
3345  /// \brief Conditionally issue a diagnostic based on the current
3346  /// evaluation context.
3347  ///
3348  /// \param Statement If Statement is non-null, delay reporting the
3349  /// diagnostic until the function body is parsed, and then do a basic
3350  /// reachability analysis to determine if the statement is reachable.
3351  /// If it is unreachable, the diagnostic will not be emitted.
3352  bool DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
3353                           const PartialDiagnostic &PD);
3354
3355  // Primary Expressions.
3356  SourceRange getExprRange(Expr *E) const;
3357
3358  ExprResult ActOnIdExpression(Scope *S, CXXScopeSpec &SS,
3359                               SourceLocation TemplateKWLoc,
3360                               UnqualifiedId &Id,
3361                               bool HasTrailingLParen, bool IsAddressOfOperand,
3362                               CorrectionCandidateCallback *CCC = nullptr,
3363                               bool IsInlineAsmIdentifier = false);
3364
3365  void DecomposeUnqualifiedId(const UnqualifiedId &Id,
3366                              TemplateArgumentListInfo &Buffer,
3367                              DeclarationNameInfo &NameInfo,
3368                              const TemplateArgumentListInfo *&TemplateArgs);
3369
3370  bool
3371  DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
3372                      CorrectionCandidateCallback &CCC,
3373                      TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr,
3374                      ArrayRef<Expr *> Args = None);
3375
3376  ExprResult LookupInObjCMethod(LookupResult &LookUp, Scope *S,
3377                                IdentifierInfo *II,
3378                                bool AllowBuiltinCreation=false);
3379
3380  ExprResult ActOnDependentIdExpression(const CXXScopeSpec &SS,
3381                                        SourceLocation TemplateKWLoc,
3382                                        const DeclarationNameInfo &NameInfo,
3383                                        bool isAddressOfOperand,
3384                                const TemplateArgumentListInfo *TemplateArgs);
3385
3386  ExprResult BuildDeclRefExpr(ValueDecl *D, QualType Ty,
3387                              ExprValueKind VK,
3388                              SourceLocation Loc,
3389                              const CXXScopeSpec *SS = nullptr);
3390  ExprResult
3391  BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
3392                   const DeclarationNameInfo &NameInfo,
3393                   const CXXScopeSpec *SS = nullptr,
3394                   NamedDecl *FoundD = nullptr,
3395                   const TemplateArgumentListInfo *TemplateArgs = nullptr);
3396  ExprResult
3397  BuildAnonymousStructUnionMemberReference(
3398      const CXXScopeSpec &SS,
3399      SourceLocation nameLoc,
3400      IndirectFieldDecl *indirectField,
3401      DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_none),
3402      Expr *baseObjectExpr = nullptr,
3403      SourceLocation opLoc = SourceLocation());
3404
3405  ExprResult BuildPossibleImplicitMemberExpr(const CXXScopeSpec &SS,
3406                                             SourceLocation TemplateKWLoc,
3407                                             LookupResult &R,
3408                                const TemplateArgumentListInfo *TemplateArgs);
3409  ExprResult BuildImplicitMemberExpr(const CXXScopeSpec &SS,
3410                                     SourceLocation TemplateKWLoc,
3411                                     LookupResult &R,
3412                                const TemplateArgumentListInfo *TemplateArgs,
3413                                     bool IsDefiniteInstance);
3414  bool UseArgumentDependentLookup(const CXXScopeSpec &SS,
3415                                  const LookupResult &R,
3416                                  bool HasTrailingLParen);
3417
3418  ExprResult BuildQualifiedDeclarationNameExpr(
3419      CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo,
3420      bool IsAddressOfOperand, TypeSourceInfo **RecoveryTSI = nullptr);
3421
3422  ExprResult BuildDependentDeclRefExpr(const CXXScopeSpec &SS,
3423                                       SourceLocation TemplateKWLoc,
3424                                const DeclarationNameInfo &NameInfo,
3425                                const TemplateArgumentListInfo *TemplateArgs);
3426
3427  ExprResult BuildDeclarationNameExpr(const CXXScopeSpec &SS,
3428                                      LookupResult &R,
3429                                      bool NeedsADL);
3430  ExprResult BuildDeclarationNameExpr(
3431      const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
3432      NamedDecl *FoundD = nullptr,
3433      const TemplateArgumentListInfo *TemplateArgs = nullptr);
3434
3435  ExprResult BuildLiteralOperatorCall(LookupResult &R,
3436                      DeclarationNameInfo &SuffixInfo,
3437                      ArrayRef<Expr *> Args,
3438                      SourceLocation LitEndLoc,
3439                      TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr);
3440
3441  ExprResult BuildPredefinedExpr(SourceLocation Loc,
3442                                 PredefinedExpr::IdentType IT);
3443  ExprResult ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind);
3444  ExprResult ActOnIntegerConstant(SourceLocation Loc, uint64_t Val);
3445  ExprResult ActOnNumericConstant(const Token &Tok, Scope *UDLScope = nullptr);
3446  ExprResult ActOnCharacterConstant(const Token &Tok,
3447                                    Scope *UDLScope = nullptr);
3448  ExprResult ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E);
3449  ExprResult ActOnParenListExpr(SourceLocation L,
3450                                SourceLocation R,
3451                                MultiExprArg Val);
3452
3453  /// ActOnStringLiteral - The specified tokens were lexed as pasted string
3454  /// fragments (e.g. "foo" "bar" L"baz").
3455  ExprResult ActOnStringLiteral(ArrayRef<Token> StringToks,
3456                                Scope *UDLScope = nullptr);
3457
3458  ExprResult ActOnGenericSelectionExpr(SourceLocation KeyLoc,
3459                                       SourceLocation DefaultLoc,
3460                                       SourceLocation RParenLoc,
3461                                       Expr *ControllingExpr,
3462                                       ArrayRef<ParsedType> ArgTypes,
3463                                       ArrayRef<Expr *> ArgExprs);
3464  ExprResult CreateGenericSelectionExpr(SourceLocation KeyLoc,
3465                                        SourceLocation DefaultLoc,
3466                                        SourceLocation RParenLoc,
3467                                        Expr *ControllingExpr,
3468                                        ArrayRef<TypeSourceInfo *> Types,
3469                                        ArrayRef<Expr *> Exprs);
3470
3471  // Binary/Unary Operators.  'Tok' is the token for the operator.
3472  ExprResult CreateBuiltinUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc,
3473                                  Expr *InputExpr);
3474  ExprResult BuildUnaryOp(Scope *S, SourceLocation OpLoc,
3475                          UnaryOperatorKind Opc, Expr *Input);
3476  ExprResult ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
3477                          tok::TokenKind Op, Expr *Input);
3478
3479  QualType CheckAddressOfOperand(ExprResult &Operand, SourceLocation OpLoc);
3480
3481  ExprResult CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
3482                                            SourceLocation OpLoc,
3483                                            UnaryExprOrTypeTrait ExprKind,
3484                                            SourceRange R);
3485  ExprResult CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
3486                                            UnaryExprOrTypeTrait ExprKind);
3487  ExprResult
3488    ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
3489                                  UnaryExprOrTypeTrait ExprKind,
3490                                  bool IsType, void *TyOrEx,
3491                                  const SourceRange &ArgRange);
3492
3493  ExprResult CheckPlaceholderExpr(Expr *E);
3494  bool CheckVecStepExpr(Expr *E);
3495
3496  bool CheckUnaryExprOrTypeTraitOperand(Expr *E, UnaryExprOrTypeTrait ExprKind);
3497  bool CheckUnaryExprOrTypeTraitOperand(QualType ExprType, SourceLocation OpLoc,
3498                                        SourceRange ExprRange,
3499                                        UnaryExprOrTypeTrait ExprKind);
3500  ExprResult ActOnSizeofParameterPackExpr(Scope *S,
3501                                          SourceLocation OpLoc,
3502                                          IdentifierInfo &Name,
3503                                          SourceLocation NameLoc,
3504                                          SourceLocation RParenLoc);
3505  ExprResult ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
3506                                 tok::TokenKind Kind, Expr *Input);
3507
3508  ExprResult ActOnArraySubscriptExpr(Scope *S, Expr *Base, SourceLocation LLoc,
3509                                     Expr *Idx, SourceLocation RLoc);
3510  ExprResult CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
3511                                             Expr *Idx, SourceLocation RLoc);
3512
3513  // This struct is for use by ActOnMemberAccess to allow
3514  // BuildMemberReferenceExpr to be able to reinvoke ActOnMemberAccess after
3515  // changing the access operator from a '.' to a '->' (to see if that is the
3516  // change needed to fix an error about an unknown member, e.g. when the class
3517  // defines a custom operator->).
3518  struct ActOnMemberAccessExtraArgs {
3519    Scope *S;
3520    UnqualifiedId &Id;
3521    Decl *ObjCImpDecl;
3522    bool HasTrailingLParen;
3523  };
3524
3525  ExprResult BuildMemberReferenceExpr(
3526      Expr *Base, QualType BaseType, SourceLocation OpLoc, bool IsArrow,
3527      CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
3528      NamedDecl *FirstQualifierInScope, const DeclarationNameInfo &NameInfo,
3529      const TemplateArgumentListInfo *TemplateArgs,
3530      ActOnMemberAccessExtraArgs *ExtraArgs = nullptr);
3531
3532  ExprResult
3533  BuildMemberReferenceExpr(Expr *Base, QualType BaseType, SourceLocation OpLoc,
3534                           bool IsArrow, const CXXScopeSpec &SS,
3535                           SourceLocation TemplateKWLoc,
3536                           NamedDecl *FirstQualifierInScope, LookupResult &R,
3537                           const TemplateArgumentListInfo *TemplateArgs,
3538                           bool SuppressQualifierCheck = false,
3539                           ActOnMemberAccessExtraArgs *ExtraArgs = nullptr);
3540
3541  ExprResult PerformMemberExprBaseConversion(Expr *Base, bool IsArrow);
3542
3543  bool CheckQualifiedMemberReference(Expr *BaseExpr, QualType BaseType,
3544                                     const CXXScopeSpec &SS,
3545                                     const LookupResult &R);
3546
3547  ExprResult ActOnDependentMemberExpr(Expr *Base, QualType BaseType,
3548                                      bool IsArrow, SourceLocation OpLoc,
3549                                      const CXXScopeSpec &SS,
3550                                      SourceLocation TemplateKWLoc,
3551                                      NamedDecl *FirstQualifierInScope,
3552                               const DeclarationNameInfo &NameInfo,
3553                               const TemplateArgumentListInfo *TemplateArgs);
3554
3555  ExprResult ActOnMemberAccessExpr(Scope *S, Expr *Base,
3556                                   SourceLocation OpLoc,
3557                                   tok::TokenKind OpKind,
3558                                   CXXScopeSpec &SS,
3559                                   SourceLocation TemplateKWLoc,
3560                                   UnqualifiedId &Member,
3561                                   Decl *ObjCImpDecl,
3562                                   bool HasTrailingLParen);
3563
3564  void ActOnDefaultCtorInitializers(Decl *CDtorDecl);
3565  bool ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
3566                               FunctionDecl *FDecl,
3567                               const FunctionProtoType *Proto,
3568                               ArrayRef<Expr *> Args,
3569                               SourceLocation RParenLoc,
3570                               bool ExecConfig = false);
3571  void CheckStaticArrayArgument(SourceLocation CallLoc,
3572                                ParmVarDecl *Param,
3573                                const Expr *ArgExpr);
3574
3575  /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
3576  /// This provides the location of the left/right parens and a list of comma
3577  /// locations.
3578  ExprResult ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
3579                           MultiExprArg ArgExprs, SourceLocation RParenLoc,
3580                           Expr *ExecConfig = nullptr,
3581                           bool IsExecConfig = false);
3582  ExprResult BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
3583                                   SourceLocation LParenLoc,
3584                                   ArrayRef<Expr *> Arg,
3585                                   SourceLocation RParenLoc,
3586                                   Expr *Config = nullptr,
3587                                   bool IsExecConfig = false);
3588
3589  ExprResult ActOnCUDAExecConfigExpr(Scope *S, SourceLocation LLLLoc,
3590                                     MultiExprArg ExecConfig,
3591                                     SourceLocation GGGLoc);
3592
3593  ExprResult ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
3594                           Declarator &D, ParsedType &Ty,
3595                           SourceLocation RParenLoc, Expr *CastExpr);
3596  ExprResult BuildCStyleCastExpr(SourceLocation LParenLoc,
3597                                 TypeSourceInfo *Ty,
3598                                 SourceLocation RParenLoc,
3599                                 Expr *Op);
3600  CastKind PrepareScalarCast(ExprResult &src, QualType destType);
3601
3602  /// \brief Build an altivec or OpenCL literal.
3603  ExprResult BuildVectorLiteral(SourceLocation LParenLoc,
3604                                SourceLocation RParenLoc, Expr *E,
3605                                TypeSourceInfo *TInfo);
3606
3607  ExprResult MaybeConvertParenListExprToParenExpr(Scope *S, Expr *ME);
3608
3609  ExprResult ActOnCompoundLiteral(SourceLocation LParenLoc,
3610                                  ParsedType Ty,
3611                                  SourceLocation RParenLoc,
3612                                  Expr *InitExpr);
3613
3614  ExprResult BuildCompoundLiteralExpr(SourceLocation LParenLoc,
3615                                      TypeSourceInfo *TInfo,
3616                                      SourceLocation RParenLoc,
3617                                      Expr *LiteralExpr);
3618
3619  ExprResult ActOnInitList(SourceLocation LBraceLoc,
3620                           MultiExprArg InitArgList,
3621                           SourceLocation RBraceLoc);
3622
3623  ExprResult ActOnDesignatedInitializer(Designation &Desig,
3624                                        SourceLocation Loc,
3625                                        bool GNUSyntax,
3626                                        ExprResult Init);
3627
3628  ExprResult ActOnBinOp(Scope *S, SourceLocation TokLoc,
3629                        tok::TokenKind Kind, Expr *LHSExpr, Expr *RHSExpr);
3630  ExprResult BuildBinOp(Scope *S, SourceLocation OpLoc,
3631                        BinaryOperatorKind Opc, Expr *LHSExpr, Expr *RHSExpr);
3632  ExprResult CreateBuiltinBinOp(SourceLocation OpLoc, BinaryOperatorKind Opc,
3633                                Expr *LHSExpr, Expr *RHSExpr);
3634
3635  /// ActOnConditionalOp - Parse a ?: operation.  Note that 'LHS' may be null
3636  /// in the case of a the GNU conditional expr extension.
3637  ExprResult ActOnConditionalOp(SourceLocation QuestionLoc,
3638                                SourceLocation ColonLoc,
3639                                Expr *CondExpr, Expr *LHSExpr, Expr *RHSExpr);
3640
3641  /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
3642  ExprResult ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
3643                            LabelDecl *TheDecl);
3644
3645  void ActOnStartStmtExpr();
3646  ExprResult ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
3647                           SourceLocation RPLoc); // "({..})"
3648  void ActOnStmtExprError();
3649
3650  // __builtin_offsetof(type, identifier(.identifier|[expr])*)
3651  struct OffsetOfComponent {
3652    SourceLocation LocStart, LocEnd;
3653    bool isBrackets;  // true if [expr], false if .ident
3654    union {
3655      IdentifierInfo *IdentInfo;
3656      Expr *E;
3657    } U;
3658  };
3659
3660  /// __builtin_offsetof(type, a.b[123][456].c)
3661  ExprResult BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
3662                                  TypeSourceInfo *TInfo,
3663                                  OffsetOfComponent *CompPtr,
3664                                  unsigned NumComponents,
3665                                  SourceLocation RParenLoc);
3666  ExprResult ActOnBuiltinOffsetOf(Scope *S,
3667                                  SourceLocation BuiltinLoc,
3668                                  SourceLocation TypeLoc,
3669                                  ParsedType ParsedArgTy,
3670                                  OffsetOfComponent *CompPtr,
3671                                  unsigned NumComponents,
3672                                  SourceLocation RParenLoc);
3673
3674  // __builtin_choose_expr(constExpr, expr1, expr2)
3675  ExprResult ActOnChooseExpr(SourceLocation BuiltinLoc,
3676                             Expr *CondExpr, Expr *LHSExpr,
3677                             Expr *RHSExpr, SourceLocation RPLoc);
3678
3679  // __builtin_va_arg(expr, type)
3680  ExprResult ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty,
3681                        SourceLocation RPLoc);
3682  ExprResult BuildVAArgExpr(SourceLocation BuiltinLoc, Expr *E,
3683                            TypeSourceInfo *TInfo, SourceLocation RPLoc);
3684
3685  // __null
3686  ExprResult ActOnGNUNullExpr(SourceLocation TokenLoc);
3687
3688  bool CheckCaseExpression(Expr *E);
3689
3690  /// \brief Describes the result of an "if-exists" condition check.
3691  enum IfExistsResult {
3692    /// \brief The symbol exists.
3693    IER_Exists,
3694
3695    /// \brief The symbol does not exist.
3696    IER_DoesNotExist,
3697
3698    /// \brief The name is a dependent name, so the results will differ
3699    /// from one instantiation to the next.
3700    IER_Dependent,
3701
3702    /// \brief An error occurred.
3703    IER_Error
3704  };
3705
3706  IfExistsResult
3707  CheckMicrosoftIfExistsSymbol(Scope *S, CXXScopeSpec &SS,
3708                               const DeclarationNameInfo &TargetNameInfo);
3709
3710  IfExistsResult
3711  CheckMicrosoftIfExistsSymbol(Scope *S, SourceLocation KeywordLoc,
3712                               bool IsIfExists, CXXScopeSpec &SS,
3713                               UnqualifiedId &Name);
3714
3715  StmtResult BuildMSDependentExistsStmt(SourceLocation KeywordLoc,
3716                                        bool IsIfExists,
3717                                        NestedNameSpecifierLoc QualifierLoc,
3718                                        DeclarationNameInfo NameInfo,
3719                                        Stmt *Nested);
3720  StmtResult ActOnMSDependentExistsStmt(SourceLocation KeywordLoc,
3721                                        bool IsIfExists,
3722                                        CXXScopeSpec &SS, UnqualifiedId &Name,
3723                                        Stmt *Nested);
3724
3725  //===------------------------- "Block" Extension ------------------------===//
3726
3727  /// ActOnBlockStart - This callback is invoked when a block literal is
3728  /// started.
3729  void ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope);
3730
3731  /// ActOnBlockArguments - This callback allows processing of block arguments.
3732  /// If there are no arguments, this is still invoked.
3733  void ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
3734                           Scope *CurScope);
3735
3736  /// ActOnBlockError - If there is an error parsing a block, this callback
3737  /// is invoked to pop the information about the block from the action impl.
3738  void ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope);
3739
3740  /// ActOnBlockStmtExpr - This is called when the body of a block statement
3741  /// literal was successfully completed.  ^(int x){...}
3742  ExprResult ActOnBlockStmtExpr(SourceLocation CaretLoc, Stmt *Body,
3743                                Scope *CurScope);
3744
3745  //===---------------------------- Clang Extensions ----------------------===//
3746
3747  /// __builtin_convertvector(...)
3748  ExprResult ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy,
3749                                    SourceLocation BuiltinLoc,
3750                                    SourceLocation RParenLoc);
3751
3752  //===---------------------------- OpenCL Features -----------------------===//
3753
3754  /// __builtin_astype(...)
3755  ExprResult ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
3756                             SourceLocation BuiltinLoc,
3757                             SourceLocation RParenLoc);
3758
3759  //===---------------------------- C++ Features --------------------------===//
3760
3761  // Act on C++ namespaces
3762  Decl *ActOnStartNamespaceDef(Scope *S, SourceLocation InlineLoc,
3763                               SourceLocation NamespaceLoc,
3764                               SourceLocation IdentLoc,
3765                               IdentifierInfo *Ident,
3766                               SourceLocation LBrace,
3767                               AttributeList *AttrList);
3768  void ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace);
3769
3770  NamespaceDecl *getStdNamespace() const;
3771  NamespaceDecl *getOrCreateStdNamespace();
3772
3773  CXXRecordDecl *getStdBadAlloc() const;
3774
3775  /// \brief Tests whether Ty is an instance of std::initializer_list and, if
3776  /// it is and Element is not NULL, assigns the element type to Element.
3777  bool isStdInitializerList(QualType Ty, QualType *Element);
3778
3779  /// \brief Looks for the std::initializer_list template and instantiates it
3780  /// with Element, or emits an error if it's not found.
3781  ///
3782  /// \returns The instantiated template, or null on error.
3783  QualType BuildStdInitializerList(QualType Element, SourceLocation Loc);
3784
3785  /// \brief Determine whether Ctor is an initializer-list constructor, as
3786  /// defined in [dcl.init.list]p2.
3787  bool isInitListConstructor(const CXXConstructorDecl *Ctor);
3788
3789  Decl *ActOnUsingDirective(Scope *CurScope,
3790                            SourceLocation UsingLoc,
3791                            SourceLocation NamespcLoc,
3792                            CXXScopeSpec &SS,
3793                            SourceLocation IdentLoc,
3794                            IdentifierInfo *NamespcName,
3795                            AttributeList *AttrList);
3796
3797  void PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir);
3798
3799  Decl *ActOnNamespaceAliasDef(Scope *CurScope,
3800                               SourceLocation NamespaceLoc,
3801                               SourceLocation AliasLoc,
3802                               IdentifierInfo *Alias,
3803                               CXXScopeSpec &SS,
3804                               SourceLocation IdentLoc,
3805                               IdentifierInfo *Ident);
3806
3807  void HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow);
3808  bool CheckUsingShadowDecl(UsingDecl *UD, NamedDecl *Target,
3809                            const LookupResult &PreviousDecls,
3810                            UsingShadowDecl *&PrevShadow);
3811  UsingShadowDecl *BuildUsingShadowDecl(Scope *S, UsingDecl *UD,
3812                                        NamedDecl *Target,
3813                                        UsingShadowDecl *PrevDecl);
3814
3815  bool CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
3816                                   bool HasTypenameKeyword,
3817                                   const CXXScopeSpec &SS,
3818                                   SourceLocation NameLoc,
3819                                   const LookupResult &Previous);
3820  bool CheckUsingDeclQualifier(SourceLocation UsingLoc,
3821                               const CXXScopeSpec &SS,
3822                               const DeclarationNameInfo &NameInfo,
3823                               SourceLocation NameLoc);
3824
3825  NamedDecl *BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
3826                                   SourceLocation UsingLoc,
3827                                   CXXScopeSpec &SS,
3828                                   DeclarationNameInfo NameInfo,
3829                                   AttributeList *AttrList,
3830                                   bool IsInstantiation,
3831                                   bool HasTypenameKeyword,
3832                                   SourceLocation TypenameLoc);
3833
3834  bool CheckInheritingConstructorUsingDecl(UsingDecl *UD);
3835
3836  Decl *ActOnUsingDeclaration(Scope *CurScope,
3837                              AccessSpecifier AS,
3838                              bool HasUsingKeyword,
3839                              SourceLocation UsingLoc,
3840                              CXXScopeSpec &SS,
3841                              UnqualifiedId &Name,
3842                              AttributeList *AttrList,
3843                              bool HasTypenameKeyword,
3844                              SourceLocation TypenameLoc);
3845  Decl *ActOnAliasDeclaration(Scope *CurScope,
3846                              AccessSpecifier AS,
3847                              MultiTemplateParamsArg TemplateParams,
3848                              SourceLocation UsingLoc,
3849                              UnqualifiedId &Name,
3850                              AttributeList *AttrList,
3851                              TypeResult Type);
3852
3853  /// BuildCXXConstructExpr - Creates a complete call to a constructor,
3854  /// including handling of its default argument expressions.
3855  ///
3856  /// \param ConstructKind - a CXXConstructExpr::ConstructionKind
3857  ExprResult
3858  BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
3859                        CXXConstructorDecl *Constructor, MultiExprArg Exprs,
3860                        bool HadMultipleCandidates, bool IsListInitialization,
3861                        bool RequiresZeroInit, unsigned ConstructKind,
3862                        SourceRange ParenRange);
3863
3864  // FIXME: Can re remove this and have the above BuildCXXConstructExpr check if
3865  // the constructor can be elidable?
3866  ExprResult
3867  BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
3868                        CXXConstructorDecl *Constructor, bool Elidable,
3869                        MultiExprArg Exprs, bool HadMultipleCandidates,
3870                        bool IsListInitialization, bool RequiresZeroInit,
3871                        unsigned ConstructKind, SourceRange ParenRange);
3872
3873  /// BuildCXXDefaultArgExpr - Creates a CXXDefaultArgExpr, instantiating
3874  /// the default expr if needed.
3875  ExprResult BuildCXXDefaultArgExpr(SourceLocation CallLoc,
3876                                    FunctionDecl *FD,
3877                                    ParmVarDecl *Param);
3878
3879  /// FinalizeVarWithDestructor - Prepare for calling destructor on the
3880  /// constructed variable.
3881  void FinalizeVarWithDestructor(VarDecl *VD, const RecordType *DeclInitType);
3882
3883  /// \brief Helper class that collects exception specifications for
3884  /// implicitly-declared special member functions.
3885  class ImplicitExceptionSpecification {
3886    // Pointer to allow copying
3887    Sema *Self;
3888    // We order exception specifications thus:
3889    // noexcept is the most restrictive, but is only used in C++11.
3890    // throw() comes next.
3891    // Then a throw(collected exceptions)
3892    // Finally no specification, which is expressed as noexcept(false).
3893    // throw(...) is used instead if any called function uses it.
3894    ExceptionSpecificationType ComputedEST;
3895    llvm::SmallPtrSet<CanQualType, 4> ExceptionsSeen;
3896    SmallVector<QualType, 4> Exceptions;
3897
3898    void ClearExceptions() {
3899      ExceptionsSeen.clear();
3900      Exceptions.clear();
3901    }
3902
3903  public:
3904    explicit ImplicitExceptionSpecification(Sema &Self)
3905      : Self(&Self), ComputedEST(EST_BasicNoexcept) {
3906      if (!Self.getLangOpts().CPlusPlus11)
3907        ComputedEST = EST_DynamicNone;
3908    }
3909
3910    /// \brief Get the computed exception specification type.
3911    ExceptionSpecificationType getExceptionSpecType() const {
3912      assert(ComputedEST != EST_ComputedNoexcept &&
3913             "noexcept(expr) should not be a possible result");
3914      return ComputedEST;
3915    }
3916
3917    /// \brief The number of exceptions in the exception specification.
3918    unsigned size() const { return Exceptions.size(); }
3919
3920    /// \brief The set of exceptions in the exception specification.
3921    const QualType *data() const { return Exceptions.data(); }
3922
3923    /// \brief Integrate another called method into the collected data.
3924    void CalledDecl(SourceLocation CallLoc, const CXXMethodDecl *Method);
3925
3926    /// \brief Integrate an invoked expression into the collected data.
3927    void CalledExpr(Expr *E);
3928
3929    /// \brief Overwrite an EPI's exception specification with this
3930    /// computed exception specification.
3931    void getEPI(FunctionProtoType::ExtProtoInfo &EPI) const {
3932      EPI.ExceptionSpecType = getExceptionSpecType();
3933      if (EPI.ExceptionSpecType == EST_Dynamic) {
3934        EPI.NumExceptions = size();
3935        EPI.Exceptions = data();
3936      } else if (EPI.ExceptionSpecType == EST_None) {
3937        /// C++11 [except.spec]p14:
3938        ///   The exception-specification is noexcept(false) if the set of
3939        ///   potential exceptions of the special member function contains "any"
3940        EPI.ExceptionSpecType = EST_ComputedNoexcept;
3941        EPI.NoexceptExpr = Self->ActOnCXXBoolLiteral(SourceLocation(),
3942                                                     tok::kw_false).get();
3943      }
3944    }
3945    FunctionProtoType::ExtProtoInfo getEPI() const {
3946      FunctionProtoType::ExtProtoInfo EPI;
3947      getEPI(EPI);
3948      return EPI;
3949    }
3950  };
3951
3952  /// \brief Determine what sort of exception specification a defaulted
3953  /// copy constructor of a class will have.
3954  ImplicitExceptionSpecification
3955  ComputeDefaultedDefaultCtorExceptionSpec(SourceLocation Loc,
3956                                           CXXMethodDecl *MD);
3957
3958  /// \brief Determine what sort of exception specification a defaulted
3959  /// default constructor of a class will have, and whether the parameter
3960  /// will be const.
3961  ImplicitExceptionSpecification
3962  ComputeDefaultedCopyCtorExceptionSpec(CXXMethodDecl *MD);
3963
3964  /// \brief Determine what sort of exception specification a defautled
3965  /// copy assignment operator of a class will have, and whether the
3966  /// parameter will be const.
3967  ImplicitExceptionSpecification
3968  ComputeDefaultedCopyAssignmentExceptionSpec(CXXMethodDecl *MD);
3969
3970  /// \brief Determine what sort of exception specification a defaulted move
3971  /// constructor of a class will have.
3972  ImplicitExceptionSpecification
3973  ComputeDefaultedMoveCtorExceptionSpec(CXXMethodDecl *MD);
3974
3975  /// \brief Determine what sort of exception specification a defaulted move
3976  /// assignment operator of a class will have.
3977  ImplicitExceptionSpecification
3978  ComputeDefaultedMoveAssignmentExceptionSpec(CXXMethodDecl *MD);
3979
3980  /// \brief Determine what sort of exception specification a defaulted
3981  /// destructor of a class will have.
3982  ImplicitExceptionSpecification
3983  ComputeDefaultedDtorExceptionSpec(CXXMethodDecl *MD);
3984
3985  /// \brief Determine what sort of exception specification an inheriting
3986  /// constructor of a class will have.
3987  ImplicitExceptionSpecification
3988  ComputeInheritingCtorExceptionSpec(CXXConstructorDecl *CD);
3989
3990  /// \brief Evaluate the implicit exception specification for a defaulted
3991  /// special member function.
3992  void EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD);
3993
3994  /// \brief Check the given exception-specification and update the
3995  /// extended prototype information with the results.
3996  void checkExceptionSpecification(ExceptionSpecificationType EST,
3997                                   ArrayRef<ParsedType> DynamicExceptions,
3998                                   ArrayRef<SourceRange> DynamicExceptionRanges,
3999                                   Expr *NoexceptExpr,
4000                                   SmallVectorImpl<QualType> &Exceptions,
4001                                   FunctionProtoType::ExtProtoInfo &EPI);
4002
4003  /// \brief Determine if a special member function should have a deleted
4004  /// definition when it is defaulted.
4005  bool ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
4006                                 bool Diagnose = false);
4007
4008  /// \brief Declare the implicit default constructor for the given class.
4009  ///
4010  /// \param ClassDecl The class declaration into which the implicit
4011  /// default constructor will be added.
4012  ///
4013  /// \returns The implicitly-declared default constructor.
4014  CXXConstructorDecl *DeclareImplicitDefaultConstructor(
4015                                                     CXXRecordDecl *ClassDecl);
4016
4017  /// DefineImplicitDefaultConstructor - Checks for feasibility of
4018  /// defining this constructor as the default constructor.
4019  void DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
4020                                        CXXConstructorDecl *Constructor);
4021
4022  /// \brief Declare the implicit destructor for the given class.
4023  ///
4024  /// \param ClassDecl The class declaration into which the implicit
4025  /// destructor will be added.
4026  ///
4027  /// \returns The implicitly-declared destructor.
4028  CXXDestructorDecl *DeclareImplicitDestructor(CXXRecordDecl *ClassDecl);
4029
4030  /// DefineImplicitDestructor - Checks for feasibility of
4031  /// defining this destructor as the default destructor.
4032  void DefineImplicitDestructor(SourceLocation CurrentLocation,
4033                                CXXDestructorDecl *Destructor);
4034
4035  /// \brief Build an exception spec for destructors that don't have one.
4036  ///
4037  /// C++11 says that user-defined destructors with no exception spec get one
4038  /// that looks as if the destructor was implicitly declared.
4039  void AdjustDestructorExceptionSpec(CXXRecordDecl *ClassDecl,
4040                                     CXXDestructorDecl *Destructor);
4041
4042  /// \brief Declare all inheriting constructors for the given class.
4043  ///
4044  /// \param ClassDecl The class declaration into which the inheriting
4045  /// constructors will be added.
4046  void DeclareInheritingConstructors(CXXRecordDecl *ClassDecl);
4047
4048  /// \brief Define the specified inheriting constructor.
4049  void DefineInheritingConstructor(SourceLocation UseLoc,
4050                                   CXXConstructorDecl *Constructor);
4051
4052  /// \brief Declare the implicit copy constructor for the given class.
4053  ///
4054  /// \param ClassDecl The class declaration into which the implicit
4055  /// copy constructor will be added.
4056  ///
4057  /// \returns The implicitly-declared copy constructor.
4058  CXXConstructorDecl *DeclareImplicitCopyConstructor(CXXRecordDecl *ClassDecl);
4059
4060  /// DefineImplicitCopyConstructor - Checks for feasibility of
4061  /// defining this constructor as the copy constructor.
4062  void DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
4063                                     CXXConstructorDecl *Constructor);
4064
4065  /// \brief Declare the implicit move constructor for the given class.
4066  ///
4067  /// \param ClassDecl The Class declaration into which the implicit
4068  /// move constructor will be added.
4069  ///
4070  /// \returns The implicitly-declared move constructor, or NULL if it wasn't
4071  /// declared.
4072  CXXConstructorDecl *DeclareImplicitMoveConstructor(CXXRecordDecl *ClassDecl);
4073
4074  /// DefineImplicitMoveConstructor - Checks for feasibility of
4075  /// defining this constructor as the move constructor.
4076  void DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
4077                                     CXXConstructorDecl *Constructor);
4078
4079  /// \brief Declare the implicit copy assignment operator for the given class.
4080  ///
4081  /// \param ClassDecl The class declaration into which the implicit
4082  /// copy assignment operator will be added.
4083  ///
4084  /// \returns The implicitly-declared copy assignment operator.
4085  CXXMethodDecl *DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl);
4086
4087  /// \brief Defines an implicitly-declared copy assignment operator.
4088  void DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
4089                                    CXXMethodDecl *MethodDecl);
4090
4091  /// \brief Declare the implicit move assignment operator for the given class.
4092  ///
4093  /// \param ClassDecl The Class declaration into which the implicit
4094  /// move assignment operator will be added.
4095  ///
4096  /// \returns The implicitly-declared move assignment operator, or NULL if it
4097  /// wasn't declared.
4098  CXXMethodDecl *DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl);
4099
4100  /// \brief Defines an implicitly-declared move assignment operator.
4101  void DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
4102                                    CXXMethodDecl *MethodDecl);
4103
4104  /// \brief Force the declaration of any implicitly-declared members of this
4105  /// class.
4106  void ForceDeclarationOfImplicitMembers(CXXRecordDecl *Class);
4107
4108  /// \brief Determine whether the given function is an implicitly-deleted
4109  /// special member function.
4110  bool isImplicitlyDeleted(FunctionDecl *FD);
4111
4112  /// \brief Check whether 'this' shows up in the type of a static member
4113  /// function after the (naturally empty) cv-qualifier-seq would be.
4114  ///
4115  /// \returns true if an error occurred.
4116  bool checkThisInStaticMemberFunctionType(CXXMethodDecl *Method);
4117
4118  /// \brief Whether this' shows up in the exception specification of a static
4119  /// member function.
4120  bool checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method);
4121
4122  /// \brief Check whether 'this' shows up in the attributes of the given
4123  /// static member function.
4124  ///
4125  /// \returns true if an error occurred.
4126  bool checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method);
4127
4128  /// MaybeBindToTemporary - If the passed in expression has a record type with
4129  /// a non-trivial destructor, this will return CXXBindTemporaryExpr. Otherwise
4130  /// it simply returns the passed in expression.
4131  ExprResult MaybeBindToTemporary(Expr *E);
4132
4133  bool CompleteConstructorCall(CXXConstructorDecl *Constructor,
4134                               MultiExprArg ArgsPtr,
4135                               SourceLocation Loc,
4136                               SmallVectorImpl<Expr*> &ConvertedArgs,
4137                               bool AllowExplicit = false,
4138                               bool IsListInitialization = false);
4139
4140  ParsedType getInheritingConstructorName(CXXScopeSpec &SS,
4141                                          SourceLocation NameLoc,
4142                                          IdentifierInfo &Name);
4143
4144  ParsedType getDestructorName(SourceLocation TildeLoc,
4145                               IdentifierInfo &II, SourceLocation NameLoc,
4146                               Scope *S, CXXScopeSpec &SS,
4147                               ParsedType ObjectType,
4148                               bool EnteringContext);
4149
4150  ParsedType getDestructorType(const DeclSpec& DS, ParsedType ObjectType);
4151
4152  // Checks that reinterpret casts don't have undefined behavior.
4153  void CheckCompatibleReinterpretCast(QualType SrcType, QualType DestType,
4154                                      bool IsDereference, SourceRange Range);
4155
4156  /// ActOnCXXNamedCast - Parse {dynamic,static,reinterpret,const}_cast's.
4157  ExprResult ActOnCXXNamedCast(SourceLocation OpLoc,
4158                               tok::TokenKind Kind,
4159                               SourceLocation LAngleBracketLoc,
4160                               Declarator &D,
4161                               SourceLocation RAngleBracketLoc,
4162                               SourceLocation LParenLoc,
4163                               Expr *E,
4164                               SourceLocation RParenLoc);
4165
4166  ExprResult BuildCXXNamedCast(SourceLocation OpLoc,
4167                               tok::TokenKind Kind,
4168                               TypeSourceInfo *Ty,
4169                               Expr *E,
4170                               SourceRange AngleBrackets,
4171                               SourceRange Parens);
4172
4173  ExprResult BuildCXXTypeId(QualType TypeInfoType,
4174                            SourceLocation TypeidLoc,
4175                            TypeSourceInfo *Operand,
4176                            SourceLocation RParenLoc);
4177  ExprResult BuildCXXTypeId(QualType TypeInfoType,
4178                            SourceLocation TypeidLoc,
4179                            Expr *Operand,
4180                            SourceLocation RParenLoc);
4181
4182  /// ActOnCXXTypeid - Parse typeid( something ).
4183  ExprResult ActOnCXXTypeid(SourceLocation OpLoc,
4184                            SourceLocation LParenLoc, bool isType,
4185                            void *TyOrExpr,
4186                            SourceLocation RParenLoc);
4187
4188  ExprResult BuildCXXUuidof(QualType TypeInfoType,
4189                            SourceLocation TypeidLoc,
4190                            TypeSourceInfo *Operand,
4191                            SourceLocation RParenLoc);
4192  ExprResult BuildCXXUuidof(QualType TypeInfoType,
4193                            SourceLocation TypeidLoc,
4194                            Expr *Operand,
4195                            SourceLocation RParenLoc);
4196
4197  /// ActOnCXXUuidof - Parse __uuidof( something ).
4198  ExprResult ActOnCXXUuidof(SourceLocation OpLoc,
4199                            SourceLocation LParenLoc, bool isType,
4200                            void *TyOrExpr,
4201                            SourceLocation RParenLoc);
4202
4203
4204  //// ActOnCXXThis -  Parse 'this' pointer.
4205  ExprResult ActOnCXXThis(SourceLocation loc);
4206
4207  /// \brief Try to retrieve the type of the 'this' pointer.
4208  ///
4209  /// \returns The type of 'this', if possible. Otherwise, returns a NULL type.
4210  QualType getCurrentThisType();
4211
4212  /// \brief When non-NULL, the C++ 'this' expression is allowed despite the
4213  /// current context not being a non-static member function. In such cases,
4214  /// this provides the type used for 'this'.
4215  QualType CXXThisTypeOverride;
4216
4217  /// \brief RAII object used to temporarily allow the C++ 'this' expression
4218  /// to be used, with the given qualifiers on the current class type.
4219  class CXXThisScopeRAII {
4220    Sema &S;
4221    QualType OldCXXThisTypeOverride;
4222    bool Enabled;
4223
4224  public:
4225    /// \brief Introduce a new scope where 'this' may be allowed (when enabled),
4226    /// using the given declaration (which is either a class template or a
4227    /// class) along with the given qualifiers.
4228    /// along with the qualifiers placed on '*this'.
4229    CXXThisScopeRAII(Sema &S, Decl *ContextDecl, unsigned CXXThisTypeQuals,
4230                     bool Enabled = true);
4231
4232    ~CXXThisScopeRAII();
4233  };
4234
4235  /// \brief Make sure the value of 'this' is actually available in the current
4236  /// context, if it is a potentially evaluated context.
4237  ///
4238  /// \param Loc The location at which the capture of 'this' occurs.
4239  ///
4240  /// \param Explicit Whether 'this' is explicitly captured in a lambda
4241  /// capture list.
4242  ///
4243  /// \param FunctionScopeIndexToStopAt If non-null, it points to the index
4244  /// of the FunctionScopeInfo stack beyond which we do not attempt to capture.
4245  /// This is useful when enclosing lambdas must speculatively capture
4246  /// 'this' that may or may not be used in certain specializations of
4247  /// a nested generic lambda (depending on whether the name resolves to
4248  /// a non-static member function or a static function).
4249  /// \return returns 'true' if failed, 'false' if success.
4250  bool CheckCXXThisCapture(SourceLocation Loc, bool Explicit = false,
4251      bool BuildAndDiagnose = true,
4252      const unsigned *const FunctionScopeIndexToStopAt = nullptr);
4253
4254  /// \brief Determine whether the given type is the type of *this that is used
4255  /// outside of the body of a member function for a type that is currently
4256  /// being defined.
4257  bool isThisOutsideMemberFunctionBody(QualType BaseType);
4258
4259  /// ActOnCXXBoolLiteral - Parse {true,false} literals.
4260  ExprResult ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind);
4261
4262
4263  /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
4264  ExprResult ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind);
4265
4266  /// ActOnCXXNullPtrLiteral - Parse 'nullptr'.
4267  ExprResult ActOnCXXNullPtrLiteral(SourceLocation Loc);
4268
4269  //// ActOnCXXThrow -  Parse throw expressions.
4270  ExprResult ActOnCXXThrow(Scope *S, SourceLocation OpLoc, Expr *expr);
4271  ExprResult BuildCXXThrow(SourceLocation OpLoc, Expr *Ex,
4272                           bool IsThrownVarInScope);
4273  ExprResult CheckCXXThrowOperand(SourceLocation ThrowLoc, Expr *E,
4274                                  bool IsThrownVarInScope);
4275
4276  /// ActOnCXXTypeConstructExpr - Parse construction of a specified type.
4277  /// Can be interpreted either as function-style casting ("int(x)")
4278  /// or class type construction ("ClassType(x,y,z)")
4279  /// or creation of a value-initialized type ("int()").
4280  ExprResult ActOnCXXTypeConstructExpr(ParsedType TypeRep,
4281                                       SourceLocation LParenLoc,
4282                                       MultiExprArg Exprs,
4283                                       SourceLocation RParenLoc);
4284
4285  ExprResult BuildCXXTypeConstructExpr(TypeSourceInfo *Type,
4286                                       SourceLocation LParenLoc,
4287                                       MultiExprArg Exprs,
4288                                       SourceLocation RParenLoc);
4289
4290  /// ActOnCXXNew - Parsed a C++ 'new' expression.
4291  ExprResult ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
4292                         SourceLocation PlacementLParen,
4293                         MultiExprArg PlacementArgs,
4294                         SourceLocation PlacementRParen,
4295                         SourceRange TypeIdParens, Declarator &D,
4296                         Expr *Initializer);
4297  ExprResult BuildCXXNew(SourceRange Range, bool UseGlobal,
4298                         SourceLocation PlacementLParen,
4299                         MultiExprArg PlacementArgs,
4300                         SourceLocation PlacementRParen,
4301                         SourceRange TypeIdParens,
4302                         QualType AllocType,
4303                         TypeSourceInfo *AllocTypeInfo,
4304                         Expr *ArraySize,
4305                         SourceRange DirectInitRange,
4306                         Expr *Initializer,
4307                         bool TypeMayContainAuto = true);
4308
4309  bool CheckAllocatedType(QualType AllocType, SourceLocation Loc,
4310                          SourceRange R);
4311  bool FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,
4312                               bool UseGlobal, QualType AllocType, bool IsArray,
4313                               MultiExprArg PlaceArgs,
4314                               FunctionDecl *&OperatorNew,
4315                               FunctionDecl *&OperatorDelete);
4316  bool FindAllocationOverload(SourceLocation StartLoc, SourceRange Range,
4317                              DeclarationName Name, MultiExprArg Args,
4318                              DeclContext *Ctx,
4319                              bool AllowMissing, FunctionDecl *&Operator,
4320                              bool Diagnose = true);
4321  void DeclareGlobalNewDelete();
4322  void DeclareGlobalAllocationFunction(DeclarationName Name, QualType Return,
4323                                       QualType Param1,
4324                                       QualType Param2 = QualType(),
4325                                       bool addMallocAttr = false);
4326
4327  bool FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD,
4328                                DeclarationName Name, FunctionDecl* &Operator,
4329                                bool Diagnose = true);
4330  FunctionDecl *FindUsualDeallocationFunction(SourceLocation StartLoc,
4331                                              bool CanProvideSize,
4332                                              DeclarationName Name);
4333
4334  /// ActOnCXXDelete - Parsed a C++ 'delete' expression
4335  ExprResult ActOnCXXDelete(SourceLocation StartLoc,
4336                            bool UseGlobal, bool ArrayForm,
4337                            Expr *Operand);
4338
4339  DeclResult ActOnCXXConditionDeclaration(Scope *S, Declarator &D);
4340  ExprResult CheckConditionVariable(VarDecl *ConditionVar,
4341                                    SourceLocation StmtLoc,
4342                                    bool ConvertToBoolean);
4343
4344  ExprResult ActOnNoexceptExpr(SourceLocation KeyLoc, SourceLocation LParen,
4345                               Expr *Operand, SourceLocation RParen);
4346  ExprResult BuildCXXNoexceptExpr(SourceLocation KeyLoc, Expr *Operand,
4347                                  SourceLocation RParen);
4348
4349  /// \brief Parsed one of the type trait support pseudo-functions.
4350  ExprResult ActOnTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
4351                            ArrayRef<ParsedType> Args,
4352                            SourceLocation RParenLoc);
4353  ExprResult BuildTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
4354                            ArrayRef<TypeSourceInfo *> Args,
4355                            SourceLocation RParenLoc);
4356
4357  /// ActOnArrayTypeTrait - Parsed one of the bianry type trait support
4358  /// pseudo-functions.
4359  ExprResult ActOnArrayTypeTrait(ArrayTypeTrait ATT,
4360                                 SourceLocation KWLoc,
4361                                 ParsedType LhsTy,
4362                                 Expr *DimExpr,
4363                                 SourceLocation RParen);
4364
4365  ExprResult BuildArrayTypeTrait(ArrayTypeTrait ATT,
4366                                 SourceLocation KWLoc,
4367                                 TypeSourceInfo *TSInfo,
4368                                 Expr *DimExpr,
4369                                 SourceLocation RParen);
4370
4371  /// ActOnExpressionTrait - Parsed one of the unary type trait support
4372  /// pseudo-functions.
4373  ExprResult ActOnExpressionTrait(ExpressionTrait OET,
4374                                  SourceLocation KWLoc,
4375                                  Expr *Queried,
4376                                  SourceLocation RParen);
4377
4378  ExprResult BuildExpressionTrait(ExpressionTrait OET,
4379                                  SourceLocation KWLoc,
4380                                  Expr *Queried,
4381                                  SourceLocation RParen);
4382
4383  ExprResult ActOnStartCXXMemberReference(Scope *S,
4384                                          Expr *Base,
4385                                          SourceLocation OpLoc,
4386                                          tok::TokenKind OpKind,
4387                                          ParsedType &ObjectType,
4388                                          bool &MayBePseudoDestructor);
4389
4390  ExprResult DiagnoseDtorReference(SourceLocation NameLoc, Expr *MemExpr);
4391
4392  ExprResult BuildPseudoDestructorExpr(Expr *Base,
4393                                       SourceLocation OpLoc,
4394                                       tok::TokenKind OpKind,
4395                                       const CXXScopeSpec &SS,
4396                                       TypeSourceInfo *ScopeType,
4397                                       SourceLocation CCLoc,
4398                                       SourceLocation TildeLoc,
4399                                     PseudoDestructorTypeStorage DestroyedType,
4400                                       bool HasTrailingLParen);
4401
4402  ExprResult ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
4403                                       SourceLocation OpLoc,
4404                                       tok::TokenKind OpKind,
4405                                       CXXScopeSpec &SS,
4406                                       UnqualifiedId &FirstTypeName,
4407                                       SourceLocation CCLoc,
4408                                       SourceLocation TildeLoc,
4409                                       UnqualifiedId &SecondTypeName,
4410                                       bool HasTrailingLParen);
4411
4412  ExprResult ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
4413                                       SourceLocation OpLoc,
4414                                       tok::TokenKind OpKind,
4415                                       SourceLocation TildeLoc,
4416                                       const DeclSpec& DS,
4417                                       bool HasTrailingLParen);
4418
4419  /// MaybeCreateExprWithCleanups - If the current full-expression
4420  /// requires any cleanups, surround it with a ExprWithCleanups node.
4421  /// Otherwise, just returns the passed-in expression.
4422  Expr *MaybeCreateExprWithCleanups(Expr *SubExpr);
4423  Stmt *MaybeCreateStmtWithCleanups(Stmt *SubStmt);
4424  ExprResult MaybeCreateExprWithCleanups(ExprResult SubExpr);
4425
4426  ExprResult ActOnFinishFullExpr(Expr *Expr) {
4427    return ActOnFinishFullExpr(Expr, Expr ? Expr->getExprLoc()
4428                                          : SourceLocation());
4429  }
4430  ExprResult ActOnFinishFullExpr(Expr *Expr, SourceLocation CC,
4431                                 bool DiscardedValue = false,
4432                                 bool IsConstexpr = false,
4433                                 bool IsLambdaInitCaptureInitializer = false);
4434  StmtResult ActOnFinishFullStmt(Stmt *Stmt);
4435
4436  // Marks SS invalid if it represents an incomplete type.
4437  bool RequireCompleteDeclContext(CXXScopeSpec &SS, DeclContext *DC);
4438
4439  DeclContext *computeDeclContext(QualType T);
4440  DeclContext *computeDeclContext(const CXXScopeSpec &SS,
4441                                  bool EnteringContext = false);
4442  bool isDependentScopeSpecifier(const CXXScopeSpec &SS);
4443  CXXRecordDecl *getCurrentInstantiationOf(NestedNameSpecifier *NNS);
4444
4445  /// \brief The parser has parsed a global nested-name-specifier '::'.
4446  ///
4447  /// \param S The scope in which this nested-name-specifier occurs.
4448  ///
4449  /// \param CCLoc The location of the '::'.
4450  ///
4451  /// \param SS The nested-name-specifier, which will be updated in-place
4452  /// to reflect the parsed nested-name-specifier.
4453  ///
4454  /// \returns true if an error occurred, false otherwise.
4455  bool ActOnCXXGlobalScopeSpecifier(Scope *S, SourceLocation CCLoc,
4456                                    CXXScopeSpec &SS);
4457
4458  bool isAcceptableNestedNameSpecifier(const NamedDecl *SD);
4459  NamedDecl *FindFirstQualifierInScope(Scope *S, NestedNameSpecifier *NNS);
4460
4461  bool isNonTypeNestedNameSpecifier(Scope *S, CXXScopeSpec &SS,
4462                                    SourceLocation IdLoc,
4463                                    IdentifierInfo &II,
4464                                    ParsedType ObjectType);
4465
4466  bool BuildCXXNestedNameSpecifier(Scope *S,
4467                                   IdentifierInfo &Identifier,
4468                                   SourceLocation IdentifierLoc,
4469                                   SourceLocation CCLoc,
4470                                   QualType ObjectType,
4471                                   bool EnteringContext,
4472                                   CXXScopeSpec &SS,
4473                                   NamedDecl *ScopeLookupResult,
4474                                   bool ErrorRecoveryLookup,
4475                                   bool *IsCorrectedToColon = nullptr);
4476
4477  /// \brief The parser has parsed a nested-name-specifier 'identifier::'.
4478  ///
4479  /// \param S The scope in which this nested-name-specifier occurs.
4480  ///
4481  /// \param Identifier The identifier preceding the '::'.
4482  ///
4483  /// \param IdentifierLoc The location of the identifier.
4484  ///
4485  /// \param CCLoc The location of the '::'.
4486  ///
4487  /// \param ObjectType The type of the object, if we're parsing
4488  /// nested-name-specifier in a member access expression.
4489  ///
4490  /// \param EnteringContext Whether we're entering the context nominated by
4491  /// this nested-name-specifier.
4492  ///
4493  /// \param SS The nested-name-specifier, which is both an input
4494  /// parameter (the nested-name-specifier before this type) and an
4495  /// output parameter (containing the full nested-name-specifier,
4496  /// including this new type).
4497  ///
4498  /// \param ErrorRecoveryLookup If true, then this method is called to improve
4499  /// error recovery. In this case do not emit error message.
4500  ///
4501  /// \param IsCorrectedToColon If not null, suggestions to replace '::' -> ':'
4502  /// are allowed.  The bool value pointed by this parameter is set to 'true'
4503  /// if the identifier is treated as if it was followed by ':', not '::'.
4504  ///
4505  /// \returns true if an error occurred, false otherwise.
4506  bool ActOnCXXNestedNameSpecifier(Scope *S,
4507                                   IdentifierInfo &Identifier,
4508                                   SourceLocation IdentifierLoc,
4509                                   SourceLocation CCLoc,
4510                                   ParsedType ObjectType,
4511                                   bool EnteringContext,
4512                                   CXXScopeSpec &SS,
4513                                   bool ErrorRecoveryLookup = false,
4514                                   bool *IsCorrectedToColon = nullptr);
4515
4516  ExprResult ActOnDecltypeExpression(Expr *E);
4517
4518  bool ActOnCXXNestedNameSpecifierDecltype(CXXScopeSpec &SS,
4519                                           const DeclSpec &DS,
4520                                           SourceLocation ColonColonLoc);
4521
4522  bool IsInvalidUnlessNestedName(Scope *S, CXXScopeSpec &SS,
4523                                 IdentifierInfo &Identifier,
4524                                 SourceLocation IdentifierLoc,
4525                                 SourceLocation ColonLoc,
4526                                 ParsedType ObjectType,
4527                                 bool EnteringContext);
4528
4529  /// \brief The parser has parsed a nested-name-specifier
4530  /// 'template[opt] template-name < template-args >::'.
4531  ///
4532  /// \param S The scope in which this nested-name-specifier occurs.
4533  ///
4534  /// \param SS The nested-name-specifier, which is both an input
4535  /// parameter (the nested-name-specifier before this type) and an
4536  /// output parameter (containing the full nested-name-specifier,
4537  /// including this new type).
4538  ///
4539  /// \param TemplateKWLoc the location of the 'template' keyword, if any.
4540  /// \param TemplateName the template name.
4541  /// \param TemplateNameLoc The location of the template name.
4542  /// \param LAngleLoc The location of the opening angle bracket  ('<').
4543  /// \param TemplateArgs The template arguments.
4544  /// \param RAngleLoc The location of the closing angle bracket  ('>').
4545  /// \param CCLoc The location of the '::'.
4546  ///
4547  /// \param EnteringContext Whether we're entering the context of the
4548  /// nested-name-specifier.
4549  ///
4550  ///
4551  /// \returns true if an error occurred, false otherwise.
4552  bool ActOnCXXNestedNameSpecifier(Scope *S,
4553                                   CXXScopeSpec &SS,
4554                                   SourceLocation TemplateKWLoc,
4555                                   TemplateTy TemplateName,
4556                                   SourceLocation TemplateNameLoc,
4557                                   SourceLocation LAngleLoc,
4558                                   ASTTemplateArgsPtr TemplateArgs,
4559                                   SourceLocation RAngleLoc,
4560                                   SourceLocation CCLoc,
4561                                   bool EnteringContext);
4562
4563  /// \brief Given a C++ nested-name-specifier, produce an annotation value
4564  /// that the parser can use later to reconstruct the given
4565  /// nested-name-specifier.
4566  ///
4567  /// \param SS A nested-name-specifier.
4568  ///
4569  /// \returns A pointer containing all of the information in the
4570  /// nested-name-specifier \p SS.
4571  void *SaveNestedNameSpecifierAnnotation(CXXScopeSpec &SS);
4572
4573  /// \brief Given an annotation pointer for a nested-name-specifier, restore
4574  /// the nested-name-specifier structure.
4575  ///
4576  /// \param Annotation The annotation pointer, produced by
4577  /// \c SaveNestedNameSpecifierAnnotation().
4578  ///
4579  /// \param AnnotationRange The source range corresponding to the annotation.
4580  ///
4581  /// \param SS The nested-name-specifier that will be updated with the contents
4582  /// of the annotation pointer.
4583  void RestoreNestedNameSpecifierAnnotation(void *Annotation,
4584                                            SourceRange AnnotationRange,
4585                                            CXXScopeSpec &SS);
4586
4587  bool ShouldEnterDeclaratorScope(Scope *S, const CXXScopeSpec &SS);
4588
4589  /// ActOnCXXEnterDeclaratorScope - Called when a C++ scope specifier (global
4590  /// scope or nested-name-specifier) is parsed, part of a declarator-id.
4591  /// After this method is called, according to [C++ 3.4.3p3], names should be
4592  /// looked up in the declarator-id's scope, until the declarator is parsed and
4593  /// ActOnCXXExitDeclaratorScope is called.
4594  /// The 'SS' should be a non-empty valid CXXScopeSpec.
4595  bool ActOnCXXEnterDeclaratorScope(Scope *S, CXXScopeSpec &SS);
4596
4597  /// ActOnCXXExitDeclaratorScope - Called when a declarator that previously
4598  /// invoked ActOnCXXEnterDeclaratorScope(), is finished. 'SS' is the same
4599  /// CXXScopeSpec that was passed to ActOnCXXEnterDeclaratorScope as well.
4600  /// Used to indicate that names should revert to being looked up in the
4601  /// defining scope.
4602  void ActOnCXXExitDeclaratorScope(Scope *S, const CXXScopeSpec &SS);
4603
4604  /// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse an
4605  /// initializer for the declaration 'Dcl'.
4606  /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
4607  /// static data member of class X, names should be looked up in the scope of
4608  /// class X.
4609  void ActOnCXXEnterDeclInitializer(Scope *S, Decl *Dcl);
4610
4611  /// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
4612  /// initializer for the declaration 'Dcl'.
4613  void ActOnCXXExitDeclInitializer(Scope *S, Decl *Dcl);
4614
4615  /// \brief Create a new lambda closure type.
4616  CXXRecordDecl *createLambdaClosureType(SourceRange IntroducerRange,
4617                                         TypeSourceInfo *Info,
4618                                         bool KnownDependent,
4619                                         LambdaCaptureDefault CaptureDefault);
4620
4621  /// \brief Start the definition of a lambda expression.
4622  CXXMethodDecl *startLambdaDefinition(CXXRecordDecl *Class,
4623                                       SourceRange IntroducerRange,
4624                                       TypeSourceInfo *MethodType,
4625                                       SourceLocation EndLoc,
4626                                       ArrayRef<ParmVarDecl *> Params);
4627
4628  /// \brief Endow the lambda scope info with the relevant properties.
4629  void buildLambdaScope(sema::LambdaScopeInfo *LSI,
4630                        CXXMethodDecl *CallOperator,
4631                        SourceRange IntroducerRange,
4632                        LambdaCaptureDefault CaptureDefault,
4633                        SourceLocation CaptureDefaultLoc,
4634                        bool ExplicitParams,
4635                        bool ExplicitResultType,
4636                        bool Mutable);
4637
4638  /// \brief Perform initialization analysis of the init-capture and perform
4639  /// any implicit conversions such as an lvalue-to-rvalue conversion if
4640  /// not being used to initialize a reference.
4641  QualType performLambdaInitCaptureInitialization(SourceLocation Loc,
4642      bool ByRef, IdentifierInfo *Id, Expr *&Init);
4643  /// \brief Create a dummy variable within the declcontext of the lambda's
4644  ///  call operator, for name lookup purposes for a lambda init capture.
4645  ///
4646  ///  CodeGen handles emission of lambda captures, ignoring these dummy
4647  ///  variables appropriately.
4648  VarDecl *createLambdaInitCaptureVarDecl(SourceLocation Loc,
4649    QualType InitCaptureType, IdentifierInfo *Id, Expr *Init);
4650
4651  /// \brief Build the implicit field for an init-capture.
4652  FieldDecl *buildInitCaptureField(sema::LambdaScopeInfo *LSI, VarDecl *Var);
4653
4654  /// \brief Note that we have finished the explicit captures for the
4655  /// given lambda.
4656  void finishLambdaExplicitCaptures(sema::LambdaScopeInfo *LSI);
4657
4658  /// \brief Introduce the lambda parameters into scope.
4659  void addLambdaParameters(CXXMethodDecl *CallOperator, Scope *CurScope);
4660
4661  /// \brief Deduce a block or lambda's return type based on the return
4662  /// statements present in the body.
4663  void deduceClosureReturnType(sema::CapturingScopeInfo &CSI);
4664
4665  /// ActOnStartOfLambdaDefinition - This is called just before we start
4666  /// parsing the body of a lambda; it analyzes the explicit captures and
4667  /// arguments, and sets up various data-structures for the body of the
4668  /// lambda.
4669  void ActOnStartOfLambdaDefinition(LambdaIntroducer &Intro,
4670                                    Declarator &ParamInfo, Scope *CurScope);
4671
4672  /// ActOnLambdaError - If there is an error parsing a lambda, this callback
4673  /// is invoked to pop the information about the lambda.
4674  void ActOnLambdaError(SourceLocation StartLoc, Scope *CurScope,
4675                        bool IsInstantiation = false);
4676
4677  /// ActOnLambdaExpr - This is called when the body of a lambda expression
4678  /// was successfully completed.
4679  ExprResult ActOnLambdaExpr(SourceLocation StartLoc, Stmt *Body,
4680                             Scope *CurScope,
4681                             bool IsInstantiation = false);
4682
4683  /// \brief Define the "body" of the conversion from a lambda object to a
4684  /// function pointer.
4685  ///
4686  /// This routine doesn't actually define a sensible body; rather, it fills
4687  /// in the initialization expression needed to copy the lambda object into
4688  /// the block, and IR generation actually generates the real body of the
4689  /// block pointer conversion.
4690  void DefineImplicitLambdaToFunctionPointerConversion(
4691         SourceLocation CurrentLoc, CXXConversionDecl *Conv);
4692
4693  /// \brief Define the "body" of the conversion from a lambda object to a
4694  /// block pointer.
4695  ///
4696  /// This routine doesn't actually define a sensible body; rather, it fills
4697  /// in the initialization expression needed to copy the lambda object into
4698  /// the block, and IR generation actually generates the real body of the
4699  /// block pointer conversion.
4700  void DefineImplicitLambdaToBlockPointerConversion(SourceLocation CurrentLoc,
4701                                                    CXXConversionDecl *Conv);
4702
4703  ExprResult BuildBlockForLambdaConversion(SourceLocation CurrentLocation,
4704                                           SourceLocation ConvLocation,
4705                                           CXXConversionDecl *Conv,
4706                                           Expr *Src);
4707
4708  // ParseObjCStringLiteral - Parse Objective-C string literals.
4709  ExprResult ParseObjCStringLiteral(SourceLocation *AtLocs,
4710                                    Expr **Strings,
4711                                    unsigned NumStrings);
4712
4713  ExprResult BuildObjCStringLiteral(SourceLocation AtLoc, StringLiteral *S);
4714
4715  /// BuildObjCNumericLiteral - builds an ObjCBoxedExpr AST node for the
4716  /// numeric literal expression. Type of the expression will be "NSNumber *"
4717  /// or "id" if NSNumber is unavailable.
4718  ExprResult BuildObjCNumericLiteral(SourceLocation AtLoc, Expr *Number);
4719  ExprResult ActOnObjCBoolLiteral(SourceLocation AtLoc, SourceLocation ValueLoc,
4720                                  bool Value);
4721  ExprResult BuildObjCArrayLiteral(SourceRange SR, MultiExprArg Elements);
4722
4723  /// BuildObjCBoxedExpr - builds an ObjCBoxedExpr AST node for the
4724  /// '@' prefixed parenthesized expression. The type of the expression will
4725  /// either be "NSNumber *" or "NSString *" depending on the type of
4726  /// ValueType, which is allowed to be a built-in numeric type or
4727  /// "char *" or "const char *".
4728  ExprResult BuildObjCBoxedExpr(SourceRange SR, Expr *ValueExpr);
4729
4730  ExprResult BuildObjCSubscriptExpression(SourceLocation RB, Expr *BaseExpr,
4731                                          Expr *IndexExpr,
4732                                          ObjCMethodDecl *getterMethod,
4733                                          ObjCMethodDecl *setterMethod);
4734
4735  ExprResult BuildObjCDictionaryLiteral(SourceRange SR,
4736                                        ObjCDictionaryElement *Elements,
4737                                        unsigned NumElements);
4738
4739  ExprResult BuildObjCEncodeExpression(SourceLocation AtLoc,
4740                                  TypeSourceInfo *EncodedTypeInfo,
4741                                  SourceLocation RParenLoc);
4742  ExprResult BuildCXXMemberCallExpr(Expr *Exp, NamedDecl *FoundDecl,
4743                                    CXXConversionDecl *Method,
4744                                    bool HadMultipleCandidates);
4745
4746  ExprResult ParseObjCEncodeExpression(SourceLocation AtLoc,
4747                                       SourceLocation EncodeLoc,
4748                                       SourceLocation LParenLoc,
4749                                       ParsedType Ty,
4750                                       SourceLocation RParenLoc);
4751
4752  /// ParseObjCSelectorExpression - Build selector expression for \@selector
4753  ExprResult ParseObjCSelectorExpression(Selector Sel,
4754                                         SourceLocation AtLoc,
4755                                         SourceLocation SelLoc,
4756                                         SourceLocation LParenLoc,
4757                                         SourceLocation RParenLoc,
4758                                         bool WarnMultipleSelectors);
4759
4760  /// ParseObjCProtocolExpression - Build protocol expression for \@protocol
4761  ExprResult ParseObjCProtocolExpression(IdentifierInfo * ProtocolName,
4762                                         SourceLocation AtLoc,
4763                                         SourceLocation ProtoLoc,
4764                                         SourceLocation LParenLoc,
4765                                         SourceLocation ProtoIdLoc,
4766                                         SourceLocation RParenLoc);
4767
4768  //===--------------------------------------------------------------------===//
4769  // C++ Declarations
4770  //
4771  Decl *ActOnStartLinkageSpecification(Scope *S,
4772                                       SourceLocation ExternLoc,
4773                                       Expr *LangStr,
4774                                       SourceLocation LBraceLoc);
4775  Decl *ActOnFinishLinkageSpecification(Scope *S,
4776                                        Decl *LinkageSpec,
4777                                        SourceLocation RBraceLoc);
4778
4779
4780  //===--------------------------------------------------------------------===//
4781  // C++ Classes
4782  //
4783  bool isCurrentClassName(const IdentifierInfo &II, Scope *S,
4784                          const CXXScopeSpec *SS = nullptr);
4785  bool isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS);
4786
4787  bool ActOnAccessSpecifier(AccessSpecifier Access,
4788                            SourceLocation ASLoc,
4789                            SourceLocation ColonLoc,
4790                            AttributeList *Attrs = nullptr);
4791
4792  NamedDecl *ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS,
4793                                 Declarator &D,
4794                                 MultiTemplateParamsArg TemplateParameterLists,
4795                                 Expr *BitfieldWidth, const VirtSpecifiers &VS,
4796                                 InClassInitStyle InitStyle);
4797
4798  void ActOnStartCXXInClassMemberInitializer();
4799  void ActOnFinishCXXInClassMemberInitializer(Decl *VarDecl,
4800                                              SourceLocation EqualLoc,
4801                                              Expr *Init);
4802
4803  MemInitResult ActOnMemInitializer(Decl *ConstructorD,
4804                                    Scope *S,
4805                                    CXXScopeSpec &SS,
4806                                    IdentifierInfo *MemberOrBase,
4807                                    ParsedType TemplateTypeTy,
4808                                    const DeclSpec &DS,
4809                                    SourceLocation IdLoc,
4810                                    SourceLocation LParenLoc,
4811                                    ArrayRef<Expr *> Args,
4812                                    SourceLocation RParenLoc,
4813                                    SourceLocation EllipsisLoc);
4814
4815  MemInitResult ActOnMemInitializer(Decl *ConstructorD,
4816                                    Scope *S,
4817                                    CXXScopeSpec &SS,
4818                                    IdentifierInfo *MemberOrBase,
4819                                    ParsedType TemplateTypeTy,
4820                                    const DeclSpec &DS,
4821                                    SourceLocation IdLoc,
4822                                    Expr *InitList,
4823                                    SourceLocation EllipsisLoc);
4824
4825  MemInitResult BuildMemInitializer(Decl *ConstructorD,
4826                                    Scope *S,
4827                                    CXXScopeSpec &SS,
4828                                    IdentifierInfo *MemberOrBase,
4829                                    ParsedType TemplateTypeTy,
4830                                    const DeclSpec &DS,
4831                                    SourceLocation IdLoc,
4832                                    Expr *Init,
4833                                    SourceLocation EllipsisLoc);
4834
4835  MemInitResult BuildMemberInitializer(ValueDecl *Member,
4836                                       Expr *Init,
4837                                       SourceLocation IdLoc);
4838
4839  MemInitResult BuildBaseInitializer(QualType BaseType,
4840                                     TypeSourceInfo *BaseTInfo,
4841                                     Expr *Init,
4842                                     CXXRecordDecl *ClassDecl,
4843                                     SourceLocation EllipsisLoc);
4844
4845  MemInitResult BuildDelegatingInitializer(TypeSourceInfo *TInfo,
4846                                           Expr *Init,
4847                                           CXXRecordDecl *ClassDecl);
4848
4849  bool SetDelegatingInitializer(CXXConstructorDecl *Constructor,
4850                                CXXCtorInitializer *Initializer);
4851
4852  bool SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
4853                           ArrayRef<CXXCtorInitializer *> Initializers = None);
4854
4855  void SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation);
4856
4857
4858  /// MarkBaseAndMemberDestructorsReferenced - Given a record decl,
4859  /// mark all the non-trivial destructors of its members and bases as
4860  /// referenced.
4861  void MarkBaseAndMemberDestructorsReferenced(SourceLocation Loc,
4862                                              CXXRecordDecl *Record);
4863
4864  /// \brief The list of classes whose vtables have been used within
4865  /// this translation unit, and the source locations at which the
4866  /// first use occurred.
4867  typedef std::pair<CXXRecordDecl*, SourceLocation> VTableUse;
4868
4869  /// \brief The list of vtables that are required but have not yet been
4870  /// materialized.
4871  SmallVector<VTableUse, 16> VTableUses;
4872
4873  /// \brief The set of classes whose vtables have been used within
4874  /// this translation unit, and a bit that will be true if the vtable is
4875  /// required to be emitted (otherwise, it should be emitted only if needed
4876  /// by code generation).
4877  llvm::DenseMap<CXXRecordDecl *, bool> VTablesUsed;
4878
4879  /// \brief Load any externally-stored vtable uses.
4880  void LoadExternalVTableUses();
4881
4882  typedef LazyVector<CXXRecordDecl *, ExternalSemaSource,
4883                     &ExternalSemaSource::ReadDynamicClasses, 2, 2>
4884    DynamicClassesType;
4885
4886  /// \brief A list of all of the dynamic classes in this translation
4887  /// unit.
4888  DynamicClassesType DynamicClasses;
4889
4890  /// \brief Note that the vtable for the given class was used at the
4891  /// given location.
4892  void MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
4893                      bool DefinitionRequired = false);
4894
4895  /// \brief Mark the exception specifications of all virtual member functions
4896  /// in the given class as needed.
4897  void MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
4898                                             const CXXRecordDecl *RD);
4899
4900  /// MarkVirtualMembersReferenced - Will mark all members of the given
4901  /// CXXRecordDecl referenced.
4902  void MarkVirtualMembersReferenced(SourceLocation Loc,
4903                                    const CXXRecordDecl *RD);
4904
4905  /// \brief Define all of the vtables that have been used in this
4906  /// translation unit and reference any virtual members used by those
4907  /// vtables.
4908  ///
4909  /// \returns true if any work was done, false otherwise.
4910  bool DefineUsedVTables();
4911
4912  void AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl);
4913
4914  void ActOnMemInitializers(Decl *ConstructorDecl,
4915                            SourceLocation ColonLoc,
4916                            ArrayRef<CXXCtorInitializer*> MemInits,
4917                            bool AnyErrors);
4918
4919  void CheckCompletedCXXClass(CXXRecordDecl *Record);
4920  void ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
4921                                         Decl *TagDecl,
4922                                         SourceLocation LBrac,
4923                                         SourceLocation RBrac,
4924                                         AttributeList *AttrList);
4925  void ActOnFinishCXXMemberDecls();
4926
4927  void ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param);
4928  unsigned ActOnReenterTemplateScope(Scope *S, Decl *Template);
4929  void ActOnStartDelayedMemberDeclarations(Scope *S, Decl *Record);
4930  void ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *Method);
4931  void ActOnDelayedCXXMethodParameter(Scope *S, Decl *Param);
4932  void ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *Record);
4933  void ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *Method);
4934  void ActOnFinishDelayedMemberInitializers(Decl *Record);
4935  void MarkAsLateParsedTemplate(FunctionDecl *FD, Decl *FnD,
4936                                CachedTokens &Toks);
4937  void UnmarkAsLateParsedTemplate(FunctionDecl *FD);
4938  bool IsInsideALocalClassWithinATemplateFunction();
4939
4940  Decl *ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
4941                                     Expr *AssertExpr,
4942                                     Expr *AssertMessageExpr,
4943                                     SourceLocation RParenLoc);
4944  Decl *BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
4945                                     Expr *AssertExpr,
4946                                     StringLiteral *AssertMessageExpr,
4947                                     SourceLocation RParenLoc,
4948                                     bool Failed);
4949
4950  FriendDecl *CheckFriendTypeDecl(SourceLocation LocStart,
4951                                  SourceLocation FriendLoc,
4952                                  TypeSourceInfo *TSInfo);
4953  Decl *ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
4954                            MultiTemplateParamsArg TemplateParams);
4955  NamedDecl *ActOnFriendFunctionDecl(Scope *S, Declarator &D,
4956                                     MultiTemplateParamsArg TemplateParams);
4957
4958  QualType CheckConstructorDeclarator(Declarator &D, QualType R,
4959                                      StorageClass& SC);
4960  void CheckConstructor(CXXConstructorDecl *Constructor);
4961  QualType CheckDestructorDeclarator(Declarator &D, QualType R,
4962                                     StorageClass& SC);
4963  bool CheckDestructor(CXXDestructorDecl *Destructor);
4964  void CheckConversionDeclarator(Declarator &D, QualType &R,
4965                                 StorageClass& SC);
4966  Decl *ActOnConversionDeclarator(CXXConversionDecl *Conversion);
4967
4968  void CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD);
4969  void CheckExplicitlyDefaultedMemberExceptionSpec(CXXMethodDecl *MD,
4970                                                   const FunctionProtoType *T);
4971  void CheckDelayedMemberExceptionSpecs();
4972
4973  //===--------------------------------------------------------------------===//
4974  // C++ Derived Classes
4975  //
4976
4977  /// ActOnBaseSpecifier - Parsed a base specifier
4978  CXXBaseSpecifier *CheckBaseSpecifier(CXXRecordDecl *Class,
4979                                       SourceRange SpecifierRange,
4980                                       bool Virtual, AccessSpecifier Access,
4981                                       TypeSourceInfo *TInfo,
4982                                       SourceLocation EllipsisLoc);
4983
4984  BaseResult ActOnBaseSpecifier(Decl *classdecl,
4985                                SourceRange SpecifierRange,
4986                                ParsedAttributes &Attrs,
4987                                bool Virtual, AccessSpecifier Access,
4988                                ParsedType basetype,
4989                                SourceLocation BaseLoc,
4990                                SourceLocation EllipsisLoc);
4991
4992  bool AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
4993                            unsigned NumBases);
4994  void ActOnBaseSpecifiers(Decl *ClassDecl, CXXBaseSpecifier **Bases,
4995                           unsigned NumBases);
4996
4997  bool IsDerivedFrom(QualType Derived, QualType Base);
4998  bool IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths);
4999
5000  // FIXME: I don't like this name.
5001  void BuildBasePathArray(const CXXBasePaths &Paths, CXXCastPath &BasePath);
5002
5003  bool BasePathInvolvesVirtualBase(const CXXCastPath &BasePath);
5004
5005  bool CheckDerivedToBaseConversion(QualType Derived, QualType Base,
5006                                    SourceLocation Loc, SourceRange Range,
5007                                    CXXCastPath *BasePath = nullptr,
5008                                    bool IgnoreAccess = false);
5009  bool CheckDerivedToBaseConversion(QualType Derived, QualType Base,
5010                                    unsigned InaccessibleBaseID,
5011                                    unsigned AmbigiousBaseConvID,
5012                                    SourceLocation Loc, SourceRange Range,
5013                                    DeclarationName Name,
5014                                    CXXCastPath *BasePath);
5015
5016  std::string getAmbiguousPathsDisplayString(CXXBasePaths &Paths);
5017
5018  bool CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
5019                                         const CXXMethodDecl *Old);
5020
5021  /// CheckOverridingFunctionReturnType - Checks whether the return types are
5022  /// covariant, according to C++ [class.virtual]p5.
5023  bool CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
5024                                         const CXXMethodDecl *Old);
5025
5026  /// CheckOverridingFunctionExceptionSpec - Checks whether the exception
5027  /// spec is a subset of base spec.
5028  bool CheckOverridingFunctionExceptionSpec(const CXXMethodDecl *New,
5029                                            const CXXMethodDecl *Old);
5030
5031  bool CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange);
5032
5033  /// CheckOverrideControl - Check C++11 override control semantics.
5034  void CheckOverrideControl(NamedDecl *D);
5035
5036  /// CheckForFunctionMarkedFinal - Checks whether a virtual member function
5037  /// overrides a virtual member function marked 'final', according to
5038  /// C++11 [class.virtual]p4.
5039  bool CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
5040                                              const CXXMethodDecl *Old);
5041
5042
5043  //===--------------------------------------------------------------------===//
5044  // C++ Access Control
5045  //
5046
5047  enum AccessResult {
5048    AR_accessible,
5049    AR_inaccessible,
5050    AR_dependent,
5051    AR_delayed
5052  };
5053
5054  bool SetMemberAccessSpecifier(NamedDecl *MemberDecl,
5055                                NamedDecl *PrevMemberDecl,
5056                                AccessSpecifier LexicalAS);
5057
5058  AccessResult CheckUnresolvedMemberAccess(UnresolvedMemberExpr *E,
5059                                           DeclAccessPair FoundDecl);
5060  AccessResult CheckUnresolvedLookupAccess(UnresolvedLookupExpr *E,
5061                                           DeclAccessPair FoundDecl);
5062  AccessResult CheckAllocationAccess(SourceLocation OperatorLoc,
5063                                     SourceRange PlacementRange,
5064                                     CXXRecordDecl *NamingClass,
5065                                     DeclAccessPair FoundDecl,
5066                                     bool Diagnose = true);
5067  AccessResult CheckConstructorAccess(SourceLocation Loc,
5068                                      CXXConstructorDecl *D,
5069                                      const InitializedEntity &Entity,
5070                                      AccessSpecifier Access,
5071                                      bool IsCopyBindingRefToTemp = false);
5072  AccessResult CheckConstructorAccess(SourceLocation Loc,
5073                                      CXXConstructorDecl *D,
5074                                      const InitializedEntity &Entity,
5075                                      AccessSpecifier Access,
5076                                      const PartialDiagnostic &PDiag);
5077  AccessResult CheckDestructorAccess(SourceLocation Loc,
5078                                     CXXDestructorDecl *Dtor,
5079                                     const PartialDiagnostic &PDiag,
5080                                     QualType objectType = QualType());
5081  AccessResult CheckFriendAccess(NamedDecl *D);
5082  AccessResult CheckMemberAccess(SourceLocation UseLoc,
5083                                 CXXRecordDecl *NamingClass,
5084                                 DeclAccessPair Found);
5085  AccessResult CheckMemberOperatorAccess(SourceLocation Loc,
5086                                         Expr *ObjectExpr,
5087                                         Expr *ArgExpr,
5088                                         DeclAccessPair FoundDecl);
5089  AccessResult CheckAddressOfMemberAccess(Expr *OvlExpr,
5090                                          DeclAccessPair FoundDecl);
5091  AccessResult CheckBaseClassAccess(SourceLocation AccessLoc,
5092                                    QualType Base, QualType Derived,
5093                                    const CXXBasePath &Path,
5094                                    unsigned DiagID,
5095                                    bool ForceCheck = false,
5096                                    bool ForceUnprivileged = false);
5097  void CheckLookupAccess(const LookupResult &R);
5098  bool IsSimplyAccessible(NamedDecl *decl, DeclContext *Ctx);
5099  bool isSpecialMemberAccessibleForDeletion(CXXMethodDecl *decl,
5100                                            AccessSpecifier access,
5101                                            QualType objectType);
5102
5103  void HandleDependentAccessCheck(const DependentDiagnostic &DD,
5104                         const MultiLevelTemplateArgumentList &TemplateArgs);
5105  void PerformDependentDiagnostics(const DeclContext *Pattern,
5106                        const MultiLevelTemplateArgumentList &TemplateArgs);
5107
5108  void HandleDelayedAccessCheck(sema::DelayedDiagnostic &DD, Decl *Ctx);
5109
5110  /// \brief When true, access checking violations are treated as SFINAE
5111  /// failures rather than hard errors.
5112  bool AccessCheckingSFINAE;
5113
5114  enum AbstractDiagSelID {
5115    AbstractNone = -1,
5116    AbstractReturnType,
5117    AbstractParamType,
5118    AbstractVariableType,
5119    AbstractFieldType,
5120