• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 
56 namespace 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 
64 namespace 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 
188 namespace 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.
204 typedef std::pair<llvm::PointerUnion<const TemplateTypeParmType*, NamedDecl*>,
205                   SourceLocation> UnexpandedParameterPack;
206 
207 /// Sema - This implements semantic analysis and AST building for C.
208 class 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
shouldLinkPossiblyHiddenDecl(const NamedDecl * Old,const NamedDecl * New)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 
231 public:
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;
SlotPragmaStack::Slot310       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);
PragmaStackPragmaStack320     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 
SetLateTemplateParser(LateTemplateParserCB * LTP,void * P)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:
DelayedDiagnostics()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.
shouldDelayDiagnostics()507     bool shouldDelayDiagnostics() { return CurPool != nullptr; }
508 
509     /// Returns the current delayed-diagnostics pool.
getCurrentPool()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.
push(sema::DelayedDiagnosticPool & 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".
popWithoutEmitting(DelayedDiagnosticsState state)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.
pushUndelayed()532     DelayedDiagnosticsState pushUndelayed() {
533       DelayedDiagnosticsState state;
534       state.SavedPool = CurPool;
535       CurPool = nullptr;
536       return state;
537     }
538 
539     /// Undo a previous pushUndelayed().
popUndelayed(DelayedDiagnosticsState state)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)
S(S)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 
pop()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 
~ContextRAII()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:
SynthesizedFunctionScope(Sema & S,DeclContext * DC)586     SynthesizedFunctionScope(Sema &S, DeclContext *DC)
587       : S(S), SavedContext(S, DC)
588     {
589       S.PushFunctionScope();
590       S.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated);
591     }
592 
~SynthesizedFunctionScope()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 
ExpressionEvaluationContextRecordExpressionEvaluationContextRecord770     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 
isUnevaluatedExpressionEvaluationContextRecord783     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:
SpecialMemberOverloadResult(const llvm::FoldingSetNodeID & ID)820     SpecialMemberOverloadResult(const llvm::FoldingSetNodeID &ID)
821       : FastFoldingSetNode(ID)
822     {}
823 
getMethod()824     CXXMethodDecl *getMethod() const { return Pair.getPointer(); }
setMethod(CXXMethodDecl * MD)825     void setMethod(CXXMethodDecl *MD) { Pair.setPointer(MD); }
826 
getKind()827     Kind getKind() const { return static_cast<Kind>(Pair.getInt()); }
setKind(Kind K)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:
FPContractStateRAII(Sema & S)921     FPContractStateRAII(Sema& S)
922       : S(S), OldFPContractState(S.FPFeatures.fp_contract) {}
~FPContractStateRAII()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 
933 public:
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 
getLangOpts()943   const LangOptions &getLangOpts() const { return LangOpts; }
getOpenCLOptions()944   OpenCLOptions &getOpenCLOptions() { return OpenCLFeatures; }
getFPOptions()945   FPOptions     &getFPOptions() { return FPFeatures; }
946 
getDiagnostics()947   DiagnosticsEngine &getDiagnostics() const { return Diags; }
getSourceManager()948   SourceManager &getSourceManager() const { return SourceMgr; }
getPreprocessor()949   Preprocessor &getPreprocessor() const { return PP; }
getASTContext()950   ASTContext &getASTContext() const { return Context; }
getASTConsumer()951   ASTConsumer &getASTConsumer() const { return Consumer; }
952   ASTMutationListener *getASTMutationListener() const;
getExternalSource()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:
SemaDiagnosticBuilder(DiagnosticBuilder & DB,Sema & SemaRef,unsigned DiagID)978     SemaDiagnosticBuilder(DiagnosticBuilder &DB, Sema &SemaRef, unsigned DiagID)
979       : DiagnosticBuilder(DB), SemaRef(SemaRef), DiagID(DiagID) { }
980 
~SemaDiagnosticBuilder()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.
Diag(SourceLocation Loc,unsigned DiagID)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 
getCurFunction()1059   sema::FunctionScopeInfo *getCurFunction() const {
1060     return FunctionScopes.back();
1061   }
1062 
getEnclosingFunction()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
WeakTopLevelDecls()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 
SuppressedTypeDiagnoser1213     TypeDiagnoser(bool Suppressed = false) : Suppressed(Suppressed) { }
1214 
1215     virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) = 0;
~TypeDiagnoserTypeDiagnoser1216     virtual ~TypeDiagnoser() {}
1217   };
1218 
getPrintable(int I)1219   static int getPrintable(int I) { return I; }
getPrintable(unsigned I)1220   static unsigned getPrintable(unsigned I) { return I; }
getPrintable(bool B)1221   static bool getPrintable(bool B) { return B; }
getPrintable(const char * S)1222   static const char * getPrintable(const char *S) { return S; }
getPrintable(StringRef S)1223   static StringRef getPrintable(StringRef S) { return S; }
getPrintable(const std::string & S)1224   static const std::string &getPrintable(const std::string &S) { return S; }
getPrintable(const IdentifierInfo * II)1225   static const IdentifierInfo *getPrintable(const IdentifierInfo *II) {
1226     return II;
1227   }
getPrintable(DeclarationName N)1228   static DeclarationName getPrintable(DeclarationName N) { return N; }
getPrintable(QualType T)1229   static QualType getPrintable(QualType T) { return T; }
getPrintable(SourceRange R)1230   static SourceRange getPrintable(SourceRange R) { return R; }
getPrintable(SourceLocation L)1231   static SourceRange getPrintable(SourceLocation L) { return L; }
getPrintable(Expr * E)1232   static SourceRange getPrintable(Expr *E) { return E->getSourceRange(); }
getPrintable(TypeLoc TL)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:
BoundTypeDiagnoser1(unsigned DiagID,const T1 & Arg1)1241     BoundTypeDiagnoser1(unsigned DiagID, const T1 &Arg1)
1242       : TypeDiagnoser(DiagID == 0), DiagID(DiagID), Arg1(Arg1) { }
diagnose(Sema & S,SourceLocation Loc,QualType T)1243     void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
1244       if (Suppressed) return;
1245       S.Diag(Loc, DiagID) << getPrintable(Arg1) << T;
1246     }
1247 
~BoundTypeDiagnoser1()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:
BoundTypeDiagnoser2(unsigned DiagID,const T1 & Arg1,const T2 & Arg2)1258     BoundTypeDiagnoser2(unsigned DiagID, const T1 &Arg1,
1259                                   const T2 &Arg2)
1260       : TypeDiagnoser(DiagID == 0), DiagID(DiagID), Arg1(Arg1),
1261         Arg2(Arg2) { }
1262 
diagnose(Sema & S,SourceLocation Loc,QualType T)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 
~BoundTypeDiagnoser2()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:
BoundTypeDiagnoser3(unsigned DiagID,const T1 & Arg1,const T2 & Arg2,const T3 & Arg3)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 
diagnose(Sema & S,SourceLocation Loc,QualType T)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 
~BoundTypeDiagnoser3()1290     virtual ~BoundTypeDiagnoser3() { }
1291   };
1292 
1293 private:
1294   bool RequireCompleteTypeImpl(SourceLocation Loc, QualType T,
1295                            TypeDiagnoser &Diagnoser);
1296 public:
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>
RequireCompleteType(SourceLocation Loc,QualType T,unsigned DiagID,const T1 & Arg1)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>
RequireCompleteType(SourceLocation Loc,QualType T,unsigned DiagID,const T1 & Arg1,const T2 & Arg2)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>
RequireCompleteType(SourceLocation Loc,QualType T,unsigned DiagID,const T1 & Arg1,const T2 & Arg2,const T3 & Arg3)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>
RequireCompleteExprType(Expr * E,unsigned DiagID,const T1 & Arg1)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>
RequireCompleteExprType(Expr * E,unsigned DiagID,const T1 & Arg1,const T2 & Arg2)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>
RequireCompleteExprType(Expr * E,unsigned DiagID,const T1 & Arg1,const T2 & Arg2,const T3 & Arg3)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>
RequireLiteralType(SourceLocation Loc,QualType T,unsigned DiagID,const T1 & Arg1)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>
RequireLiteralType(SourceLocation Loc,QualType T,unsigned DiagID,const T1 & Arg1,const T2 & Arg2)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>
RequireLiteralType(SourceLocation Loc,QualType T,unsigned DiagID,const T1 & Arg1,const T2 & Arg2,const T3 & Arg3)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 
NameClassification(NameClassificationKind Kind)1446     explicit NameClassification(NameClassificationKind Kind) : Kind(Kind) {}
1447 
1448   public:
NameClassification(ExprResult Expr)1449     NameClassification(ExprResult Expr) : Kind(NC_Expression), Expr(Expr) {}
1450 
NameClassification(ParsedType Type)1451     NameClassification(ParsedType Type) : Kind(NC_Type), Type(Type) {}
1452 
NameClassification(const IdentifierInfo * Keyword)1453     NameClassification(const IdentifierInfo *Keyword)
1454       : Kind(NC_Keyword), Keyword(Keyword) { }
1455 
Error()1456     static NameClassification Error() {
1457       return NameClassification(NC_Error);
1458     }
1459 
Unknown()1460     static NameClassification Unknown() {
1461       return NameClassification(NC_Unknown);
1462     }
1463 
NestedNameSpecifier()1464     static NameClassification NestedNameSpecifier() {
1465       return NameClassification(NC_NestedNameSpecifier);
1466     }
1467 
TypeTemplate(TemplateName Name)1468     static NameClassification TypeTemplate(TemplateName Name) {
1469       NameClassification Result(NC_TypeTemplate);
1470       Result.Template = Name;
1471       return Result;
1472     }
1473 
VarTemplate(TemplateName Name)1474     static NameClassification VarTemplate(TemplateName Name) {
1475       NameClassification Result(NC_VarTemplate);
1476       Result.Template = Name;
1477       return Result;
1478     }
1479 
FunctionTemplate(TemplateName Name)1480     static NameClassification FunctionTemplate(TemplateName Name) {
1481       NameClassification Result(NC_FunctionTemplate);
1482       Result.Template = Name;
1483       return Result;
1484     }
1485 
getKind()1486     NameClassificationKind getKind() const { return Kind; }
1487 
getType()1488     ParsedType getType() const {
1489       assert(Kind == NC_Type);
1490       return Type;
1491     }
1492 
getExpression()1493     ExprResult getExpression() const {
1494       assert(Kind == NC_Expression);
1495       return Expr;
1496     }
1497 
getTemplateName()1498     TemplateName getTemplateName() const {
1499       assert(Kind == NC_TypeTemplate || Kind == NC_FunctionTemplate ||
1500              Kind == NC_VarTemplate);
1501       return Template;
1502     }
1503 
getTemplateNameKind()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);
isObjCMethodDecl(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.
getPrintingPolicy()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)
Suppress(Suppress)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 
~ContextualImplicitConverter()2179     virtual ~ContextualImplicitConverter() {}
2180   };
2181 
2182   class ICEConvertDiagnoser : public ContextualImplicitConverter {
2183     bool AllowScopedEnumerations;
2184 
2185   public:
ICEConvertDiagnoser(bool AllowScopedEnumerations,bool Suppress,bool SuppressConversion)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
diagnoseNoMatch(Sema & S,SourceLocation Loc,QualType T)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 
2561 private:
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 
2574 public:
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 
2860 private:
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 
2882 public:
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.
2931 public:
2932   class FullExprArg {
2933   public:
FullExprArg(Sema & actions)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).
FullExprArg(const FullExprArg & Other)2939     FullExprArg(const FullExprArg& Other) : E(Other.E) {}
2940 
release()2941     ExprResult release() {
2942       return E;
2943     }
2944 
get()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 
FullExprArg(Expr * expr)2956     explicit FullExprArg(Expr *expr) : E(expr) {}
2957 
2958     Expr *E;
2959   };
2960 
MakeFullExpr(Expr * Arg)2961   FullExprArg MakeFullExpr(Expr *Arg) {
2962     return MakeFullExpr(Arg, Arg ? Arg->getExprLoc() : SourceLocation());
2963   }
MakeFullExpr(Expr * Arg,SourceLocation CC)2964   FullExprArg MakeFullExpr(Expr *Arg, SourceLocation CC) {
2965     return FullExprArg(ActOnFinishFullExpr(Arg, CC).get());
2966   }
MakeFullDiscardedValueExpr(Expr * Arg)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:
CompoundScopeRAII(Sema & S)2988     CompoundScopeRAII(Sema &S): S(S) {
2989       S.ActOnStartOfCompoundStmt();
2990     }
2991 
~CompoundScopeRAII()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 
PushParsingDeclaration(sema::DelayedDiagnosticPool & pool)3203   ParsingDeclState PushParsingDeclaration(sema::DelayedDiagnosticPool &pool) {
3204     return DelayedDiagnostics.push(pool);
3205   }
3206   void PopParsingDeclaration(ParsingDeclState state, Decl *decl);
3207 
3208   typedef ProcessingContextState ParsingClassState;
PushParsingClass()3209   ParsingClassState PushParsingClass() {
3210     return DelayedDiagnostics.pushUndelayed();
3211   }
PopParsingClass(ParsingClassState state)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 
ClearExceptions()3898     void ClearExceptions() {
3899       ExceptionsSeen.clear();
3900       Exceptions.clear();
3901     }
3902 
3903   public:
ImplicitExceptionSpecification(Sema & Self)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.
getExceptionSpecType()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.
size()3918     unsigned size() const { return Exceptions.size(); }
3919 
3920     /// \brief The set of exceptions in the exception specification.
data()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.
getEPI(FunctionProtoType::ExtProtoInfo & EPI)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     }
getEPI()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 
ActOnFinishFullExpr(Expr * Expr)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     AbstractIvarType,
5121     AbstractSynthesizedIvarType,
5122     AbstractArrayType
5123   };
5124 
5125   bool RequireNonAbstractType(SourceLocation Loc, QualType T,
5126                               TypeDiagnoser &Diagnoser);
5127   template<typename T1>
RequireNonAbstractType(SourceLocation Loc,QualType T,unsigned DiagID,const T1 & Arg1)5128   bool RequireNonAbstractType(SourceLocation Loc, QualType T,
5129                               unsigned DiagID,
5130                               const T1 &Arg1) {
5131     BoundTypeDiagnoser1<T1> Diagnoser(DiagID, Arg1);
5132     return RequireNonAbstractType(Loc, T, Diagnoser);
5133   }
5134 
5135   template<typename T1, typename T2>
RequireNonAbstractType(SourceLocation Loc,QualType T,unsigned DiagID,const T1 & Arg1,const T2 & Arg2)5136   bool RequireNonAbstractType(SourceLocation Loc, QualType T,
5137                               unsigned DiagID,
5138                               const T1 &Arg1, const T2 &Arg2) {
5139     BoundTypeDiagnoser2<T1, T2> Diagnoser(DiagID, Arg1, Arg2);
5140     return RequireNonAbstractType(Loc, T, Diagnoser);
5141   }
5142 
5143   template<typename T1, typename T2, typename T3>
RequireNonAbstractType(SourceLocation Loc,QualType T,unsigned DiagID,const T1 & Arg1,const T2 & Arg2,const T3 & Arg3)5144   bool RequireNonAbstractType(SourceLocation Loc, QualType T,
5145                               unsigned DiagID,
5146                               const T1 &Arg1, const T2 &Arg2, const T3 &Arg3) {
5147     BoundTypeDiagnoser3<T1, T2, T3> Diagnoser(DiagID, Arg1, Arg2, Arg3);
5148     return RequireNonAbstractType(Loc, T, Diagnoser);
5149   }
5150 
5151   void DiagnoseAbstractType(const CXXRecordDecl *RD);
5152 
5153   bool RequireNonAbstractType(SourceLocation Loc, QualType T, unsigned DiagID,
5154                               AbstractDiagSelID SelID = AbstractNone);
5155 
5156   //===--------------------------------------------------------------------===//
5157   // C++ Overloaded Operators [C++ 13.5]
5158   //
5159 
5160   bool CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl);
5161 
5162   bool CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl);
5163 
5164   //===--------------------------------------------------------------------===//
5165   // C++ Templates [C++ 14]
5166   //
5167   void FilterAcceptableTemplateNames(LookupResult &R,
5168                                      bool AllowFunctionTemplates = true);
5169   bool hasAnyAcceptableTemplateNames(LookupResult &R,
5170                                      bool AllowFunctionTemplates = true);
5171 
5172   void LookupTemplateName(LookupResult &R, Scope *S, CXXScopeSpec &SS,
5173                           QualType ObjectType, bool EnteringContext,
5174                           bool &MemberOfUnknownSpecialization);
5175 
5176   TemplateNameKind isTemplateName(Scope *S,
5177                                   CXXScopeSpec &SS,
5178                                   bool hasTemplateKeyword,
5179                                   UnqualifiedId &Name,
5180                                   ParsedType ObjectType,
5181                                   bool EnteringContext,
5182                                   TemplateTy &Template,
5183                                   bool &MemberOfUnknownSpecialization);
5184 
5185   bool DiagnoseUnknownTemplateName(const IdentifierInfo &II,
5186                                    SourceLocation IILoc,
5187                                    Scope *S,
5188                                    const CXXScopeSpec *SS,
5189                                    TemplateTy &SuggestedTemplate,
5190                                    TemplateNameKind &SuggestedKind);
5191 
5192   void DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl);
5193   TemplateDecl *AdjustDeclIfTemplate(Decl *&Decl);
5194 
5195   Decl *ActOnTypeParameter(Scope *S, bool Typename,
5196                            SourceLocation EllipsisLoc,
5197                            SourceLocation KeyLoc,
5198                            IdentifierInfo *ParamName,
5199                            SourceLocation ParamNameLoc,
5200                            unsigned Depth, unsigned Position,
5201                            SourceLocation EqualLoc,
5202                            ParsedType DefaultArg);
5203 
5204   QualType CheckNonTypeTemplateParameterType(QualType T, SourceLocation Loc);
5205   Decl *ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
5206                                       unsigned Depth,
5207                                       unsigned Position,
5208                                       SourceLocation EqualLoc,
5209                                       Expr *DefaultArg);
5210   Decl *ActOnTemplateTemplateParameter(Scope *S,
5211                                        SourceLocation TmpLoc,
5212                                        TemplateParameterList *Params,
5213                                        SourceLocation EllipsisLoc,
5214                                        IdentifierInfo *ParamName,
5215                                        SourceLocation ParamNameLoc,
5216                                        unsigned Depth,
5217                                        unsigned Position,
5218                                        SourceLocation EqualLoc,
5219                                        ParsedTemplateArgument DefaultArg);
5220 
5221   TemplateParameterList *
5222   ActOnTemplateParameterList(unsigned Depth,
5223                              SourceLocation ExportLoc,
5224                              SourceLocation TemplateLoc,
5225                              SourceLocation LAngleLoc,
5226                              Decl **Params, unsigned NumParams,
5227                              SourceLocation RAngleLoc);
5228 
5229   /// \brief The context in which we are checking a template parameter list.
5230   enum TemplateParamListContext {
5231     TPC_ClassTemplate,
5232     TPC_VarTemplate,
5233     TPC_FunctionTemplate,
5234     TPC_ClassTemplateMember,
5235     TPC_FriendClassTemplate,
5236     TPC_FriendFunctionTemplate,
5237     TPC_FriendFunctionTemplateDefinition,
5238     TPC_TypeAliasTemplate
5239   };
5240 
5241   bool CheckTemplateParameterList(TemplateParameterList *NewParams,
5242                                   TemplateParameterList *OldParams,
5243                                   TemplateParamListContext TPC);
5244   TemplateParameterList *MatchTemplateParametersToScopeSpecifier(
5245       SourceLocation DeclStartLoc, SourceLocation DeclLoc,
5246       const CXXScopeSpec &SS, TemplateIdAnnotation *TemplateId,
5247       ArrayRef<TemplateParameterList *> ParamLists,
5248       bool IsFriend, bool &IsExplicitSpecialization, bool &Invalid);
5249 
5250   DeclResult CheckClassTemplate(Scope *S, unsigned TagSpec, TagUseKind TUK,
5251                                 SourceLocation KWLoc, CXXScopeSpec &SS,
5252                                 IdentifierInfo *Name, SourceLocation NameLoc,
5253                                 AttributeList *Attr,
5254                                 TemplateParameterList *TemplateParams,
5255                                 AccessSpecifier AS,
5256                                 SourceLocation ModulePrivateLoc,
5257                                 unsigned NumOuterTemplateParamLists,
5258                             TemplateParameterList **OuterTemplateParamLists);
5259 
5260   void translateTemplateArguments(const ASTTemplateArgsPtr &In,
5261                                   TemplateArgumentListInfo &Out);
5262 
5263   void NoteAllFoundTemplates(TemplateName Name);
5264 
5265   QualType CheckTemplateIdType(TemplateName Template,
5266                                SourceLocation TemplateLoc,
5267                               TemplateArgumentListInfo &TemplateArgs);
5268 
5269   TypeResult
5270   ActOnTemplateIdType(CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
5271                       TemplateTy Template, SourceLocation TemplateLoc,
5272                       SourceLocation LAngleLoc,
5273                       ASTTemplateArgsPtr TemplateArgs,
5274                       SourceLocation RAngleLoc,
5275                       bool IsCtorOrDtorName = false);
5276 
5277   /// \brief Parsed an elaborated-type-specifier that refers to a template-id,
5278   /// such as \c class T::template apply<U>.
5279   TypeResult ActOnTagTemplateIdType(TagUseKind TUK,
5280                                     TypeSpecifierType TagSpec,
5281                                     SourceLocation TagLoc,
5282                                     CXXScopeSpec &SS,
5283                                     SourceLocation TemplateKWLoc,
5284                                     TemplateTy TemplateD,
5285                                     SourceLocation TemplateLoc,
5286                                     SourceLocation LAngleLoc,
5287                                     ASTTemplateArgsPtr TemplateArgsIn,
5288                                     SourceLocation RAngleLoc);
5289 
5290   DeclResult ActOnVarTemplateSpecialization(
5291       Scope *S, Declarator &D, TypeSourceInfo *DI,
5292       SourceLocation TemplateKWLoc, TemplateParameterList *TemplateParams,
5293       StorageClass SC, bool IsPartialSpecialization);
5294 
5295   DeclResult CheckVarTemplateId(VarTemplateDecl *Template,
5296                                 SourceLocation TemplateLoc,
5297                                 SourceLocation TemplateNameLoc,
5298                                 const TemplateArgumentListInfo &TemplateArgs);
5299 
5300   ExprResult CheckVarTemplateId(const CXXScopeSpec &SS,
5301                                 const DeclarationNameInfo &NameInfo,
5302                                 VarTemplateDecl *Template,
5303                                 SourceLocation TemplateLoc,
5304                                 const TemplateArgumentListInfo *TemplateArgs);
5305 
5306   ExprResult BuildTemplateIdExpr(const CXXScopeSpec &SS,
5307                                  SourceLocation TemplateKWLoc,
5308                                  LookupResult &R,
5309                                  bool RequiresADL,
5310                                const TemplateArgumentListInfo *TemplateArgs);
5311 
5312   ExprResult BuildQualifiedTemplateIdExpr(CXXScopeSpec &SS,
5313                                           SourceLocation TemplateKWLoc,
5314                                const DeclarationNameInfo &NameInfo,
5315                                const TemplateArgumentListInfo *TemplateArgs);
5316 
5317   TemplateNameKind ActOnDependentTemplateName(Scope *S,
5318                                               CXXScopeSpec &SS,
5319                                               SourceLocation TemplateKWLoc,
5320                                               UnqualifiedId &Name,
5321                                               ParsedType ObjectType,
5322                                               bool EnteringContext,
5323                                               TemplateTy &Template);
5324 
5325   DeclResult
5326   ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec, TagUseKind TUK,
5327                                    SourceLocation KWLoc,
5328                                    SourceLocation ModulePrivateLoc,
5329                                    TemplateIdAnnotation &TemplateId,
5330                                    AttributeList *Attr,
5331                                  MultiTemplateParamsArg TemplateParameterLists);
5332 
5333   Decl *ActOnTemplateDeclarator(Scope *S,
5334                                 MultiTemplateParamsArg TemplateParameterLists,
5335                                 Declarator &D);
5336 
5337   Decl *ActOnStartOfFunctionTemplateDef(Scope *FnBodyScope,
5338                                   MultiTemplateParamsArg TemplateParameterLists,
5339                                         Declarator &D);
5340 
5341   bool
5342   CheckSpecializationInstantiationRedecl(SourceLocation NewLoc,
5343                                          TemplateSpecializationKind NewTSK,
5344                                          NamedDecl *PrevDecl,
5345                                          TemplateSpecializationKind PrevTSK,
5346                                          SourceLocation PrevPtOfInstantiation,
5347                                          bool &SuppressNew);
5348 
5349   bool CheckDependentFunctionTemplateSpecialization(FunctionDecl *FD,
5350                     const TemplateArgumentListInfo &ExplicitTemplateArgs,
5351                                                     LookupResult &Previous);
5352 
5353   bool CheckFunctionTemplateSpecialization(FunctionDecl *FD,
5354                          TemplateArgumentListInfo *ExplicitTemplateArgs,
5355                                            LookupResult &Previous);
5356   bool CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous);
5357 
5358   DeclResult
5359   ActOnExplicitInstantiation(Scope *S,
5360                              SourceLocation ExternLoc,
5361                              SourceLocation TemplateLoc,
5362                              unsigned TagSpec,
5363                              SourceLocation KWLoc,
5364                              const CXXScopeSpec &SS,
5365                              TemplateTy Template,
5366                              SourceLocation TemplateNameLoc,
5367                              SourceLocation LAngleLoc,
5368                              ASTTemplateArgsPtr TemplateArgs,
5369                              SourceLocation RAngleLoc,
5370                              AttributeList *Attr);
5371 
5372   DeclResult
5373   ActOnExplicitInstantiation(Scope *S,
5374                              SourceLocation ExternLoc,
5375                              SourceLocation TemplateLoc,
5376                              unsigned TagSpec,
5377                              SourceLocation KWLoc,
5378                              CXXScopeSpec &SS,
5379                              IdentifierInfo *Name,
5380                              SourceLocation NameLoc,
5381                              AttributeList *Attr);
5382 
5383   DeclResult ActOnExplicitInstantiation(Scope *S,
5384                                         SourceLocation ExternLoc,
5385                                         SourceLocation TemplateLoc,
5386                                         Declarator &D);
5387 
5388   TemplateArgumentLoc
5389   SubstDefaultTemplateArgumentIfAvailable(TemplateDecl *Template,
5390                                           SourceLocation TemplateLoc,
5391                                           SourceLocation RAngleLoc,
5392                                           Decl *Param,
5393                                           SmallVectorImpl<TemplateArgument>
5394                                             &Converted,
5395                                           bool &HasDefaultArg);
5396 
5397   /// \brief Specifies the context in which a particular template
5398   /// argument is being checked.
5399   enum CheckTemplateArgumentKind {
5400     /// \brief The template argument was specified in the code or was
5401     /// instantiated with some deduced template arguments.
5402     CTAK_Specified,
5403 
5404     /// \brief The template argument was deduced via template argument
5405     /// deduction.
5406     CTAK_Deduced,
5407 
5408     /// \brief The template argument was deduced from an array bound
5409     /// via template argument deduction.
5410     CTAK_DeducedFromArrayBound
5411   };
5412 
5413   bool CheckTemplateArgument(NamedDecl *Param,
5414                              TemplateArgumentLoc &Arg,
5415                              NamedDecl *Template,
5416                              SourceLocation TemplateLoc,
5417                              SourceLocation RAngleLoc,
5418                              unsigned ArgumentPackIndex,
5419                            SmallVectorImpl<TemplateArgument> &Converted,
5420                              CheckTemplateArgumentKind CTAK = CTAK_Specified);
5421 
5422   /// \brief Check that the given template arguments can be be provided to
5423   /// the given template, converting the arguments along the way.
5424   ///
5425   /// \param Template The template to which the template arguments are being
5426   /// provided.
5427   ///
5428   /// \param TemplateLoc The location of the template name in the source.
5429   ///
5430   /// \param TemplateArgs The list of template arguments. If the template is
5431   /// a template template parameter, this function may extend the set of
5432   /// template arguments to also include substituted, defaulted template
5433   /// arguments.
5434   ///
5435   /// \param PartialTemplateArgs True if the list of template arguments is
5436   /// intentionally partial, e.g., because we're checking just the initial
5437   /// set of template arguments.
5438   ///
5439   /// \param Converted Will receive the converted, canonicalized template
5440   /// arguments.
5441   ///
5442   /// \returns true if an error occurred, false otherwise.
5443   bool CheckTemplateArgumentList(TemplateDecl *Template,
5444                                  SourceLocation TemplateLoc,
5445                                  TemplateArgumentListInfo &TemplateArgs,
5446                                  bool PartialTemplateArgs,
5447                            SmallVectorImpl<TemplateArgument> &Converted);
5448 
5449   bool CheckTemplateTypeArgument(TemplateTypeParmDecl *Param,
5450                                  TemplateArgumentLoc &Arg,
5451                            SmallVectorImpl<TemplateArgument> &Converted);
5452 
5453   bool CheckTemplateArgument(TemplateTypeParmDecl *Param,
5454                              TypeSourceInfo *Arg);
5455   ExprResult CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
5456                                    QualType InstantiatedParamType, Expr *Arg,
5457                                    TemplateArgument &Converted,
5458                                CheckTemplateArgumentKind CTAK = CTAK_Specified);
5459   bool CheckTemplateArgument(TemplateTemplateParmDecl *Param,
5460                              TemplateArgumentLoc &Arg,
5461                              unsigned ArgumentPackIndex);
5462 
5463   ExprResult
5464   BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg,
5465                                           QualType ParamType,
5466                                           SourceLocation Loc);
5467   ExprResult
5468   BuildExpressionFromIntegralTemplateArgument(const TemplateArgument &Arg,
5469                                               SourceLocation Loc);
5470 
5471   /// \brief Enumeration describing how template parameter lists are compared
5472   /// for equality.
5473   enum TemplateParameterListEqualKind {
5474     /// \brief We are matching the template parameter lists of two templates
5475     /// that might be redeclarations.
5476     ///
5477     /// \code
5478     /// template<typename T> struct X;
5479     /// template<typename T> struct X;
5480     /// \endcode
5481     TPL_TemplateMatch,
5482 
5483     /// \brief We are matching the template parameter lists of two template
5484     /// template parameters as part of matching the template parameter lists
5485     /// of two templates that might be redeclarations.
5486     ///
5487     /// \code
5488     /// template<template<int I> class TT> struct X;
5489     /// template<template<int Value> class Other> struct X;
5490     /// \endcode
5491     TPL_TemplateTemplateParmMatch,
5492 
5493     /// \brief We are matching the template parameter lists of a template
5494     /// template argument against the template parameter lists of a template
5495     /// template parameter.
5496     ///
5497     /// \code
5498     /// template<template<int Value> class Metafun> struct X;
5499     /// template<int Value> struct integer_c;
5500     /// X<integer_c> xic;
5501     /// \endcode
5502     TPL_TemplateTemplateArgumentMatch
5503   };
5504 
5505   bool TemplateParameterListsAreEqual(TemplateParameterList *New,
5506                                       TemplateParameterList *Old,
5507                                       bool Complain,
5508                                       TemplateParameterListEqualKind Kind,
5509                                       SourceLocation TemplateArgLoc
5510                                         = SourceLocation());
5511 
5512   bool CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams);
5513 
5514   /// \brief Called when the parser has parsed a C++ typename
5515   /// specifier, e.g., "typename T::type".
5516   ///
5517   /// \param S The scope in which this typename type occurs.
5518   /// \param TypenameLoc the location of the 'typename' keyword
5519   /// \param SS the nested-name-specifier following the typename (e.g., 'T::').
5520   /// \param II the identifier we're retrieving (e.g., 'type' in the example).
5521   /// \param IdLoc the location of the identifier.
5522   TypeResult
5523   ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
5524                     const CXXScopeSpec &SS, const IdentifierInfo &II,
5525                     SourceLocation IdLoc);
5526 
5527   /// \brief Called when the parser has parsed a C++ typename
5528   /// specifier that ends in a template-id, e.g.,
5529   /// "typename MetaFun::template apply<T1, T2>".
5530   ///
5531   /// \param S The scope in which this typename type occurs.
5532   /// \param TypenameLoc the location of the 'typename' keyword
5533   /// \param SS the nested-name-specifier following the typename (e.g., 'T::').
5534   /// \param TemplateLoc the location of the 'template' keyword, if any.
5535   /// \param TemplateName The template name.
5536   /// \param TemplateNameLoc The location of the template name.
5537   /// \param LAngleLoc The location of the opening angle bracket  ('<').
5538   /// \param TemplateArgs The template arguments.
5539   /// \param RAngleLoc The location of the closing angle bracket  ('>').
5540   TypeResult
5541   ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
5542                     const CXXScopeSpec &SS,
5543                     SourceLocation TemplateLoc,
5544                     TemplateTy TemplateName,
5545                     SourceLocation TemplateNameLoc,
5546                     SourceLocation LAngleLoc,
5547                     ASTTemplateArgsPtr TemplateArgs,
5548                     SourceLocation RAngleLoc);
5549 
5550   QualType CheckTypenameType(ElaboratedTypeKeyword Keyword,
5551                              SourceLocation KeywordLoc,
5552                              NestedNameSpecifierLoc QualifierLoc,
5553                              const IdentifierInfo &II,
5554                              SourceLocation IILoc);
5555 
5556   TypeSourceInfo *RebuildTypeInCurrentInstantiation(TypeSourceInfo *T,
5557                                                     SourceLocation Loc,
5558                                                     DeclarationName Name);
5559   bool RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS);
5560 
5561   ExprResult RebuildExprInCurrentInstantiation(Expr *E);
5562   bool RebuildTemplateParamsInCurrentInstantiation(
5563                                                 TemplateParameterList *Params);
5564 
5565   std::string
5566   getTemplateArgumentBindingsText(const TemplateParameterList *Params,
5567                                   const TemplateArgumentList &Args);
5568 
5569   std::string
5570   getTemplateArgumentBindingsText(const TemplateParameterList *Params,
5571                                   const TemplateArgument *Args,
5572                                   unsigned NumArgs);
5573 
5574   //===--------------------------------------------------------------------===//
5575   // C++ Variadic Templates (C++0x [temp.variadic])
5576   //===--------------------------------------------------------------------===//
5577 
5578   /// \brief The context in which an unexpanded parameter pack is
5579   /// being diagnosed.
5580   ///
5581   /// Note that the values of this enumeration line up with the first
5582   /// argument to the \c err_unexpanded_parameter_pack diagnostic.
5583   enum UnexpandedParameterPackContext {
5584     /// \brief An arbitrary expression.
5585     UPPC_Expression = 0,
5586 
5587     /// \brief The base type of a class type.
5588     UPPC_BaseType,
5589 
5590     /// \brief The type of an arbitrary declaration.
5591     UPPC_DeclarationType,
5592 
5593     /// \brief The type of a data member.
5594     UPPC_DataMemberType,
5595 
5596     /// \brief The size of a bit-field.
5597     UPPC_BitFieldWidth,
5598 
5599     /// \brief The expression in a static assertion.
5600     UPPC_StaticAssertExpression,
5601 
5602     /// \brief The fixed underlying type of an enumeration.
5603     UPPC_FixedUnderlyingType,
5604 
5605     /// \brief The enumerator value.
5606     UPPC_EnumeratorValue,
5607 
5608     /// \brief A using declaration.
5609     UPPC_UsingDeclaration,
5610 
5611     /// \brief A friend declaration.
5612     UPPC_FriendDeclaration,
5613 
5614     /// \brief A declaration qualifier.
5615     UPPC_DeclarationQualifier,
5616 
5617     /// \brief An initializer.
5618     UPPC_Initializer,
5619 
5620     /// \brief A default argument.
5621     UPPC_DefaultArgument,
5622 
5623     /// \brief The type of a non-type template parameter.
5624     UPPC_NonTypeTemplateParameterType,
5625 
5626     /// \brief The type of an exception.
5627     UPPC_ExceptionType,
5628 
5629     /// \brief Partial specialization.
5630     UPPC_PartialSpecialization,
5631 
5632     /// \brief Microsoft __if_exists.
5633     UPPC_IfExists,
5634 
5635     /// \brief Microsoft __if_not_exists.
5636     UPPC_IfNotExists,
5637 
5638     /// \brief Lambda expression.
5639     UPPC_Lambda,
5640 
5641     /// \brief Block expression,
5642     UPPC_Block
5643   };
5644 
5645   /// \brief Diagnose unexpanded parameter packs.
5646   ///
5647   /// \param Loc The location at which we should emit the diagnostic.
5648   ///
5649   /// \param UPPC The context in which we are diagnosing unexpanded
5650   /// parameter packs.
5651   ///
5652   /// \param Unexpanded the set of unexpanded parameter packs.
5653   ///
5654   /// \returns true if an error occurred, false otherwise.
5655   bool DiagnoseUnexpandedParameterPacks(SourceLocation Loc,
5656                                         UnexpandedParameterPackContext UPPC,
5657                                   ArrayRef<UnexpandedParameterPack> Unexpanded);
5658 
5659   /// \brief If the given type contains an unexpanded parameter pack,
5660   /// diagnose the error.
5661   ///
5662   /// \param Loc The source location where a diagnostc should be emitted.
5663   ///
5664   /// \param T The type that is being checked for unexpanded parameter
5665   /// packs.
5666   ///
5667   /// \returns true if an error occurred, false otherwise.
5668   bool DiagnoseUnexpandedParameterPack(SourceLocation Loc, TypeSourceInfo *T,
5669                                        UnexpandedParameterPackContext UPPC);
5670 
5671   /// \brief If the given expression contains an unexpanded parameter
5672   /// pack, diagnose the error.
5673   ///
5674   /// \param E The expression that is being checked for unexpanded
5675   /// parameter packs.
5676   ///
5677   /// \returns true if an error occurred, false otherwise.
5678   bool DiagnoseUnexpandedParameterPack(Expr *E,
5679                        UnexpandedParameterPackContext UPPC = UPPC_Expression);
5680 
5681   /// \brief If the given nested-name-specifier contains an unexpanded
5682   /// parameter pack, diagnose the error.
5683   ///
5684   /// \param SS The nested-name-specifier that is being checked for
5685   /// unexpanded parameter packs.
5686   ///
5687   /// \returns true if an error occurred, false otherwise.
5688   bool DiagnoseUnexpandedParameterPack(const CXXScopeSpec &SS,
5689                                        UnexpandedParameterPackContext UPPC);
5690 
5691   /// \brief If the given name contains an unexpanded parameter pack,
5692   /// diagnose the error.
5693   ///
5694   /// \param NameInfo The name (with source location information) that
5695   /// is being checked for unexpanded parameter packs.
5696   ///
5697   /// \returns true if an error occurred, false otherwise.
5698   bool DiagnoseUnexpandedParameterPack(const DeclarationNameInfo &NameInfo,
5699                                        UnexpandedParameterPackContext UPPC);
5700 
5701   /// \brief If the given template name contains an unexpanded parameter pack,
5702   /// diagnose the error.
5703   ///
5704   /// \param Loc The location of the template name.
5705   ///
5706   /// \param Template The template name that is being checked for unexpanded
5707   /// parameter packs.
5708   ///
5709   /// \returns true if an error occurred, false otherwise.
5710   bool DiagnoseUnexpandedParameterPack(SourceLocation Loc,
5711                                        TemplateName Template,
5712                                        UnexpandedParameterPackContext UPPC);
5713 
5714   /// \brief If the given template argument contains an unexpanded parameter
5715   /// pack, diagnose the error.
5716   ///
5717   /// \param Arg The template argument that is being checked for unexpanded
5718   /// parameter packs.
5719   ///
5720   /// \returns true if an error occurred, false otherwise.
5721   bool DiagnoseUnexpandedParameterPack(TemplateArgumentLoc Arg,
5722                                        UnexpandedParameterPackContext UPPC);
5723 
5724   /// \brief Collect the set of unexpanded parameter packs within the given
5725   /// template argument.
5726   ///
5727   /// \param Arg The template argument that will be traversed to find
5728   /// unexpanded parameter packs.
5729   void collectUnexpandedParameterPacks(TemplateArgument Arg,
5730                    SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
5731 
5732   /// \brief Collect the set of unexpanded parameter packs within the given
5733   /// template argument.
5734   ///
5735   /// \param Arg The template argument that will be traversed to find
5736   /// unexpanded parameter packs.
5737   void collectUnexpandedParameterPacks(TemplateArgumentLoc Arg,
5738                     SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
5739 
5740   /// \brief Collect the set of unexpanded parameter packs within the given
5741   /// type.
5742   ///
5743   /// \param T The type that will be traversed to find
5744   /// unexpanded parameter packs.
5745   void collectUnexpandedParameterPacks(QualType T,
5746                    SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
5747 
5748   /// \brief Collect the set of unexpanded parameter packs within the given
5749   /// type.
5750   ///
5751   /// \param TL The type that will be traversed to find
5752   /// unexpanded parameter packs.
5753   void collectUnexpandedParameterPacks(TypeLoc TL,
5754                    SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
5755 
5756   /// \brief Collect the set of unexpanded parameter packs within the given
5757   /// nested-name-specifier.
5758   ///
5759   /// \param SS The nested-name-specifier that will be traversed to find
5760   /// unexpanded parameter packs.
5761   void collectUnexpandedParameterPacks(CXXScopeSpec &SS,
5762                          SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
5763 
5764   /// \brief Collect the set of unexpanded parameter packs within the given
5765   /// name.
5766   ///
5767   /// \param NameInfo The name that will be traversed to find
5768   /// unexpanded parameter packs.
5769   void collectUnexpandedParameterPacks(const DeclarationNameInfo &NameInfo,
5770                          SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
5771 
5772   /// \brief Invoked when parsing a template argument followed by an
5773   /// ellipsis, which creates a pack expansion.
5774   ///
5775   /// \param Arg The template argument preceding the ellipsis, which
5776   /// may already be invalid.
5777   ///
5778   /// \param EllipsisLoc The location of the ellipsis.
5779   ParsedTemplateArgument ActOnPackExpansion(const ParsedTemplateArgument &Arg,
5780                                             SourceLocation EllipsisLoc);
5781 
5782   /// \brief Invoked when parsing a type followed by an ellipsis, which
5783   /// creates a pack expansion.
5784   ///
5785   /// \param Type The type preceding the ellipsis, which will become
5786   /// the pattern of the pack expansion.
5787   ///
5788   /// \param EllipsisLoc The location of the ellipsis.
5789   TypeResult ActOnPackExpansion(ParsedType Type, SourceLocation EllipsisLoc);
5790 
5791   /// \brief Construct a pack expansion type from the pattern of the pack
5792   /// expansion.
5793   TypeSourceInfo *CheckPackExpansion(TypeSourceInfo *Pattern,
5794                                      SourceLocation EllipsisLoc,
5795                                      Optional<unsigned> NumExpansions);
5796 
5797   /// \brief Construct a pack expansion type from the pattern of the pack
5798   /// expansion.
5799   QualType CheckPackExpansion(QualType Pattern,
5800                               SourceRange PatternRange,
5801                               SourceLocation EllipsisLoc,
5802                               Optional<unsigned> NumExpansions);
5803 
5804   /// \brief Invoked when parsing an expression followed by an ellipsis, which
5805   /// creates a pack expansion.
5806   ///
5807   /// \param Pattern The expression preceding the ellipsis, which will become
5808   /// the pattern of the pack expansion.
5809   ///
5810   /// \param EllipsisLoc The location of the ellipsis.
5811   ExprResult ActOnPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc);
5812 
5813   /// \brief Invoked when parsing an expression followed by an ellipsis, which
5814   /// creates a pack expansion.
5815   ///
5816   /// \param Pattern The expression preceding the ellipsis, which will become
5817   /// the pattern of the pack expansion.
5818   ///
5819   /// \param EllipsisLoc The location of the ellipsis.
5820   ExprResult CheckPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc,
5821                                 Optional<unsigned> NumExpansions);
5822 
5823   /// \brief Determine whether we could expand a pack expansion with the
5824   /// given set of parameter packs into separate arguments by repeatedly
5825   /// transforming the pattern.
5826   ///
5827   /// \param EllipsisLoc The location of the ellipsis that identifies the
5828   /// pack expansion.
5829   ///
5830   /// \param PatternRange The source range that covers the entire pattern of
5831   /// the pack expansion.
5832   ///
5833   /// \param Unexpanded The set of unexpanded parameter packs within the
5834   /// pattern.
5835   ///
5836   /// \param ShouldExpand Will be set to \c true if the transformer should
5837   /// expand the corresponding pack expansions into separate arguments. When
5838   /// set, \c NumExpansions must also be set.
5839   ///
5840   /// \param RetainExpansion Whether the caller should add an unexpanded
5841   /// pack expansion after all of the expanded arguments. This is used
5842   /// when extending explicitly-specified template argument packs per
5843   /// C++0x [temp.arg.explicit]p9.
5844   ///
5845   /// \param NumExpansions The number of separate arguments that will be in
5846   /// the expanded form of the corresponding pack expansion. This is both an
5847   /// input and an output parameter, which can be set by the caller if the
5848   /// number of expansions is known a priori (e.g., due to a prior substitution)
5849   /// and will be set by the callee when the number of expansions is known.
5850   /// The callee must set this value when \c ShouldExpand is \c true; it may
5851   /// set this value in other cases.
5852   ///
5853   /// \returns true if an error occurred (e.g., because the parameter packs
5854   /// are to be instantiated with arguments of different lengths), false
5855   /// otherwise. If false, \c ShouldExpand (and possibly \c NumExpansions)
5856   /// must be set.
5857   bool CheckParameterPacksForExpansion(SourceLocation EllipsisLoc,
5858                                        SourceRange PatternRange,
5859                              ArrayRef<UnexpandedParameterPack> Unexpanded,
5860                              const MultiLevelTemplateArgumentList &TemplateArgs,
5861                                        bool &ShouldExpand,
5862                                        bool &RetainExpansion,
5863                                        Optional<unsigned> &NumExpansions);
5864 
5865   /// \brief Determine the number of arguments in the given pack expansion
5866   /// type.
5867   ///
5868   /// This routine assumes that the number of arguments in the expansion is
5869   /// consistent across all of the unexpanded parameter packs in its pattern.
5870   ///
5871   /// Returns an empty Optional if the type can't be expanded.
5872   Optional<unsigned> getNumArgumentsInExpansion(QualType T,
5873       const MultiLevelTemplateArgumentList &TemplateArgs);
5874 
5875   /// \brief Determine whether the given declarator contains any unexpanded
5876   /// parameter packs.
5877   ///
5878   /// This routine is used by the parser to disambiguate function declarators
5879   /// with an ellipsis prior to the ')', e.g.,
5880   ///
5881   /// \code
5882   ///   void f(T...);
5883   /// \endcode
5884   ///
5885   /// To determine whether we have an (unnamed) function parameter pack or
5886   /// a variadic function.
5887   ///
5888   /// \returns true if the declarator contains any unexpanded parameter packs,
5889   /// false otherwise.
5890   bool containsUnexpandedParameterPacks(Declarator &D);
5891 
5892   /// \brief Returns the pattern of the pack expansion for a template argument.
5893   ///
5894   /// \param OrigLoc The template argument to expand.
5895   ///
5896   /// \param Ellipsis Will be set to the location of the ellipsis.
5897   ///
5898   /// \param NumExpansions Will be set to the number of expansions that will
5899   /// be generated from this pack expansion, if known a priori.
5900   TemplateArgumentLoc getTemplateArgumentPackExpansionPattern(
5901       TemplateArgumentLoc OrigLoc,
5902       SourceLocation &Ellipsis,
5903       Optional<unsigned> &NumExpansions) const;
5904 
5905   //===--------------------------------------------------------------------===//
5906   // C++ Template Argument Deduction (C++ [temp.deduct])
5907   //===--------------------------------------------------------------------===//
5908 
5909   QualType adjustCCAndNoReturn(QualType ArgFunctionType, QualType FunctionType);
5910 
5911   /// \brief Describes the result of template argument deduction.
5912   ///
5913   /// The TemplateDeductionResult enumeration describes the result of
5914   /// template argument deduction, as returned from
5915   /// DeduceTemplateArguments(). The separate TemplateDeductionInfo
5916   /// structure provides additional information about the results of
5917   /// template argument deduction, e.g., the deduced template argument
5918   /// list (if successful) or the specific template parameters or
5919   /// deduced arguments that were involved in the failure.
5920   enum TemplateDeductionResult {
5921     /// \brief Template argument deduction was successful.
5922     TDK_Success = 0,
5923     /// \brief The declaration was invalid; do nothing.
5924     TDK_Invalid,
5925     /// \brief Template argument deduction exceeded the maximum template
5926     /// instantiation depth (which has already been diagnosed).
5927     TDK_InstantiationDepth,
5928     /// \brief Template argument deduction did not deduce a value
5929     /// for every template parameter.
5930     TDK_Incomplete,
5931     /// \brief Template argument deduction produced inconsistent
5932     /// deduced values for the given template parameter.
5933     TDK_Inconsistent,
5934     /// \brief Template argument deduction failed due to inconsistent
5935     /// cv-qualifiers on a template parameter type that would
5936     /// otherwise be deduced, e.g., we tried to deduce T in "const T"
5937     /// but were given a non-const "X".
5938     TDK_Underqualified,
5939     /// \brief Substitution of the deduced template argument values
5940     /// resulted in an error.
5941     TDK_SubstitutionFailure,
5942     /// \brief A non-depnedent component of the parameter did not match the
5943     /// corresponding component of the argument.
5944     TDK_NonDeducedMismatch,
5945     /// \brief When performing template argument deduction for a function
5946     /// template, there were too many call arguments.
5947     TDK_TooManyArguments,
5948     /// \brief When performing template argument deduction for a function
5949     /// template, there were too few call arguments.
5950     TDK_TooFewArguments,
5951     /// \brief The explicitly-specified template arguments were not valid
5952     /// template arguments for the given template.
5953     TDK_InvalidExplicitArguments,
5954     /// \brief The arguments included an overloaded function name that could
5955     /// not be resolved to a suitable function.
5956     TDK_FailedOverloadResolution,
5957     /// \brief Deduction failed; that's all we know.
5958     TDK_MiscellaneousDeductionFailure
5959   };
5960 
5961   TemplateDeductionResult
5962   DeduceTemplateArguments(ClassTemplatePartialSpecializationDecl *Partial,
5963                           const TemplateArgumentList &TemplateArgs,
5964                           sema::TemplateDeductionInfo &Info);
5965 
5966   TemplateDeductionResult
5967   DeduceTemplateArguments(VarTemplatePartialSpecializationDecl *Partial,
5968                           const TemplateArgumentList &TemplateArgs,
5969                           sema::TemplateDeductionInfo &Info);
5970 
5971   TemplateDeductionResult SubstituteExplicitTemplateArguments(
5972       FunctionTemplateDecl *FunctionTemplate,
5973       TemplateArgumentListInfo &ExplicitTemplateArgs,
5974       SmallVectorImpl<DeducedTemplateArgument> &Deduced,
5975       SmallVectorImpl<QualType> &ParamTypes, QualType *FunctionType,
5976       sema::TemplateDeductionInfo &Info);
5977 
5978   /// brief A function argument from which we performed template argument
5979   // deduction for a call.
5980   struct OriginalCallArg {
OriginalCallArgOriginalCallArg5981     OriginalCallArg(QualType OriginalParamType,
5982                     unsigned ArgIdx,
5983                     QualType OriginalArgType)
5984       : OriginalParamType(OriginalParamType), ArgIdx(ArgIdx),
5985         OriginalArgType(OriginalArgType) { }
5986 
5987     QualType OriginalParamType;
5988     unsigned ArgIdx;
5989     QualType OriginalArgType;
5990   };
5991 
5992   TemplateDeductionResult
5993   FinishTemplateArgumentDeduction(FunctionTemplateDecl *FunctionTemplate,
5994                       SmallVectorImpl<DeducedTemplateArgument> &Deduced,
5995                                   unsigned NumExplicitlySpecified,
5996                                   FunctionDecl *&Specialization,
5997                                   sema::TemplateDeductionInfo &Info,
5998            SmallVectorImpl<OriginalCallArg> const *OriginalCallArgs = nullptr);
5999 
6000   TemplateDeductionResult
6001   DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
6002                           TemplateArgumentListInfo *ExplicitTemplateArgs,
6003                           ArrayRef<Expr *> Args,
6004                           FunctionDecl *&Specialization,
6005                           sema::TemplateDeductionInfo &Info);
6006 
6007   TemplateDeductionResult
6008   DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
6009                           TemplateArgumentListInfo *ExplicitTemplateArgs,
6010                           QualType ArgFunctionType,
6011                           FunctionDecl *&Specialization,
6012                           sema::TemplateDeductionInfo &Info,
6013                           bool InOverloadResolution = false);
6014 
6015   TemplateDeductionResult
6016   DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
6017                           QualType ToType,
6018                           CXXConversionDecl *&Specialization,
6019                           sema::TemplateDeductionInfo &Info);
6020 
6021   TemplateDeductionResult
6022   DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
6023                           TemplateArgumentListInfo *ExplicitTemplateArgs,
6024                           FunctionDecl *&Specialization,
6025                           sema::TemplateDeductionInfo &Info,
6026                           bool InOverloadResolution = false);
6027 
6028   /// \brief Substitute Replacement for \p auto in \p TypeWithAuto
6029   QualType SubstAutoType(QualType TypeWithAuto, QualType Replacement);
6030   /// \brief Substitute Replacement for auto in TypeWithAuto
6031   TypeSourceInfo* SubstAutoTypeSourceInfo(TypeSourceInfo *TypeWithAuto,
6032                                           QualType Replacement);
6033 
6034   /// \brief Result type of DeduceAutoType.
6035   enum DeduceAutoResult {
6036     DAR_Succeeded,
6037     DAR_Failed,
6038     DAR_FailedAlreadyDiagnosed
6039   };
6040 
6041   DeduceAutoResult DeduceAutoType(TypeSourceInfo *AutoType, Expr *&Initializer,
6042                                   QualType &Result);
6043   DeduceAutoResult DeduceAutoType(TypeLoc AutoTypeLoc, Expr *&Initializer,
6044                                   QualType &Result);
6045   void DiagnoseAutoDeductionFailure(VarDecl *VDecl, Expr *Init);
6046   bool DeduceReturnType(FunctionDecl *FD, SourceLocation Loc,
6047                         bool Diagnose = true);
6048 
6049   bool DeduceFunctionTypeFromReturnExpr(FunctionDecl *FD,
6050                                         SourceLocation ReturnLoc,
6051                                         Expr *&RetExpr, AutoType *AT);
6052 
6053   FunctionTemplateDecl *getMoreSpecializedTemplate(FunctionTemplateDecl *FT1,
6054                                                    FunctionTemplateDecl *FT2,
6055                                                    SourceLocation Loc,
6056                                            TemplatePartialOrderingContext TPOC,
6057                                                    unsigned NumCallArguments1,
6058                                                    unsigned NumCallArguments2);
6059   UnresolvedSetIterator
6060   getMostSpecialized(UnresolvedSetIterator SBegin, UnresolvedSetIterator SEnd,
6061                      TemplateSpecCandidateSet &FailedCandidates,
6062                      SourceLocation Loc,
6063                      const PartialDiagnostic &NoneDiag,
6064                      const PartialDiagnostic &AmbigDiag,
6065                      const PartialDiagnostic &CandidateDiag,
6066                      bool Complain = true, QualType TargetType = QualType());
6067 
6068   ClassTemplatePartialSpecializationDecl *
6069   getMoreSpecializedPartialSpecialization(
6070                                   ClassTemplatePartialSpecializationDecl *PS1,
6071                                   ClassTemplatePartialSpecializationDecl *PS2,
6072                                   SourceLocation Loc);
6073 
6074   VarTemplatePartialSpecializationDecl *getMoreSpecializedPartialSpecialization(
6075       VarTemplatePartialSpecializationDecl *PS1,
6076       VarTemplatePartialSpecializationDecl *PS2, SourceLocation Loc);
6077 
6078   void MarkUsedTemplateParameters(const TemplateArgumentList &TemplateArgs,
6079                                   bool OnlyDeduced,
6080                                   unsigned Depth,
6081                                   llvm::SmallBitVector &Used);
MarkDeducedTemplateParameters(const FunctionTemplateDecl * FunctionTemplate,llvm::SmallBitVector & Deduced)6082   void MarkDeducedTemplateParameters(
6083                                   const FunctionTemplateDecl *FunctionTemplate,
6084                                   llvm::SmallBitVector &Deduced) {
6085     return MarkDeducedTemplateParameters(Context, FunctionTemplate, Deduced);
6086   }
6087   static void MarkDeducedTemplateParameters(ASTContext &Ctx,
6088                                   const FunctionTemplateDecl *FunctionTemplate,
6089                                   llvm::SmallBitVector &Deduced);
6090 
6091   //===--------------------------------------------------------------------===//
6092   // C++ Template Instantiation
6093   //
6094 
6095   MultiLevelTemplateArgumentList
6096   getTemplateInstantiationArgs(NamedDecl *D,
6097                                const TemplateArgumentList *Innermost = nullptr,
6098                                bool RelativeToPrimary = false,
6099                                const FunctionDecl *Pattern = nullptr);
6100 
6101   /// \brief A template instantiation that is currently in progress.
6102   struct ActiveTemplateInstantiation {
6103     /// \brief The kind of template instantiation we are performing
6104     enum InstantiationKind {
6105       /// We are instantiating a template declaration. The entity is
6106       /// the declaration we're instantiating (e.g., a CXXRecordDecl).
6107       TemplateInstantiation,
6108 
6109       /// We are instantiating a default argument for a template
6110       /// parameter. The Entity is the template, and
6111       /// TemplateArgs/NumTemplateArguments provides the template
6112       /// arguments as specified.
6113       /// FIXME: Use a TemplateArgumentList
6114       DefaultTemplateArgumentInstantiation,
6115 
6116       /// We are instantiating a default argument for a function.
6117       /// The Entity is the ParmVarDecl, and TemplateArgs/NumTemplateArgs
6118       /// provides the template arguments as specified.
6119       DefaultFunctionArgumentInstantiation,
6120 
6121       /// We are substituting explicit template arguments provided for
6122       /// a function template. The entity is a FunctionTemplateDecl.
6123       ExplicitTemplateArgumentSubstitution,
6124 
6125       /// We are substituting template argument determined as part of
6126       /// template argument deduction for either a class template
6127       /// partial specialization or a function template. The
6128       /// Entity is either a ClassTemplatePartialSpecializationDecl or
6129       /// a FunctionTemplateDecl.
6130       DeducedTemplateArgumentSubstitution,
6131 
6132       /// We are substituting prior template arguments into a new
6133       /// template parameter. The template parameter itself is either a
6134       /// NonTypeTemplateParmDecl or a TemplateTemplateParmDecl.
6135       PriorTemplateArgumentSubstitution,
6136 
6137       /// We are checking the validity of a default template argument that
6138       /// has been used when naming a template-id.
6139       DefaultTemplateArgumentChecking,
6140 
6141       /// We are instantiating the exception specification for a function
6142       /// template which was deferred until it was needed.
6143       ExceptionSpecInstantiation
6144     } Kind;
6145 
6146     /// \brief The point of instantiation within the source code.
6147     SourceLocation PointOfInstantiation;
6148 
6149     /// \brief The template (or partial specialization) in which we are
6150     /// performing the instantiation, for substitutions of prior template
6151     /// arguments.
6152     NamedDecl *Template;
6153 
6154     /// \brief The entity that is being instantiated.
6155     Decl *Entity;
6156 
6157     /// \brief The list of template arguments we are substituting, if they
6158     /// are not part of the entity.
6159     const TemplateArgument *TemplateArgs;
6160 
6161     /// \brief The number of template arguments in TemplateArgs.
6162     unsigned NumTemplateArgs;
6163 
6164     /// \brief The template deduction info object associated with the
6165     /// substitution or checking of explicit or deduced template arguments.
6166     sema::TemplateDeductionInfo *DeductionInfo;
6167 
6168     /// \brief The source range that covers the construct that cause
6169     /// the instantiation, e.g., the template-id that causes a class
6170     /// template instantiation.
6171     SourceRange InstantiationRange;
6172 
ActiveTemplateInstantiationActiveTemplateInstantiation6173     ActiveTemplateInstantiation()
6174       : Kind(TemplateInstantiation), Template(nullptr), Entity(nullptr),
6175         TemplateArgs(nullptr), NumTemplateArgs(0), DeductionInfo(nullptr) {}
6176 
6177     /// \brief Determines whether this template is an actual instantiation
6178     /// that should be counted toward the maximum instantiation depth.
6179     bool isInstantiationRecord() const;
6180 
6181     friend bool operator==(const ActiveTemplateInstantiation &X,
6182                            const ActiveTemplateInstantiation &Y) {
6183       if (X.Kind != Y.Kind)
6184         return false;
6185 
6186       if (X.Entity != Y.Entity)
6187         return false;
6188 
6189       switch (X.Kind) {
6190       case TemplateInstantiation:
6191       case ExceptionSpecInstantiation:
6192         return true;
6193 
6194       case PriorTemplateArgumentSubstitution:
6195       case DefaultTemplateArgumentChecking:
6196         return X.Template == Y.Template && X.TemplateArgs == Y.TemplateArgs;
6197 
6198       case DefaultTemplateArgumentInstantiation:
6199       case ExplicitTemplateArgumentSubstitution:
6200       case DeducedTemplateArgumentSubstitution:
6201       case DefaultFunctionArgumentInstantiation:
6202         return X.TemplateArgs == Y.TemplateArgs;
6203 
6204       }
6205 
6206       llvm_unreachable("Invalid InstantiationKind!");
6207     }
6208 
6209     friend bool operator!=(const ActiveTemplateInstantiation &X,
6210                            const ActiveTemplateInstantiation &Y) {
6211       return !(X == Y);
6212     }
6213   };
6214 
6215   /// \brief List of active template instantiations.
6216   ///
6217   /// This vector is treated as a stack. As one template instantiation
6218   /// requires another template instantiation, additional
6219   /// instantiations are pushed onto the stack up to a
6220   /// user-configurable limit LangOptions::InstantiationDepth.
6221   SmallVector<ActiveTemplateInstantiation, 16>
6222     ActiveTemplateInstantiations;
6223 
6224   /// \brief Extra modules inspected when performing a lookup during a template
6225   /// instantiation. Computed lazily.
6226   SmallVector<Module*, 16> ActiveTemplateInstantiationLookupModules;
6227 
6228   /// \brief Cache of additional modules that should be used for name lookup
6229   /// within the current template instantiation. Computed lazily; use
6230   /// getLookupModules() to get a complete set.
6231   llvm::DenseSet<Module*> LookupModulesCache;
6232 
6233   /// \brief Get the set of additional modules that should be checked during
6234   /// name lookup. A module and its imports become visible when instanting a
6235   /// template defined within it.
6236   llvm::DenseSet<Module*> &getLookupModules();
6237 
6238   /// \brief Whether we are in a SFINAE context that is not associated with
6239   /// template instantiation.
6240   ///
6241   /// This is used when setting up a SFINAE trap (\c see SFINAETrap) outside
6242   /// of a template instantiation or template argument deduction.
6243   bool InNonInstantiationSFINAEContext;
6244 
6245   /// \brief The number of ActiveTemplateInstantiation entries in
6246   /// \c ActiveTemplateInstantiations that are not actual instantiations and,
6247   /// therefore, should not be counted as part of the instantiation depth.
6248   unsigned NonInstantiationEntries;
6249 
6250   /// \brief The last template from which a template instantiation
6251   /// error or warning was produced.
6252   ///
6253   /// This value is used to suppress printing of redundant template
6254   /// instantiation backtraces when there are multiple errors in the
6255   /// same instantiation. FIXME: Does this belong in Sema? It's tough
6256   /// to implement it anywhere else.
6257   ActiveTemplateInstantiation LastTemplateInstantiationErrorContext;
6258 
6259   /// \brief The current index into pack expansion arguments that will be
6260   /// used for substitution of parameter packs.
6261   ///
6262   /// The pack expansion index will be -1 to indicate that parameter packs
6263   /// should be instantiated as themselves. Otherwise, the index specifies
6264   /// which argument within the parameter pack will be used for substitution.
6265   int ArgumentPackSubstitutionIndex;
6266 
6267   /// \brief RAII object used to change the argument pack substitution index
6268   /// within a \c Sema object.
6269   ///
6270   /// See \c ArgumentPackSubstitutionIndex for more information.
6271   class ArgumentPackSubstitutionIndexRAII {
6272     Sema &Self;
6273     int OldSubstitutionIndex;
6274 
6275   public:
ArgumentPackSubstitutionIndexRAII(Sema & Self,int NewSubstitutionIndex)6276     ArgumentPackSubstitutionIndexRAII(Sema &Self, int NewSubstitutionIndex)
6277       : Self(Self), OldSubstitutionIndex(Self.ArgumentPackSubstitutionIndex) {
6278       Self.ArgumentPackSubstitutionIndex = NewSubstitutionIndex;
6279     }
6280 
~ArgumentPackSubstitutionIndexRAII()6281     ~ArgumentPackSubstitutionIndexRAII() {
6282       Self.ArgumentPackSubstitutionIndex = OldSubstitutionIndex;
6283     }
6284   };
6285 
6286   friend class ArgumentPackSubstitutionRAII;
6287 
6288   /// \brief The stack of calls expression undergoing template instantiation.
6289   ///
6290   /// The top of this stack is used by a fixit instantiating unresolved
6291   /// function calls to fix the AST to match the textual change it prints.
6292   SmallVector<CallExpr *, 8> CallsUndergoingInstantiation;
6293 
6294   /// \brief For each declaration that involved template argument deduction, the
6295   /// set of diagnostics that were suppressed during that template argument
6296   /// deduction.
6297   ///
6298   /// FIXME: Serialize this structure to the AST file.
6299   typedef llvm::DenseMap<Decl *, SmallVector<PartialDiagnosticAt, 1> >
6300     SuppressedDiagnosticsMap;
6301   SuppressedDiagnosticsMap SuppressedDiagnostics;
6302 
6303   /// \brief A stack object to be created when performing template
6304   /// instantiation.
6305   ///
6306   /// Construction of an object of type \c InstantiatingTemplate
6307   /// pushes the current instantiation onto the stack of active
6308   /// instantiations. If the size of this stack exceeds the maximum
6309   /// number of recursive template instantiations, construction
6310   /// produces an error and evaluates true.
6311   ///
6312   /// Destruction of this object will pop the named instantiation off
6313   /// the stack.
6314   struct InstantiatingTemplate {
6315     /// \brief Note that we are instantiating a class template,
6316     /// function template, or a member thereof.
6317     InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
6318                           Decl *Entity,
6319                           SourceRange InstantiationRange = SourceRange());
6320 
6321     struct ExceptionSpecification {};
6322     /// \brief Note that we are instantiating an exception specification
6323     /// of a function template.
6324     InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
6325                           FunctionDecl *Entity, ExceptionSpecification,
6326                           SourceRange InstantiationRange = SourceRange());
6327 
6328     /// \brief Note that we are instantiating a default argument in a
6329     /// template-id.
6330     InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
6331                           TemplateDecl *Template,
6332                           ArrayRef<TemplateArgument> TemplateArgs,
6333                           SourceRange InstantiationRange = SourceRange());
6334 
6335     /// \brief Note that we are instantiating a default argument in a
6336     /// template-id.
6337     InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
6338                           FunctionTemplateDecl *FunctionTemplate,
6339                           ArrayRef<TemplateArgument> TemplateArgs,
6340                           ActiveTemplateInstantiation::InstantiationKind Kind,
6341                           sema::TemplateDeductionInfo &DeductionInfo,
6342                           SourceRange InstantiationRange = SourceRange());
6343 
6344     /// \brief Note that we are instantiating as part of template
6345     /// argument deduction for a class template partial
6346     /// specialization.
6347     InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
6348                           ClassTemplatePartialSpecializationDecl *PartialSpec,
6349                           ArrayRef<TemplateArgument> TemplateArgs,
6350                           sema::TemplateDeductionInfo &DeductionInfo,
6351                           SourceRange InstantiationRange = SourceRange());
6352 
6353     /// \brief Note that we are instantiating as part of template
6354     /// argument deduction for a variable template partial
6355     /// specialization.
6356     InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
6357                           VarTemplatePartialSpecializationDecl *PartialSpec,
6358                           ArrayRef<TemplateArgument> TemplateArgs,
6359                           sema::TemplateDeductionInfo &DeductionInfo,
6360                           SourceRange InstantiationRange = SourceRange());
6361 
6362     InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
6363                           ParmVarDecl *Param,
6364                           ArrayRef<TemplateArgument> TemplateArgs,
6365                           SourceRange InstantiationRange = SourceRange());
6366 
6367     /// \brief Note that we are substituting prior template arguments into a
6368     /// non-type parameter.
6369     InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
6370                           NamedDecl *Template,
6371                           NonTypeTemplateParmDecl *Param,
6372                           ArrayRef<TemplateArgument> TemplateArgs,
6373                           SourceRange InstantiationRange);
6374 
6375     /// \brief Note that we are substituting prior template arguments into a
6376     /// template template parameter.
6377     InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
6378                           NamedDecl *Template,
6379                           TemplateTemplateParmDecl *Param,
6380                           ArrayRef<TemplateArgument> TemplateArgs,
6381                           SourceRange InstantiationRange);
6382 
6383     /// \brief Note that we are checking the default template argument
6384     /// against the template parameter for a given template-id.
6385     InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
6386                           TemplateDecl *Template,
6387                           NamedDecl *Param,
6388                           ArrayRef<TemplateArgument> TemplateArgs,
6389                           SourceRange InstantiationRange);
6390 
6391 
6392     /// \brief Note that we have finished instantiating this template.
6393     void Clear();
6394 
~InstantiatingTemplateInstantiatingTemplate6395     ~InstantiatingTemplate() { Clear(); }
6396 
6397     /// \brief Determines whether we have exceeded the maximum
6398     /// recursive template instantiations.
isInvalidInstantiatingTemplate6399     bool isInvalid() const { return Invalid; }
6400 
6401   private:
6402     Sema &SemaRef;
6403     bool Invalid;
6404     bool SavedInNonInstantiationSFINAEContext;
6405     bool CheckInstantiationDepth(SourceLocation PointOfInstantiation,
6406                                  SourceRange InstantiationRange);
6407 
6408     // FIXME: Replace this with a constructor once we can use delegating
6409     // constructors in llvm.
6410     void Initialize(
6411         ActiveTemplateInstantiation::InstantiationKind Kind,
6412         SourceLocation PointOfInstantiation, SourceRange InstantiationRange,
6413         Decl *Entity, NamedDecl *Template = nullptr,
6414         ArrayRef<TemplateArgument> TemplateArgs = ArrayRef<TemplateArgument>(),
6415         sema::TemplateDeductionInfo *DeductionInfo = nullptr);
6416 
6417     InstantiatingTemplate(const InstantiatingTemplate&) LLVM_DELETED_FUNCTION;
6418 
6419     InstantiatingTemplate&
6420     operator=(const InstantiatingTemplate&) LLVM_DELETED_FUNCTION;
6421   };
6422 
6423   void PrintInstantiationStack();
6424 
6425   /// \brief Determines whether we are currently in a context where
6426   /// template argument substitution failures are not considered
6427   /// errors.
6428   ///
6429   /// \returns An empty \c Optional if we're not in a SFINAE context.
6430   /// Otherwise, contains a pointer that, if non-NULL, contains the nearest
6431   /// template-deduction context object, which can be used to capture
6432   /// diagnostics that will be suppressed.
6433   Optional<sema::TemplateDeductionInfo *> isSFINAEContext() const;
6434 
6435   /// \brief Determines whether we are currently in a context that
6436   /// is not evaluated as per C++ [expr] p5.
isUnevaluatedContext()6437   bool isUnevaluatedContext() const {
6438     assert(!ExprEvalContexts.empty() &&
6439            "Must be in an expression evaluation context");
6440     return ExprEvalContexts.back().isUnevaluated();
6441   }
6442 
6443   /// \brief RAII class used to determine whether SFINAE has
6444   /// trapped any errors that occur during template argument
6445   /// deduction.
6446   class SFINAETrap {
6447     Sema &SemaRef;
6448     unsigned PrevSFINAEErrors;
6449     bool PrevInNonInstantiationSFINAEContext;
6450     bool PrevAccessCheckingSFINAE;
6451 
6452   public:
6453     explicit SFINAETrap(Sema &SemaRef, bool AccessCheckingSFINAE = false)
SemaRef(SemaRef)6454       : SemaRef(SemaRef), PrevSFINAEErrors(SemaRef.NumSFINAEErrors),
6455         PrevInNonInstantiationSFINAEContext(
6456                                       SemaRef.InNonInstantiationSFINAEContext),
6457         PrevAccessCheckingSFINAE(SemaRef.AccessCheckingSFINAE)
6458     {
6459       if (!SemaRef.isSFINAEContext())
6460         SemaRef.InNonInstantiationSFINAEContext = true;
6461       SemaRef.AccessCheckingSFINAE = AccessCheckingSFINAE;
6462     }
6463 
~SFINAETrap()6464     ~SFINAETrap() {
6465       SemaRef.NumSFINAEErrors = PrevSFINAEErrors;
6466       SemaRef.InNonInstantiationSFINAEContext
6467         = PrevInNonInstantiationSFINAEContext;
6468       SemaRef.AccessCheckingSFINAE = PrevAccessCheckingSFINAE;
6469     }
6470 
6471     /// \brief Determine whether any SFINAE errors have been trapped.
hasErrorOccurred()6472     bool hasErrorOccurred() const {
6473       return SemaRef.NumSFINAEErrors > PrevSFINAEErrors;
6474     }
6475   };
6476 
6477   /// \brief RAII class used to indicate that we are performing provisional
6478   /// semantic analysis to determine the validity of a construct, so
6479   /// typo-correction and diagnostics in the immediate context (not within
6480   /// implicitly-instantiated templates) should be suppressed.
6481   class TentativeAnalysisScope {
6482     Sema &SemaRef;
6483     // FIXME: Using a SFINAETrap for this is a hack.
6484     SFINAETrap Trap;
6485     bool PrevDisableTypoCorrection;
6486   public:
TentativeAnalysisScope(Sema & SemaRef)6487     explicit TentativeAnalysisScope(Sema &SemaRef)
6488         : SemaRef(SemaRef), Trap(SemaRef, true),
6489           PrevDisableTypoCorrection(SemaRef.DisableTypoCorrection) {
6490       SemaRef.DisableTypoCorrection = true;
6491     }
~TentativeAnalysisScope()6492     ~TentativeAnalysisScope() {
6493       SemaRef.DisableTypoCorrection = PrevDisableTypoCorrection;
6494     }
6495   };
6496 
6497   /// \brief The current instantiation scope used to store local
6498   /// variables.
6499   LocalInstantiationScope *CurrentInstantiationScope;
6500 
6501   /// \brief Tracks whether we are in a context where typo correction is
6502   /// disabled.
6503   bool DisableTypoCorrection;
6504 
6505   /// \brief The number of typos corrected by CorrectTypo.
6506   unsigned TyposCorrected;
6507 
6508   typedef llvm::DenseMap<IdentifierInfo *, TypoCorrection>
6509     UnqualifiedTyposCorrectedMap;
6510 
6511   /// \brief A cache containing the results of typo correction for unqualified
6512   /// name lookup.
6513   ///
6514   /// The string is the string that we corrected to (which may be empty, if
6515   /// there was no correction), while the boolean will be true when the
6516   /// string represents a keyword.
6517   UnqualifiedTyposCorrectedMap UnqualifiedTyposCorrected;
6518 
6519   typedef llvm::SmallSet<SourceLocation, 2> SrcLocSet;
6520   typedef llvm::DenseMap<IdentifierInfo *, SrcLocSet> IdentifierSourceLocations;
6521 
6522   /// \brief A cache containing identifiers for which typo correction failed and
6523   /// their locations, so that repeated attempts to correct an identifier in a
6524   /// given location are ignored if typo correction already failed for it.
6525   IdentifierSourceLocations TypoCorrectionFailures;
6526 
6527   /// \brief Worker object for performing CFG-based warnings.
6528   sema::AnalysisBasedWarnings AnalysisWarnings;
6529 
6530   /// \brief An entity for which implicit template instantiation is required.
6531   ///
6532   /// The source location associated with the declaration is the first place in
6533   /// the source code where the declaration was "used". It is not necessarily
6534   /// the point of instantiation (which will be either before or after the
6535   /// namespace-scope declaration that triggered this implicit instantiation),
6536   /// However, it is the location that diagnostics should generally refer to,
6537   /// because users will need to know what code triggered the instantiation.
6538   typedef std::pair<ValueDecl *, SourceLocation> PendingImplicitInstantiation;
6539 
6540   /// \brief The queue of implicit template instantiations that are required
6541   /// but have not yet been performed.
6542   std::deque<PendingImplicitInstantiation> PendingInstantiations;
6543 
6544   /// \brief The queue of implicit template instantiations that are required
6545   /// and must be performed within the current local scope.
6546   ///
6547   /// This queue is only used for member functions of local classes in
6548   /// templates, which must be instantiated in the same scope as their
6549   /// enclosing function, so that they can reference function-local
6550   /// types, static variables, enumerators, etc.
6551   std::deque<PendingImplicitInstantiation> PendingLocalImplicitInstantiations;
6552 
6553   class SavePendingLocalImplicitInstantiationsRAII {
6554   public:
SavePendingLocalImplicitInstantiationsRAII(Sema & S)6555     SavePendingLocalImplicitInstantiationsRAII(Sema &S): S(S) {
6556       SavedPendingLocalImplicitInstantiations.swap(
6557           S.PendingLocalImplicitInstantiations);
6558     }
6559 
~SavePendingLocalImplicitInstantiationsRAII()6560     ~SavePendingLocalImplicitInstantiationsRAII() {
6561       assert(S.PendingLocalImplicitInstantiations.empty() &&
6562              "there shouldn't be any pending local implicit instantiations");
6563       SavedPendingLocalImplicitInstantiations.swap(
6564           S.PendingLocalImplicitInstantiations);
6565     }
6566 
6567   private:
6568     Sema &S;
6569     std::deque<PendingImplicitInstantiation>
6570     SavedPendingLocalImplicitInstantiations;
6571   };
6572 
6573   void PerformPendingInstantiations(bool LocalOnly = false);
6574 
6575   TypeSourceInfo *SubstType(TypeSourceInfo *T,
6576                             const MultiLevelTemplateArgumentList &TemplateArgs,
6577                             SourceLocation Loc, DeclarationName Entity);
6578 
6579   QualType SubstType(QualType T,
6580                      const MultiLevelTemplateArgumentList &TemplateArgs,
6581                      SourceLocation Loc, DeclarationName Entity);
6582 
6583   TypeSourceInfo *SubstType(TypeLoc TL,
6584                             const MultiLevelTemplateArgumentList &TemplateArgs,
6585                             SourceLocation Loc, DeclarationName Entity);
6586 
6587   TypeSourceInfo *SubstFunctionDeclType(TypeSourceInfo *T,
6588                             const MultiLevelTemplateArgumentList &TemplateArgs,
6589                                         SourceLocation Loc,
6590                                         DeclarationName Entity,
6591                                         CXXRecordDecl *ThisContext,
6592                                         unsigned ThisTypeQuals);
6593   ParmVarDecl *SubstParmVarDecl(ParmVarDecl *D,
6594                             const MultiLevelTemplateArgumentList &TemplateArgs,
6595                                 int indexAdjustment,
6596                                 Optional<unsigned> NumExpansions,
6597                                 bool ExpectParameterPack);
6598   bool SubstParmTypes(SourceLocation Loc,
6599                       ParmVarDecl **Params, unsigned NumParams,
6600                       const MultiLevelTemplateArgumentList &TemplateArgs,
6601                       SmallVectorImpl<QualType> &ParamTypes,
6602                       SmallVectorImpl<ParmVarDecl *> *OutParams = nullptr);
6603   ExprResult SubstExpr(Expr *E,
6604                        const MultiLevelTemplateArgumentList &TemplateArgs);
6605 
6606   /// \brief Substitute the given template arguments into a list of
6607   /// expressions, expanding pack expansions if required.
6608   ///
6609   /// \param Exprs The list of expressions to substitute into.
6610   ///
6611   /// \param NumExprs The number of expressions in \p Exprs.
6612   ///
6613   /// \param IsCall Whether this is some form of call, in which case
6614   /// default arguments will be dropped.
6615   ///
6616   /// \param TemplateArgs The set of template arguments to substitute.
6617   ///
6618   /// \param Outputs Will receive all of the substituted arguments.
6619   ///
6620   /// \returns true if an error occurred, false otherwise.
6621   bool SubstExprs(Expr **Exprs, unsigned NumExprs, bool IsCall,
6622                   const MultiLevelTemplateArgumentList &TemplateArgs,
6623                   SmallVectorImpl<Expr *> &Outputs);
6624 
6625   StmtResult SubstStmt(Stmt *S,
6626                        const MultiLevelTemplateArgumentList &TemplateArgs);
6627 
6628   Decl *SubstDecl(Decl *D, DeclContext *Owner,
6629                   const MultiLevelTemplateArgumentList &TemplateArgs);
6630 
6631   ExprResult SubstInitializer(Expr *E,
6632                        const MultiLevelTemplateArgumentList &TemplateArgs,
6633                        bool CXXDirectInit);
6634 
6635   bool
6636   SubstBaseSpecifiers(CXXRecordDecl *Instantiation,
6637                       CXXRecordDecl *Pattern,
6638                       const MultiLevelTemplateArgumentList &TemplateArgs);
6639 
6640   bool
6641   InstantiateClass(SourceLocation PointOfInstantiation,
6642                    CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern,
6643                    const MultiLevelTemplateArgumentList &TemplateArgs,
6644                    TemplateSpecializationKind TSK,
6645                    bool Complain = true);
6646 
6647   bool InstantiateEnum(SourceLocation PointOfInstantiation,
6648                        EnumDecl *Instantiation, EnumDecl *Pattern,
6649                        const MultiLevelTemplateArgumentList &TemplateArgs,
6650                        TemplateSpecializationKind TSK);
6651 
6652   struct LateInstantiatedAttribute {
6653     const Attr *TmplAttr;
6654     LocalInstantiationScope *Scope;
6655     Decl *NewDecl;
6656 
LateInstantiatedAttributeLateInstantiatedAttribute6657     LateInstantiatedAttribute(const Attr *A, LocalInstantiationScope *S,
6658                               Decl *D)
6659       : TmplAttr(A), Scope(S), NewDecl(D)
6660     { }
6661   };
6662   typedef SmallVector<LateInstantiatedAttribute, 16> LateInstantiatedAttrVec;
6663 
6664   void InstantiateAttrs(const MultiLevelTemplateArgumentList &TemplateArgs,
6665                         const Decl *Pattern, Decl *Inst,
6666                         LateInstantiatedAttrVec *LateAttrs = nullptr,
6667                         LocalInstantiationScope *OuterMostScope = nullptr);
6668 
6669   bool
6670   InstantiateClassTemplateSpecialization(SourceLocation PointOfInstantiation,
6671                            ClassTemplateSpecializationDecl *ClassTemplateSpec,
6672                            TemplateSpecializationKind TSK,
6673                            bool Complain = true);
6674 
6675   void InstantiateClassMembers(SourceLocation PointOfInstantiation,
6676                                CXXRecordDecl *Instantiation,
6677                             const MultiLevelTemplateArgumentList &TemplateArgs,
6678                                TemplateSpecializationKind TSK);
6679 
6680   void InstantiateClassTemplateSpecializationMembers(
6681                                           SourceLocation PointOfInstantiation,
6682                            ClassTemplateSpecializationDecl *ClassTemplateSpec,
6683                                                 TemplateSpecializationKind TSK);
6684 
6685   NestedNameSpecifierLoc
6686   SubstNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS,
6687                            const MultiLevelTemplateArgumentList &TemplateArgs);
6688 
6689   DeclarationNameInfo
6690   SubstDeclarationNameInfo(const DeclarationNameInfo &NameInfo,
6691                            const MultiLevelTemplateArgumentList &TemplateArgs);
6692   TemplateName
6693   SubstTemplateName(NestedNameSpecifierLoc QualifierLoc, TemplateName Name,
6694                     SourceLocation Loc,
6695                     const MultiLevelTemplateArgumentList &TemplateArgs);
6696   bool Subst(const TemplateArgumentLoc *Args, unsigned NumArgs,
6697              TemplateArgumentListInfo &Result,
6698              const MultiLevelTemplateArgumentList &TemplateArgs);
6699 
6700   void InstantiateExceptionSpec(SourceLocation PointOfInstantiation,
6701                                 FunctionDecl *Function);
6702   void InstantiateFunctionDefinition(SourceLocation PointOfInstantiation,
6703                                      FunctionDecl *Function,
6704                                      bool Recursive = false,
6705                                      bool DefinitionRequired = false);
6706   VarTemplateSpecializationDecl *BuildVarTemplateInstantiation(
6707       VarTemplateDecl *VarTemplate, VarDecl *FromVar,
6708       const TemplateArgumentList &TemplateArgList,
6709       const TemplateArgumentListInfo &TemplateArgsInfo,
6710       SmallVectorImpl<TemplateArgument> &Converted,
6711       SourceLocation PointOfInstantiation, void *InsertPos,
6712       LateInstantiatedAttrVec *LateAttrs = nullptr,
6713       LocalInstantiationScope *StartingScope = nullptr);
6714   VarTemplateSpecializationDecl *CompleteVarTemplateSpecializationDecl(
6715       VarTemplateSpecializationDecl *VarSpec, VarDecl *PatternDecl,
6716       const MultiLevelTemplateArgumentList &TemplateArgs);
6717   void
6718   BuildVariableInstantiation(VarDecl *NewVar, VarDecl *OldVar,
6719                              const MultiLevelTemplateArgumentList &TemplateArgs,
6720                              LateInstantiatedAttrVec *LateAttrs,
6721                              DeclContext *Owner,
6722                              LocalInstantiationScope *StartingScope,
6723                              bool InstantiatingVarTemplate = false);
6724   void InstantiateVariableInitializer(
6725       VarDecl *Var, VarDecl *OldVar,
6726       const MultiLevelTemplateArgumentList &TemplateArgs);
6727   void InstantiateVariableDefinition(SourceLocation PointOfInstantiation,
6728                                      VarDecl *Var, bool Recursive = false,
6729                                      bool DefinitionRequired = false);
6730   void InstantiateStaticDataMemberDefinition(
6731                                      SourceLocation PointOfInstantiation,
6732                                      VarDecl *Var,
6733                                      bool Recursive = false,
6734                                      bool DefinitionRequired = false);
6735 
6736   void InstantiateMemInitializers(CXXConstructorDecl *New,
6737                                   const CXXConstructorDecl *Tmpl,
6738                             const MultiLevelTemplateArgumentList &TemplateArgs);
6739 
6740   NamedDecl *FindInstantiatedDecl(SourceLocation Loc, NamedDecl *D,
6741                           const MultiLevelTemplateArgumentList &TemplateArgs);
6742   DeclContext *FindInstantiatedContext(SourceLocation Loc, DeclContext *DC,
6743                           const MultiLevelTemplateArgumentList &TemplateArgs);
6744 
6745   // Objective-C declarations.
6746   enum ObjCContainerKind {
6747     OCK_None = -1,
6748     OCK_Interface = 0,
6749     OCK_Protocol,
6750     OCK_Category,
6751     OCK_ClassExtension,
6752     OCK_Implementation,
6753     OCK_CategoryImplementation
6754   };
6755   ObjCContainerKind getObjCContainerKind() const;
6756 
6757   Decl *ActOnStartClassInterface(SourceLocation AtInterfaceLoc,
6758                                  IdentifierInfo *ClassName,
6759                                  SourceLocation ClassLoc,
6760                                  IdentifierInfo *SuperName,
6761                                  SourceLocation SuperLoc,
6762                                  Decl * const *ProtoRefs,
6763                                  unsigned NumProtoRefs,
6764                                  const SourceLocation *ProtoLocs,
6765                                  SourceLocation EndProtoLoc,
6766                                  AttributeList *AttrList);
6767 
6768   void ActOnTypedefedProtocols(SmallVectorImpl<Decl *> &ProtocolRefs,
6769                                IdentifierInfo *SuperName,
6770                                SourceLocation SuperLoc);
6771 
6772   Decl *ActOnCompatibilityAlias(
6773                     SourceLocation AtCompatibilityAliasLoc,
6774                     IdentifierInfo *AliasName,  SourceLocation AliasLocation,
6775                     IdentifierInfo *ClassName, SourceLocation ClassLocation);
6776 
6777   bool CheckForwardProtocolDeclarationForCircularDependency(
6778     IdentifierInfo *PName,
6779     SourceLocation &PLoc, SourceLocation PrevLoc,
6780     const ObjCList<ObjCProtocolDecl> &PList);
6781 
6782   Decl *ActOnStartProtocolInterface(
6783                     SourceLocation AtProtoInterfaceLoc,
6784                     IdentifierInfo *ProtocolName, SourceLocation ProtocolLoc,
6785                     Decl * const *ProtoRefNames, unsigned NumProtoRefs,
6786                     const SourceLocation *ProtoLocs,
6787                     SourceLocation EndProtoLoc,
6788                     AttributeList *AttrList);
6789 
6790   Decl *ActOnStartCategoryInterface(SourceLocation AtInterfaceLoc,
6791                                     IdentifierInfo *ClassName,
6792                                     SourceLocation ClassLoc,
6793                                     IdentifierInfo *CategoryName,
6794                                     SourceLocation CategoryLoc,
6795                                     Decl * const *ProtoRefs,
6796                                     unsigned NumProtoRefs,
6797                                     const SourceLocation *ProtoLocs,
6798                                     SourceLocation EndProtoLoc);
6799 
6800   Decl *ActOnStartClassImplementation(
6801                     SourceLocation AtClassImplLoc,
6802                     IdentifierInfo *ClassName, SourceLocation ClassLoc,
6803                     IdentifierInfo *SuperClassname,
6804                     SourceLocation SuperClassLoc);
6805 
6806   Decl *ActOnStartCategoryImplementation(SourceLocation AtCatImplLoc,
6807                                          IdentifierInfo *ClassName,
6808                                          SourceLocation ClassLoc,
6809                                          IdentifierInfo *CatName,
6810                                          SourceLocation CatLoc);
6811 
6812   DeclGroupPtrTy ActOnFinishObjCImplementation(Decl *ObjCImpDecl,
6813                                                ArrayRef<Decl *> Decls);
6814 
6815   DeclGroupPtrTy ActOnForwardClassDeclaration(SourceLocation Loc,
6816                                      IdentifierInfo **IdentList,
6817                                      SourceLocation *IdentLocs,
6818                                      unsigned NumElts);
6819 
6820   DeclGroupPtrTy ActOnForwardProtocolDeclaration(SourceLocation AtProtoclLoc,
6821                                         const IdentifierLocPair *IdentList,
6822                                         unsigned NumElts,
6823                                         AttributeList *attrList);
6824 
6825   void FindProtocolDeclaration(bool WarnOnDeclarations,
6826                                const IdentifierLocPair *ProtocolId,
6827                                unsigned NumProtocols,
6828                                SmallVectorImpl<Decl *> &Protocols);
6829 
6830   /// Ensure attributes are consistent with type.
6831   /// \param [in, out] Attributes The attributes to check; they will
6832   /// be modified to be consistent with \p PropertyTy.
6833   void CheckObjCPropertyAttributes(Decl *PropertyPtrTy,
6834                                    SourceLocation Loc,
6835                                    unsigned &Attributes,
6836                                    bool propertyInPrimaryClass);
6837 
6838   /// Process the specified property declaration and create decls for the
6839   /// setters and getters as needed.
6840   /// \param property The property declaration being processed
6841   /// \param CD The semantic container for the property
6842   /// \param redeclaredProperty Declaration for property if redeclared
6843   ///        in class extension.
6844   /// \param lexicalDC Container for redeclaredProperty.
6845   void ProcessPropertyDecl(ObjCPropertyDecl *property,
6846                            ObjCContainerDecl *CD,
6847                            ObjCPropertyDecl *redeclaredProperty = nullptr,
6848                            ObjCContainerDecl *lexicalDC = nullptr);
6849 
6850 
6851   void DiagnosePropertyMismatch(ObjCPropertyDecl *Property,
6852                                 ObjCPropertyDecl *SuperProperty,
6853                                 const IdentifierInfo *Name,
6854                                 bool OverridingProtocolProperty);
6855 
6856   void DiagnoseClassExtensionDupMethods(ObjCCategoryDecl *CAT,
6857                                         ObjCInterfaceDecl *ID);
6858 
6859   Decl *ActOnAtEnd(Scope *S, SourceRange AtEnd,
6860                    ArrayRef<Decl *> allMethods = None,
6861                    ArrayRef<DeclGroupPtrTy> allTUVars = None);
6862 
6863   Decl *ActOnProperty(Scope *S, SourceLocation AtLoc,
6864                       SourceLocation LParenLoc,
6865                       FieldDeclarator &FD, ObjCDeclSpec &ODS,
6866                       Selector GetterSel, Selector SetterSel,
6867                       bool *OverridingProperty,
6868                       tok::ObjCKeywordKind MethodImplKind,
6869                       DeclContext *lexicalDC = nullptr);
6870 
6871   Decl *ActOnPropertyImplDecl(Scope *S,
6872                               SourceLocation AtLoc,
6873                               SourceLocation PropertyLoc,
6874                               bool ImplKind,
6875                               IdentifierInfo *PropertyId,
6876                               IdentifierInfo *PropertyIvar,
6877                               SourceLocation PropertyIvarLoc);
6878 
6879   enum ObjCSpecialMethodKind {
6880     OSMK_None,
6881     OSMK_Alloc,
6882     OSMK_New,
6883     OSMK_Copy,
6884     OSMK_RetainingInit,
6885     OSMK_NonRetainingInit
6886   };
6887 
6888   struct ObjCArgInfo {
6889     IdentifierInfo *Name;
6890     SourceLocation NameLoc;
6891     // The Type is null if no type was specified, and the DeclSpec is invalid
6892     // in this case.
6893     ParsedType Type;
6894     ObjCDeclSpec DeclSpec;
6895 
6896     /// ArgAttrs - Attribute list for this argument.
6897     AttributeList *ArgAttrs;
6898   };
6899 
6900   Decl *ActOnMethodDeclaration(
6901     Scope *S,
6902     SourceLocation BeginLoc, // location of the + or -.
6903     SourceLocation EndLoc,   // location of the ; or {.
6904     tok::TokenKind MethodType,
6905     ObjCDeclSpec &ReturnQT, ParsedType ReturnType,
6906     ArrayRef<SourceLocation> SelectorLocs, Selector Sel,
6907     // optional arguments. The number of types/arguments is obtained
6908     // from the Sel.getNumArgs().
6909     ObjCArgInfo *ArgInfo,
6910     DeclaratorChunk::ParamInfo *CParamInfo, unsigned CNumArgs, // c-style args
6911     AttributeList *AttrList, tok::ObjCKeywordKind MethodImplKind,
6912     bool isVariadic, bool MethodDefinition);
6913 
6914   ObjCMethodDecl *LookupMethodInQualifiedType(Selector Sel,
6915                                               const ObjCObjectPointerType *OPT,
6916                                               bool IsInstance);
6917   ObjCMethodDecl *LookupMethodInObjectType(Selector Sel, QualType Ty,
6918                                            bool IsInstance);
6919 
6920   bool CheckARCMethodDecl(ObjCMethodDecl *method);
6921   bool inferObjCARCLifetime(ValueDecl *decl);
6922 
6923   ExprResult
6924   HandleExprPropertyRefExpr(const ObjCObjectPointerType *OPT,
6925                             Expr *BaseExpr,
6926                             SourceLocation OpLoc,
6927                             DeclarationName MemberName,
6928                             SourceLocation MemberLoc,
6929                             SourceLocation SuperLoc, QualType SuperType,
6930                             bool Super);
6931 
6932   ExprResult
6933   ActOnClassPropertyRefExpr(IdentifierInfo &receiverName,
6934                             IdentifierInfo &propertyName,
6935                             SourceLocation receiverNameLoc,
6936                             SourceLocation propertyNameLoc);
6937 
6938   ObjCMethodDecl *tryCaptureObjCSelf(SourceLocation Loc);
6939 
6940   /// \brief Describes the kind of message expression indicated by a message
6941   /// send that starts with an identifier.
6942   enum ObjCMessageKind {
6943     /// \brief The message is sent to 'super'.
6944     ObjCSuperMessage,
6945     /// \brief The message is an instance message.
6946     ObjCInstanceMessage,
6947     /// \brief The message is a class message, and the identifier is a type
6948     /// name.
6949     ObjCClassMessage
6950   };
6951 
6952   ObjCMessageKind getObjCMessageKind(Scope *S,
6953                                      IdentifierInfo *Name,
6954                                      SourceLocation NameLoc,
6955                                      bool IsSuper,
6956                                      bool HasTrailingDot,
6957                                      ParsedType &ReceiverType);
6958 
6959   ExprResult ActOnSuperMessage(Scope *S, SourceLocation SuperLoc,
6960                                Selector Sel,
6961                                SourceLocation LBracLoc,
6962                                ArrayRef<SourceLocation> SelectorLocs,
6963                                SourceLocation RBracLoc,
6964                                MultiExprArg Args);
6965 
6966   ExprResult BuildClassMessage(TypeSourceInfo *ReceiverTypeInfo,
6967                                QualType ReceiverType,
6968                                SourceLocation SuperLoc,
6969                                Selector Sel,
6970                                ObjCMethodDecl *Method,
6971                                SourceLocation LBracLoc,
6972                                ArrayRef<SourceLocation> SelectorLocs,
6973                                SourceLocation RBracLoc,
6974                                MultiExprArg Args,
6975                                bool isImplicit = false);
6976 
6977   ExprResult BuildClassMessageImplicit(QualType ReceiverType,
6978                                        bool isSuperReceiver,
6979                                        SourceLocation Loc,
6980                                        Selector Sel,
6981                                        ObjCMethodDecl *Method,
6982                                        MultiExprArg Args);
6983 
6984   ExprResult ActOnClassMessage(Scope *S,
6985                                ParsedType Receiver,
6986                                Selector Sel,
6987                                SourceLocation LBracLoc,
6988                                ArrayRef<SourceLocation> SelectorLocs,
6989                                SourceLocation RBracLoc,
6990                                MultiExprArg Args);
6991 
6992   ExprResult BuildInstanceMessage(Expr *Receiver,
6993                                   QualType ReceiverType,
6994                                   SourceLocation SuperLoc,
6995                                   Selector Sel,
6996                                   ObjCMethodDecl *Method,
6997                                   SourceLocation LBracLoc,
6998                                   ArrayRef<SourceLocation> SelectorLocs,
6999                                   SourceLocation RBracLoc,
7000                                   MultiExprArg Args,
7001                                   bool isImplicit = false);
7002 
7003   ExprResult BuildInstanceMessageImplicit(Expr *Receiver,
7004                                           QualType ReceiverType,
7005                                           SourceLocation Loc,
7006                                           Selector Sel,
7007                                           ObjCMethodDecl *Method,
7008                                           MultiExprArg Args);
7009 
7010   ExprResult ActOnInstanceMessage(Scope *S,
7011                                   Expr *Receiver,
7012                                   Selector Sel,
7013                                   SourceLocation LBracLoc,
7014                                   ArrayRef<SourceLocation> SelectorLocs,
7015                                   SourceLocation RBracLoc,
7016                                   MultiExprArg Args);
7017 
7018   ExprResult BuildObjCBridgedCast(SourceLocation LParenLoc,
7019                                   ObjCBridgeCastKind Kind,
7020                                   SourceLocation BridgeKeywordLoc,
7021                                   TypeSourceInfo *TSInfo,
7022                                   Expr *SubExpr);
7023 
7024   ExprResult ActOnObjCBridgedCast(Scope *S,
7025                                   SourceLocation LParenLoc,
7026                                   ObjCBridgeCastKind Kind,
7027                                   SourceLocation BridgeKeywordLoc,
7028                                   ParsedType Type,
7029                                   SourceLocation RParenLoc,
7030                                   Expr *SubExpr);
7031 
7032   void CheckTollFreeBridgeCast(QualType castType, Expr *castExpr);
7033 
7034   void CheckObjCBridgeRelatedCast(QualType castType, Expr *castExpr);
7035 
7036   bool CheckTollFreeBridgeStaticCast(QualType castType, Expr *castExpr,
7037                                      CastKind &Kind);
7038 
7039   bool checkObjCBridgeRelatedComponents(SourceLocation Loc,
7040                                         QualType DestType, QualType SrcType,
7041                                         ObjCInterfaceDecl *&RelatedClass,
7042                                         ObjCMethodDecl *&ClassMethod,
7043                                         ObjCMethodDecl *&InstanceMethod,
7044                                         TypedefNameDecl *&TDNDecl,
7045                                         bool CfToNs);
7046 
7047   bool CheckObjCBridgeRelatedConversions(SourceLocation Loc,
7048                                          QualType DestType, QualType SrcType,
7049                                          Expr *&SrcExpr);
7050 
7051   bool ConversionToObjCStringLiteralCheck(QualType DstType, Expr *&SrcExpr);
7052 
7053   bool checkInitMethod(ObjCMethodDecl *method, QualType receiverTypeIfCall);
7054 
7055   /// \brief Check whether the given new method is a valid override of the
7056   /// given overridden method, and set any properties that should be inherited.
7057   void CheckObjCMethodOverride(ObjCMethodDecl *NewMethod,
7058                                const ObjCMethodDecl *Overridden);
7059 
7060   /// \brief Describes the compatibility of a result type with its method.
7061   enum ResultTypeCompatibilityKind {
7062     RTC_Compatible,
7063     RTC_Incompatible,
7064     RTC_Unknown
7065   };
7066 
7067   void CheckObjCMethodOverrides(ObjCMethodDecl *ObjCMethod,
7068                                 ObjCInterfaceDecl *CurrentClass,
7069                                 ResultTypeCompatibilityKind RTC);
7070 
7071   enum PragmaOptionsAlignKind {
7072     POAK_Native,  // #pragma options align=native
7073     POAK_Natural, // #pragma options align=natural
7074     POAK_Packed,  // #pragma options align=packed
7075     POAK_Power,   // #pragma options align=power
7076     POAK_Mac68k,  // #pragma options align=mac68k
7077     POAK_Reset    // #pragma options align=reset
7078   };
7079 
7080   /// ActOnPragmaOptionsAlign - Called on well formed \#pragma options align.
7081   void ActOnPragmaOptionsAlign(PragmaOptionsAlignKind Kind,
7082                                SourceLocation PragmaLoc);
7083 
7084   enum PragmaPackKind {
7085     PPK_Default, // #pragma pack([n])
7086     PPK_Show,    // #pragma pack(show), only supported by MSVC.
7087     PPK_Push,    // #pragma pack(push, [identifier], [n])
7088     PPK_Pop      // #pragma pack(pop, [identifier], [n])
7089   };
7090 
7091   enum PragmaMSStructKind {
7092     PMSST_OFF,  // #pragms ms_struct off
7093     PMSST_ON    // #pragms ms_struct on
7094   };
7095 
7096   enum PragmaMSCommentKind {
7097     PCK_Unknown,
7098     PCK_Linker,   // #pragma comment(linker, ...)
7099     PCK_Lib,      // #pragma comment(lib, ...)
7100     PCK_Compiler, // #pragma comment(compiler, ...)
7101     PCK_ExeStr,   // #pragma comment(exestr, ...)
7102     PCK_User      // #pragma comment(user, ...)
7103   };
7104 
7105   /// ActOnPragmaPack - Called on well formed \#pragma pack(...).
7106   void ActOnPragmaPack(PragmaPackKind Kind,
7107                        IdentifierInfo *Name,
7108                        Expr *Alignment,
7109                        SourceLocation PragmaLoc,
7110                        SourceLocation LParenLoc,
7111                        SourceLocation RParenLoc);
7112 
7113   /// ActOnPragmaMSStruct - Called on well formed \#pragma ms_struct [on|off].
7114   void ActOnPragmaMSStruct(PragmaMSStructKind Kind);
7115 
7116   /// ActOnPragmaMSComment - Called on well formed
7117   /// \#pragma comment(kind, "arg").
7118   void ActOnPragmaMSComment(PragmaMSCommentKind Kind, StringRef Arg);
7119 
7120   /// ActOnPragmaMSPointersToMembers - called on well formed \#pragma
7121   /// pointers_to_members(representation method[, general purpose
7122   /// representation]).
7123   void ActOnPragmaMSPointersToMembers(
7124       LangOptions::PragmaMSPointersToMembersKind Kind,
7125       SourceLocation PragmaLoc);
7126 
7127   /// \brief Called on well formed \#pragma vtordisp().
7128   void ActOnPragmaMSVtorDisp(PragmaVtorDispKind Kind, SourceLocation PragmaLoc,
7129                              MSVtorDispAttr::Mode Value);
7130 
7131   enum PragmaSectionKind {
7132     PSK_DataSeg,
7133     PSK_BSSSeg,
7134     PSK_ConstSeg,
7135     PSK_CodeSeg,
7136   };
7137 
7138   enum PragmaSectionFlag : unsigned {
7139     PSF_None = 0,
7140     PSF_Read = 0x1,
7141     PSF_Write = 0x2,
7142     PSF_Execute = 0x4,
7143     PSF_Implicit = 0x8,
7144     PSF_Invalid = 0x80000000U,
7145   };
7146 
7147   struct SectionInfo {
7148     DeclaratorDecl *Decl;
7149     SourceLocation PragmaSectionLocation;
7150     int SectionFlags;
SectionInfoSectionInfo7151     SectionInfo() {}
SectionInfoSectionInfo7152     SectionInfo(DeclaratorDecl *Decl,
7153                 SourceLocation PragmaSectionLocation,
7154                 int SectionFlags)
7155       : Decl(Decl),
7156         PragmaSectionLocation(PragmaSectionLocation),
7157         SectionFlags(SectionFlags) {}
7158   };
7159 
7160   llvm::StringMap<SectionInfo> SectionInfos;
7161   bool UnifySection(const StringRef &SectionName,
7162                     int SectionFlags,
7163                     DeclaratorDecl *TheDecl);
7164   bool UnifySection(const StringRef &SectionName,
7165                     int SectionFlags,
7166                     SourceLocation PragmaSectionLocation);
7167 
7168   /// \brief Called on well formed \#pragma bss_seg/data_seg/const_seg/code_seg.
7169   void ActOnPragmaMSSeg(SourceLocation PragmaLocation,
7170                         PragmaMsStackAction Action,
7171                         llvm::StringRef StackSlotLabel,
7172                         StringLiteral *SegmentName,
7173                         llvm::StringRef PragmaName);
7174 
7175   /// \brief Called on well formed \#pragma section().
7176   void ActOnPragmaMSSection(SourceLocation PragmaLocation,
7177                             int SectionFlags, StringLiteral *SegmentName);
7178 
7179   /// ActOnPragmaDetectMismatch - Call on well-formed \#pragma detect_mismatch
7180   void ActOnPragmaDetectMismatch(StringRef Name, StringRef Value);
7181 
7182   /// ActOnPragmaUnused - Called on well-formed '\#pragma unused'.
7183   void ActOnPragmaUnused(const Token &Identifier,
7184                          Scope *curScope,
7185                          SourceLocation PragmaLoc);
7186 
7187   /// ActOnPragmaVisibility - Called on well formed \#pragma GCC visibility... .
7188   void ActOnPragmaVisibility(const IdentifierInfo* VisType,
7189                              SourceLocation PragmaLoc);
7190 
7191   NamedDecl *DeclClonePragmaWeak(NamedDecl *ND, IdentifierInfo *II,
7192                                  SourceLocation Loc);
7193   void DeclApplyPragmaWeak(Scope *S, NamedDecl *ND, WeakInfo &W);
7194 
7195   /// ActOnPragmaWeakID - Called on well formed \#pragma weak ident.
7196   void ActOnPragmaWeakID(IdentifierInfo* WeakName,
7197                          SourceLocation PragmaLoc,
7198                          SourceLocation WeakNameLoc);
7199 
7200   /// ActOnPragmaRedefineExtname - Called on well formed
7201   /// \#pragma redefine_extname oldname newname.
7202   void ActOnPragmaRedefineExtname(IdentifierInfo* WeakName,
7203                                   IdentifierInfo* AliasName,
7204                                   SourceLocation PragmaLoc,
7205                                   SourceLocation WeakNameLoc,
7206                                   SourceLocation AliasNameLoc);
7207 
7208   /// ActOnPragmaWeakAlias - Called on well formed \#pragma weak ident = ident.
7209   void ActOnPragmaWeakAlias(IdentifierInfo* WeakName,
7210                             IdentifierInfo* AliasName,
7211                             SourceLocation PragmaLoc,
7212                             SourceLocation WeakNameLoc,
7213                             SourceLocation AliasNameLoc);
7214 
7215   /// ActOnPragmaFPContract - Called on well formed
7216   /// \#pragma {STDC,OPENCL} FP_CONTRACT
7217   void ActOnPragmaFPContract(tok::OnOffSwitch OOS);
7218 
7219   /// AddAlignmentAttributesForRecord - Adds any needed alignment attributes to
7220   /// a the record decl, to handle '\#pragma pack' and '\#pragma options align'.
7221   void AddAlignmentAttributesForRecord(RecordDecl *RD);
7222 
7223   /// AddMsStructLayoutForRecord - Adds ms_struct layout attribute to record.
7224   void AddMsStructLayoutForRecord(RecordDecl *RD);
7225 
7226   /// FreePackedContext - Deallocate and null out PackContext.
7227   void FreePackedContext();
7228 
7229   /// PushNamespaceVisibilityAttr - Note that we've entered a
7230   /// namespace with a visibility attribute.
7231   void PushNamespaceVisibilityAttr(const VisibilityAttr *Attr,
7232                                    SourceLocation Loc);
7233 
7234   /// AddPushedVisibilityAttribute - If '\#pragma GCC visibility' was used,
7235   /// add an appropriate visibility attribute.
7236   void AddPushedVisibilityAttribute(Decl *RD);
7237 
7238   /// PopPragmaVisibility - Pop the top element of the visibility stack; used
7239   /// for '\#pragma GCC visibility' and visibility attributes on namespaces.
7240   void PopPragmaVisibility(bool IsNamespaceEnd, SourceLocation EndLoc);
7241 
7242   /// FreeVisContext - Deallocate and null out VisContext.
7243   void FreeVisContext();
7244 
7245   /// AddCFAuditedAttribute - Check whether we're currently within
7246   /// '\#pragma clang arc_cf_code_audited' and, if so, consider adding
7247   /// the appropriate attribute.
7248   void AddCFAuditedAttribute(Decl *D);
7249 
7250   /// \brief Called on well formed \#pragma clang optimize.
7251   void ActOnPragmaOptimize(bool On, SourceLocation PragmaLoc);
7252 
7253   /// \brief Get the location for the currently active "\#pragma clang optimize
7254   /// off". If this location is invalid, then the state of the pragma is "on".
getOptimizeOffPragmaLocation()7255   SourceLocation getOptimizeOffPragmaLocation() const {
7256     return OptimizeOffPragmaLocation;
7257   }
7258 
7259   /// \brief Only called on function definitions; if there is a pragma in scope
7260   /// with the effect of a range-based optnone, consider marking the function
7261   /// with attribute optnone.
7262   void AddRangeBasedOptnone(FunctionDecl *FD);
7263 
7264   /// \brief Adds the 'optnone' attribute to the function declaration if there
7265   /// are no conflicts; Loc represents the location causing the 'optnone'
7266   /// attribute to be added (usually because of a pragma).
7267   void AddOptnoneAttributeIfNoConflicts(FunctionDecl *FD, SourceLocation Loc);
7268 
7269   /// AddAlignedAttr - Adds an aligned attribute to a particular declaration.
7270   void AddAlignedAttr(SourceRange AttrRange, Decl *D, Expr *E,
7271                       unsigned SpellingListIndex, bool IsPackExpansion);
7272   void AddAlignedAttr(SourceRange AttrRange, Decl *D, TypeSourceInfo *T,
7273                       unsigned SpellingListIndex, bool IsPackExpansion);
7274 
7275   // OpenMP directives and clauses.
7276 private:
7277   void *VarDataSharingAttributesStack;
7278   /// \brief Initialization of data-sharing attributes stack.
7279   void InitDataSharingAttributesStack();
7280   void DestroyDataSharingAttributesStack();
7281   ExprResult VerifyPositiveIntegerConstantInClause(Expr *Op,
7282                                                    OpenMPClauseKind CKind);
7283 public:
7284   ExprResult PerformOpenMPImplicitIntegerConversion(SourceLocation OpLoc,
7285                                                     Expr *Op);
7286   /// \brief Called on start of new data sharing attribute block.
7287   void StartOpenMPDSABlock(OpenMPDirectiveKind K,
7288                            const DeclarationNameInfo &DirName, Scope *CurScope,
7289                            SourceLocation Loc);
7290   /// \brief Called on end of data sharing attribute block.
7291   void EndOpenMPDSABlock(Stmt *CurDirective);
7292 
7293   // OpenMP directives and clauses.
7294   /// \brief Called on correct id-expression from the '#pragma omp
7295   /// threadprivate'.
7296   ExprResult ActOnOpenMPIdExpression(Scope *CurScope,
7297                                      CXXScopeSpec &ScopeSpec,
7298                                      const DeclarationNameInfo &Id);
7299   /// \brief Called on well-formed '#pragma omp threadprivate'.
7300   DeclGroupPtrTy ActOnOpenMPThreadprivateDirective(
7301                                      SourceLocation Loc,
7302                                      ArrayRef<Expr *> VarList);
7303   // \brief Builds a new OpenMPThreadPrivateDecl and checks its correctness.
7304   OMPThreadPrivateDecl *CheckOMPThreadPrivateDecl(
7305                                      SourceLocation Loc,
7306                                      ArrayRef<Expr *> VarList);
7307 
7308   // brief Initialization of captured region for OpenMP region.
7309   void ActOnOpenMPRegionStart(OpenMPDirectiveKind DKind, Scope *CurScope);
7310   StmtResult ActOnOpenMPExecutableDirective(OpenMPDirectiveKind Kind,
7311                                             ArrayRef<OMPClause *> Clauses,
7312                                             Stmt *AStmt,
7313                                             SourceLocation StartLoc,
7314                                             SourceLocation EndLoc);
7315   /// \brief Called on well-formed '\#pragma omp parallel' after parsing
7316   /// of the  associated statement.
7317   StmtResult ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses,
7318                                           Stmt *AStmt,
7319                                           SourceLocation StartLoc,
7320                                           SourceLocation EndLoc);
7321   /// \brief Called on well-formed '\#pragma omp simd' after parsing
7322   /// of the associated statement.
7323   StmtResult ActOnOpenMPSimdDirective(
7324       ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7325       SourceLocation EndLoc,
7326       llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA);
7327   /// \brief Called on well-formed '\#pragma omp for' after parsing
7328   /// of the associated statement.
7329   StmtResult ActOnOpenMPForDirective(
7330       ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7331       SourceLocation EndLoc,
7332       llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA);
7333   /// \brief Called on well-formed '\#pragma omp sections' after parsing
7334   /// of the associated statement.
7335   StmtResult ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses,
7336                                           Stmt *AStmt, SourceLocation StartLoc,
7337                                           SourceLocation EndLoc);
7338   /// \brief Called on well-formed '\#pragma omp section' after parsing of the
7339   /// associated statement.
7340   StmtResult ActOnOpenMPSectionDirective(Stmt *AStmt, SourceLocation StartLoc,
7341                                          SourceLocation EndLoc);
7342   /// \brief Called on well-formed '\#pragma omp single' after parsing of the
7343   /// associated statement.
7344   StmtResult ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses,
7345                                         Stmt *AStmt, SourceLocation StartLoc,
7346                                         SourceLocation EndLoc);
7347   /// \brief Called on well-formed '\#pragma omp parallel for' after parsing
7348   /// of the  associated statement.
7349   StmtResult ActOnOpenMPParallelForDirective(
7350       ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7351       SourceLocation EndLoc,
7352       llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA);
7353   /// \brief Called on well-formed '\#pragma omp parallel sections' after
7354   /// parsing of the  associated statement.
7355   StmtResult ActOnOpenMPParallelSectionsDirective(ArrayRef<OMPClause *> Clauses,
7356                                                   Stmt *AStmt,
7357                                                   SourceLocation StartLoc,
7358                                                   SourceLocation EndLoc);
7359 
7360   OMPClause *ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind,
7361                                          Expr *Expr,
7362                                          SourceLocation StartLoc,
7363                                          SourceLocation LParenLoc,
7364                                          SourceLocation EndLoc);
7365   /// \brief Called on well-formed 'if' clause.
7366   OMPClause *ActOnOpenMPIfClause(Expr *Condition, SourceLocation StartLoc,
7367                                  SourceLocation LParenLoc,
7368                                  SourceLocation EndLoc);
7369   /// \brief Called on well-formed 'num_threads' clause.
7370   OMPClause *ActOnOpenMPNumThreadsClause(Expr *NumThreads,
7371                                          SourceLocation StartLoc,
7372                                          SourceLocation LParenLoc,
7373                                          SourceLocation EndLoc);
7374   /// \brief Called on well-formed 'safelen' clause.
7375   OMPClause *ActOnOpenMPSafelenClause(Expr *Length,
7376                                       SourceLocation StartLoc,
7377                                       SourceLocation LParenLoc,
7378                                       SourceLocation EndLoc);
7379   /// \brief Called on well-formed 'collapse' clause.
7380   OMPClause *ActOnOpenMPCollapseClause(Expr *NumForLoops,
7381                                        SourceLocation StartLoc,
7382                                        SourceLocation LParenLoc,
7383                                        SourceLocation EndLoc);
7384 
7385   OMPClause *ActOnOpenMPSimpleClause(OpenMPClauseKind Kind,
7386                                      unsigned Argument,
7387                                      SourceLocation ArgumentLoc,
7388                                      SourceLocation StartLoc,
7389                                      SourceLocation LParenLoc,
7390                                      SourceLocation EndLoc);
7391   /// \brief Called on well-formed 'default' clause.
7392   OMPClause *ActOnOpenMPDefaultClause(OpenMPDefaultClauseKind Kind,
7393                                       SourceLocation KindLoc,
7394                                       SourceLocation StartLoc,
7395                                       SourceLocation LParenLoc,
7396                                       SourceLocation EndLoc);
7397   /// \brief Called on well-formed 'proc_bind' clause.
7398   OMPClause *ActOnOpenMPProcBindClause(OpenMPProcBindClauseKind Kind,
7399                                        SourceLocation KindLoc,
7400                                        SourceLocation StartLoc,
7401                                        SourceLocation LParenLoc,
7402                                        SourceLocation EndLoc);
7403 
7404   OMPClause *ActOnOpenMPSingleExprWithArgClause(OpenMPClauseKind Kind,
7405                                                 unsigned Argument, Expr *Expr,
7406                                                 SourceLocation StartLoc,
7407                                                 SourceLocation LParenLoc,
7408                                                 SourceLocation ArgumentLoc,
7409                                                 SourceLocation CommaLoc,
7410                                                 SourceLocation EndLoc);
7411   /// \brief Called on well-formed 'schedule' clause.
7412   OMPClause *ActOnOpenMPScheduleClause(OpenMPScheduleClauseKind Kind,
7413                                        Expr *ChunkSize, SourceLocation StartLoc,
7414                                        SourceLocation LParenLoc,
7415                                        SourceLocation KindLoc,
7416                                        SourceLocation CommaLoc,
7417                                        SourceLocation EndLoc);
7418 
7419   OMPClause *ActOnOpenMPClause(OpenMPClauseKind Kind, SourceLocation StartLoc,
7420                                SourceLocation EndLoc);
7421   /// \brief Called on well-formed 'ordered' clause.
7422   OMPClause *ActOnOpenMPOrderedClause(SourceLocation StartLoc,
7423                                       SourceLocation EndLoc);
7424   /// \brief Called on well-formed 'nowait' clause.
7425   OMPClause *ActOnOpenMPNowaitClause(SourceLocation StartLoc,
7426                                      SourceLocation EndLoc);
7427 
7428   OMPClause *
7429   ActOnOpenMPVarListClause(OpenMPClauseKind Kind, ArrayRef<Expr *> Vars,
7430                            Expr *TailExpr, SourceLocation StartLoc,
7431                            SourceLocation LParenLoc, SourceLocation ColonLoc,
7432                            SourceLocation EndLoc,
7433                            CXXScopeSpec &ReductionIdScopeSpec,
7434                            const DeclarationNameInfo &ReductionId);
7435   /// \brief Called on well-formed 'private' clause.
7436   OMPClause *ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList,
7437                                       SourceLocation StartLoc,
7438                                       SourceLocation LParenLoc,
7439                                       SourceLocation EndLoc);
7440   /// \brief Called on well-formed 'firstprivate' clause.
7441   OMPClause *ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList,
7442                                            SourceLocation StartLoc,
7443                                            SourceLocation LParenLoc,
7444                                            SourceLocation EndLoc);
7445   /// \brief Called on well-formed 'lastprivate' clause.
7446   OMPClause *ActOnOpenMPLastprivateClause(ArrayRef<Expr *> VarList,
7447                                           SourceLocation StartLoc,
7448                                           SourceLocation LParenLoc,
7449                                           SourceLocation EndLoc);
7450   /// \brief Called on well-formed 'shared' clause.
7451   OMPClause *ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList,
7452                                      SourceLocation StartLoc,
7453                                      SourceLocation LParenLoc,
7454                                      SourceLocation EndLoc);
7455   /// \brief Called on well-formed 'reduction' clause.
7456   OMPClause *
7457   ActOnOpenMPReductionClause(ArrayRef<Expr *> VarList, SourceLocation StartLoc,
7458                              SourceLocation LParenLoc, SourceLocation ColonLoc,
7459                              SourceLocation EndLoc,
7460                              CXXScopeSpec &ReductionIdScopeSpec,
7461                              const DeclarationNameInfo &ReductionId);
7462   /// \brief Called on well-formed 'linear' clause.
7463   OMPClause *ActOnOpenMPLinearClause(ArrayRef<Expr *> VarList,
7464                                      Expr *Step,
7465                                      SourceLocation StartLoc,
7466                                      SourceLocation LParenLoc,
7467                                      SourceLocation ColonLoc,
7468                                      SourceLocation EndLoc);
7469   /// \brief Called on well-formed 'aligned' clause.
7470   OMPClause *ActOnOpenMPAlignedClause(ArrayRef<Expr *> VarList,
7471                                       Expr *Alignment,
7472                                       SourceLocation StartLoc,
7473                                       SourceLocation LParenLoc,
7474                                       SourceLocation ColonLoc,
7475                                       SourceLocation EndLoc);
7476   /// \brief Called on well-formed 'copyin' clause.
7477   OMPClause *ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList,
7478                                      SourceLocation StartLoc,
7479                                      SourceLocation LParenLoc,
7480                                      SourceLocation EndLoc);
7481   /// \brief Called on well-formed 'copyprivate' clause.
7482   OMPClause *ActOnOpenMPCopyprivateClause(ArrayRef<Expr *> VarList,
7483                                           SourceLocation StartLoc,
7484                                           SourceLocation LParenLoc,
7485                                           SourceLocation EndLoc);
7486 
7487   /// \brief The kind of conversion being performed.
7488   enum CheckedConversionKind {
7489     /// \brief An implicit conversion.
7490     CCK_ImplicitConversion,
7491     /// \brief A C-style cast.
7492     CCK_CStyleCast,
7493     /// \brief A functional-style cast.
7494     CCK_FunctionalCast,
7495     /// \brief A cast other than a C-style cast.
7496     CCK_OtherCast
7497   };
7498 
7499   /// ImpCastExprToType - If Expr is not of type 'Type', insert an implicit
7500   /// cast.  If there is already an implicit cast, merge into the existing one.
7501   /// If isLvalue, the result of the cast is an lvalue.
7502   ExprResult ImpCastExprToType(Expr *E, QualType Type, CastKind CK,
7503                                ExprValueKind VK = VK_RValue,
7504                                const CXXCastPath *BasePath = nullptr,
7505                                CheckedConversionKind CCK
7506                                   = CCK_ImplicitConversion);
7507 
7508   /// ScalarTypeToBooleanCastKind - Returns the cast kind corresponding
7509   /// to the conversion from scalar type ScalarTy to the Boolean type.
7510   static CastKind ScalarTypeToBooleanCastKind(QualType ScalarTy);
7511 
7512   /// IgnoredValueConversions - Given that an expression's result is
7513   /// syntactically ignored, perform any conversions that are
7514   /// required.
7515   ExprResult IgnoredValueConversions(Expr *E);
7516 
7517   // UsualUnaryConversions - promotes integers (C99 6.3.1.1p2) and converts
7518   // functions and arrays to their respective pointers (C99 6.3.2.1).
7519   ExprResult UsualUnaryConversions(Expr *E);
7520 
7521   /// CallExprUnaryConversions - a special case of an unary conversion
7522   /// performed on a function designator of a call expression.
7523   ExprResult CallExprUnaryConversions(Expr *E);
7524 
7525   // DefaultFunctionArrayConversion - converts functions and arrays
7526   // to their respective pointers (C99 6.3.2.1).
7527   ExprResult DefaultFunctionArrayConversion(Expr *E);
7528 
7529   // DefaultFunctionArrayLvalueConversion - converts functions and
7530   // arrays to their respective pointers and performs the
7531   // lvalue-to-rvalue conversion.
7532   ExprResult DefaultFunctionArrayLvalueConversion(Expr *E);
7533 
7534   // DefaultLvalueConversion - performs lvalue-to-rvalue conversion on
7535   // the operand.  This is DefaultFunctionArrayLvalueConversion,
7536   // except that it assumes the operand isn't of function or array
7537   // type.
7538   ExprResult DefaultLvalueConversion(Expr *E);
7539 
7540   // DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
7541   // do not have a prototype. Integer promotions are performed on each
7542   // argument, and arguments that have type float are promoted to double.
7543   ExprResult DefaultArgumentPromotion(Expr *E);
7544 
7545   // Used for emitting the right warning by DefaultVariadicArgumentPromotion
7546   enum VariadicCallType {
7547     VariadicFunction,
7548     VariadicBlock,
7549     VariadicMethod,
7550     VariadicConstructor,
7551     VariadicDoesNotApply
7552   };
7553 
7554   VariadicCallType getVariadicCallType(FunctionDecl *FDecl,
7555                                        const FunctionProtoType *Proto,
7556                                        Expr *Fn);
7557 
7558   // Used for determining in which context a type is allowed to be passed to a
7559   // vararg function.
7560   enum VarArgKind {
7561     VAK_Valid,
7562     VAK_ValidInCXX11,
7563     VAK_Undefined,
7564     VAK_Invalid
7565   };
7566 
7567   // Determines which VarArgKind fits an expression.
7568   VarArgKind isValidVarArgType(const QualType &Ty);
7569 
7570   /// Check to see if the given expression is a valid argument to a variadic
7571   /// function, issuing a diagnostic if not.
7572   void checkVariadicArgument(const Expr *E, VariadicCallType CT);
7573 
7574   /// Check to see if a given expression could have '.c_str()' called on it.
7575   bool hasCStrMethod(const Expr *E);
7576 
7577   /// GatherArgumentsForCall - Collector argument expressions for various
7578   /// form of call prototypes.
7579   bool GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl,
7580                               const FunctionProtoType *Proto,
7581                               unsigned FirstParam, ArrayRef<Expr *> Args,
7582                               SmallVectorImpl<Expr *> &AllArgs,
7583                               VariadicCallType CallType = VariadicDoesNotApply,
7584                               bool AllowExplicit = false,
7585                               bool IsListInitialization = false);
7586 
7587   // DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
7588   // will create a runtime trap if the resulting type is not a POD type.
7589   ExprResult DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
7590                                               FunctionDecl *FDecl);
7591 
7592   // UsualArithmeticConversions - performs the UsualUnaryConversions on it's
7593   // operands and then handles various conversions that are common to binary
7594   // operators (C99 6.3.1.8). If both operands aren't arithmetic, this
7595   // routine returns the first non-arithmetic type found. The client is
7596   // responsible for emitting appropriate error diagnostics.
7597   QualType UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
7598                                       bool IsCompAssign = false);
7599 
7600   /// AssignConvertType - All of the 'assignment' semantic checks return this
7601   /// enum to indicate whether the assignment was allowed.  These checks are
7602   /// done for simple assignments, as well as initialization, return from
7603   /// function, argument passing, etc.  The query is phrased in terms of a
7604   /// source and destination type.
7605   enum AssignConvertType {
7606     /// Compatible - the types are compatible according to the standard.
7607     Compatible,
7608 
7609     /// PointerToInt - The assignment converts a pointer to an int, which we
7610     /// accept as an extension.
7611     PointerToInt,
7612 
7613     /// IntToPointer - The assignment converts an int to a pointer, which we
7614     /// accept as an extension.
7615     IntToPointer,
7616 
7617     /// FunctionVoidPointer - The assignment is between a function pointer and
7618     /// void*, which the standard doesn't allow, but we accept as an extension.
7619     FunctionVoidPointer,
7620 
7621     /// IncompatiblePointer - The assignment is between two pointers types that
7622     /// are not compatible, but we accept them as an extension.
7623     IncompatiblePointer,
7624 
7625     /// IncompatiblePointer - The assignment is between two pointers types which
7626     /// point to integers which have a different sign, but are otherwise
7627     /// identical. This is a subset of the above, but broken out because it's by
7628     /// far the most common case of incompatible pointers.
7629     IncompatiblePointerSign,
7630 
7631     /// CompatiblePointerDiscardsQualifiers - The assignment discards
7632     /// c/v/r qualifiers, which we accept as an extension.
7633     CompatiblePointerDiscardsQualifiers,
7634 
7635     /// IncompatiblePointerDiscardsQualifiers - The assignment
7636     /// discards qualifiers that we don't permit to be discarded,
7637     /// like address spaces.
7638     IncompatiblePointerDiscardsQualifiers,
7639 
7640     /// IncompatibleNestedPointerQualifiers - The assignment is between two
7641     /// nested pointer types, and the qualifiers other than the first two
7642     /// levels differ e.g. char ** -> const char **, but we accept them as an
7643     /// extension.
7644     IncompatibleNestedPointerQualifiers,
7645 
7646     /// IncompatibleVectors - The assignment is between two vector types that
7647     /// have the same size, which we accept as an extension.
7648     IncompatibleVectors,
7649 
7650     /// IntToBlockPointer - The assignment converts an int to a block
7651     /// pointer. We disallow this.
7652     IntToBlockPointer,
7653 
7654     /// IncompatibleBlockPointer - The assignment is between two block
7655     /// pointers types that are not compatible.
7656     IncompatibleBlockPointer,
7657 
7658     /// IncompatibleObjCQualifiedId - The assignment is between a qualified
7659     /// id type and something else (that is incompatible with it). For example,
7660     /// "id <XXX>" = "Foo *", where "Foo *" doesn't implement the XXX protocol.
7661     IncompatibleObjCQualifiedId,
7662 
7663     /// IncompatibleObjCWeakRef - Assigning a weak-unavailable object to an
7664     /// object with __weak qualifier.
7665     IncompatibleObjCWeakRef,
7666 
7667     /// Incompatible - We reject this conversion outright, it is invalid to
7668     /// represent it in the AST.
7669     Incompatible
7670   };
7671 
7672   /// DiagnoseAssignmentResult - Emit a diagnostic, if required, for the
7673   /// assignment conversion type specified by ConvTy.  This returns true if the
7674   /// conversion was invalid or false if the conversion was accepted.
7675   bool DiagnoseAssignmentResult(AssignConvertType ConvTy,
7676                                 SourceLocation Loc,
7677                                 QualType DstType, QualType SrcType,
7678                                 Expr *SrcExpr, AssignmentAction Action,
7679                                 bool *Complained = nullptr);
7680 
7681   /// DiagnoseAssignmentEnum - Warn if assignment to enum is a constant
7682   /// integer not in the range of enum values.
7683   void DiagnoseAssignmentEnum(QualType DstType, QualType SrcType,
7684                               Expr *SrcExpr);
7685 
7686   /// CheckAssignmentConstraints - Perform type checking for assignment,
7687   /// argument passing, variable initialization, and function return values.
7688   /// C99 6.5.16.
7689   AssignConvertType CheckAssignmentConstraints(SourceLocation Loc,
7690                                                QualType LHSType,
7691                                                QualType RHSType);
7692 
7693   /// Check assignment constraints and prepare for a conversion of the
7694   /// RHS to the LHS type.
7695   AssignConvertType CheckAssignmentConstraints(QualType LHSType,
7696                                                ExprResult &RHS,
7697                                                CastKind &Kind);
7698 
7699   // CheckSingleAssignmentConstraints - Currently used by
7700   // CheckAssignmentOperands, and ActOnReturnStmt. Prior to type checking,
7701   // this routine performs the default function/array converions.
7702   AssignConvertType CheckSingleAssignmentConstraints(QualType LHSType,
7703                                                      ExprResult &RHS,
7704                                                      bool Diagnose = true,
7705                                                      bool DiagnoseCFAudited = false);
7706 
7707   // \brief If the lhs type is a transparent union, check whether we
7708   // can initialize the transparent union with the given expression.
7709   AssignConvertType CheckTransparentUnionArgumentConstraints(QualType ArgType,
7710                                                              ExprResult &RHS);
7711 
7712   bool IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType);
7713 
7714   bool CheckExceptionSpecCompatibility(Expr *From, QualType ToType);
7715 
7716   ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
7717                                        AssignmentAction Action,
7718                                        bool AllowExplicit = false);
7719   ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
7720                                        AssignmentAction Action,
7721                                        bool AllowExplicit,
7722                                        ImplicitConversionSequence& ICS);
7723   ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
7724                                        const ImplicitConversionSequence& ICS,
7725                                        AssignmentAction Action,
7726                                        CheckedConversionKind CCK
7727                                           = CCK_ImplicitConversion);
7728   ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
7729                                        const StandardConversionSequence& SCS,
7730                                        AssignmentAction Action,
7731                                        CheckedConversionKind CCK);
7732 
7733   /// the following "Check" methods will return a valid/converted QualType
7734   /// or a null QualType (indicating an error diagnostic was issued).
7735 
7736   /// type checking binary operators (subroutines of CreateBuiltinBinOp).
7737   QualType InvalidOperands(SourceLocation Loc, ExprResult &LHS,
7738                            ExprResult &RHS);
7739   QualType CheckPointerToMemberOperands( // C++ 5.5
7740     ExprResult &LHS, ExprResult &RHS, ExprValueKind &VK,
7741     SourceLocation OpLoc, bool isIndirect);
7742   QualType CheckMultiplyDivideOperands( // C99 6.5.5
7743     ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign,
7744     bool IsDivide);
7745   QualType CheckRemainderOperands( // C99 6.5.5
7746     ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
7747     bool IsCompAssign = false);
7748   QualType CheckAdditionOperands( // C99 6.5.6
7749     ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc,
7750     QualType* CompLHSTy = nullptr);
7751   QualType CheckSubtractionOperands( // C99 6.5.6
7752     ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
7753     QualType* CompLHSTy = nullptr);
7754   QualType CheckShiftOperands( // C99 6.5.7
7755     ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc,
7756     bool IsCompAssign = false);
7757   QualType CheckCompareOperands( // C99 6.5.8/9
7758     ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned OpaqueOpc,
7759                                 bool isRelational);
7760   QualType CheckBitwiseOperands( // C99 6.5.[10...12]
7761     ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
7762     bool IsCompAssign = false);
7763   QualType CheckLogicalOperands( // C99 6.5.[13,14]
7764     ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc);
7765   // CheckAssignmentOperands is used for both simple and compound assignment.
7766   // For simple assignment, pass both expressions and a null converted type.
7767   // For compound assignment, pass both expressions and the converted type.
7768   QualType CheckAssignmentOperands( // C99 6.5.16.[1,2]
7769     Expr *LHSExpr, ExprResult &RHS, SourceLocation Loc, QualType CompoundType);
7770 
7771   ExprResult checkPseudoObjectIncDec(Scope *S, SourceLocation OpLoc,
7772                                      UnaryOperatorKind Opcode, Expr *Op);
7773   ExprResult checkPseudoObjectAssignment(Scope *S, SourceLocation OpLoc,
7774                                          BinaryOperatorKind Opcode,
7775                                          Expr *LHS, Expr *RHS);
7776   ExprResult checkPseudoObjectRValue(Expr *E);
7777   Expr *recreateSyntacticForm(PseudoObjectExpr *E);
7778 
7779   QualType CheckConditionalOperands( // C99 6.5.15
7780     ExprResult &Cond, ExprResult &LHS, ExprResult &RHS,
7781     ExprValueKind &VK, ExprObjectKind &OK, SourceLocation QuestionLoc);
7782   QualType CXXCheckConditionalOperands( // C++ 5.16
7783     ExprResult &cond, ExprResult &lhs, ExprResult &rhs,
7784     ExprValueKind &VK, ExprObjectKind &OK, SourceLocation questionLoc);
7785   QualType FindCompositePointerType(SourceLocation Loc, Expr *&E1, Expr *&E2,
7786                                     bool *NonStandardCompositeType = nullptr);
7787   QualType FindCompositePointerType(SourceLocation Loc,
7788                                     ExprResult &E1, ExprResult &E2,
7789                                     bool *NonStandardCompositeType = nullptr) {
7790     Expr *E1Tmp = E1.get(), *E2Tmp = E2.get();
7791     QualType Composite = FindCompositePointerType(Loc, E1Tmp, E2Tmp,
7792                                                   NonStandardCompositeType);
7793     E1 = E1Tmp;
7794     E2 = E2Tmp;
7795     return Composite;
7796   }
7797 
7798   QualType FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
7799                                         SourceLocation QuestionLoc);
7800 
7801   bool DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
7802                                   SourceLocation QuestionLoc);
7803 
7804   void DiagnoseAlwaysNonNullPointer(Expr *E,
7805                                     Expr::NullPointerConstantKind NullType,
7806                                     bool IsEqual, SourceRange Range);
7807 
7808   /// type checking for vector binary operators.
7809   QualType CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
7810                                SourceLocation Loc, bool IsCompAssign);
7811   QualType GetSignedVectorType(QualType V);
7812   QualType CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
7813                                       SourceLocation Loc, bool isRelational);
7814   QualType CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
7815                                       SourceLocation Loc);
7816 
7817   bool isLaxVectorConversion(QualType srcType, QualType destType);
7818 
7819   /// type checking declaration initializers (C99 6.7.8)
7820   bool CheckForConstantInitializer(Expr *e, QualType t);
7821 
7822   // type checking C++ declaration initializers (C++ [dcl.init]).
7823 
7824   /// ReferenceCompareResult - Expresses the result of comparing two
7825   /// types (cv1 T1 and cv2 T2) to determine their compatibility for the
7826   /// purposes of initialization by reference (C++ [dcl.init.ref]p4).
7827   enum ReferenceCompareResult {
7828     /// Ref_Incompatible - The two types are incompatible, so direct
7829     /// reference binding is not possible.
7830     Ref_Incompatible = 0,
7831     /// Ref_Related - The two types are reference-related, which means
7832     /// that their unqualified forms (T1 and T2) are either the same
7833     /// or T1 is a base class of T2.
7834     Ref_Related,
7835     /// Ref_Compatible_With_Added_Qualification - The two types are
7836     /// reference-compatible with added qualification, meaning that
7837     /// they are reference-compatible and the qualifiers on T1 (cv1)
7838     /// are greater than the qualifiers on T2 (cv2).
7839     Ref_Compatible_With_Added_Qualification,
7840     /// Ref_Compatible - The two types are reference-compatible and
7841     /// have equivalent qualifiers (cv1 == cv2).
7842     Ref_Compatible
7843   };
7844 
7845   ReferenceCompareResult CompareReferenceRelationship(SourceLocation Loc,
7846                                                       QualType T1, QualType T2,
7847                                                       bool &DerivedToBase,
7848                                                       bool &ObjCConversion,
7849                                                 bool &ObjCLifetimeConversion);
7850 
7851   ExprResult checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
7852                                  Expr *CastExpr, CastKind &CastKind,
7853                                  ExprValueKind &VK, CXXCastPath &Path);
7854 
7855   /// \brief Force an expression with unknown-type to an expression of the
7856   /// given type.
7857   ExprResult forceUnknownAnyToType(Expr *E, QualType ToType);
7858 
7859   /// \brief Type-check an expression that's being passed to an
7860   /// __unknown_anytype parameter.
7861   ExprResult checkUnknownAnyArg(SourceLocation callLoc,
7862                                 Expr *result, QualType &paramType);
7863 
7864   // CheckVectorCast - check type constraints for vectors.
7865   // Since vectors are an extension, there are no C standard reference for this.
7866   // We allow casting between vectors and integer datatypes of the same size.
7867   // returns true if the cast is invalid
7868   bool CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
7869                        CastKind &Kind);
7870 
7871   // CheckExtVectorCast - check type constraints for extended vectors.
7872   // Since vectors are an extension, there are no C standard reference for this.
7873   // We allow casting between vectors and integer datatypes of the same size,
7874   // or vectors and the element type of that vector.
7875   // returns the cast expr
7876   ExprResult CheckExtVectorCast(SourceRange R, QualType DestTy, Expr *CastExpr,
7877                                 CastKind &Kind);
7878 
7879   ExprResult BuildCXXFunctionalCastExpr(TypeSourceInfo *TInfo,
7880                                         SourceLocation LParenLoc,
7881                                         Expr *CastExpr,
7882                                         SourceLocation RParenLoc);
7883 
7884   enum ARCConversionResult { ACR_okay, ACR_unbridged };
7885 
7886   /// \brief Checks for invalid conversions and casts between
7887   /// retainable pointers and other pointer kinds.
7888   ARCConversionResult CheckObjCARCConversion(SourceRange castRange,
7889                                              QualType castType, Expr *&op,
7890                                              CheckedConversionKind CCK,
7891                                              bool DiagnoseCFAudited = false,
7892                                              BinaryOperatorKind Opc = BO_PtrMemD
7893                                              );
7894 
7895   Expr *stripARCUnbridgedCast(Expr *e);
7896   void diagnoseARCUnbridgedCast(Expr *e);
7897 
7898   bool CheckObjCARCUnavailableWeakConversion(QualType castType,
7899                                              QualType ExprType);
7900 
7901   /// checkRetainCycles - Check whether an Objective-C message send
7902   /// might create an obvious retain cycle.
7903   void checkRetainCycles(ObjCMessageExpr *msg);
7904   void checkRetainCycles(Expr *receiver, Expr *argument);
7905   void checkRetainCycles(VarDecl *Var, Expr *Init);
7906 
7907   /// checkUnsafeAssigns - Check whether +1 expr is being assigned
7908   /// to weak/__unsafe_unretained type.
7909   bool checkUnsafeAssigns(SourceLocation Loc, QualType LHS, Expr *RHS);
7910 
7911   /// checkUnsafeExprAssigns - Check whether +1 expr is being assigned
7912   /// to weak/__unsafe_unretained expression.
7913   void checkUnsafeExprAssigns(SourceLocation Loc, Expr *LHS, Expr *RHS);
7914 
7915   /// CheckMessageArgumentTypes - Check types in an Obj-C message send.
7916   /// \param Method - May be null.
7917   /// \param [out] ReturnType - The return type of the send.
7918   /// \return true iff there were any incompatible types.
7919   bool CheckMessageArgumentTypes(QualType ReceiverType,
7920                                  MultiExprArg Args, Selector Sel,
7921                                  ArrayRef<SourceLocation> SelectorLocs,
7922                                  ObjCMethodDecl *Method, bool isClassMessage,
7923                                  bool isSuperMessage,
7924                                  SourceLocation lbrac, SourceLocation rbrac,
7925                                  QualType &ReturnType, ExprValueKind &VK);
7926 
7927   /// \brief Determine the result of a message send expression based on
7928   /// the type of the receiver, the method expected to receive the message,
7929   /// and the form of the message send.
7930   QualType getMessageSendResultType(QualType ReceiverType,
7931                                     ObjCMethodDecl *Method,
7932                                     bool isClassMessage, bool isSuperMessage);
7933 
7934   /// \brief If the given expression involves a message send to a method
7935   /// with a related result type, emit a note describing what happened.
7936   void EmitRelatedResultTypeNote(const Expr *E);
7937 
7938   /// \brief Given that we had incompatible pointer types in a return
7939   /// statement, check whether we're in a method with a related result
7940   /// type, and if so, emit a note describing what happened.
7941   void EmitRelatedResultTypeNoteForReturn(QualType destType);
7942 
7943   /// CheckBooleanCondition - Diagnose problems involving the use of
7944   /// the given expression as a boolean condition (e.g. in an if
7945   /// statement).  Also performs the standard function and array
7946   /// decays, possibly changing the input variable.
7947   ///
7948   /// \param Loc - A location associated with the condition, e.g. the
7949   /// 'if' keyword.
7950   /// \return true iff there were any errors
7951   ExprResult CheckBooleanCondition(Expr *E, SourceLocation Loc);
7952 
7953   ExprResult ActOnBooleanCondition(Scope *S, SourceLocation Loc,
7954                                    Expr *SubExpr);
7955 
7956   /// DiagnoseAssignmentAsCondition - Given that an expression is
7957   /// being used as a boolean condition, warn if it's an assignment.
7958   void DiagnoseAssignmentAsCondition(Expr *E);
7959 
7960   /// \brief Redundant parentheses over an equality comparison can indicate
7961   /// that the user intended an assignment used as condition.
7962   void DiagnoseEqualityWithExtraParens(ParenExpr *ParenE);
7963 
7964   /// CheckCXXBooleanCondition - Returns true if conversion to bool is invalid.
7965   ExprResult CheckCXXBooleanCondition(Expr *CondExpr);
7966 
7967   /// ConvertIntegerToTypeWarnOnOverflow - Convert the specified APInt to have
7968   /// the specified width and sign.  If an overflow occurs, detect it and emit
7969   /// the specified diagnostic.
7970   void ConvertIntegerToTypeWarnOnOverflow(llvm::APSInt &OldVal,
7971                                           unsigned NewWidth, bool NewSign,
7972                                           SourceLocation Loc, unsigned DiagID);
7973 
7974   /// Checks that the Objective-C declaration is declared in the global scope.
7975   /// Emits an error and marks the declaration as invalid if it's not declared
7976   /// in the global scope.
7977   bool CheckObjCDeclScope(Decl *D);
7978 
7979   /// \brief Abstract base class used for diagnosing integer constant
7980   /// expression violations.
7981   class VerifyICEDiagnoser {
7982   public:
7983     bool Suppress;
7984 
Suppress(Suppress)7985     VerifyICEDiagnoser(bool Suppress = false) : Suppress(Suppress) { }
7986 
7987     virtual void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) =0;
7988     virtual void diagnoseFold(Sema &S, SourceLocation Loc, SourceRange SR);
~VerifyICEDiagnoser()7989     virtual ~VerifyICEDiagnoser() { }
7990   };
7991 
7992   /// VerifyIntegerConstantExpression - Verifies that an expression is an ICE,
7993   /// and reports the appropriate diagnostics. Returns false on success.
7994   /// Can optionally return the value of the expression.
7995   ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
7996                                              VerifyICEDiagnoser &Diagnoser,
7997                                              bool AllowFold = true);
7998   ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
7999                                              unsigned DiagID,
8000                                              bool AllowFold = true);
8001   ExprResult VerifyIntegerConstantExpression(Expr *E,
8002                                              llvm::APSInt *Result = nullptr);
8003 
8004   /// VerifyBitField - verifies that a bit field expression is an ICE and has
8005   /// the correct width, and that the field type is valid.
8006   /// Returns false on success.
8007   /// Can optionally return whether the bit-field is of width 0
8008   ExprResult VerifyBitField(SourceLocation FieldLoc, IdentifierInfo *FieldName,
8009                             QualType FieldTy, bool IsMsStruct,
8010                             Expr *BitWidth, bool *ZeroWidth = nullptr);
8011 
8012   enum CUDAFunctionTarget {
8013     CFT_Device,
8014     CFT_Global,
8015     CFT_Host,
8016     CFT_HostDevice
8017   };
8018 
8019   CUDAFunctionTarget IdentifyCUDATarget(const FunctionDecl *D);
8020 
8021   bool CheckCUDATarget(CUDAFunctionTarget CallerTarget,
8022                        CUDAFunctionTarget CalleeTarget);
8023 
CheckCUDATarget(const FunctionDecl * Caller,const FunctionDecl * Callee)8024   bool CheckCUDATarget(const FunctionDecl *Caller, const FunctionDecl *Callee) {
8025     return CheckCUDATarget(IdentifyCUDATarget(Caller),
8026                            IdentifyCUDATarget(Callee));
8027   }
8028 
8029   /// \name Code completion
8030   //@{
8031   /// \brief Describes the context in which code completion occurs.
8032   enum ParserCompletionContext {
8033     /// \brief Code completion occurs at top-level or namespace context.
8034     PCC_Namespace,
8035     /// \brief Code completion occurs within a class, struct, or union.
8036     PCC_Class,
8037     /// \brief Code completion occurs within an Objective-C interface, protocol,
8038     /// or category.
8039     PCC_ObjCInterface,
8040     /// \brief Code completion occurs within an Objective-C implementation or
8041     /// category implementation
8042     PCC_ObjCImplementation,
8043     /// \brief Code completion occurs within the list of instance variables
8044     /// in an Objective-C interface, protocol, category, or implementation.
8045     PCC_ObjCInstanceVariableList,
8046     /// \brief Code completion occurs following one or more template
8047     /// headers.
8048     PCC_Template,
8049     /// \brief Code completion occurs following one or more template
8050     /// headers within a class.
8051     PCC_MemberTemplate,
8052     /// \brief Code completion occurs within an expression.
8053     PCC_Expression,
8054     /// \brief Code completion occurs within a statement, which may
8055     /// also be an expression or a declaration.
8056     PCC_Statement,
8057     /// \brief Code completion occurs at the beginning of the
8058     /// initialization statement (or expression) in a for loop.
8059     PCC_ForInit,
8060     /// \brief Code completion occurs within the condition of an if,
8061     /// while, switch, or for statement.
8062     PCC_Condition,
8063     /// \brief Code completion occurs within the body of a function on a
8064     /// recovery path, where we do not have a specific handle on our position
8065     /// in the grammar.
8066     PCC_RecoveryInFunction,
8067     /// \brief Code completion occurs where only a type is permitted.
8068     PCC_Type,
8069     /// \brief Code completion occurs in a parenthesized expression, which
8070     /// might also be a type cast.
8071     PCC_ParenthesizedExpression,
8072     /// \brief Code completion occurs within a sequence of declaration
8073     /// specifiers within a function, method, or block.
8074     PCC_LocalDeclarationSpecifiers
8075   };
8076 
8077   void CodeCompleteModuleImport(SourceLocation ImportLoc, ModuleIdPath Path);
8078   void CodeCompleteOrdinaryName(Scope *S,
8079                                 ParserCompletionContext CompletionContext);
8080   void CodeCompleteDeclSpec(Scope *S, DeclSpec &DS,
8081                             bool AllowNonIdentifiers,
8082                             bool AllowNestedNameSpecifiers);
8083 
8084   struct CodeCompleteExpressionData;
8085   void CodeCompleteExpression(Scope *S,
8086                               const CodeCompleteExpressionData &Data);
8087   void CodeCompleteMemberReferenceExpr(Scope *S, Expr *Base,
8088                                        SourceLocation OpLoc,
8089                                        bool IsArrow);
8090   void CodeCompletePostfixExpression(Scope *S, ExprResult LHS);
8091   void CodeCompleteTag(Scope *S, unsigned TagSpec);
8092   void CodeCompleteTypeQualifiers(DeclSpec &DS);
8093   void CodeCompleteCase(Scope *S);
8094   void CodeCompleteCall(Scope *S, Expr *Fn, ArrayRef<Expr *> Args);
8095   void CodeCompleteInitializer(Scope *S, Decl *D);
8096   void CodeCompleteReturn(Scope *S);
8097   void CodeCompleteAfterIf(Scope *S);
8098   void CodeCompleteAssignmentRHS(Scope *S, Expr *LHS);
8099 
8100   void CodeCompleteQualifiedId(Scope *S, CXXScopeSpec &SS,
8101                                bool EnteringContext);
8102   void CodeCompleteUsing(Scope *S);
8103   void CodeCompleteUsingDirective(Scope *S);
8104   void CodeCompleteNamespaceDecl(Scope *S);
8105   void CodeCompleteNamespaceAliasDecl(Scope *S);
8106   void CodeCompleteOperatorName(Scope *S);
8107   void CodeCompleteConstructorInitializer(
8108                                 Decl *Constructor,
8109                                 ArrayRef<CXXCtorInitializer *> Initializers);
8110 
8111   void CodeCompleteLambdaIntroducer(Scope *S, LambdaIntroducer &Intro,
8112                                     bool AfterAmpersand);
8113 
8114   void CodeCompleteObjCAtDirective(Scope *S);
8115   void CodeCompleteObjCAtVisibility(Scope *S);
8116   void CodeCompleteObjCAtStatement(Scope *S);
8117   void CodeCompleteObjCAtExpression(Scope *S);
8118   void CodeCompleteObjCPropertyFlags(Scope *S, ObjCDeclSpec &ODS);
8119   void CodeCompleteObjCPropertyGetter(Scope *S);
8120   void CodeCompleteObjCPropertySetter(Scope *S);
8121   void CodeCompleteObjCPassingType(Scope *S, ObjCDeclSpec &DS,
8122                                    bool IsParameter);
8123   void CodeCompleteObjCMessageReceiver(Scope *S);
8124   void CodeCompleteObjCSuperMessage(Scope *S, SourceLocation SuperLoc,
8125                                     ArrayRef<IdentifierInfo *> SelIdents,
8126                                     bool AtArgumentExpression);
8127   void CodeCompleteObjCClassMessage(Scope *S, ParsedType Receiver,
8128                                     ArrayRef<IdentifierInfo *> SelIdents,
8129                                     bool AtArgumentExpression,
8130                                     bool IsSuper = false);
8131   void CodeCompleteObjCInstanceMessage(Scope *S, Expr *Receiver,
8132                                        ArrayRef<IdentifierInfo *> SelIdents,
8133                                        bool AtArgumentExpression,
8134                                        ObjCInterfaceDecl *Super = nullptr);
8135   void CodeCompleteObjCForCollection(Scope *S,
8136                                      DeclGroupPtrTy IterationVar);
8137   void CodeCompleteObjCSelector(Scope *S,
8138                                 ArrayRef<IdentifierInfo *> SelIdents);
8139   void CodeCompleteObjCProtocolReferences(IdentifierLocPair *Protocols,
8140                                           unsigned NumProtocols);
8141   void CodeCompleteObjCProtocolDecl(Scope *S);
8142   void CodeCompleteObjCInterfaceDecl(Scope *S);
8143   void CodeCompleteObjCSuperclass(Scope *S,
8144                                   IdentifierInfo *ClassName,
8145                                   SourceLocation ClassNameLoc);
8146   void CodeCompleteObjCImplementationDecl(Scope *S);
8147   void CodeCompleteObjCInterfaceCategory(Scope *S,
8148                                          IdentifierInfo *ClassName,
8149                                          SourceLocation ClassNameLoc);
8150   void CodeCompleteObjCImplementationCategory(Scope *S,
8151                                               IdentifierInfo *ClassName,
8152                                               SourceLocation ClassNameLoc);
8153   void CodeCompleteObjCPropertyDefinition(Scope *S);
8154   void CodeCompleteObjCPropertySynthesizeIvar(Scope *S,
8155                                               IdentifierInfo *PropertyName);
8156   void CodeCompleteObjCMethodDecl(Scope *S,
8157                                   bool IsInstanceMethod,
8158                                   ParsedType ReturnType);
8159   void CodeCompleteObjCMethodDeclSelector(Scope *S,
8160                                           bool IsInstanceMethod,
8161                                           bool AtParameterName,
8162                                           ParsedType ReturnType,
8163                                           ArrayRef<IdentifierInfo *> SelIdents);
8164   void CodeCompletePreprocessorDirective(bool InConditional);
8165   void CodeCompleteInPreprocessorConditionalExclusion(Scope *S);
8166   void CodeCompletePreprocessorMacroName(bool IsDefinition);
8167   void CodeCompletePreprocessorExpression();
8168   void CodeCompletePreprocessorMacroArgument(Scope *S,
8169                                              IdentifierInfo *Macro,
8170                                              MacroInfo *MacroInfo,
8171                                              unsigned Argument);
8172   void CodeCompleteNaturalLanguage();
8173   void GatherGlobalCodeCompletions(CodeCompletionAllocator &Allocator,
8174                                    CodeCompletionTUInfo &CCTUInfo,
8175                   SmallVectorImpl<CodeCompletionResult> &Results);
8176   //@}
8177 
8178   //===--------------------------------------------------------------------===//
8179   // Extra semantic analysis beyond the C type system
8180 
8181 public:
8182   SourceLocation getLocationOfStringLiteralByte(const StringLiteral *SL,
8183                                                 unsigned ByteNo) const;
8184 
8185 private:
8186   void CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
8187                         const ArraySubscriptExpr *ASE=nullptr,
8188                         bool AllowOnePastEnd=true, bool IndexNegated=false);
8189   void CheckArrayAccess(const Expr *E);
8190   // Used to grab the relevant information from a FormatAttr and a
8191   // FunctionDeclaration.
8192   struct FormatStringInfo {
8193     unsigned FormatIdx;
8194     unsigned FirstDataArg;
8195     bool HasVAListArg;
8196   };
8197 
8198   bool getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
8199                            FormatStringInfo *FSI);
8200   bool CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
8201                          const FunctionProtoType *Proto);
8202   bool CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation loc,
8203                            ArrayRef<const Expr *> Args);
8204   bool CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
8205                         const FunctionProtoType *Proto);
8206   bool CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto);
8207   void CheckConstructorCall(FunctionDecl *FDecl,
8208                             ArrayRef<const Expr *> Args,
8209                             const FunctionProtoType *Proto,
8210                             SourceLocation Loc);
8211 
8212   void checkCall(NamedDecl *FDecl, ArrayRef<const Expr *> Args,
8213                  unsigned NumParams, bool IsMemberFunction, SourceLocation Loc,
8214                  SourceRange Range, VariadicCallType CallType);
8215 
8216   bool CheckObjCString(Expr *Arg);
8217 
8218   ExprResult CheckBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
8219 
8220   bool CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
8221                                     unsigned MaxWidth);
8222   bool CheckNeonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
8223   bool CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
8224 
8225   bool CheckAArch64BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
8226   bool CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
8227   bool CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
8228 
8229   bool SemaBuiltinVAStart(CallExpr *TheCall);
8230   bool SemaBuiltinUnorderedCompare(CallExpr *TheCall);
8231   bool SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs);
8232 
8233 public:
8234   // Used by C++ template instantiation.
8235   ExprResult SemaBuiltinShuffleVector(CallExpr *TheCall);
8236   ExprResult SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
8237                                    SourceLocation BuiltinLoc,
8238                                    SourceLocation RParenLoc);
8239 
8240 private:
8241   bool SemaBuiltinPrefetch(CallExpr *TheCall);
8242   bool SemaBuiltinLongjmp(CallExpr *TheCall);
8243   ExprResult SemaBuiltinAtomicOverloaded(ExprResult TheCallResult);
8244   ExprResult SemaAtomicOpsOverloaded(ExprResult TheCallResult,
8245                                      AtomicExpr::AtomicOp Op);
8246   bool SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
8247                               llvm::APSInt &Result);
8248   bool SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
8249                                    int Low, int High);
8250 
8251 public:
8252   enum FormatStringType {
8253     FST_Scanf,
8254     FST_Printf,
8255     FST_NSString,
8256     FST_Strftime,
8257     FST_Strfmon,
8258     FST_Kprintf,
8259     FST_Unknown
8260   };
8261   static FormatStringType GetFormatStringType(const FormatAttr *Format);
8262 
8263   void CheckFormatString(const StringLiteral *FExpr, const Expr *OrigFormatExpr,
8264                          ArrayRef<const Expr *> Args, bool HasVAListArg,
8265                          unsigned format_idx, unsigned firstDataArg,
8266                          FormatStringType Type, bool inFunctionCall,
8267                          VariadicCallType CallType,
8268                          llvm::SmallBitVector &CheckedVarArgs);
8269 
8270 private:
8271   bool CheckFormatArguments(const FormatAttr *Format,
8272                             ArrayRef<const Expr *> Args,
8273                             bool IsCXXMember,
8274                             VariadicCallType CallType,
8275                             SourceLocation Loc, SourceRange Range,
8276                             llvm::SmallBitVector &CheckedVarArgs);
8277   bool CheckFormatArguments(ArrayRef<const Expr *> Args,
8278                             bool HasVAListArg, unsigned format_idx,
8279                             unsigned firstDataArg, FormatStringType Type,
8280                             VariadicCallType CallType,
8281                             SourceLocation Loc, SourceRange range,
8282                             llvm::SmallBitVector &CheckedVarArgs);
8283 
8284   void CheckAbsoluteValueFunction(const CallExpr *Call,
8285                                   const FunctionDecl *FDecl,
8286                                   IdentifierInfo *FnInfo);
8287 
8288   void CheckMemaccessArguments(const CallExpr *Call,
8289                                unsigned BId,
8290                                IdentifierInfo *FnName);
8291 
8292   void CheckStrlcpycatArguments(const CallExpr *Call,
8293                                 IdentifierInfo *FnName);
8294 
8295   void CheckStrncatArguments(const CallExpr *Call,
8296                              IdentifierInfo *FnName);
8297 
8298   void CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
8299                           SourceLocation ReturnLoc,
8300                           bool isObjCMethod = false,
8301                           const AttrVec *Attrs = nullptr,
8302                           const FunctionDecl *FD = nullptr);
8303 
8304   void CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr* RHS);
8305   void CheckImplicitConversions(Expr *E, SourceLocation CC = SourceLocation());
8306   void CheckForIntOverflow(Expr *E);
8307   void CheckUnsequencedOperations(Expr *E);
8308 
8309   /// \brief Perform semantic checks on a completed expression. This will either
8310   /// be a full-expression or a default argument expression.
8311   void CheckCompletedExpr(Expr *E, SourceLocation CheckLoc = SourceLocation(),
8312                           bool IsConstexpr = false);
8313 
8314   void CheckBitFieldInitialization(SourceLocation InitLoc, FieldDecl *Field,
8315                                    Expr *Init);
8316 
8317   /// \brief Check if the given expression contains 'break' or 'continue'
8318   /// statement that produces control flow different from GCC.
8319   void CheckBreakContinueBinding(Expr *E);
8320 
8321 public:
8322   /// \brief Register a magic integral constant to be used as a type tag.
8323   void RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
8324                                   uint64_t MagicValue, QualType Type,
8325                                   bool LayoutCompatible, bool MustBeNull);
8326 
8327   struct TypeTagData {
TypeTagDataTypeTagData8328     TypeTagData() {}
8329 
TypeTagDataTypeTagData8330     TypeTagData(QualType Type, bool LayoutCompatible, bool MustBeNull) :
8331         Type(Type), LayoutCompatible(LayoutCompatible),
8332         MustBeNull(MustBeNull)
8333     {}
8334 
8335     QualType Type;
8336 
8337     /// If true, \c Type should be compared with other expression's types for
8338     /// layout-compatibility.
8339     unsigned LayoutCompatible : 1;
8340     unsigned MustBeNull : 1;
8341   };
8342 
8343   /// A pair of ArgumentKind identifier and magic value.  This uniquely
8344   /// identifies the magic value.
8345   typedef std::pair<const IdentifierInfo *, uint64_t> TypeTagMagicValue;
8346 
8347 private:
8348   /// \brief A map from magic value to type information.
8349   std::unique_ptr<llvm::DenseMap<TypeTagMagicValue, TypeTagData>>
8350       TypeTagForDatatypeMagicValues;
8351 
8352   /// \brief Peform checks on a call of a function with argument_with_type_tag
8353   /// or pointer_with_type_tag attributes.
8354   void CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
8355                                 const Expr * const *ExprArgs);
8356 
8357   /// \brief The parser's current scope.
8358   ///
8359   /// The parser maintains this state here.
8360   Scope *CurScope;
8361 
8362   mutable IdentifierInfo *Ident_super;
8363   mutable IdentifierInfo *Ident___float128;
8364 
8365 protected:
8366   friend class Parser;
8367   friend class InitializationSequence;
8368   friend class ASTReader;
8369   friend class ASTWriter;
8370 
8371 public:
8372   /// \brief Retrieve the parser's current scope.
8373   ///
8374   /// This routine must only be used when it is certain that semantic analysis
8375   /// and the parser are in precisely the same context, which is not the case
8376   /// when, e.g., we are performing any kind of template instantiation.
8377   /// Therefore, the only safe places to use this scope are in the parser
8378   /// itself and in routines directly invoked from the parser and *never* from
8379   /// template substitution or instantiation.
getCurScope()8380   Scope *getCurScope() const { return CurScope; }
8381 
incrementMSLocalManglingNumber()8382   void incrementMSLocalManglingNumber() const {
8383     return CurScope->incrementMSLocalManglingNumber();
8384   }
8385 
8386   IdentifierInfo *getSuperIdentifier() const;
8387   IdentifierInfo *getFloat128Identifier() const;
8388 
8389   Decl *getObjCDeclContext() const;
8390 
getCurLexicalContext()8391   DeclContext *getCurLexicalContext() const {
8392     return OriginalLexicalContext ? OriginalLexicalContext : CurContext;
8393   }
8394 
8395   AvailabilityResult getCurContextAvailability() const;
8396 
getCurObjCLexicalContext()8397   const DeclContext *getCurObjCLexicalContext() const {
8398     const DeclContext *DC = getCurLexicalContext();
8399     // A category implicitly has the attribute of the interface.
8400     if (const ObjCCategoryDecl *CatD = dyn_cast<ObjCCategoryDecl>(DC))
8401       DC = CatD->getClassInterface();
8402     return DC;
8403   }
8404 };
8405 
8406 /// \brief RAII object that enters a new expression evaluation context.
8407 class EnterExpressionEvaluationContext {
8408   Sema &Actions;
8409 
8410 public:
8411   EnterExpressionEvaluationContext(Sema &Actions,
8412                                    Sema::ExpressionEvaluationContext NewContext,
8413                                    Decl *LambdaContextDecl = nullptr,
8414                                    bool IsDecltype = false)
Actions(Actions)8415     : Actions(Actions) {
8416     Actions.PushExpressionEvaluationContext(NewContext, LambdaContextDecl,
8417                                             IsDecltype);
8418   }
8419   EnterExpressionEvaluationContext(Sema &Actions,
8420                                    Sema::ExpressionEvaluationContext NewContext,
8421                                    Sema::ReuseLambdaContextDecl_t,
8422                                    bool IsDecltype = false)
Actions(Actions)8423     : Actions(Actions) {
8424     Actions.PushExpressionEvaluationContext(NewContext,
8425                                             Sema::ReuseLambdaContextDecl,
8426                                             IsDecltype);
8427   }
8428 
~EnterExpressionEvaluationContext()8429   ~EnterExpressionEvaluationContext() {
8430     Actions.PopExpressionEvaluationContext();
8431   }
8432 };
8433 
8434 DeductionFailureInfo
8435 MakeDeductionFailureInfo(ASTContext &Context, Sema::TemplateDeductionResult TDK,
8436                          sema::TemplateDeductionInfo &Info);
8437 
8438 /// \brief Contains a late templated function.
8439 /// Will be parsed at the end of the translation unit, used by Sema & Parser.
8440 struct LateParsedTemplate {
8441   CachedTokens Toks;
8442   /// \brief The template function declaration to be late parsed.
8443   Decl *D;
8444 };
8445 
8446 } // end namespace clang
8447 
8448 #endif
8449