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/Availability.h"
20 #include "clang/AST/ComparisonCategories.h"
21 #include "clang/AST/DeclTemplate.h"
22 #include "clang/AST/DeclarationName.h"
23 #include "clang/AST/Expr.h"
24 #include "clang/AST/ExprCXX.h"
25 #include "clang/AST/ExprObjC.h"
26 #include "clang/AST/ExternalASTSource.h"
27 #include "clang/AST/LocInfoType.h"
28 #include "clang/AST/MangleNumberingContext.h"
29 #include "clang/AST/NSAPI.h"
30 #include "clang/AST/PrettyPrinter.h"
31 #include "clang/AST/StmtCXX.h"
32 #include "clang/AST/TypeLoc.h"
33 #include "clang/AST/TypeOrdering.h"
34 #include "clang/Basic/ExpressionTraits.h"
35 #include "clang/Basic/Module.h"
36 #include "clang/Basic/OpenMPKinds.h"
37 #include "clang/Basic/PragmaKinds.h"
38 #include "clang/Basic/Specifiers.h"
39 #include "clang/Basic/TemplateKinds.h"
40 #include "clang/Basic/TypeTraits.h"
41 #include "clang/Sema/AnalysisBasedWarnings.h"
42 #include "clang/Sema/CleanupInfo.h"
43 #include "clang/Sema/DeclSpec.h"
44 #include "clang/Sema/ExternalSemaSource.h"
45 #include "clang/Sema/IdentifierResolver.h"
46 #include "clang/Sema/ObjCMethodList.h"
47 #include "clang/Sema/Ownership.h"
48 #include "clang/Sema/Scope.h"
49 #include "clang/Sema/TypoCorrection.h"
50 #include "clang/Sema/Weak.h"
51 #include "llvm/ADT/ArrayRef.h"
52 #include "llvm/ADT/Optional.h"
53 #include "llvm/ADT/SetVector.h"
54 #include "llvm/ADT/SmallBitVector.h"
55 #include "llvm/ADT/SmallPtrSet.h"
56 #include "llvm/ADT/SmallVector.h"
57 #include "llvm/ADT/TinyPtrVector.h"
58 #include <deque>
59 #include <memory>
60 #include <string>
61 #include <vector>
62 
63 namespace llvm {
64   class APSInt;
65   template <typename ValueT> struct DenseMapInfo;
66   template <typename ValueT, typename ValueInfoT> class DenseSet;
67   class SmallBitVector;
68   struct InlineAsmIdentifierInfo;
69 }
70 
71 namespace clang {
72   class ADLResult;
73   class ASTConsumer;
74   class ASTContext;
75   class ASTMutationListener;
76   class ASTReader;
77   class ASTWriter;
78   class ArrayType;
79   class ParsedAttr;
80   class BindingDecl;
81   class BlockDecl;
82   class CapturedDecl;
83   class CXXBasePath;
84   class CXXBasePaths;
85   class CXXBindTemporaryExpr;
86   typedef SmallVector<CXXBaseSpecifier*, 4> CXXCastPath;
87   class CXXConstructorDecl;
88   class CXXConversionDecl;
89   class CXXDeleteExpr;
90   class CXXDestructorDecl;
91   class CXXFieldCollector;
92   class CXXMemberCallExpr;
93   class CXXMethodDecl;
94   class CXXScopeSpec;
95   class CXXTemporary;
96   class CXXTryStmt;
97   class CallExpr;
98   class ClassTemplateDecl;
99   class ClassTemplatePartialSpecializationDecl;
100   class ClassTemplateSpecializationDecl;
101   class VarTemplatePartialSpecializationDecl;
102   class CodeCompleteConsumer;
103   class CodeCompletionAllocator;
104   class CodeCompletionTUInfo;
105   class CodeCompletionResult;
106   class CoroutineBodyStmt;
107   class Decl;
108   class DeclAccessPair;
109   class DeclContext;
110   class DeclRefExpr;
111   class DeclaratorDecl;
112   class DeducedTemplateArgument;
113   class DependentDiagnostic;
114   class DesignatedInitExpr;
115   class Designation;
116   class EnableIfAttr;
117   class EnumConstantDecl;
118   class Expr;
119   class ExtVectorType;
120   class FormatAttr;
121   class FriendDecl;
122   class FunctionDecl;
123   class FunctionProtoType;
124   class FunctionTemplateDecl;
125   class ImplicitConversionSequence;
126   typedef MutableArrayRef<ImplicitConversionSequence> ConversionSequenceList;
127   class InitListExpr;
128   class InitializationKind;
129   class InitializationSequence;
130   class InitializedEntity;
131   class IntegerLiteral;
132   class LabelStmt;
133   class LambdaExpr;
134   class LangOptions;
135   class LocalInstantiationScope;
136   class LookupResult;
137   class MacroInfo;
138   typedef ArrayRef<std::pair<IdentifierInfo *, SourceLocation>> ModuleIdPath;
139   class ModuleLoader;
140   class MultiLevelTemplateArgumentList;
141   class NamedDecl;
142   class ObjCCategoryDecl;
143   class ObjCCategoryImplDecl;
144   class ObjCCompatibleAliasDecl;
145   class ObjCContainerDecl;
146   class ObjCImplDecl;
147   class ObjCImplementationDecl;
148   class ObjCInterfaceDecl;
149   class ObjCIvarDecl;
150   template <class T> class ObjCList;
151   class ObjCMessageExpr;
152   class ObjCMethodDecl;
153   class ObjCPropertyDecl;
154   class ObjCProtocolDecl;
155   class OMPThreadPrivateDecl;
156   class OMPDeclareReductionDecl;
157   class OMPDeclareSimdDecl;
158   class OMPClause;
159   struct OverloadCandidate;
160   class OverloadCandidateSet;
161   class OverloadExpr;
162   class ParenListExpr;
163   class ParmVarDecl;
164   class Preprocessor;
165   class PseudoDestructorTypeStorage;
166   class PseudoObjectExpr;
167   class QualType;
168   class StandardConversionSequence;
169   class Stmt;
170   class StringLiteral;
171   class SwitchStmt;
172   class TemplateArgument;
173   class TemplateArgumentList;
174   class TemplateArgumentLoc;
175   class TemplateDecl;
176   class TemplateInstantiationCallback;
177   class TemplateParameterList;
178   class TemplatePartialOrderingContext;
179   class TemplateTemplateParmDecl;
180   class Token;
181   class TypeAliasDecl;
182   class TypedefDecl;
183   class TypedefNameDecl;
184   class TypeLoc;
185   class TypoCorrectionConsumer;
186   class UnqualifiedId;
187   class UnresolvedLookupExpr;
188   class UnresolvedMemberExpr;
189   class UnresolvedSetImpl;
190   class UnresolvedSetIterator;
191   class UsingDecl;
192   class UsingShadowDecl;
193   class ValueDecl;
194   class VarDecl;
195   class VarTemplateSpecializationDecl;
196   class VisibilityAttr;
197   class VisibleDeclConsumer;
198   class IndirectFieldDecl;
199   struct DeductionFailureInfo;
200   class TemplateSpecCandidateSet;
201 
202 namespace sema {
203   class AccessedEntity;
204   class BlockScopeInfo;
205   class Capture;
206   class CapturedRegionScopeInfo;
207   class CapturingScopeInfo;
208   class CompoundScopeInfo;
209   class DelayedDiagnostic;
210   class DelayedDiagnosticPool;
211   class FunctionScopeInfo;
212   class LambdaScopeInfo;
213   class PossiblyUnreachableDiag;
214   class SemaPPCallbacks;
215   class TemplateDeductionInfo;
216 }
217 
218 namespace threadSafety {
219   class BeforeSet;
220   void threadSafetyCleanup(BeforeSet* Cache);
221 }
222 
223 // FIXME: No way to easily map from TemplateTypeParmTypes to
224 // TemplateTypeParmDecls, so we have this horrible PointerUnion.
225 typedef std::pair<llvm::PointerUnion<const TemplateTypeParmType*, NamedDecl*>,
226                   SourceLocation> UnexpandedParameterPack;
227 
228 /// Describes whether we've seen any nullability information for the given
229 /// file.
230 struct FileNullability {
231   /// The first pointer declarator (of any pointer kind) in the file that does
232   /// not have a corresponding nullability annotation.
233   SourceLocation PointerLoc;
234 
235   /// The end location for the first pointer declarator in the file. Used for
236   /// placing fix-its.
237   SourceLocation PointerEndLoc;
238 
239   /// Which kind of pointer declarator we saw.
240   uint8_t PointerKind;
241 
242   /// Whether we saw any type nullability annotations in the given file.
243   bool SawTypeNullability = false;
244 };
245 
246 /// A mapping from file IDs to a record of whether we've seen nullability
247 /// information in that file.
248 class FileNullabilityMap {
249   /// A mapping from file IDs to the nullability information for each file ID.
250   llvm::DenseMap<FileID, FileNullability> Map;
251 
252   /// A single-element cache based on the file ID.
253   struct {
254     FileID File;
255     FileNullability Nullability;
256   } Cache;
257 
258 public:
259   FileNullability &operator[](FileID file) {
260     // Check the single-element cache.
261     if (file == Cache.File)
262       return Cache.Nullability;
263 
264     // It's not in the single-element cache; flush the cache if we have one.
265     if (!Cache.File.isInvalid()) {
266       Map[Cache.File] = Cache.Nullability;
267     }
268 
269     // Pull this entry into the cache.
270     Cache.File = file;
271     Cache.Nullability = Map[file];
272     return Cache.Nullability;
273   }
274 };
275 
276 /// Sema - This implements semantic analysis and AST building for C.
277 class Sema {
278   Sema(const Sema &) = delete;
279   void operator=(const Sema &) = delete;
280 
281   ///Source of additional semantic information.
282   ExternalSemaSource *ExternalSource;
283 
284   ///Whether Sema has generated a multiplexer and has to delete it.
285   bool isMultiplexExternalSource;
286 
287   static bool mightHaveNonExternalLinkage(const DeclaratorDecl *FD);
288 
289   bool isVisibleSlow(const NamedDecl *D);
290 
291   /// Determine whether two declarations should be linked together, given that
292   /// the old declaration might not be visible and the new declaration might
293   /// not have external linkage.
shouldLinkPossiblyHiddenDecl(const NamedDecl * Old,const NamedDecl * New)294   bool shouldLinkPossiblyHiddenDecl(const NamedDecl *Old,
295                                     const NamedDecl *New) {
296     if (isVisible(Old))
297      return true;
298     // See comment in below overload for why it's safe to compute the linkage
299     // of the new declaration here.
300     if (New->isExternallyDeclarable()) {
301       assert(Old->isExternallyDeclarable() &&
302              "should not have found a non-externally-declarable previous decl");
303       return true;
304     }
305     return false;
306   }
307   bool shouldLinkPossiblyHiddenDecl(LookupResult &Old, const NamedDecl *New);
308 
309 public:
310   typedef OpaquePtr<DeclGroupRef> DeclGroupPtrTy;
311   typedef OpaquePtr<TemplateName> TemplateTy;
312   typedef OpaquePtr<QualType> TypeTy;
313 
314   OpenCLOptions OpenCLFeatures;
315   FPOptions FPFeatures;
316 
317   const LangOptions &LangOpts;
318   Preprocessor &PP;
319   ASTContext &Context;
320   ASTConsumer &Consumer;
321   DiagnosticsEngine &Diags;
322   SourceManager &SourceMgr;
323 
324   /// Flag indicating whether or not to collect detailed statistics.
325   bool CollectStats;
326 
327   /// Code-completion consumer.
328   CodeCompleteConsumer *CodeCompleter;
329 
330   /// CurContext - This is the current declaration context of parsing.
331   DeclContext *CurContext;
332 
333   /// Generally null except when we temporarily switch decl contexts,
334   /// like in \see ActOnObjCTemporaryExitContainerContext.
335   DeclContext *OriginalLexicalContext;
336 
337   /// VAListTagName - The declaration name corresponding to __va_list_tag.
338   /// This is used as part of a hack to omit that class from ADL results.
339   DeclarationName VAListTagName;
340 
341   bool MSStructPragmaOn; // True when \#pragma ms_struct on
342 
343   /// Controls member pointer representation format under the MS ABI.
344   LangOptions::PragmaMSPointersToMembersKind
345       MSPointerToMemberRepresentationMethod;
346 
347   /// Stack of active SEH __finally scopes.  Can be empty.
348   SmallVector<Scope*, 2> CurrentSEHFinally;
349 
350   /// Source location for newly created implicit MSInheritanceAttrs
351   SourceLocation ImplicitMSInheritanceAttrLoc;
352 
353   /// pragma clang section kind
354   enum PragmaClangSectionKind {
355     PCSK_Invalid      = 0,
356     PCSK_BSS          = 1,
357     PCSK_Data         = 2,
358     PCSK_Rodata       = 3,
359     PCSK_Text         = 4
360    };
361 
362   enum PragmaClangSectionAction {
363     PCSA_Set     = 0,
364     PCSA_Clear   = 1
365   };
366 
367   struct PragmaClangSection {
368     std::string SectionName;
369     bool Valid = false;
370     SourceLocation PragmaLocation;
371 
372     void Act(SourceLocation PragmaLocation,
373              PragmaClangSectionAction Action,
374              StringLiteral* Name);
375    };
376 
377    PragmaClangSection PragmaClangBSSSection;
378    PragmaClangSection PragmaClangDataSection;
379    PragmaClangSection PragmaClangRodataSection;
380    PragmaClangSection PragmaClangTextSection;
381 
382   enum PragmaMsStackAction {
383     PSK_Reset     = 0x0,                // #pragma ()
384     PSK_Set       = 0x1,                // #pragma (value)
385     PSK_Push      = 0x2,                // #pragma (push[, id])
386     PSK_Pop       = 0x4,                // #pragma (pop[, id])
387     PSK_Show      = 0x8,                // #pragma (show) -- only for "pack"!
388     PSK_Push_Set  = PSK_Push | PSK_Set, // #pragma (push[, id], value)
389     PSK_Pop_Set   = PSK_Pop | PSK_Set,  // #pragma (pop[, id], value)
390   };
391 
392   template<typename ValueType>
393   struct PragmaStack {
394     struct Slot {
395       llvm::StringRef StackSlotLabel;
396       ValueType Value;
397       SourceLocation PragmaLocation;
398       SourceLocation PragmaPushLocation;
SlotPragmaStack::Slot399       Slot(llvm::StringRef StackSlotLabel, ValueType Value,
400            SourceLocation PragmaLocation, SourceLocation PragmaPushLocation)
401           : StackSlotLabel(StackSlotLabel), Value(Value),
402             PragmaLocation(PragmaLocation),
403             PragmaPushLocation(PragmaPushLocation) {}
404     };
405     void Act(SourceLocation PragmaLocation,
406              PragmaMsStackAction Action,
407              llvm::StringRef StackSlotLabel,
408              ValueType Value);
409 
410     // MSVC seems to add artificial slots to #pragma stacks on entering a C++
411     // method body to restore the stacks on exit, so it works like this:
412     //
413     //   struct S {
414     //     #pragma <name>(push, InternalPragmaSlot, <current_pragma_value>)
415     //     void Method {}
416     //     #pragma <name>(pop, InternalPragmaSlot)
417     //   };
418     //
419     // It works even with #pragma vtordisp, although MSVC doesn't support
420     //   #pragma vtordisp(push [, id], n)
421     // syntax.
422     //
423     // Push / pop a named sentinel slot.
SentinelActionPragmaStack424     void SentinelAction(PragmaMsStackAction Action, StringRef Label) {
425       assert((Action == PSK_Push || Action == PSK_Pop) &&
426              "Can only push / pop #pragma stack sentinels!");
427       Act(CurrentPragmaLocation, Action, Label, CurrentValue);
428     }
429 
430     // Constructors.
PragmaStackPragmaStack431     explicit PragmaStack(const ValueType &Default)
432         : DefaultValue(Default), CurrentValue(Default) {}
433 
hasValuePragmaStack434     bool hasValue() const { return CurrentValue != DefaultValue; }
435 
436     SmallVector<Slot, 2> Stack;
437     ValueType DefaultValue; // Value used for PSK_Reset action.
438     ValueType CurrentValue;
439     SourceLocation CurrentPragmaLocation;
440   };
441   // FIXME: We should serialize / deserialize these if they occur in a PCH (but
442   // we shouldn't do so if they're in a module).
443 
444   /// Whether to insert vtordisps prior to virtual bases in the Microsoft
445   /// C++ ABI.  Possible values are 0, 1, and 2, which mean:
446   ///
447   /// 0: Suppress all vtordisps
448   /// 1: Insert vtordisps in the presence of vbase overrides and non-trivial
449   ///    structors
450   /// 2: Always insert vtordisps to support RTTI on partially constructed
451   ///    objects
452   PragmaStack<MSVtorDispAttr::Mode> VtorDispStack;
453   // #pragma pack.
454   // Sentinel to represent when the stack is set to mac68k alignment.
455   static const unsigned kMac68kAlignmentSentinel = ~0U;
456   PragmaStack<unsigned> PackStack;
457   // The current #pragma pack values and locations at each #include.
458   struct PackIncludeState {
459     unsigned CurrentValue;
460     SourceLocation CurrentPragmaLocation;
461     bool HasNonDefaultValue, ShouldWarnOnInclude;
462   };
463   SmallVector<PackIncludeState, 8> PackIncludeStack;
464   // Segment #pragmas.
465   PragmaStack<StringLiteral *> DataSegStack;
466   PragmaStack<StringLiteral *> BSSSegStack;
467   PragmaStack<StringLiteral *> ConstSegStack;
468   PragmaStack<StringLiteral *> CodeSegStack;
469 
470   // RAII object to push / pop sentinel slots for all MS #pragma stacks.
471   // Actions should be performed only if we enter / exit a C++ method body.
472   class PragmaStackSentinelRAII {
473   public:
474     PragmaStackSentinelRAII(Sema &S, StringRef SlotLabel, bool ShouldAct);
475     ~PragmaStackSentinelRAII();
476 
477   private:
478     Sema &S;
479     StringRef SlotLabel;
480     bool ShouldAct;
481   };
482 
483   /// A mapping that describes the nullability we've seen in each header file.
484   FileNullabilityMap NullabilityMap;
485 
486   /// Last section used with #pragma init_seg.
487   StringLiteral *CurInitSeg;
488   SourceLocation CurInitSegLoc;
489 
490   /// VisContext - Manages the stack for \#pragma GCC visibility.
491   void *VisContext; // Really a "PragmaVisStack*"
492 
493   /// This represents the stack of attributes that were pushed by
494   /// \#pragma clang attribute.
495   struct PragmaAttributeEntry {
496     SourceLocation Loc;
497     ParsedAttr *Attribute;
498     SmallVector<attr::SubjectMatchRule, 4> MatchRules;
499     bool IsUsed;
500   };
501   SmallVector<PragmaAttributeEntry, 2> PragmaAttributeStack;
502 
503   /// The declaration that is currently receiving an attribute from the
504   /// #pragma attribute stack.
505   const Decl *PragmaAttributeCurrentTargetDecl;
506 
507   /// This represents the last location of a "#pragma clang optimize off"
508   /// directive if such a directive has not been closed by an "on" yet. If
509   /// optimizations are currently "on", this is set to an invalid location.
510   SourceLocation OptimizeOffPragmaLocation;
511 
512   /// Flag indicating if Sema is building a recovery call expression.
513   ///
514   /// This flag is used to avoid building recovery call expressions
515   /// if Sema is already doing so, which would cause infinite recursions.
516   bool IsBuildingRecoveryCallExpr;
517 
518   /// Used to control the generation of ExprWithCleanups.
519   CleanupInfo Cleanup;
520 
521   /// ExprCleanupObjects - This is the stack of objects requiring
522   /// cleanup that are created by the current full expression.  The
523   /// element type here is ExprWithCleanups::Object.
524   SmallVector<BlockDecl*, 8> ExprCleanupObjects;
525 
526   /// Store a list of either DeclRefExprs or MemberExprs
527   ///  that contain a reference to a variable (constant) that may or may not
528   ///  be odr-used in this Expr, and we won't know until all lvalue-to-rvalue
529   ///  and discarded value conversions have been applied to all subexpressions
530   ///  of the enclosing full expression.  This is cleared at the end of each
531   ///  full expression.
532   llvm::SmallPtrSet<Expr*, 2> MaybeODRUseExprs;
533 
534   std::unique_ptr<sema::FunctionScopeInfo> PreallocatedFunctionScope;
535 
536   /// Stack containing information about each of the nested
537   /// function, block, and method scopes that are currently active.
538   SmallVector<sema::FunctionScopeInfo *, 4> FunctionScopes;
539 
540   typedef LazyVector<TypedefNameDecl *, ExternalSemaSource,
541                      &ExternalSemaSource::ReadExtVectorDecls, 2, 2>
542     ExtVectorDeclsType;
543 
544   /// ExtVectorDecls - This is a list all the extended vector types. This allows
545   /// us to associate a raw vector type with one of the ext_vector type names.
546   /// This is only necessary for issuing pretty diagnostics.
547   ExtVectorDeclsType ExtVectorDecls;
548 
549   /// FieldCollector - Collects CXXFieldDecls during parsing of C++ classes.
550   std::unique_ptr<CXXFieldCollector> FieldCollector;
551 
552   typedef llvm::SmallSetVector<NamedDecl *, 16> NamedDeclSetType;
553 
554   /// Set containing all declared private fields that are not used.
555   NamedDeclSetType UnusedPrivateFields;
556 
557   /// Set containing all typedefs that are likely unused.
558   llvm::SmallSetVector<const TypedefNameDecl *, 4>
559       UnusedLocalTypedefNameCandidates;
560 
561   /// Delete-expressions to be analyzed at the end of translation unit
562   ///
563   /// This list contains class members, and locations of delete-expressions
564   /// that could not be proven as to whether they mismatch with new-expression
565   /// used in initializer of the field.
566   typedef std::pair<SourceLocation, bool> DeleteExprLoc;
567   typedef llvm::SmallVector<DeleteExprLoc, 4> DeleteLocs;
568   llvm::MapVector<FieldDecl *, DeleteLocs> DeleteExprs;
569 
570   typedef llvm::SmallPtrSet<const CXXRecordDecl*, 8> RecordDeclSetTy;
571 
572   /// PureVirtualClassDiagSet - a set of class declarations which we have
573   /// emitted a list of pure virtual functions. Used to prevent emitting the
574   /// same list more than once.
575   std::unique_ptr<RecordDeclSetTy> PureVirtualClassDiagSet;
576 
577   /// ParsingInitForAutoVars - a set of declarations with auto types for which
578   /// we are currently parsing the initializer.
579   llvm::SmallPtrSet<const Decl*, 4> ParsingInitForAutoVars;
580 
581   /// Look for a locally scoped extern "C" declaration by the given name.
582   NamedDecl *findLocallyScopedExternCDecl(DeclarationName Name);
583 
584   typedef LazyVector<VarDecl *, ExternalSemaSource,
585                      &ExternalSemaSource::ReadTentativeDefinitions, 2, 2>
586     TentativeDefinitionsType;
587 
588   /// All the tentative definitions encountered in the TU.
589   TentativeDefinitionsType TentativeDefinitions;
590 
591   typedef LazyVector<const DeclaratorDecl *, ExternalSemaSource,
592                      &ExternalSemaSource::ReadUnusedFileScopedDecls, 2, 2>
593     UnusedFileScopedDeclsType;
594 
595   /// The set of file scoped decls seen so far that have not been used
596   /// and must warn if not used. Only contains the first declaration.
597   UnusedFileScopedDeclsType UnusedFileScopedDecls;
598 
599   typedef LazyVector<CXXConstructorDecl *, ExternalSemaSource,
600                      &ExternalSemaSource::ReadDelegatingConstructors, 2, 2>
601     DelegatingCtorDeclsType;
602 
603   /// All the delegating constructors seen so far in the file, used for
604   /// cycle detection at the end of the TU.
605   DelegatingCtorDeclsType DelegatingCtorDecls;
606 
607   /// All the overriding functions seen during a class definition
608   /// that had their exception spec checks delayed, plus the overridden
609   /// function.
610   SmallVector<std::pair<const CXXMethodDecl*, const CXXMethodDecl*>, 2>
611     DelayedExceptionSpecChecks;
612 
613   /// All the members seen during a class definition which were both
614   /// explicitly defaulted and had explicitly-specified exception
615   /// specifications, along with the function type containing their
616   /// user-specified exception specification. Those exception specifications
617   /// were overridden with the default specifications, but we still need to
618   /// check whether they are compatible with the default specification, and
619   /// we can't do that until the nesting set of class definitions is complete.
620   SmallVector<std::pair<CXXMethodDecl*, const FunctionProtoType*>, 2>
621     DelayedDefaultedMemberExceptionSpecs;
622 
623   typedef llvm::MapVector<const FunctionDecl *,
624                           std::unique_ptr<LateParsedTemplate>>
625       LateParsedTemplateMapT;
626   LateParsedTemplateMapT LateParsedTemplateMap;
627 
628   /// Callback to the parser to parse templated functions when needed.
629   typedef void LateTemplateParserCB(void *P, LateParsedTemplate &LPT);
630   typedef void LateTemplateParserCleanupCB(void *P);
631   LateTemplateParserCB *LateTemplateParser;
632   LateTemplateParserCleanupCB *LateTemplateParserCleanup;
633   void *OpaqueParser;
634 
SetLateTemplateParser(LateTemplateParserCB * LTP,LateTemplateParserCleanupCB * LTPCleanup,void * P)635   void SetLateTemplateParser(LateTemplateParserCB *LTP,
636                              LateTemplateParserCleanupCB *LTPCleanup,
637                              void *P) {
638     LateTemplateParser = LTP;
639     LateTemplateParserCleanup = LTPCleanup;
640     OpaqueParser = P;
641   }
642 
643   class DelayedDiagnostics;
644 
645   class DelayedDiagnosticsState {
646     sema::DelayedDiagnosticPool *SavedPool;
647     friend class Sema::DelayedDiagnostics;
648   };
649   typedef DelayedDiagnosticsState ParsingDeclState;
650   typedef DelayedDiagnosticsState ProcessingContextState;
651 
652   /// A class which encapsulates the logic for delaying diagnostics
653   /// during parsing and other processing.
654   class DelayedDiagnostics {
655     /// The current pool of diagnostics into which delayed
656     /// diagnostics should go.
657     sema::DelayedDiagnosticPool *CurPool;
658 
659   public:
DelayedDiagnostics()660     DelayedDiagnostics() : CurPool(nullptr) {}
661 
662     /// Adds a delayed diagnostic.
663     void add(const sema::DelayedDiagnostic &diag); // in DelayedDiagnostic.h
664 
665     /// Determines whether diagnostics should be delayed.
shouldDelayDiagnostics()666     bool shouldDelayDiagnostics() { return CurPool != nullptr; }
667 
668     /// Returns the current delayed-diagnostics pool.
getCurrentPool()669     sema::DelayedDiagnosticPool *getCurrentPool() const {
670       return CurPool;
671     }
672 
673     /// Enter a new scope.  Access and deprecation diagnostics will be
674     /// collected in this pool.
push(sema::DelayedDiagnosticPool & pool)675     DelayedDiagnosticsState push(sema::DelayedDiagnosticPool &pool) {
676       DelayedDiagnosticsState state;
677       state.SavedPool = CurPool;
678       CurPool = &pool;
679       return state;
680     }
681 
682     /// Leave a delayed-diagnostic state that was previously pushed.
683     /// Do not emit any of the diagnostics.  This is performed as part
684     /// of the bookkeeping of popping a pool "properly".
popWithoutEmitting(DelayedDiagnosticsState state)685     void popWithoutEmitting(DelayedDiagnosticsState state) {
686       CurPool = state.SavedPool;
687     }
688 
689     /// Enter a new scope where access and deprecation diagnostics are
690     /// not delayed.
pushUndelayed()691     DelayedDiagnosticsState pushUndelayed() {
692       DelayedDiagnosticsState state;
693       state.SavedPool = CurPool;
694       CurPool = nullptr;
695       return state;
696     }
697 
698     /// Undo a previous pushUndelayed().
popUndelayed(DelayedDiagnosticsState state)699     void popUndelayed(DelayedDiagnosticsState state) {
700       assert(CurPool == nullptr);
701       CurPool = state.SavedPool;
702     }
703   } DelayedDiagnostics;
704 
705   /// A RAII object to temporarily push a declaration context.
706   class ContextRAII {
707   private:
708     Sema &S;
709     DeclContext *SavedContext;
710     ProcessingContextState SavedContextState;
711     QualType SavedCXXThisTypeOverride;
712 
713   public:
714     ContextRAII(Sema &S, DeclContext *ContextToPush, bool NewThisContext = true)
S(S)715       : S(S), SavedContext(S.CurContext),
716         SavedContextState(S.DelayedDiagnostics.pushUndelayed()),
717         SavedCXXThisTypeOverride(S.CXXThisTypeOverride)
718     {
719       assert(ContextToPush && "pushing null context");
720       S.CurContext = ContextToPush;
721       if (NewThisContext)
722         S.CXXThisTypeOverride = QualType();
723     }
724 
pop()725     void pop() {
726       if (!SavedContext) return;
727       S.CurContext = SavedContext;
728       S.DelayedDiagnostics.popUndelayed(SavedContextState);
729       S.CXXThisTypeOverride = SavedCXXThisTypeOverride;
730       SavedContext = nullptr;
731     }
732 
~ContextRAII()733     ~ContextRAII() {
734       pop();
735     }
736   };
737 
738   /// RAII object to handle the state changes required to synthesize
739   /// a function body.
740   class SynthesizedFunctionScope {
741     Sema &S;
742     Sema::ContextRAII SavedContext;
743     bool PushedCodeSynthesisContext = false;
744 
745   public:
SynthesizedFunctionScope(Sema & S,DeclContext * DC)746     SynthesizedFunctionScope(Sema &S, DeclContext *DC)
747         : S(S), SavedContext(S, DC) {
748       S.PushFunctionScope();
749       S.PushExpressionEvaluationContext(
750           Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
751       if (auto *FD = dyn_cast<FunctionDecl>(DC))
752         FD->setWillHaveBody(true);
753       else
754         assert(isa<ObjCMethodDecl>(DC));
755     }
756 
addContextNote(SourceLocation UseLoc)757     void addContextNote(SourceLocation UseLoc) {
758       assert(!PushedCodeSynthesisContext);
759 
760       Sema::CodeSynthesisContext Ctx;
761       Ctx.Kind = Sema::CodeSynthesisContext::DefiningSynthesizedFunction;
762       Ctx.PointOfInstantiation = UseLoc;
763       Ctx.Entity = cast<Decl>(S.CurContext);
764       S.pushCodeSynthesisContext(Ctx);
765 
766       PushedCodeSynthesisContext = true;
767     }
768 
~SynthesizedFunctionScope()769     ~SynthesizedFunctionScope() {
770       if (PushedCodeSynthesisContext)
771         S.popCodeSynthesisContext();
772       if (auto *FD = dyn_cast<FunctionDecl>(S.CurContext))
773         FD->setWillHaveBody(false);
774       S.PopExpressionEvaluationContext();
775       S.PopFunctionScopeInfo();
776     }
777   };
778 
779   /// WeakUndeclaredIdentifiers - Identifiers contained in
780   /// \#pragma weak before declared. rare. may alias another
781   /// identifier, declared or undeclared
782   llvm::MapVector<IdentifierInfo *, WeakInfo> WeakUndeclaredIdentifiers;
783 
784   /// ExtnameUndeclaredIdentifiers - Identifiers contained in
785   /// \#pragma redefine_extname before declared.  Used in Solaris system headers
786   /// to define functions that occur in multiple standards to call the version
787   /// in the currently selected standard.
788   llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*> ExtnameUndeclaredIdentifiers;
789 
790 
791   /// Load weak undeclared identifiers from the external source.
792   void LoadExternalWeakUndeclaredIdentifiers();
793 
794   /// WeakTopLevelDecl - Translation-unit scoped declarations generated by
795   /// \#pragma weak during processing of other Decls.
796   /// I couldn't figure out a clean way to generate these in-line, so
797   /// we store them here and handle separately -- which is a hack.
798   /// It would be best to refactor this.
799   SmallVector<Decl*,2> WeakTopLevelDecl;
800 
801   IdentifierResolver IdResolver;
802 
803   /// Translation Unit Scope - useful to Objective-C actions that need
804   /// to lookup file scope declarations in the "ordinary" C decl namespace.
805   /// For example, user-defined classes, built-in "id" type, etc.
806   Scope *TUScope;
807 
808   /// The C++ "std" namespace, where the standard library resides.
809   LazyDeclPtr StdNamespace;
810 
811   /// The C++ "std::bad_alloc" class, which is defined by the C++
812   /// standard library.
813   LazyDeclPtr StdBadAlloc;
814 
815   /// The C++ "std::align_val_t" enum class, which is defined by the C++
816   /// standard library.
817   LazyDeclPtr StdAlignValT;
818 
819   /// The C++ "std::experimental" namespace, where the experimental parts
820   /// of the standard library resides.
821   NamespaceDecl *StdExperimentalNamespaceCache;
822 
823   /// The C++ "std::initializer_list" template, which is defined in
824   /// \<initializer_list>.
825   ClassTemplateDecl *StdInitializerList;
826 
827   /// The C++ "std::coroutine_traits" template, which is defined in
828   /// \<coroutine_traits>
829   ClassTemplateDecl *StdCoroutineTraitsCache;
830 
831   /// The C++ "type_info" declaration, which is defined in \<typeinfo>.
832   RecordDecl *CXXTypeInfoDecl;
833 
834   /// The MSVC "_GUID" struct, which is defined in MSVC header files.
835   RecordDecl *MSVCGuidDecl;
836 
837   /// Caches identifiers/selectors for NSFoundation APIs.
838   std::unique_ptr<NSAPI> NSAPIObj;
839 
840   /// The declaration of the Objective-C NSNumber class.
841   ObjCInterfaceDecl *NSNumberDecl;
842 
843   /// The declaration of the Objective-C NSValue class.
844   ObjCInterfaceDecl *NSValueDecl;
845 
846   /// Pointer to NSNumber type (NSNumber *).
847   QualType NSNumberPointer;
848 
849   /// Pointer to NSValue type (NSValue *).
850   QualType NSValuePointer;
851 
852   /// The Objective-C NSNumber methods used to create NSNumber literals.
853   ObjCMethodDecl *NSNumberLiteralMethods[NSAPI::NumNSNumberLiteralMethods];
854 
855   /// The declaration of the Objective-C NSString class.
856   ObjCInterfaceDecl *NSStringDecl;
857 
858   /// Pointer to NSString type (NSString *).
859   QualType NSStringPointer;
860 
861   /// The declaration of the stringWithUTF8String: method.
862   ObjCMethodDecl *StringWithUTF8StringMethod;
863 
864   /// The declaration of the valueWithBytes:objCType: method.
865   ObjCMethodDecl *ValueWithBytesObjCTypeMethod;
866 
867   /// The declaration of the Objective-C NSArray class.
868   ObjCInterfaceDecl *NSArrayDecl;
869 
870   /// The declaration of the arrayWithObjects:count: method.
871   ObjCMethodDecl *ArrayWithObjectsMethod;
872 
873   /// The declaration of the Objective-C NSDictionary class.
874   ObjCInterfaceDecl *NSDictionaryDecl;
875 
876   /// The declaration of the dictionaryWithObjects:forKeys:count: method.
877   ObjCMethodDecl *DictionaryWithObjectsMethod;
878 
879   /// id<NSCopying> type.
880   QualType QIDNSCopying;
881 
882   /// will hold 'respondsToSelector:'
883   Selector RespondsToSelectorSel;
884 
885   /// A flag to remember whether the implicit forms of operator new and delete
886   /// have been declared.
887   bool GlobalNewDeleteDeclared;
888 
889   /// A flag to indicate that we're in a context that permits abstract
890   /// references to fields.  This is really a
891   bool AllowAbstractFieldReference;
892 
893   /// Describes how the expressions currently being parsed are
894   /// evaluated at run-time, if at all.
895   enum class ExpressionEvaluationContext {
896     /// The current expression and its subexpressions occur within an
897     /// unevaluated operand (C++11 [expr]p7), such as the subexpression of
898     /// \c sizeof, where the type of the expression may be significant but
899     /// no code will be generated to evaluate the value of the expression at
900     /// run time.
901     Unevaluated,
902 
903     /// The current expression occurs within a braced-init-list within
904     /// an unevaluated operand. This is mostly like a regular unevaluated
905     /// context, except that we still instantiate constexpr functions that are
906     /// referenced here so that we can perform narrowing checks correctly.
907     UnevaluatedList,
908 
909     /// The current expression occurs within a discarded statement.
910     /// This behaves largely similarly to an unevaluated operand in preventing
911     /// definitions from being required, but not in other ways.
912     DiscardedStatement,
913 
914     /// The current expression occurs within an unevaluated
915     /// operand that unconditionally permits abstract references to
916     /// fields, such as a SIZE operator in MS-style inline assembly.
917     UnevaluatedAbstract,
918 
919     /// The current context is "potentially evaluated" in C++11 terms,
920     /// but the expression is evaluated at compile-time (like the values of
921     /// cases in a switch statement).
922     ConstantEvaluated,
923 
924     /// The current expression is potentially evaluated at run time,
925     /// which means that code may be generated to evaluate the value of the
926     /// expression at run time.
927     PotentiallyEvaluated,
928 
929     /// The current expression is potentially evaluated, but any
930     /// declarations referenced inside that expression are only used if
931     /// in fact the current expression is used.
932     ///
933     /// This value is used when parsing default function arguments, for which
934     /// we would like to provide diagnostics (e.g., passing non-POD arguments
935     /// through varargs) but do not want to mark declarations as "referenced"
936     /// until the default argument is used.
937     PotentiallyEvaluatedIfUsed
938   };
939 
940   /// Data structure used to record current or nested
941   /// expression evaluation contexts.
942   struct ExpressionEvaluationContextRecord {
943     /// The expression evaluation context.
944     ExpressionEvaluationContext Context;
945 
946     /// Whether the enclosing context needed a cleanup.
947     CleanupInfo ParentCleanup;
948 
949     /// Whether we are in a decltype expression.
950     bool IsDecltype;
951 
952     /// The number of active cleanup objects when we entered
953     /// this expression evaluation context.
954     unsigned NumCleanupObjects;
955 
956     /// The number of typos encountered during this expression evaluation
957     /// context (i.e. the number of TypoExprs created).
958     unsigned NumTypos;
959 
960     llvm::SmallPtrSet<Expr*, 2> SavedMaybeODRUseExprs;
961 
962     /// The lambdas that are present within this context, if it
963     /// is indeed an unevaluated context.
964     SmallVector<LambdaExpr *, 2> Lambdas;
965 
966     /// The declaration that provides context for lambda expressions
967     /// and block literals if the normal declaration context does not
968     /// suffice, e.g., in a default function argument.
969     Decl *ManglingContextDecl;
970 
971     /// The context information used to mangle lambda expressions
972     /// and block literals within this context.
973     ///
974     /// This mangling information is allocated lazily, since most contexts
975     /// do not have lambda expressions or block literals.
976     std::unique_ptr<MangleNumberingContext> MangleNumbering;
977 
978     /// If we are processing a decltype type, a set of call expressions
979     /// for which we have deferred checking the completeness of the return type.
980     SmallVector<CallExpr *, 8> DelayedDecltypeCalls;
981 
982     /// If we are processing a decltype type, a set of temporary binding
983     /// expressions for which we have deferred checking the destructor.
984     SmallVector<CXXBindTemporaryExpr *, 8> DelayedDecltypeBinds;
985 
986     /// \brief Describes whether we are in an expression constext which we have
987     /// to handle differently.
988     enum ExpressionKind {
989       EK_Decltype, EK_TemplateArgument, EK_Other
990     } ExprContext;
991 
ExpressionEvaluationContextRecordExpressionEvaluationContextRecord992     ExpressionEvaluationContextRecord(ExpressionEvaluationContext Context,
993                                       unsigned NumCleanupObjects,
994                                       CleanupInfo ParentCleanup,
995                                       Decl *ManglingContextDecl,
996                                       ExpressionKind ExprContext)
997         : Context(Context), ParentCleanup(ParentCleanup),
998           NumCleanupObjects(NumCleanupObjects), NumTypos(0),
999           ManglingContextDecl(ManglingContextDecl), MangleNumbering(),
1000           ExprContext(ExprContext) {}
1001 
1002     /// Retrieve the mangling numbering context, used to consistently
1003     /// number constructs like lambdas for mangling.
1004     MangleNumberingContext &getMangleNumberingContext(ASTContext &Ctx);
1005 
isUnevaluatedExpressionEvaluationContextRecord1006     bool isUnevaluated() const {
1007       return Context == ExpressionEvaluationContext::Unevaluated ||
1008              Context == ExpressionEvaluationContext::UnevaluatedAbstract ||
1009              Context == ExpressionEvaluationContext::UnevaluatedList;
1010     }
isConstantEvaluatedExpressionEvaluationContextRecord1011     bool isConstantEvaluated() const {
1012       return Context == ExpressionEvaluationContext::ConstantEvaluated;
1013     }
1014   };
1015 
1016   /// A stack of expression evaluation contexts.
1017   SmallVector<ExpressionEvaluationContextRecord, 8> ExprEvalContexts;
1018 
1019   /// Compute the mangling number context for a lambda expression or
1020   /// block literal.
1021   ///
1022   /// \param DC - The DeclContext containing the lambda expression or
1023   /// block literal.
1024   /// \param[out] ManglingContextDecl - Returns the ManglingContextDecl
1025   /// associated with the context, if relevant.
1026   MangleNumberingContext *getCurrentMangleNumberContext(
1027     const DeclContext *DC,
1028     Decl *&ManglingContextDecl);
1029 
1030 
1031   /// SpecialMemberOverloadResult - The overloading result for a special member
1032   /// function.
1033   ///
1034   /// This is basically a wrapper around PointerIntPair. The lowest bits of the
1035   /// integer are used to determine whether overload resolution succeeded.
1036   class SpecialMemberOverloadResult {
1037   public:
1038     enum Kind {
1039       NoMemberOrDeleted,
1040       Ambiguous,
1041       Success
1042     };
1043 
1044   private:
1045     llvm::PointerIntPair<CXXMethodDecl*, 2> Pair;
1046 
1047   public:
SpecialMemberOverloadResult()1048     SpecialMemberOverloadResult() : Pair() {}
SpecialMemberOverloadResult(CXXMethodDecl * MD)1049     SpecialMemberOverloadResult(CXXMethodDecl *MD)
1050         : Pair(MD, MD->isDeleted() ? NoMemberOrDeleted : Success) {}
1051 
getMethod()1052     CXXMethodDecl *getMethod() const { return Pair.getPointer(); }
setMethod(CXXMethodDecl * MD)1053     void setMethod(CXXMethodDecl *MD) { Pair.setPointer(MD); }
1054 
getKind()1055     Kind getKind() const { return static_cast<Kind>(Pair.getInt()); }
setKind(Kind K)1056     void setKind(Kind K) { Pair.setInt(K); }
1057   };
1058 
1059   class SpecialMemberOverloadResultEntry
1060       : public llvm::FastFoldingSetNode,
1061         public SpecialMemberOverloadResult {
1062   public:
SpecialMemberOverloadResultEntry(const llvm::FoldingSetNodeID & ID)1063     SpecialMemberOverloadResultEntry(const llvm::FoldingSetNodeID &ID)
1064       : FastFoldingSetNode(ID)
1065     {}
1066   };
1067 
1068   /// A cache of special member function overload resolution results
1069   /// for C++ records.
1070   llvm::FoldingSet<SpecialMemberOverloadResultEntry> SpecialMemberCache;
1071 
1072   /// A cache of the flags available in enumerations with the flag_bits
1073   /// attribute.
1074   mutable llvm::DenseMap<const EnumDecl*, llvm::APInt> FlagBitsCache;
1075 
1076   /// The kind of translation unit we are processing.
1077   ///
1078   /// When we're processing a complete translation unit, Sema will perform
1079   /// end-of-translation-unit semantic tasks (such as creating
1080   /// initializers for tentative definitions in C) once parsing has
1081   /// completed. Modules and precompiled headers perform different kinds of
1082   /// checks.
1083   TranslationUnitKind TUKind;
1084 
1085   llvm::BumpPtrAllocator BumpAlloc;
1086 
1087   /// The number of SFINAE diagnostics that have been trapped.
1088   unsigned NumSFINAEErrors;
1089 
1090   typedef llvm::DenseMap<ParmVarDecl *, llvm::TinyPtrVector<ParmVarDecl *>>
1091     UnparsedDefaultArgInstantiationsMap;
1092 
1093   /// A mapping from parameters with unparsed default arguments to the
1094   /// set of instantiations of each parameter.
1095   ///
1096   /// This mapping is a temporary data structure used when parsing
1097   /// nested class templates or nested classes of class templates,
1098   /// where we might end up instantiating an inner class before the
1099   /// default arguments of its methods have been parsed.
1100   UnparsedDefaultArgInstantiationsMap UnparsedDefaultArgInstantiations;
1101 
1102   // Contains the locations of the beginning of unparsed default
1103   // argument locations.
1104   llvm::DenseMap<ParmVarDecl *, SourceLocation> UnparsedDefaultArgLocs;
1105 
1106   /// UndefinedInternals - all the used, undefined objects which require a
1107   /// definition in this translation unit.
1108   llvm::MapVector<NamedDecl *, SourceLocation> UndefinedButUsed;
1109 
1110   /// Determine if VD, which must be a variable or function, is an external
1111   /// symbol that nonetheless can't be referenced from outside this translation
1112   /// unit because its type has no linkage and it's not extern "C".
1113   bool isExternalWithNoLinkageType(ValueDecl *VD);
1114 
1115   /// Obtain a sorted list of functions that are undefined but ODR-used.
1116   void getUndefinedButUsed(
1117       SmallVectorImpl<std::pair<NamedDecl *, SourceLocation> > &Undefined);
1118 
1119   /// Retrieves list of suspicious delete-expressions that will be checked at
1120   /// the end of translation unit.
1121   const llvm::MapVector<FieldDecl *, DeleteLocs> &
1122   getMismatchingDeleteExpressions() const;
1123 
1124   typedef std::pair<ObjCMethodList, ObjCMethodList> GlobalMethods;
1125   typedef llvm::DenseMap<Selector, GlobalMethods> GlobalMethodPool;
1126 
1127   /// Method Pool - allows efficient lookup when typechecking messages to "id".
1128   /// We need to maintain a list, since selectors can have differing signatures
1129   /// across classes. In Cocoa, this happens to be extremely uncommon (only 1%
1130   /// of selectors are "overloaded").
1131   /// At the head of the list it is recorded whether there were 0, 1, or >= 2
1132   /// methods inside categories with a particular selector.
1133   GlobalMethodPool MethodPool;
1134 
1135   /// Method selectors used in a \@selector expression. Used for implementation
1136   /// of -Wselector.
1137   llvm::MapVector<Selector, SourceLocation> ReferencedSelectors;
1138 
1139   /// Kinds of C++ special members.
1140   enum CXXSpecialMember {
1141     CXXDefaultConstructor,
1142     CXXCopyConstructor,
1143     CXXMoveConstructor,
1144     CXXCopyAssignment,
1145     CXXMoveAssignment,
1146     CXXDestructor,
1147     CXXInvalid
1148   };
1149 
1150   typedef llvm::PointerIntPair<CXXRecordDecl *, 3, CXXSpecialMember>
1151       SpecialMemberDecl;
1152 
1153   /// The C++ special members which we are currently in the process of
1154   /// declaring. If this process recursively triggers the declaration of the
1155   /// same special member, we should act as if it is not yet declared.
1156   llvm::SmallPtrSet<SpecialMemberDecl, 4> SpecialMembersBeingDeclared;
1157 
1158   /// The function definitions which were renamed as part of typo-correction
1159   /// to match their respective declarations. We want to keep track of them
1160   /// to ensure that we don't emit a "redefinition" error if we encounter a
1161   /// correctly named definition after the renamed definition.
1162   llvm::SmallPtrSet<const NamedDecl *, 4> TypoCorrectedFunctionDefinitions;
1163 
1164   /// Stack of types that correspond to the parameter entities that are
1165   /// currently being copy-initialized. Can be empty.
1166   llvm::SmallVector<QualType, 4> CurrentParameterCopyTypes;
1167 
1168   void ReadMethodPool(Selector Sel);
1169   void updateOutOfDateSelector(Selector Sel);
1170 
1171   /// Private Helper predicate to check for 'self'.
1172   bool isSelfExpr(Expr *RExpr);
1173   bool isSelfExpr(Expr *RExpr, const ObjCMethodDecl *Method);
1174 
1175   /// Cause the active diagnostic on the DiagosticsEngine to be
1176   /// emitted. This is closely coupled to the SemaDiagnosticBuilder class and
1177   /// should not be used elsewhere.
1178   void EmitCurrentDiagnostic(unsigned DiagID);
1179 
1180   /// Records and restores the FP_CONTRACT state on entry/exit of compound
1181   /// statements.
1182   class FPContractStateRAII {
1183   public:
FPContractStateRAII(Sema & S)1184     FPContractStateRAII(Sema &S) : S(S), OldFPFeaturesState(S.FPFeatures) {}
~FPContractStateRAII()1185     ~FPContractStateRAII() { S.FPFeatures = OldFPFeaturesState; }
1186 
1187   private:
1188     Sema& S;
1189     FPOptions OldFPFeaturesState;
1190   };
1191 
1192   void addImplicitTypedef(StringRef Name, QualType T);
1193 
1194 public:
1195   Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer,
1196        TranslationUnitKind TUKind = TU_Complete,
1197        CodeCompleteConsumer *CompletionConsumer = nullptr);
1198   ~Sema();
1199 
1200   /// Perform initialization that occurs after the parser has been
1201   /// initialized but before it parses anything.
1202   void Initialize();
1203 
getLangOpts()1204   const LangOptions &getLangOpts() const { return LangOpts; }
getOpenCLOptions()1205   OpenCLOptions &getOpenCLOptions() { return OpenCLFeatures; }
getFPOptions()1206   FPOptions     &getFPOptions() { return FPFeatures; }
1207 
getDiagnostics()1208   DiagnosticsEngine &getDiagnostics() const { return Diags; }
getSourceManager()1209   SourceManager &getSourceManager() const { return SourceMgr; }
getPreprocessor()1210   Preprocessor &getPreprocessor() const { return PP; }
getASTContext()1211   ASTContext &getASTContext() const { return Context; }
getASTConsumer()1212   ASTConsumer &getASTConsumer() const { return Consumer; }
1213   ASTMutationListener *getASTMutationListener() const;
getExternalSource()1214   ExternalSemaSource* getExternalSource() const { return ExternalSource; }
1215 
1216   ///Registers an external source. If an external source already exists,
1217   /// creates a multiplex external source and appends to it.
1218   ///
1219   ///\param[in] E - A non-null external sema source.
1220   ///
1221   void addExternalSource(ExternalSemaSource *E);
1222 
1223   void PrintStats() const;
1224 
1225   /// Helper class that creates diagnostics with optional
1226   /// template instantiation stacks.
1227   ///
1228   /// This class provides a wrapper around the basic DiagnosticBuilder
1229   /// class that emits diagnostics. SemaDiagnosticBuilder is
1230   /// responsible for emitting the diagnostic (as DiagnosticBuilder
1231   /// does) and, if the diagnostic comes from inside a template
1232   /// instantiation, printing the template instantiation stack as
1233   /// well.
1234   class SemaDiagnosticBuilder : public DiagnosticBuilder {
1235     Sema &SemaRef;
1236     unsigned DiagID;
1237 
1238   public:
SemaDiagnosticBuilder(DiagnosticBuilder & DB,Sema & SemaRef,unsigned DiagID)1239     SemaDiagnosticBuilder(DiagnosticBuilder &DB, Sema &SemaRef, unsigned DiagID)
1240       : DiagnosticBuilder(DB), SemaRef(SemaRef), DiagID(DiagID) { }
1241 
1242     // This is a cunning lie. DiagnosticBuilder actually performs move
1243     // construction in its copy constructor (but due to varied uses, it's not
1244     // possible to conveniently express this as actual move construction). So
1245     // the default copy ctor here is fine, because the base class disables the
1246     // source anyway, so the user-defined ~SemaDiagnosticBuilder is a safe no-op
1247     // in that case anwyay.
1248     SemaDiagnosticBuilder(const SemaDiagnosticBuilder&) = default;
1249 
~SemaDiagnosticBuilder()1250     ~SemaDiagnosticBuilder() {
1251       // If we aren't active, there is nothing to do.
1252       if (!isActive()) return;
1253 
1254       // Otherwise, we need to emit the diagnostic. First flush the underlying
1255       // DiagnosticBuilder data, and clear the diagnostic builder itself so it
1256       // won't emit the diagnostic in its own destructor.
1257       //
1258       // This seems wasteful, in that as written the DiagnosticBuilder dtor will
1259       // do its own needless checks to see if the diagnostic needs to be
1260       // emitted. However, because we take care to ensure that the builder
1261       // objects never escape, a sufficiently smart compiler will be able to
1262       // eliminate that code.
1263       FlushCounts();
1264       Clear();
1265 
1266       // Dispatch to Sema to emit the diagnostic.
1267       SemaRef.EmitCurrentDiagnostic(DiagID);
1268     }
1269 
1270     /// Teach operator<< to produce an object of the correct type.
1271     template<typename T>
1272     friend const SemaDiagnosticBuilder &operator<<(
1273         const SemaDiagnosticBuilder &Diag, const T &Value) {
1274       const DiagnosticBuilder &BaseDiag = Diag;
1275       BaseDiag << Value;
1276       return Diag;
1277     }
1278   };
1279 
1280   /// Emit a diagnostic.
Diag(SourceLocation Loc,unsigned DiagID)1281   SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID) {
1282     DiagnosticBuilder DB = Diags.Report(Loc, DiagID);
1283     return SemaDiagnosticBuilder(DB, *this, DiagID);
1284   }
1285 
1286   /// Emit a partial diagnostic.
1287   SemaDiagnosticBuilder Diag(SourceLocation Loc, const PartialDiagnostic& PD);
1288 
1289   /// Build a partial diagnostic.
1290   PartialDiagnostic PDiag(unsigned DiagID = 0); // in SemaInternal.h
1291 
1292   bool findMacroSpelling(SourceLocation &loc, StringRef name);
1293 
1294   /// Get a string to suggest for zero-initialization of a type.
1295   std::string
1296   getFixItZeroInitializerForType(QualType T, SourceLocation Loc) const;
1297   std::string getFixItZeroLiteralForType(QualType T, SourceLocation Loc) const;
1298 
1299   /// Calls \c Lexer::getLocForEndOfToken()
1300   SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset = 0);
1301 
1302   /// Retrieve the module loader associated with the preprocessor.
1303   ModuleLoader &getModuleLoader() const;
1304 
1305   void emitAndClearUnusedLocalTypedefWarnings();
1306 
1307   void ActOnStartOfTranslationUnit();
1308   void ActOnEndOfTranslationUnit();
1309 
1310   void CheckDelegatingCtorCycles();
1311 
1312   Scope *getScopeForContext(DeclContext *Ctx);
1313 
1314   void PushFunctionScope();
1315   void PushBlockScope(Scope *BlockScope, BlockDecl *Block);
1316   sema::LambdaScopeInfo *PushLambdaScope();
1317 
1318   /// This is used to inform Sema what the current TemplateParameterDepth
1319   /// is during Parsing.  Currently it is used to pass on the depth
1320   /// when parsing generic lambda 'auto' parameters.
1321   void RecordParsingTemplateParameterDepth(unsigned Depth);
1322 
1323   void PushCapturedRegionScope(Scope *RegionScope, CapturedDecl *CD,
1324                                RecordDecl *RD,
1325                                CapturedRegionKind K);
1326   void
1327   PopFunctionScopeInfo(const sema::AnalysisBasedWarnings::Policy *WP = nullptr,
1328                        const Decl *D = nullptr,
1329                        const BlockExpr *blkExpr = nullptr);
1330 
getCurFunction()1331   sema::FunctionScopeInfo *getCurFunction() const {
1332     return FunctionScopes.empty() ? nullptr : FunctionScopes.back();
1333   }
1334 
1335   sema::FunctionScopeInfo *getEnclosingFunction() const;
1336 
1337   void setFunctionHasBranchIntoScope();
1338   void setFunctionHasBranchProtectedScope();
1339   void setFunctionHasIndirectGoto();
1340 
1341   void PushCompoundScope(bool IsStmtExpr);
1342   void PopCompoundScope();
1343 
1344   sema::CompoundScopeInfo &getCurCompoundScope() const;
1345 
1346   bool hasAnyUnrecoverableErrorsInThisFunction() const;
1347 
1348   /// Retrieve the current block, if any.
1349   sema::BlockScopeInfo *getCurBlock();
1350 
1351   /// Retrieve the current lambda scope info, if any.
1352   /// \param IgnoreNonLambdaCapturingScope true if should find the top-most
1353   /// lambda scope info ignoring all inner capturing scopes that are not
1354   /// lambda scopes.
1355   sema::LambdaScopeInfo *
1356   getCurLambda(bool IgnoreNonLambdaCapturingScope = false);
1357 
1358   /// Retrieve the current generic lambda info, if any.
1359   sema::LambdaScopeInfo *getCurGenericLambda();
1360 
1361   /// Retrieve the current captured region, if any.
1362   sema::CapturedRegionScopeInfo *getCurCapturedRegion();
1363 
1364   /// WeakTopLevelDeclDecls - access to \#pragma weak-generated Decls
WeakTopLevelDecls()1365   SmallVectorImpl<Decl *> &WeakTopLevelDecls() { return WeakTopLevelDecl; }
1366 
1367   void ActOnComment(SourceRange Comment);
1368 
1369   //===--------------------------------------------------------------------===//
1370   // Type Analysis / Processing: SemaType.cpp.
1371   //
1372 
1373   QualType BuildQualifiedType(QualType T, SourceLocation Loc, Qualifiers Qs,
1374                               const DeclSpec *DS = nullptr);
1375   QualType BuildQualifiedType(QualType T, SourceLocation Loc, unsigned CVRA,
1376                               const DeclSpec *DS = nullptr);
1377   QualType BuildPointerType(QualType T,
1378                             SourceLocation Loc, DeclarationName Entity);
1379   QualType BuildReferenceType(QualType T, bool LValueRef,
1380                               SourceLocation Loc, DeclarationName Entity);
1381   QualType BuildArrayType(QualType T, ArrayType::ArraySizeModifier ASM,
1382                           Expr *ArraySize, unsigned Quals,
1383                           SourceRange Brackets, DeclarationName Entity);
1384   QualType BuildVectorType(QualType T, Expr *VecSize, SourceLocation AttrLoc);
1385   QualType BuildExtVectorType(QualType T, Expr *ArraySize,
1386                               SourceLocation AttrLoc);
1387   QualType BuildAddressSpaceAttr(QualType &T, Expr *AddrSpace,
1388                                  SourceLocation AttrLoc);
1389 
1390   bool CheckFunctionReturnType(QualType T, SourceLocation Loc);
1391 
1392   /// Build a function type.
1393   ///
1394   /// This routine checks the function type according to C++ rules and
1395   /// under the assumption that the result type and parameter types have
1396   /// just been instantiated from a template. It therefore duplicates
1397   /// some of the behavior of GetTypeForDeclarator, but in a much
1398   /// simpler form that is only suitable for this narrow use case.
1399   ///
1400   /// \param T The return type of the function.
1401   ///
1402   /// \param ParamTypes The parameter types of the function. This array
1403   /// will be modified to account for adjustments to the types of the
1404   /// function parameters.
1405   ///
1406   /// \param Loc The location of the entity whose type involves this
1407   /// function type or, if there is no such entity, the location of the
1408   /// type that will have function type.
1409   ///
1410   /// \param Entity The name of the entity that involves the function
1411   /// type, if known.
1412   ///
1413   /// \param EPI Extra information about the function type. Usually this will
1414   /// be taken from an existing function with the same prototype.
1415   ///
1416   /// \returns A suitable function type, if there are no errors. The
1417   /// unqualified type will always be a FunctionProtoType.
1418   /// Otherwise, returns a NULL type.
1419   QualType BuildFunctionType(QualType T,
1420                              MutableArrayRef<QualType> ParamTypes,
1421                              SourceLocation Loc, DeclarationName Entity,
1422                              const FunctionProtoType::ExtProtoInfo &EPI);
1423 
1424   QualType BuildMemberPointerType(QualType T, QualType Class,
1425                                   SourceLocation Loc,
1426                                   DeclarationName Entity);
1427   QualType BuildBlockPointerType(QualType T,
1428                                  SourceLocation Loc, DeclarationName Entity);
1429   QualType BuildParenType(QualType T);
1430   QualType BuildAtomicType(QualType T, SourceLocation Loc);
1431   QualType BuildReadPipeType(QualType T,
1432                          SourceLocation Loc);
1433   QualType BuildWritePipeType(QualType T,
1434                          SourceLocation Loc);
1435 
1436   TypeSourceInfo *GetTypeForDeclarator(Declarator &D, Scope *S);
1437   TypeSourceInfo *GetTypeForDeclaratorCast(Declarator &D, QualType FromTy);
1438   TypeSourceInfo *GetTypeSourceInfoForDeclarator(Declarator &D, QualType T,
1439                                                TypeSourceInfo *ReturnTypeInfo);
1440 
1441   /// Package the given type and TSI into a ParsedType.
1442   ParsedType CreateParsedType(QualType T, TypeSourceInfo *TInfo);
1443   DeclarationNameInfo GetNameForDeclarator(Declarator &D);
1444   DeclarationNameInfo GetNameFromUnqualifiedId(const UnqualifiedId &Name);
1445   static QualType GetTypeFromParser(ParsedType Ty,
1446                                     TypeSourceInfo **TInfo = nullptr);
1447   CanThrowResult canThrow(const Expr *E);
1448   const FunctionProtoType *ResolveExceptionSpec(SourceLocation Loc,
1449                                                 const FunctionProtoType *FPT);
1450   void UpdateExceptionSpec(FunctionDecl *FD,
1451                            const FunctionProtoType::ExceptionSpecInfo &ESI);
1452   bool CheckSpecifiedExceptionType(QualType &T, SourceRange Range);
1453   bool CheckDistantExceptionSpec(QualType T);
1454   bool CheckEquivalentExceptionSpec(FunctionDecl *Old, FunctionDecl *New);
1455   bool CheckEquivalentExceptionSpec(
1456       const FunctionProtoType *Old, SourceLocation OldLoc,
1457       const FunctionProtoType *New, SourceLocation NewLoc);
1458   bool CheckEquivalentExceptionSpec(
1459       const PartialDiagnostic &DiagID, const PartialDiagnostic & NoteID,
1460       const FunctionProtoType *Old, SourceLocation OldLoc,
1461       const FunctionProtoType *New, SourceLocation NewLoc);
1462   bool handlerCanCatch(QualType HandlerType, QualType ExceptionType);
1463   bool CheckExceptionSpecSubset(const PartialDiagnostic &DiagID,
1464                                 const PartialDiagnostic &NestedDiagID,
1465                                 const PartialDiagnostic &NoteID,
1466                                 const FunctionProtoType *Superset,
1467                                 SourceLocation SuperLoc,
1468                                 const FunctionProtoType *Subset,
1469                                 SourceLocation SubLoc);
1470   bool CheckParamExceptionSpec(const PartialDiagnostic &NestedDiagID,
1471                                const PartialDiagnostic &NoteID,
1472                                const FunctionProtoType *Target,
1473                                SourceLocation TargetLoc,
1474                                const FunctionProtoType *Source,
1475                                SourceLocation SourceLoc);
1476 
1477   TypeResult ActOnTypeName(Scope *S, Declarator &D);
1478 
1479   /// The parser has parsed the context-sensitive type 'instancetype'
1480   /// in an Objective-C message declaration. Return the appropriate type.
1481   ParsedType ActOnObjCInstanceType(SourceLocation Loc);
1482 
1483   /// Abstract class used to diagnose incomplete types.
1484   struct TypeDiagnoser {
TypeDiagnoserTypeDiagnoser1485     TypeDiagnoser() {}
1486 
1487     virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) = 0;
~TypeDiagnoserTypeDiagnoser1488     virtual ~TypeDiagnoser() {}
1489   };
1490 
getPrintable(int I)1491   static int getPrintable(int I) { return I; }
getPrintable(unsigned I)1492   static unsigned getPrintable(unsigned I) { return I; }
getPrintable(bool B)1493   static bool getPrintable(bool B) { return B; }
getPrintable(const char * S)1494   static const char * getPrintable(const char *S) { return S; }
getPrintable(StringRef S)1495   static StringRef getPrintable(StringRef S) { return S; }
getPrintable(const std::string & S)1496   static const std::string &getPrintable(const std::string &S) { return S; }
getPrintable(const IdentifierInfo * II)1497   static const IdentifierInfo *getPrintable(const IdentifierInfo *II) {
1498     return II;
1499   }
getPrintable(DeclarationName N)1500   static DeclarationName getPrintable(DeclarationName N) { return N; }
getPrintable(QualType T)1501   static QualType getPrintable(QualType T) { return T; }
getPrintable(SourceRange R)1502   static SourceRange getPrintable(SourceRange R) { return R; }
getPrintable(SourceLocation L)1503   static SourceRange getPrintable(SourceLocation L) { return L; }
getPrintable(const Expr * E)1504   static SourceRange getPrintable(const Expr *E) { return E->getSourceRange(); }
getPrintable(TypeLoc TL)1505   static SourceRange getPrintable(TypeLoc TL) { return TL.getSourceRange();}
1506 
1507   template <typename... Ts> class BoundTypeDiagnoser : public TypeDiagnoser {
1508     unsigned DiagID;
1509     std::tuple<const Ts &...> Args;
1510 
1511     template <std::size_t... Is>
emit(const SemaDiagnosticBuilder & DB,llvm::index_sequence<Is...>)1512     void emit(const SemaDiagnosticBuilder &DB,
1513               llvm::index_sequence<Is...>) const {
1514       // Apply all tuple elements to the builder in order.
1515       bool Dummy[] = {false, (DB << getPrintable(std::get<Is>(Args)))...};
1516       (void)Dummy;
1517     }
1518 
1519   public:
BoundTypeDiagnoser(unsigned DiagID,const Ts &...Args)1520     BoundTypeDiagnoser(unsigned DiagID, const Ts &...Args)
1521         : TypeDiagnoser(), DiagID(DiagID), Args(Args...) {
1522       assert(DiagID != 0 && "no diagnostic for type diagnoser");
1523     }
1524 
diagnose(Sema & S,SourceLocation Loc,QualType T)1525     void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
1526       const SemaDiagnosticBuilder &DB = S.Diag(Loc, DiagID);
1527       emit(DB, llvm::index_sequence_for<Ts...>());
1528       DB << T;
1529     }
1530   };
1531 
1532 private:
1533   bool RequireCompleteTypeImpl(SourceLocation Loc, QualType T,
1534                                TypeDiagnoser *Diagnoser);
1535 
1536   struct ModuleScope {
1537     clang::Module *Module = nullptr;
1538     bool ModuleInterface = false;
1539     VisibleModuleSet OuterVisibleModules;
1540   };
1541   /// The modules we're currently parsing.
1542   llvm::SmallVector<ModuleScope, 16> ModuleScopes;
1543 
1544   /// Get the module whose scope we are currently within.
getCurrentModule()1545   Module *getCurrentModule() const {
1546     return ModuleScopes.empty() ? nullptr : ModuleScopes.back().Module;
1547   }
1548 
1549   VisibleModuleSet VisibleModules;
1550 
1551 public:
1552   /// Get the module owning an entity.
getOwningModule(Decl * Entity)1553   Module *getOwningModule(Decl *Entity) { return Entity->getOwningModule(); }
1554 
1555   /// Make a merged definition of an existing hidden definition \p ND
1556   /// visible at the specified location.
1557   void makeMergedDefinitionVisible(NamedDecl *ND);
1558 
isModuleVisible(const Module * M)1559   bool isModuleVisible(const Module *M) { return VisibleModules.isVisible(M); }
1560 
1561   /// Determine whether a declaration is visible to name lookup.
isVisible(const NamedDecl * D)1562   bool isVisible(const NamedDecl *D) {
1563     return !D->isHidden() || isVisibleSlow(D);
1564   }
1565 
1566   /// Determine whether any declaration of an entity is visible.
1567   bool
1568   hasVisibleDeclaration(const NamedDecl *D,
1569                         llvm::SmallVectorImpl<Module *> *Modules = nullptr) {
1570     return isVisible(D) || hasVisibleDeclarationSlow(D, Modules);
1571   }
1572   bool hasVisibleDeclarationSlow(const NamedDecl *D,
1573                                  llvm::SmallVectorImpl<Module *> *Modules);
1574 
1575   bool hasVisibleMergedDefinition(NamedDecl *Def);
1576   bool hasMergedDefinitionInCurrentModule(NamedDecl *Def);
1577 
1578   /// Determine if \p D and \p Suggested have a structurally compatible
1579   /// layout as described in C11 6.2.7/1.
1580   bool hasStructuralCompatLayout(Decl *D, Decl *Suggested);
1581 
1582   /// Determine if \p D has a visible definition. If not, suggest a declaration
1583   /// that should be made visible to expose the definition.
1584   bool hasVisibleDefinition(NamedDecl *D, NamedDecl **Suggested,
1585                             bool OnlyNeedComplete = false);
hasVisibleDefinition(const NamedDecl * D)1586   bool hasVisibleDefinition(const NamedDecl *D) {
1587     NamedDecl *Hidden;
1588     return hasVisibleDefinition(const_cast<NamedDecl*>(D), &Hidden);
1589   }
1590 
1591   /// Determine if the template parameter \p D has a visible default argument.
1592   bool
1593   hasVisibleDefaultArgument(const NamedDecl *D,
1594                             llvm::SmallVectorImpl<Module *> *Modules = nullptr);
1595 
1596   /// Determine if there is a visible declaration of \p D that is an explicit
1597   /// specialization declaration for a specialization of a template. (For a
1598   /// member specialization, use hasVisibleMemberSpecialization.)
1599   bool hasVisibleExplicitSpecialization(
1600       const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr);
1601 
1602   /// Determine if there is a visible declaration of \p D that is a member
1603   /// specialization declaration (as opposed to an instantiated declaration).
1604   bool hasVisibleMemberSpecialization(
1605       const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr);
1606 
1607   /// Determine if \p A and \p B are equivalent internal linkage declarations
1608   /// from different modules, and thus an ambiguity error can be downgraded to
1609   /// an extension warning.
1610   bool isEquivalentInternalLinkageDeclaration(const NamedDecl *A,
1611                                               const NamedDecl *B);
1612   void diagnoseEquivalentInternalLinkageDeclarations(
1613       SourceLocation Loc, const NamedDecl *D,
1614       ArrayRef<const NamedDecl *> Equiv);
1615 
isCompleteType(SourceLocation Loc,QualType T)1616   bool isCompleteType(SourceLocation Loc, QualType T) {
1617     return !RequireCompleteTypeImpl(Loc, T, nullptr);
1618   }
1619   bool RequireCompleteType(SourceLocation Loc, QualType T,
1620                            TypeDiagnoser &Diagnoser);
1621   bool RequireCompleteType(SourceLocation Loc, QualType T,
1622                            unsigned DiagID);
1623 
1624   template <typename... Ts>
RequireCompleteType(SourceLocation Loc,QualType T,unsigned DiagID,const Ts &...Args)1625   bool RequireCompleteType(SourceLocation Loc, QualType T, unsigned DiagID,
1626                            const Ts &...Args) {
1627     BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
1628     return RequireCompleteType(Loc, T, Diagnoser);
1629   }
1630 
1631   void completeExprArrayBound(Expr *E);
1632   bool RequireCompleteExprType(Expr *E, TypeDiagnoser &Diagnoser);
1633   bool RequireCompleteExprType(Expr *E, unsigned DiagID);
1634 
1635   template <typename... Ts>
RequireCompleteExprType(Expr * E,unsigned DiagID,const Ts &...Args)1636   bool RequireCompleteExprType(Expr *E, unsigned DiagID, const Ts &...Args) {
1637     BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
1638     return RequireCompleteExprType(E, Diagnoser);
1639   }
1640 
1641   bool RequireLiteralType(SourceLocation Loc, QualType T,
1642                           TypeDiagnoser &Diagnoser);
1643   bool RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID);
1644 
1645   template <typename... Ts>
RequireLiteralType(SourceLocation Loc,QualType T,unsigned DiagID,const Ts &...Args)1646   bool RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID,
1647                           const Ts &...Args) {
1648     BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
1649     return RequireLiteralType(Loc, T, Diagnoser);
1650   }
1651 
1652   QualType getElaboratedType(ElaboratedTypeKeyword Keyword,
1653                              const CXXScopeSpec &SS, QualType T,
1654                              TagDecl *OwnedTagDecl = nullptr);
1655 
1656   QualType BuildTypeofExprType(Expr *E, SourceLocation Loc);
1657   /// If AsUnevaluated is false, E is treated as though it were an evaluated
1658   /// context, such as when building a type for decltype(auto).
1659   QualType BuildDecltypeType(Expr *E, SourceLocation Loc,
1660                              bool AsUnevaluated = true);
1661   QualType BuildUnaryTransformType(QualType BaseType,
1662                                    UnaryTransformType::UTTKind UKind,
1663                                    SourceLocation Loc);
1664 
1665   //===--------------------------------------------------------------------===//
1666   // Symbol table / Decl tracking callbacks: SemaDecl.cpp.
1667   //
1668 
1669   struct SkipBodyInfo {
SkipBodyInfoSkipBodyInfo1670     SkipBodyInfo()
1671         : ShouldSkip(false), CheckSameAsPrevious(false), Previous(nullptr),
1672           New(nullptr) {}
1673     bool ShouldSkip;
1674     bool CheckSameAsPrevious;
1675     NamedDecl *Previous;
1676     NamedDecl *New;
1677   };
1678 
1679   DeclGroupPtrTy ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType = nullptr);
1680 
1681   void DiagnoseUseOfUnimplementedSelectors();
1682 
1683   bool isSimpleTypeSpecifier(tok::TokenKind Kind) const;
1684 
1685   ParsedType getTypeName(const IdentifierInfo &II, SourceLocation NameLoc,
1686                          Scope *S, CXXScopeSpec *SS = nullptr,
1687                          bool isClassName = false, bool HasTrailingDot = false,
1688                          ParsedType ObjectType = nullptr,
1689                          bool IsCtorOrDtorName = false,
1690                          bool WantNontrivialTypeSourceInfo = false,
1691                          bool IsClassTemplateDeductionContext = true,
1692                          IdentifierInfo **CorrectedII = nullptr);
1693   TypeSpecifierType isTagName(IdentifierInfo &II, Scope *S);
1694   bool isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S);
1695   void DiagnoseUnknownTypeName(IdentifierInfo *&II,
1696                                SourceLocation IILoc,
1697                                Scope *S,
1698                                CXXScopeSpec *SS,
1699                                ParsedType &SuggestedType,
1700                                bool IsTemplateName = false);
1701 
1702   /// Attempt to behave like MSVC in situations where lookup of an unqualified
1703   /// type name has failed in a dependent context. In these situations, we
1704   /// automatically form a DependentTypeName that will retry lookup in a related
1705   /// scope during instantiation.
1706   ParsedType ActOnMSVCUnknownTypeName(const IdentifierInfo &II,
1707                                       SourceLocation NameLoc,
1708                                       bool IsTemplateTypeArg);
1709 
1710   /// Describes the result of the name lookup and resolution performed
1711   /// by \c ClassifyName().
1712   enum NameClassificationKind {
1713     NC_Unknown,
1714     NC_Error,
1715     NC_Keyword,
1716     NC_Type,
1717     NC_Expression,
1718     NC_NestedNameSpecifier,
1719     NC_TypeTemplate,
1720     NC_VarTemplate,
1721     NC_FunctionTemplate
1722   };
1723 
1724   class NameClassification {
1725     NameClassificationKind Kind;
1726     ExprResult Expr;
1727     TemplateName Template;
1728     ParsedType Type;
1729 
NameClassification(NameClassificationKind Kind)1730     explicit NameClassification(NameClassificationKind Kind) : Kind(Kind) {}
1731 
1732   public:
NameClassification(ExprResult Expr)1733     NameClassification(ExprResult Expr) : Kind(NC_Expression), Expr(Expr) {}
1734 
NameClassification(ParsedType Type)1735     NameClassification(ParsedType Type) : Kind(NC_Type), Type(Type) {}
1736 
NameClassification(const IdentifierInfo * Keyword)1737     NameClassification(const IdentifierInfo *Keyword) : Kind(NC_Keyword) {}
1738 
Error()1739     static NameClassification Error() {
1740       return NameClassification(NC_Error);
1741     }
1742 
Unknown()1743     static NameClassification Unknown() {
1744       return NameClassification(NC_Unknown);
1745     }
1746 
NestedNameSpecifier()1747     static NameClassification NestedNameSpecifier() {
1748       return NameClassification(NC_NestedNameSpecifier);
1749     }
1750 
TypeTemplate(TemplateName Name)1751     static NameClassification TypeTemplate(TemplateName Name) {
1752       NameClassification Result(NC_TypeTemplate);
1753       Result.Template = Name;
1754       return Result;
1755     }
1756 
VarTemplate(TemplateName Name)1757     static NameClassification VarTemplate(TemplateName Name) {
1758       NameClassification Result(NC_VarTemplate);
1759       Result.Template = Name;
1760       return Result;
1761     }
1762 
FunctionTemplate(TemplateName Name)1763     static NameClassification FunctionTemplate(TemplateName Name) {
1764       NameClassification Result(NC_FunctionTemplate);
1765       Result.Template = Name;
1766       return Result;
1767     }
1768 
getKind()1769     NameClassificationKind getKind() const { return Kind; }
1770 
getType()1771     ParsedType getType() const {
1772       assert(Kind == NC_Type);
1773       return Type;
1774     }
1775 
getExpression()1776     ExprResult getExpression() const {
1777       assert(Kind == NC_Expression);
1778       return Expr;
1779     }
1780 
getTemplateName()1781     TemplateName getTemplateName() const {
1782       assert(Kind == NC_TypeTemplate || Kind == NC_FunctionTemplate ||
1783              Kind == NC_VarTemplate);
1784       return Template;
1785     }
1786 
getTemplateNameKind()1787     TemplateNameKind getTemplateNameKind() const {
1788       switch (Kind) {
1789       case NC_TypeTemplate:
1790         return TNK_Type_template;
1791       case NC_FunctionTemplate:
1792         return TNK_Function_template;
1793       case NC_VarTemplate:
1794         return TNK_Var_template;
1795       default:
1796         llvm_unreachable("unsupported name classification.");
1797       }
1798     }
1799   };
1800 
1801   /// Perform name lookup on the given name, classifying it based on
1802   /// the results of name lookup and the following token.
1803   ///
1804   /// This routine is used by the parser to resolve identifiers and help direct
1805   /// parsing. When the identifier cannot be found, this routine will attempt
1806   /// to correct the typo and classify based on the resulting name.
1807   ///
1808   /// \param S The scope in which we're performing name lookup.
1809   ///
1810   /// \param SS The nested-name-specifier that precedes the name.
1811   ///
1812   /// \param Name The identifier. If typo correction finds an alternative name,
1813   /// this pointer parameter will be updated accordingly.
1814   ///
1815   /// \param NameLoc The location of the identifier.
1816   ///
1817   /// \param NextToken The token following the identifier. Used to help
1818   /// disambiguate the name.
1819   ///
1820   /// \param IsAddressOfOperand True if this name is the operand of a unary
1821   ///        address of ('&') expression, assuming it is classified as an
1822   ///        expression.
1823   ///
1824   /// \param CCC The correction callback, if typo correction is desired.
1825   NameClassification
1826   ClassifyName(Scope *S, CXXScopeSpec &SS, IdentifierInfo *&Name,
1827                SourceLocation NameLoc, const Token &NextToken,
1828                bool IsAddressOfOperand,
1829                std::unique_ptr<CorrectionCandidateCallback> CCC = nullptr);
1830 
1831   /// Describes the detailed kind of a template name. Used in diagnostics.
1832   enum class TemplateNameKindForDiagnostics {
1833     ClassTemplate,
1834     FunctionTemplate,
1835     VarTemplate,
1836     AliasTemplate,
1837     TemplateTemplateParam,
1838     DependentTemplate
1839   };
1840   TemplateNameKindForDiagnostics
1841   getTemplateNameKindForDiagnostics(TemplateName Name);
1842 
1843   /// Determine whether it's plausible that E was intended to be a
1844   /// template-name.
mightBeIntendedToBeTemplateName(ExprResult E,bool & Dependent)1845   bool mightBeIntendedToBeTemplateName(ExprResult E, bool &Dependent) {
1846     if (!getLangOpts().CPlusPlus || E.isInvalid())
1847       return false;
1848     Dependent = false;
1849     if (auto *DRE = dyn_cast<DeclRefExpr>(E.get()))
1850       return !DRE->hasExplicitTemplateArgs();
1851     if (auto *ME = dyn_cast<MemberExpr>(E.get()))
1852       return !ME->hasExplicitTemplateArgs();
1853     Dependent = true;
1854     if (auto *DSDRE = dyn_cast<DependentScopeDeclRefExpr>(E.get()))
1855       return !DSDRE->hasExplicitTemplateArgs();
1856     if (auto *DSME = dyn_cast<CXXDependentScopeMemberExpr>(E.get()))
1857       return !DSME->hasExplicitTemplateArgs();
1858     // Any additional cases recognized here should also be handled by
1859     // diagnoseExprIntendedAsTemplateName.
1860     return false;
1861   }
1862   void diagnoseExprIntendedAsTemplateName(Scope *S, ExprResult TemplateName,
1863                                           SourceLocation Less,
1864                                           SourceLocation Greater);
1865 
1866   Decl *ActOnDeclarator(Scope *S, Declarator &D);
1867 
1868   NamedDecl *HandleDeclarator(Scope *S, Declarator &D,
1869                               MultiTemplateParamsArg TemplateParameterLists);
1870   void RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S);
1871   bool DiagnoseClassNameShadow(DeclContext *DC, DeclarationNameInfo Info);
1872   bool diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
1873                                     DeclarationName Name, SourceLocation Loc,
1874                                     bool IsTemplateId);
1875   void
1876   diagnoseIgnoredQualifiers(unsigned DiagID, unsigned Quals,
1877                             SourceLocation FallbackLoc,
1878                             SourceLocation ConstQualLoc = SourceLocation(),
1879                             SourceLocation VolatileQualLoc = SourceLocation(),
1880                             SourceLocation RestrictQualLoc = SourceLocation(),
1881                             SourceLocation AtomicQualLoc = SourceLocation(),
1882                             SourceLocation UnalignedQualLoc = SourceLocation());
1883 
1884   static bool adjustContextForLocalExternDecl(DeclContext *&DC);
1885   void DiagnoseFunctionSpecifiers(const DeclSpec &DS);
1886   NamedDecl *getShadowedDeclaration(const TypedefNameDecl *D,
1887                                     const LookupResult &R);
1888   NamedDecl *getShadowedDeclaration(const VarDecl *D, const LookupResult &R);
1889   void CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl,
1890                    const LookupResult &R);
1891   void CheckShadow(Scope *S, VarDecl *D);
1892 
1893   /// Warn if 'E', which is an expression that is about to be modified, refers
1894   /// to a shadowing declaration.
1895   void CheckShadowingDeclModification(Expr *E, SourceLocation Loc);
1896 
1897   void DiagnoseShadowingLambdaDecls(const sema::LambdaScopeInfo *LSI);
1898 
1899 private:
1900   /// Map of current shadowing declarations to shadowed declarations. Warn if
1901   /// it looks like the user is trying to modify the shadowing declaration.
1902   llvm::DenseMap<const NamedDecl *, const NamedDecl *> ShadowingDecls;
1903 
1904 public:
1905   void CheckCastAlign(Expr *Op, QualType T, SourceRange TRange);
1906   void handleTagNumbering(const TagDecl *Tag, Scope *TagScope);
1907   void setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
1908                                     TypedefNameDecl *NewTD);
1909   void CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *D);
1910   NamedDecl* ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
1911                                     TypeSourceInfo *TInfo,
1912                                     LookupResult &Previous);
1913   NamedDecl* ActOnTypedefNameDecl(Scope* S, DeclContext* DC, TypedefNameDecl *D,
1914                                   LookupResult &Previous, bool &Redeclaration);
1915   NamedDecl *ActOnVariableDeclarator(Scope *S, Declarator &D, DeclContext *DC,
1916                                      TypeSourceInfo *TInfo,
1917                                      LookupResult &Previous,
1918                                      MultiTemplateParamsArg TemplateParamLists,
1919                                      bool &AddToScope,
1920                                      ArrayRef<BindingDecl *> Bindings = None);
1921   NamedDecl *
1922   ActOnDecompositionDeclarator(Scope *S, Declarator &D,
1923                                MultiTemplateParamsArg TemplateParamLists);
1924   // Returns true if the variable declaration is a redeclaration
1925   bool CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous);
1926   void CheckVariableDeclarationType(VarDecl *NewVD);
1927   bool DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit,
1928                                      Expr *Init);
1929   void CheckCompleteVariableDeclaration(VarDecl *VD);
1930   void CheckCompleteDecompositionDeclaration(DecompositionDecl *DD);
1931   void MaybeSuggestAddingStaticToDecl(const FunctionDecl *D);
1932 
1933   NamedDecl* ActOnFunctionDeclarator(Scope* S, Declarator& D, DeclContext* DC,
1934                                      TypeSourceInfo *TInfo,
1935                                      LookupResult &Previous,
1936                                      MultiTemplateParamsArg TemplateParamLists,
1937                                      bool &AddToScope);
1938   bool AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD);
1939 
1940   bool CheckConstexprFunctionDecl(const FunctionDecl *FD);
1941   bool CheckConstexprFunctionBody(const FunctionDecl *FD, Stmt *Body);
1942 
1943   void DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD);
1944   void FindHiddenVirtualMethods(CXXMethodDecl *MD,
1945                           SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods);
1946   void NoteHiddenVirtualMethods(CXXMethodDecl *MD,
1947                           SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods);
1948   // Returns true if the function declaration is a redeclaration
1949   bool CheckFunctionDeclaration(Scope *S,
1950                                 FunctionDecl *NewFD, LookupResult &Previous,
1951                                 bool IsMemberSpecialization);
1952   bool shouldLinkDependentDeclWithPrevious(Decl *D, Decl *OldDecl);
1953   bool canFullyTypeCheckRedeclaration(ValueDecl *NewD, ValueDecl *OldD,
1954                                       QualType NewT, QualType OldT);
1955   void CheckMain(FunctionDecl *FD, const DeclSpec &D);
1956   void CheckMSVCRTEntryPoint(FunctionDecl *FD);
1957   Attr *getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD, bool IsDefinition);
1958   Decl *ActOnParamDeclarator(Scope *S, Declarator &D);
1959   ParmVarDecl *BuildParmVarDeclForTypedef(DeclContext *DC,
1960                                           SourceLocation Loc,
1961                                           QualType T);
1962   ParmVarDecl *CheckParameter(DeclContext *DC, SourceLocation StartLoc,
1963                               SourceLocation NameLoc, IdentifierInfo *Name,
1964                               QualType T, TypeSourceInfo *TSInfo,
1965                               StorageClass SC);
1966   void ActOnParamDefaultArgument(Decl *param,
1967                                  SourceLocation EqualLoc,
1968                                  Expr *defarg);
1969   void ActOnParamUnparsedDefaultArgument(Decl *param,
1970                                          SourceLocation EqualLoc,
1971                                          SourceLocation ArgLoc);
1972   void ActOnParamDefaultArgumentError(Decl *param, SourceLocation EqualLoc);
1973   bool SetParamDefaultArgument(ParmVarDecl *Param, Expr *DefaultArg,
1974                                SourceLocation EqualLoc);
1975 
1976   void AddInitializerToDecl(Decl *dcl, Expr *init, bool DirectInit);
1977   void ActOnUninitializedDecl(Decl *dcl);
1978   void ActOnInitializerError(Decl *Dcl);
1979 
1980   void ActOnPureSpecifier(Decl *D, SourceLocation PureSpecLoc);
1981   void ActOnCXXForRangeDecl(Decl *D);
1982   StmtResult ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc,
1983                                         IdentifierInfo *Ident,
1984                                         ParsedAttributes &Attrs,
1985                                         SourceLocation AttrEnd);
1986   void SetDeclDeleted(Decl *dcl, SourceLocation DelLoc);
1987   void SetDeclDefaulted(Decl *dcl, SourceLocation DefaultLoc);
1988   void FinalizeDeclaration(Decl *D);
1989   DeclGroupPtrTy FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
1990                                          ArrayRef<Decl *> Group);
1991   DeclGroupPtrTy BuildDeclaratorGroup(MutableArrayRef<Decl *> Group);
1992 
1993   /// Should be called on all declarations that might have attached
1994   /// documentation comments.
1995   void ActOnDocumentableDecl(Decl *D);
1996   void ActOnDocumentableDecls(ArrayRef<Decl *> Group);
1997 
1998   void ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
1999                                        SourceLocation LocAfterDecls);
2000   void CheckForFunctionRedefinition(
2001       FunctionDecl *FD, const FunctionDecl *EffectiveDefinition = nullptr,
2002       SkipBodyInfo *SkipBody = nullptr);
2003   Decl *ActOnStartOfFunctionDef(Scope *S, Declarator &D,
2004                                 MultiTemplateParamsArg TemplateParamLists,
2005                                 SkipBodyInfo *SkipBody = nullptr);
2006   Decl *ActOnStartOfFunctionDef(Scope *S, Decl *D,
2007                                 SkipBodyInfo *SkipBody = nullptr);
2008   void ActOnStartOfObjCMethodDef(Scope *S, Decl *D);
isObjCMethodDecl(Decl * D)2009   bool isObjCMethodDecl(Decl *D) {
2010     return D && isa<ObjCMethodDecl>(D);
2011   }
2012 
2013   /// Determine whether we can delay parsing the body of a function or
2014   /// function template until it is used, assuming we don't care about emitting
2015   /// code for that function.
2016   ///
2017   /// This will be \c false if we may need the body of the function in the
2018   /// middle of parsing an expression (where it's impractical to switch to
2019   /// parsing a different function), for instance, if it's constexpr in C++11
2020   /// or has an 'auto' return type in C++14. These cases are essentially bugs.
2021   bool canDelayFunctionBody(const Declarator &D);
2022 
2023   /// Determine whether we can skip parsing the body of a function
2024   /// definition, assuming we don't care about analyzing its body or emitting
2025   /// code for that function.
2026   ///
2027   /// This will be \c false only if we may need the body of the function in
2028   /// order to parse the rest of the program (for instance, if it is
2029   /// \c constexpr in C++11 or has an 'auto' return type in C++14).
2030   bool canSkipFunctionBody(Decl *D);
2031 
2032   void computeNRVO(Stmt *Body, sema::FunctionScopeInfo *Scope);
2033   Decl *ActOnFinishFunctionBody(Decl *Decl, Stmt *Body);
2034   Decl *ActOnFinishFunctionBody(Decl *Decl, Stmt *Body, bool IsInstantiation);
2035   Decl *ActOnSkippedFunctionBody(Decl *Decl);
2036   void ActOnFinishInlineFunctionDef(FunctionDecl *D);
2037 
2038   /// ActOnFinishDelayedAttribute - Invoked when we have finished parsing an
2039   /// attribute for which parsing is delayed.
2040   void ActOnFinishDelayedAttribute(Scope *S, Decl *D, ParsedAttributes &Attrs);
2041 
2042   /// Diagnose any unused parameters in the given sequence of
2043   /// ParmVarDecl pointers.
2044   void DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters);
2045 
2046   /// Diagnose whether the size of parameters or return value of a
2047   /// function or obj-c method definition is pass-by-value and larger than a
2048   /// specified threshold.
2049   void
2050   DiagnoseSizeOfParametersAndReturnValue(ArrayRef<ParmVarDecl *> Parameters,
2051                                          QualType ReturnTy, NamedDecl *D);
2052 
2053   void DiagnoseInvalidJumps(Stmt *Body);
2054   Decl *ActOnFileScopeAsmDecl(Expr *expr,
2055                               SourceLocation AsmLoc,
2056                               SourceLocation RParenLoc);
2057 
2058   /// Handle a C++11 empty-declaration and attribute-declaration.
2059   Decl *ActOnEmptyDeclaration(Scope *S, const ParsedAttributesView &AttrList,
2060                               SourceLocation SemiLoc);
2061 
2062   enum class ModuleDeclKind {
2063     Interface,      ///< 'export module X;'
2064     Implementation, ///< 'module X;'
2065     Partition,      ///< 'module partition X;'
2066   };
2067 
2068   /// The parser has processed a module-declaration that begins the definition
2069   /// of a module interface or implementation.
2070   DeclGroupPtrTy ActOnModuleDecl(SourceLocation StartLoc,
2071                                  SourceLocation ModuleLoc, ModuleDeclKind MDK,
2072                                  ModuleIdPath Path);
2073 
2074   /// The parser has processed a module import declaration.
2075   ///
2076   /// \param AtLoc The location of the '@' symbol, if any.
2077   ///
2078   /// \param ImportLoc The location of the 'import' keyword.
2079   ///
2080   /// \param Path The module access path.
2081   DeclResult ActOnModuleImport(SourceLocation AtLoc, SourceLocation ImportLoc,
2082                                ModuleIdPath Path);
2083 
2084   /// The parser has processed a module import translated from a
2085   /// #include or similar preprocessing directive.
2086   void ActOnModuleInclude(SourceLocation DirectiveLoc, Module *Mod);
2087   void BuildModuleInclude(SourceLocation DirectiveLoc, Module *Mod);
2088 
2089   /// The parsed has entered a submodule.
2090   void ActOnModuleBegin(SourceLocation DirectiveLoc, Module *Mod);
2091   /// The parser has left a submodule.
2092   void ActOnModuleEnd(SourceLocation DirectiveLoc, Module *Mod);
2093 
2094   /// Create an implicit import of the given module at the given
2095   /// source location, for error recovery, if possible.
2096   ///
2097   /// This routine is typically used when an entity found by name lookup
2098   /// is actually hidden within a module that we know about but the user
2099   /// has forgotten to import.
2100   void createImplicitModuleImportForErrorRecovery(SourceLocation Loc,
2101                                                   Module *Mod);
2102 
2103   /// Kinds of missing import. Note, the values of these enumerators correspond
2104   /// to %select values in diagnostics.
2105   enum class MissingImportKind {
2106     Declaration,
2107     Definition,
2108     DefaultArgument,
2109     ExplicitSpecialization,
2110     PartialSpecialization
2111   };
2112 
2113   /// Diagnose that the specified declaration needs to be visible but
2114   /// isn't, and suggest a module import that would resolve the problem.
2115   void diagnoseMissingImport(SourceLocation Loc, NamedDecl *Decl,
2116                              MissingImportKind MIK, bool Recover = true);
2117   void diagnoseMissingImport(SourceLocation Loc, NamedDecl *Decl,
2118                              SourceLocation DeclLoc, ArrayRef<Module *> Modules,
2119                              MissingImportKind MIK, bool Recover);
2120 
2121   Decl *ActOnStartExportDecl(Scope *S, SourceLocation ExportLoc,
2122                              SourceLocation LBraceLoc);
2123   Decl *ActOnFinishExportDecl(Scope *S, Decl *ExportDecl,
2124                               SourceLocation RBraceLoc);
2125 
2126   /// We've found a use of a templated declaration that would trigger an
2127   /// implicit instantiation. Check that any relevant explicit specializations
2128   /// and partial specializations are visible, and diagnose if not.
2129   void checkSpecializationVisibility(SourceLocation Loc, NamedDecl *Spec);
2130 
2131   /// We've found a use of a template specialization that would select a
2132   /// partial specialization. Check that the partial specialization is visible,
2133   /// and diagnose if not.
2134   void checkPartialSpecializationVisibility(SourceLocation Loc,
2135                                             NamedDecl *Spec);
2136 
2137   /// Retrieve a suitable printing policy for diagnostics.
getPrintingPolicy()2138   PrintingPolicy getPrintingPolicy() const {
2139     return getPrintingPolicy(Context, PP);
2140   }
2141 
2142   /// Retrieve a suitable printing policy for diagnostics.
2143   static PrintingPolicy getPrintingPolicy(const ASTContext &Ctx,
2144                                           const Preprocessor &PP);
2145 
2146   /// Scope actions.
2147   void ActOnPopScope(SourceLocation Loc, Scope *S);
2148   void ActOnTranslationUnitScope(Scope *S);
2149 
2150   Decl *ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
2151                                    RecordDecl *&AnonRecord);
2152   Decl *ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
2153                                    MultiTemplateParamsArg TemplateParams,
2154                                    bool IsExplicitInstantiation,
2155                                    RecordDecl *&AnonRecord);
2156 
2157   Decl *BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
2158                                     AccessSpecifier AS,
2159                                     RecordDecl *Record,
2160                                     const PrintingPolicy &Policy);
2161 
2162   Decl *BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
2163                                        RecordDecl *Record);
2164 
2165   /// Common ways to introduce type names without a tag for use in diagnostics.
2166   /// Keep in sync with err_tag_reference_non_tag.
2167   enum NonTagKind {
2168     NTK_NonStruct,
2169     NTK_NonClass,
2170     NTK_NonUnion,
2171     NTK_NonEnum,
2172     NTK_Typedef,
2173     NTK_TypeAlias,
2174     NTK_Template,
2175     NTK_TypeAliasTemplate,
2176     NTK_TemplateTemplateArgument,
2177   };
2178 
2179   /// Given a non-tag type declaration, returns an enum useful for indicating
2180   /// what kind of non-tag type this is.
2181   NonTagKind getNonTagTypeDeclKind(const Decl *D, TagTypeKind TTK);
2182 
2183   bool isAcceptableTagRedeclaration(const TagDecl *Previous,
2184                                     TagTypeKind NewTag, bool isDefinition,
2185                                     SourceLocation NewTagLoc,
2186                                     const IdentifierInfo *Name);
2187 
2188   enum TagUseKind {
2189     TUK_Reference,   // Reference to a tag:  'struct foo *X;'
2190     TUK_Declaration, // Fwd decl of a tag:   'struct foo;'
2191     TUK_Definition,  // Definition of a tag: 'struct foo { int X; } Y;'
2192     TUK_Friend       // Friend declaration:  'friend struct foo;'
2193   };
2194 
2195   Decl *ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
2196                  SourceLocation KWLoc, CXXScopeSpec &SS, IdentifierInfo *Name,
2197                  SourceLocation NameLoc, const ParsedAttributesView &Attr,
2198                  AccessSpecifier AS, SourceLocation ModulePrivateLoc,
2199                  MultiTemplateParamsArg TemplateParameterLists, bool &OwnedDecl,
2200                  bool &IsDependent, SourceLocation ScopedEnumKWLoc,
2201                  bool ScopedEnumUsesClassTag, TypeResult UnderlyingType,
2202                  bool IsTypeSpecifier, bool IsTemplateParamOrArg,
2203                  SkipBodyInfo *SkipBody = nullptr);
2204 
2205   Decl *ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
2206                                 unsigned TagSpec, SourceLocation TagLoc,
2207                                 CXXScopeSpec &SS, IdentifierInfo *Name,
2208                                 SourceLocation NameLoc,
2209                                 const ParsedAttributesView &Attr,
2210                                 MultiTemplateParamsArg TempParamLists);
2211 
2212   TypeResult ActOnDependentTag(Scope *S,
2213                                unsigned TagSpec,
2214                                TagUseKind TUK,
2215                                const CXXScopeSpec &SS,
2216                                IdentifierInfo *Name,
2217                                SourceLocation TagLoc,
2218                                SourceLocation NameLoc);
2219 
2220   void ActOnDefs(Scope *S, Decl *TagD, SourceLocation DeclStart,
2221                  IdentifierInfo *ClassName,
2222                  SmallVectorImpl<Decl *> &Decls);
2223   Decl *ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
2224                    Declarator &D, Expr *BitfieldWidth);
2225 
2226   FieldDecl *HandleField(Scope *S, RecordDecl *TagD, SourceLocation DeclStart,
2227                          Declarator &D, Expr *BitfieldWidth,
2228                          InClassInitStyle InitStyle,
2229                          AccessSpecifier AS);
2230   MSPropertyDecl *HandleMSProperty(Scope *S, RecordDecl *TagD,
2231                                    SourceLocation DeclStart, Declarator &D,
2232                                    Expr *BitfieldWidth,
2233                                    InClassInitStyle InitStyle,
2234                                    AccessSpecifier AS,
2235                                    const ParsedAttr &MSPropertyAttr);
2236 
2237   FieldDecl *CheckFieldDecl(DeclarationName Name, QualType T,
2238                             TypeSourceInfo *TInfo,
2239                             RecordDecl *Record, SourceLocation Loc,
2240                             bool Mutable, Expr *BitfieldWidth,
2241                             InClassInitStyle InitStyle,
2242                             SourceLocation TSSL,
2243                             AccessSpecifier AS, NamedDecl *PrevDecl,
2244                             Declarator *D = nullptr);
2245 
2246   bool CheckNontrivialField(FieldDecl *FD);
2247   void DiagnoseNontrivial(const CXXRecordDecl *Record, CXXSpecialMember CSM);
2248 
2249   enum TrivialABIHandling {
2250     /// The triviality of a method unaffected by "trivial_abi".
2251     TAH_IgnoreTrivialABI,
2252 
2253     /// The triviality of a method affected by "trivial_abi".
2254     TAH_ConsiderTrivialABI
2255   };
2256 
2257   bool SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
2258                               TrivialABIHandling TAH = TAH_IgnoreTrivialABI,
2259                               bool Diagnose = false);
2260   CXXSpecialMember getSpecialMember(const CXXMethodDecl *MD);
2261   void ActOnLastBitfield(SourceLocation DeclStart,
2262                          SmallVectorImpl<Decl *> &AllIvarDecls);
2263   Decl *ActOnIvar(Scope *S, SourceLocation DeclStart,
2264                   Declarator &D, Expr *BitfieldWidth,
2265                   tok::ObjCKeywordKind visibility);
2266 
2267   // This is used for both record definitions and ObjC interface declarations.
2268   void ActOnFields(Scope *S, SourceLocation RecLoc, Decl *TagDecl,
2269                    ArrayRef<Decl *> Fields, SourceLocation LBrac,
2270                    SourceLocation RBrac, const ParsedAttributesView &AttrList);
2271 
2272   /// ActOnTagStartDefinition - Invoked when we have entered the
2273   /// scope of a tag's definition (e.g., for an enumeration, class,
2274   /// struct, or union).
2275   void ActOnTagStartDefinition(Scope *S, Decl *TagDecl);
2276 
2277   /// Perform ODR-like check for C/ObjC when merging tag types from modules.
2278   /// Differently from C++, actually parse the body and reject / error out
2279   /// in case of a structural mismatch.
2280   bool ActOnDuplicateDefinition(DeclSpec &DS, Decl *Prev,
2281                                 SkipBodyInfo &SkipBody);
2282 
2283   typedef void *SkippedDefinitionContext;
2284 
2285   /// Invoked when we enter a tag definition that we're skipping.
2286   SkippedDefinitionContext ActOnTagStartSkippedDefinition(Scope *S, Decl *TD);
2287 
2288   Decl *ActOnObjCContainerStartDefinition(Decl *IDecl);
2289 
2290   /// ActOnStartCXXMemberDeclarations - Invoked when we have parsed a
2291   /// C++ record definition's base-specifiers clause and are starting its
2292   /// member declarations.
2293   void ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagDecl,
2294                                        SourceLocation FinalLoc,
2295                                        bool IsFinalSpelledSealed,
2296                                        SourceLocation LBraceLoc);
2297 
2298   /// ActOnTagFinishDefinition - Invoked once we have finished parsing
2299   /// the definition of a tag (enumeration, class, struct, or union).
2300   void ActOnTagFinishDefinition(Scope *S, Decl *TagDecl,
2301                                 SourceRange BraceRange);
2302 
2303   void ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context);
2304 
2305   void ActOnObjCContainerFinishDefinition();
2306 
2307   /// Invoked when we must temporarily exit the objective-c container
2308   /// scope for parsing/looking-up C constructs.
2309   ///
2310   /// Must be followed by a call to \see ActOnObjCReenterContainerContext
2311   void ActOnObjCTemporaryExitContainerContext(DeclContext *DC);
2312   void ActOnObjCReenterContainerContext(DeclContext *DC);
2313 
2314   /// ActOnTagDefinitionError - Invoked when there was an unrecoverable
2315   /// error parsing the definition of a tag.
2316   void ActOnTagDefinitionError(Scope *S, Decl *TagDecl);
2317 
2318   EnumConstantDecl *CheckEnumConstant(EnumDecl *Enum,
2319                                       EnumConstantDecl *LastEnumConst,
2320                                       SourceLocation IdLoc,
2321                                       IdentifierInfo *Id,
2322                                       Expr *val);
2323   bool CheckEnumUnderlyingType(TypeSourceInfo *TI);
2324   bool CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
2325                               QualType EnumUnderlyingTy, bool IsFixed,
2326                               const EnumDecl *Prev);
2327 
2328   /// Determine whether the body of an anonymous enumeration should be skipped.
2329   /// \param II The name of the first enumerator.
2330   SkipBodyInfo shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II,
2331                                       SourceLocation IILoc);
2332 
2333   Decl *ActOnEnumConstant(Scope *S, Decl *EnumDecl, Decl *LastEnumConstant,
2334                           SourceLocation IdLoc, IdentifierInfo *Id,
2335                           const ParsedAttributesView &Attrs,
2336                           SourceLocation EqualLoc, Expr *Val);
2337   void ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange,
2338                      Decl *EnumDecl, ArrayRef<Decl *> Elements, Scope *S,
2339                      const ParsedAttributesView &Attr);
2340 
2341   DeclContext *getContainingDC(DeclContext *DC);
2342 
2343   /// Set the current declaration context until it gets popped.
2344   void PushDeclContext(Scope *S, DeclContext *DC);
2345   void PopDeclContext();
2346 
2347   /// EnterDeclaratorContext - Used when we must lookup names in the context
2348   /// of a declarator's nested name specifier.
2349   void EnterDeclaratorContext(Scope *S, DeclContext *DC);
2350   void ExitDeclaratorContext(Scope *S);
2351 
2352   /// Push the parameters of D, which must be a function, into scope.
2353   void ActOnReenterFunctionContext(Scope* S, Decl* D);
2354   void ActOnExitFunctionContext();
2355 
2356   DeclContext *getFunctionLevelDeclContext();
2357 
2358   /// getCurFunctionDecl - If inside of a function body, this returns a pointer
2359   /// to the function decl for the function being parsed.  If we're currently
2360   /// in a 'block', this returns the containing context.
2361   FunctionDecl *getCurFunctionDecl();
2362 
2363   /// getCurMethodDecl - If inside of a method body, this returns a pointer to
2364   /// the method decl for the method being parsed.  If we're currently
2365   /// in a 'block', this returns the containing context.
2366   ObjCMethodDecl *getCurMethodDecl();
2367 
2368   /// getCurFunctionOrMethodDecl - Return the Decl for the current ObjC method
2369   /// or C function we're in, otherwise return null.  If we're currently
2370   /// in a 'block', this returns the containing context.
2371   NamedDecl *getCurFunctionOrMethodDecl();
2372 
2373   /// Add this decl to the scope shadowed decl chains.
2374   void PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext = true);
2375 
2376   /// Make the given externally-produced declaration visible at the
2377   /// top level scope.
2378   ///
2379   /// \param D The externally-produced declaration to push.
2380   ///
2381   /// \param Name The name of the externally-produced declaration.
2382   void pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name);
2383 
2384   /// isDeclInScope - If 'Ctx' is a function/method, isDeclInScope returns true
2385   /// if 'D' is in Scope 'S', otherwise 'S' is ignored and isDeclInScope returns
2386   /// true if 'D' belongs to the given declaration context.
2387   ///
2388   /// \param AllowInlineNamespace If \c true, allow the declaration to be in the
2389   ///        enclosing namespace set of the context, rather than contained
2390   ///        directly within it.
2391   bool isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S = nullptr,
2392                      bool AllowInlineNamespace = false);
2393 
2394   /// Finds the scope corresponding to the given decl context, if it
2395   /// happens to be an enclosing scope.  Otherwise return NULL.
2396   static Scope *getScopeForDeclContext(Scope *S, DeclContext *DC);
2397 
2398   /// Subroutines of ActOnDeclarator().
2399   TypedefDecl *ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
2400                                 TypeSourceInfo *TInfo);
2401   bool isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New);
2402 
2403   /// Describes the kind of merge to perform for availability
2404   /// attributes (including "deprecated", "unavailable", and "availability").
2405   enum AvailabilityMergeKind {
2406     /// Don't merge availability attributes at all.
2407     AMK_None,
2408     /// Merge availability attributes for a redeclaration, which requires
2409     /// an exact match.
2410     AMK_Redeclaration,
2411     /// Merge availability attributes for an override, which requires
2412     /// an exact match or a weakening of constraints.
2413     AMK_Override,
2414     /// Merge availability attributes for an implementation of
2415     /// a protocol requirement.
2416     AMK_ProtocolImplementation,
2417   };
2418 
2419   /// Attribute merging methods. Return true if a new attribute was added.
2420   AvailabilityAttr *mergeAvailabilityAttr(NamedDecl *D, SourceRange Range,
2421                                           IdentifierInfo *Platform,
2422                                           bool Implicit,
2423                                           VersionTuple Introduced,
2424                                           VersionTuple Deprecated,
2425                                           VersionTuple Obsoleted,
2426                                           bool IsUnavailable,
2427                                           StringRef Message,
2428                                           bool IsStrict, StringRef Replacement,
2429                                           AvailabilityMergeKind AMK,
2430                                           unsigned AttrSpellingListIndex);
2431   TypeVisibilityAttr *mergeTypeVisibilityAttr(Decl *D, SourceRange Range,
2432                                        TypeVisibilityAttr::VisibilityType Vis,
2433                                               unsigned AttrSpellingListIndex);
2434   VisibilityAttr *mergeVisibilityAttr(Decl *D, SourceRange Range,
2435                                       VisibilityAttr::VisibilityType Vis,
2436                                       unsigned AttrSpellingListIndex);
2437   UuidAttr *mergeUuidAttr(Decl *D, SourceRange Range,
2438                           unsigned AttrSpellingListIndex, StringRef Uuid);
2439   DLLImportAttr *mergeDLLImportAttr(Decl *D, SourceRange Range,
2440                                     unsigned AttrSpellingListIndex);
2441   DLLExportAttr *mergeDLLExportAttr(Decl *D, SourceRange Range,
2442                                     unsigned AttrSpellingListIndex);
2443   MSInheritanceAttr *
2444   mergeMSInheritanceAttr(Decl *D, SourceRange Range, bool BestCase,
2445                          unsigned AttrSpellingListIndex,
2446                          MSInheritanceAttr::Spelling SemanticSpelling);
2447   FormatAttr *mergeFormatAttr(Decl *D, SourceRange Range,
2448                               IdentifierInfo *Format, int FormatIdx,
2449                               int FirstArg, unsigned AttrSpellingListIndex);
2450   SectionAttr *mergeSectionAttr(Decl *D, SourceRange Range, StringRef Name,
2451                                 unsigned AttrSpellingListIndex);
2452   CodeSegAttr *mergeCodeSegAttr(Decl *D, SourceRange Range, StringRef Name,
2453                                 unsigned AttrSpellingListIndex);
2454   AlwaysInlineAttr *mergeAlwaysInlineAttr(Decl *D, SourceRange Range,
2455                                           IdentifierInfo *Ident,
2456                                           unsigned AttrSpellingListIndex);
2457   MinSizeAttr *mergeMinSizeAttr(Decl *D, SourceRange Range,
2458                                 unsigned AttrSpellingListIndex);
2459   OptimizeNoneAttr *mergeOptimizeNoneAttr(Decl *D, SourceRange Range,
2460                                           unsigned AttrSpellingListIndex);
2461   InternalLinkageAttr *mergeInternalLinkageAttr(Decl *D, SourceRange Range,
2462                                                 IdentifierInfo *Ident,
2463                                                 unsigned AttrSpellingListIndex);
2464   CommonAttr *mergeCommonAttr(Decl *D, SourceRange Range, IdentifierInfo *Ident,
2465                               unsigned AttrSpellingListIndex);
2466 
2467   void mergeDeclAttributes(NamedDecl *New, Decl *Old,
2468                            AvailabilityMergeKind AMK = AMK_Redeclaration);
2469   void MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New,
2470                             LookupResult &OldDecls);
2471   bool MergeFunctionDecl(FunctionDecl *New, NamedDecl *&Old, Scope *S,
2472                          bool MergeTypeWithOld);
2473   bool MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
2474                                     Scope *S, bool MergeTypeWithOld);
2475   void mergeObjCMethodDecls(ObjCMethodDecl *New, ObjCMethodDecl *Old);
2476   void MergeVarDecl(VarDecl *New, LookupResult &Previous);
2477   void MergeVarDeclTypes(VarDecl *New, VarDecl *Old, bool MergeTypeWithOld);
2478   void MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old);
2479   bool checkVarDeclRedefinition(VarDecl *OldDefn, VarDecl *NewDefn);
2480   void notePreviousDefinition(const NamedDecl *Old, SourceLocation New);
2481   bool MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old, Scope *S);
2482 
2483   // AssignmentAction - This is used by all the assignment diagnostic functions
2484   // to represent what is actually causing the operation
2485   enum AssignmentAction {
2486     AA_Assigning,
2487     AA_Passing,
2488     AA_Returning,
2489     AA_Converting,
2490     AA_Initializing,
2491     AA_Sending,
2492     AA_Casting,
2493     AA_Passing_CFAudited
2494   };
2495 
2496   /// C++ Overloading.
2497   enum OverloadKind {
2498     /// This is a legitimate overload: the existing declarations are
2499     /// functions or function templates with different signatures.
2500     Ovl_Overload,
2501 
2502     /// This is not an overload because the signature exactly matches
2503     /// an existing declaration.
2504     Ovl_Match,
2505 
2506     /// This is not an overload because the lookup results contain a
2507     /// non-function.
2508     Ovl_NonFunction
2509   };
2510   OverloadKind CheckOverload(Scope *S,
2511                              FunctionDecl *New,
2512                              const LookupResult &OldDecls,
2513                              NamedDecl *&OldDecl,
2514                              bool IsForUsingDecl);
2515   bool IsOverload(FunctionDecl *New, FunctionDecl *Old, bool IsForUsingDecl,
2516                   bool ConsiderCudaAttrs = true);
2517 
2518   /// Checks availability of the function depending on the current
2519   /// function context.Inside an unavailable function,unavailability is ignored.
2520   ///
2521   /// \returns true if \p FD is unavailable and current context is inside
2522   /// an available function, false otherwise.
2523   bool isFunctionConsideredUnavailable(FunctionDecl *FD);
2524 
2525   ImplicitConversionSequence
2526   TryImplicitConversion(Expr *From, QualType ToType,
2527                         bool SuppressUserConversions,
2528                         bool AllowExplicit,
2529                         bool InOverloadResolution,
2530                         bool CStyle,
2531                         bool AllowObjCWritebackConversion);
2532 
2533   bool IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType);
2534   bool IsFloatingPointPromotion(QualType FromType, QualType ToType);
2535   bool IsComplexPromotion(QualType FromType, QualType ToType);
2536   bool IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
2537                            bool InOverloadResolution,
2538                            QualType& ConvertedType, bool &IncompatibleObjC);
2539   bool isObjCPointerConversion(QualType FromType, QualType ToType,
2540                                QualType& ConvertedType, bool &IncompatibleObjC);
2541   bool isObjCWritebackConversion(QualType FromType, QualType ToType,
2542                                  QualType &ConvertedType);
2543   bool IsBlockPointerConversion(QualType FromType, QualType ToType,
2544                                 QualType& ConvertedType);
2545   bool FunctionParamTypesAreEqual(const FunctionProtoType *OldType,
2546                                   const FunctionProtoType *NewType,
2547                                   unsigned *ArgPos = nullptr);
2548   void HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
2549                                   QualType FromType, QualType ToType);
2550 
2551   void maybeExtendBlockObject(ExprResult &E);
2552   CastKind PrepareCastToObjCObjectPointer(ExprResult &E);
2553   bool CheckPointerConversion(Expr *From, QualType ToType,
2554                               CastKind &Kind,
2555                               CXXCastPath& BasePath,
2556                               bool IgnoreBaseAccess,
2557                               bool Diagnose = true);
2558   bool IsMemberPointerConversion(Expr *From, QualType FromType, QualType ToType,
2559                                  bool InOverloadResolution,
2560                                  QualType &ConvertedType);
2561   bool CheckMemberPointerConversion(Expr *From, QualType ToType,
2562                                     CastKind &Kind,
2563                                     CXXCastPath &BasePath,
2564                                     bool IgnoreBaseAccess);
2565   bool IsQualificationConversion(QualType FromType, QualType ToType,
2566                                  bool CStyle, bool &ObjCLifetimeConversion);
2567   bool IsFunctionConversion(QualType FromType, QualType ToType,
2568                             QualType &ResultTy);
2569   bool DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType);
2570   bool isSameOrCompatibleFunctionType(CanQualType Param, CanQualType Arg);
2571 
2572   ExprResult PerformMoveOrCopyInitialization(const InitializedEntity &Entity,
2573                                              const VarDecl *NRVOCandidate,
2574                                              QualType ResultType,
2575                                              Expr *Value,
2576                                              bool AllowNRVO = true);
2577 
2578   bool CanPerformCopyInitialization(const InitializedEntity &Entity,
2579                                     ExprResult Init);
2580   ExprResult PerformCopyInitialization(const InitializedEntity &Entity,
2581                                        SourceLocation EqualLoc,
2582                                        ExprResult Init,
2583                                        bool TopLevelOfInitList = false,
2584                                        bool AllowExplicit = false);
2585   ExprResult PerformObjectArgumentInitialization(Expr *From,
2586                                                  NestedNameSpecifier *Qualifier,
2587                                                  NamedDecl *FoundDecl,
2588                                                  CXXMethodDecl *Method);
2589 
2590   /// Check that the lifetime of the initializer (and its subobjects) is
2591   /// sufficient for initializing the entity, and perform lifetime extension
2592   /// (when permitted) if not.
2593   void checkInitializerLifetime(const InitializedEntity &Entity, Expr *Init);
2594 
2595   ExprResult PerformContextuallyConvertToBool(Expr *From);
2596   ExprResult PerformContextuallyConvertToObjCPointer(Expr *From);
2597 
2598   /// Contexts in which a converted constant expression is required.
2599   enum CCEKind {
2600     CCEK_CaseValue,   ///< Expression in a case label.
2601     CCEK_Enumerator,  ///< Enumerator value with fixed underlying type.
2602     CCEK_TemplateArg, ///< Value of a non-type template parameter.
2603     CCEK_NewExpr,     ///< Constant expression in a noptr-new-declarator.
2604     CCEK_ConstexprIf  ///< Condition in a constexpr if statement.
2605   };
2606   ExprResult CheckConvertedConstantExpression(Expr *From, QualType T,
2607                                               llvm::APSInt &Value, CCEKind CCE);
2608   ExprResult CheckConvertedConstantExpression(Expr *From, QualType T,
2609                                               APValue &Value, CCEKind CCE);
2610 
2611   /// Abstract base class used to perform a contextual implicit
2612   /// conversion from an expression to any type passing a filter.
2613   class ContextualImplicitConverter {
2614   public:
2615     bool Suppress;
2616     bool SuppressConversion;
2617 
2618     ContextualImplicitConverter(bool Suppress = false,
2619                                 bool SuppressConversion = false)
Suppress(Suppress)2620         : Suppress(Suppress), SuppressConversion(SuppressConversion) {}
2621 
2622     /// Determine whether the specified type is a valid destination type
2623     /// for this conversion.
2624     virtual bool match(QualType T) = 0;
2625 
2626     /// Emits a diagnostic complaining that the expression does not have
2627     /// integral or enumeration type.
2628     virtual SemaDiagnosticBuilder
2629     diagnoseNoMatch(Sema &S, SourceLocation Loc, QualType T) = 0;
2630 
2631     /// Emits a diagnostic when the expression has incomplete class type.
2632     virtual SemaDiagnosticBuilder
2633     diagnoseIncomplete(Sema &S, SourceLocation Loc, QualType T) = 0;
2634 
2635     /// Emits a diagnostic when the only matching conversion function
2636     /// is explicit.
2637     virtual SemaDiagnosticBuilder diagnoseExplicitConv(
2638         Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) = 0;
2639 
2640     /// Emits a note for the explicit conversion function.
2641     virtual SemaDiagnosticBuilder
2642     noteExplicitConv(Sema &S, CXXConversionDecl *Conv, QualType ConvTy) = 0;
2643 
2644     /// Emits a diagnostic when there are multiple possible conversion
2645     /// functions.
2646     virtual SemaDiagnosticBuilder
2647     diagnoseAmbiguous(Sema &S, SourceLocation Loc, QualType T) = 0;
2648 
2649     /// Emits a note for one of the candidate conversions.
2650     virtual SemaDiagnosticBuilder
2651     noteAmbiguous(Sema &S, CXXConversionDecl *Conv, QualType ConvTy) = 0;
2652 
2653     /// Emits a diagnostic when we picked a conversion function
2654     /// (for cases when we are not allowed to pick a conversion function).
2655     virtual SemaDiagnosticBuilder diagnoseConversion(
2656         Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) = 0;
2657 
~ContextualImplicitConverter()2658     virtual ~ContextualImplicitConverter() {}
2659   };
2660 
2661   class ICEConvertDiagnoser : public ContextualImplicitConverter {
2662     bool AllowScopedEnumerations;
2663 
2664   public:
ICEConvertDiagnoser(bool AllowScopedEnumerations,bool Suppress,bool SuppressConversion)2665     ICEConvertDiagnoser(bool AllowScopedEnumerations,
2666                         bool Suppress, bool SuppressConversion)
2667         : ContextualImplicitConverter(Suppress, SuppressConversion),
2668           AllowScopedEnumerations(AllowScopedEnumerations) {}
2669 
2670     /// Match an integral or (possibly scoped) enumeration type.
2671     bool match(QualType T) override;
2672 
2673     SemaDiagnosticBuilder
diagnoseNoMatch(Sema & S,SourceLocation Loc,QualType T)2674     diagnoseNoMatch(Sema &S, SourceLocation Loc, QualType T) override {
2675       return diagnoseNotInt(S, Loc, T);
2676     }
2677 
2678     /// Emits a diagnostic complaining that the expression does not have
2679     /// integral or enumeration type.
2680     virtual SemaDiagnosticBuilder
2681     diagnoseNotInt(Sema &S, SourceLocation Loc, QualType T) = 0;
2682   };
2683 
2684   /// Perform a contextual implicit conversion.
2685   ExprResult PerformContextualImplicitConversion(
2686       SourceLocation Loc, Expr *FromE, ContextualImplicitConverter &Converter);
2687 
2688 
2689   enum ObjCSubscriptKind {
2690     OS_Array,
2691     OS_Dictionary,
2692     OS_Error
2693   };
2694   ObjCSubscriptKind CheckSubscriptingKind(Expr *FromE);
2695 
2696   // Note that LK_String is intentionally after the other literals, as
2697   // this is used for diagnostics logic.
2698   enum ObjCLiteralKind {
2699     LK_Array,
2700     LK_Dictionary,
2701     LK_Numeric,
2702     LK_Boxed,
2703     LK_String,
2704     LK_Block,
2705     LK_None
2706   };
2707   ObjCLiteralKind CheckLiteralKind(Expr *FromE);
2708 
2709   ExprResult PerformObjectMemberConversion(Expr *From,
2710                                            NestedNameSpecifier *Qualifier,
2711                                            NamedDecl *FoundDecl,
2712                                            NamedDecl *Member);
2713 
2714   // Members have to be NamespaceDecl* or TranslationUnitDecl*.
2715   // TODO: make this is a typesafe union.
2716   typedef llvm::SmallSetVector<DeclContext   *, 16> AssociatedNamespaceSet;
2717   typedef llvm::SmallSetVector<CXXRecordDecl *, 16> AssociatedClassSet;
2718 
2719   void AddOverloadCandidate(FunctionDecl *Function,
2720                             DeclAccessPair FoundDecl,
2721                             ArrayRef<Expr *> Args,
2722                             OverloadCandidateSet &CandidateSet,
2723                             bool SuppressUserConversions = false,
2724                             bool PartialOverloading = false,
2725                             bool AllowExplicit = false,
2726                             ConversionSequenceList EarlyConversions = None);
2727   void AddFunctionCandidates(const UnresolvedSetImpl &Functions,
2728                       ArrayRef<Expr *> Args,
2729                       OverloadCandidateSet &CandidateSet,
2730                       TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr,
2731                       bool SuppressUserConversions = false,
2732                       bool PartialOverloading = false,
2733                       bool FirstArgumentIsBase = false);
2734   void AddMethodCandidate(DeclAccessPair FoundDecl,
2735                           QualType ObjectType,
2736                           Expr::Classification ObjectClassification,
2737                           ArrayRef<Expr *> Args,
2738                           OverloadCandidateSet& CandidateSet,
2739                           bool SuppressUserConversion = false);
2740   void AddMethodCandidate(CXXMethodDecl *Method,
2741                           DeclAccessPair FoundDecl,
2742                           CXXRecordDecl *ActingContext, QualType ObjectType,
2743                           Expr::Classification ObjectClassification,
2744                           ArrayRef<Expr *> Args,
2745                           OverloadCandidateSet& CandidateSet,
2746                           bool SuppressUserConversions = false,
2747                           bool PartialOverloading = false,
2748                           ConversionSequenceList EarlyConversions = None);
2749   void AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
2750                                   DeclAccessPair FoundDecl,
2751                                   CXXRecordDecl *ActingContext,
2752                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
2753                                   QualType ObjectType,
2754                                   Expr::Classification ObjectClassification,
2755                                   ArrayRef<Expr *> Args,
2756                                   OverloadCandidateSet& CandidateSet,
2757                                   bool SuppressUserConversions = false,
2758                                   bool PartialOverloading = false);
2759   void AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
2760                                     DeclAccessPair FoundDecl,
2761                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
2762                                     ArrayRef<Expr *> Args,
2763                                     OverloadCandidateSet& CandidateSet,
2764                                     bool SuppressUserConversions = false,
2765                                     bool PartialOverloading = false);
2766   bool CheckNonDependentConversions(FunctionTemplateDecl *FunctionTemplate,
2767                                     ArrayRef<QualType> ParamTypes,
2768                                     ArrayRef<Expr *> Args,
2769                                     OverloadCandidateSet &CandidateSet,
2770                                     ConversionSequenceList &Conversions,
2771                                     bool SuppressUserConversions,
2772                                     CXXRecordDecl *ActingContext = nullptr,
2773                                     QualType ObjectType = QualType(),
2774                                     Expr::Classification
2775                                         ObjectClassification = {});
2776   void AddConversionCandidate(CXXConversionDecl *Conversion,
2777                               DeclAccessPair FoundDecl,
2778                               CXXRecordDecl *ActingContext,
2779                               Expr *From, QualType ToType,
2780                               OverloadCandidateSet& CandidateSet,
2781                               bool AllowObjCConversionOnExplicit,
2782                               bool AllowResultConversion = true);
2783   void AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
2784                                       DeclAccessPair FoundDecl,
2785                                       CXXRecordDecl *ActingContext,
2786                                       Expr *From, QualType ToType,
2787                                       OverloadCandidateSet &CandidateSet,
2788                                       bool AllowObjCConversionOnExplicit,
2789                                       bool AllowResultConversion = true);
2790   void AddSurrogateCandidate(CXXConversionDecl *Conversion,
2791                              DeclAccessPair FoundDecl,
2792                              CXXRecordDecl *ActingContext,
2793                              const FunctionProtoType *Proto,
2794                              Expr *Object, ArrayRef<Expr *> Args,
2795                              OverloadCandidateSet& CandidateSet);
2796   void AddMemberOperatorCandidates(OverloadedOperatorKind Op,
2797                                    SourceLocation OpLoc, ArrayRef<Expr *> Args,
2798                                    OverloadCandidateSet& CandidateSet,
2799                                    SourceRange OpRange = SourceRange());
2800   void AddBuiltinCandidate(QualType *ParamTys, ArrayRef<Expr *> Args,
2801                            OverloadCandidateSet& CandidateSet,
2802                            bool IsAssignmentOperator = false,
2803                            unsigned NumContextualBoolArguments = 0);
2804   void AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
2805                                     SourceLocation OpLoc, ArrayRef<Expr *> Args,
2806                                     OverloadCandidateSet& CandidateSet);
2807   void AddArgumentDependentLookupCandidates(DeclarationName Name,
2808                                             SourceLocation Loc,
2809                                             ArrayRef<Expr *> Args,
2810                                 TemplateArgumentListInfo *ExplicitTemplateArgs,
2811                                             OverloadCandidateSet& CandidateSet,
2812                                             bool PartialOverloading = false);
2813 
2814   // Emit as a 'note' the specific overload candidate
2815   void NoteOverloadCandidate(NamedDecl *Found, FunctionDecl *Fn,
2816                              QualType DestType = QualType(),
2817                              bool TakingAddress = false);
2818 
2819   // Emit as a series of 'note's all template and non-templates identified by
2820   // the expression Expr
2821   void NoteAllOverloadCandidates(Expr *E, QualType DestType = QualType(),
2822                                  bool TakingAddress = false);
2823 
2824   /// Check the enable_if expressions on the given function. Returns the first
2825   /// failing attribute, or NULL if they were all successful.
2826   EnableIfAttr *CheckEnableIf(FunctionDecl *Function, ArrayRef<Expr *> Args,
2827                               bool MissingImplicitThis = false);
2828 
2829   /// Find the failed Boolean condition within a given Boolean
2830   /// constant expression, and describe it with a string.
2831   ///
2832   /// \param AllowTopLevelCond Whether to allow the result to be the
2833   /// complete top-level condition.
2834   std::pair<Expr *, std::string>
2835   findFailedBooleanCondition(Expr *Cond, bool AllowTopLevelCond);
2836 
2837   /// Emit diagnostics for the diagnose_if attributes on Function, ignoring any
2838   /// non-ArgDependent DiagnoseIfAttrs.
2839   ///
2840   /// Argument-dependent diagnose_if attributes should be checked each time a
2841   /// function is used as a direct callee of a function call.
2842   ///
2843   /// Returns true if any errors were emitted.
2844   bool diagnoseArgDependentDiagnoseIfAttrs(const FunctionDecl *Function,
2845                                            const Expr *ThisArg,
2846                                            ArrayRef<const Expr *> Args,
2847                                            SourceLocation Loc);
2848 
2849   /// Emit diagnostics for the diagnose_if attributes on Function, ignoring any
2850   /// ArgDependent DiagnoseIfAttrs.
2851   ///
2852   /// Argument-independent diagnose_if attributes should be checked on every use
2853   /// of a function.
2854   ///
2855   /// Returns true if any errors were emitted.
2856   bool diagnoseArgIndependentDiagnoseIfAttrs(const NamedDecl *ND,
2857                                              SourceLocation Loc);
2858 
2859   /// Returns whether the given function's address can be taken or not,
2860   /// optionally emitting a diagnostic if the address can't be taken.
2861   ///
2862   /// Returns false if taking the address of the function is illegal.
2863   bool checkAddressOfFunctionIsAvailable(const FunctionDecl *Function,
2864                                          bool Complain = false,
2865                                          SourceLocation Loc = SourceLocation());
2866 
2867   // [PossiblyAFunctionType]  -->   [Return]
2868   // NonFunctionType --> NonFunctionType
2869   // R (A) --> R(A)
2870   // R (*)(A) --> R (A)
2871   // R (&)(A) --> R (A)
2872   // R (S::*)(A) --> R (A)
2873   QualType ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType);
2874 
2875   FunctionDecl *
2876   ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
2877                                      QualType TargetType,
2878                                      bool Complain,
2879                                      DeclAccessPair &Found,
2880                                      bool *pHadMultipleCandidates = nullptr);
2881 
2882   FunctionDecl *
2883   resolveAddressOfOnlyViableOverloadCandidate(Expr *E,
2884                                               DeclAccessPair &FoundResult);
2885 
2886   bool resolveAndFixAddressOfOnlyViableOverloadCandidate(
2887       ExprResult &SrcExpr, bool DoFunctionPointerConversion = false);
2888 
2889   FunctionDecl *
2890   ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
2891                                               bool Complain = false,
2892                                               DeclAccessPair *Found = nullptr);
2893 
2894   bool ResolveAndFixSingleFunctionTemplateSpecialization(
2895                       ExprResult &SrcExpr,
2896                       bool DoFunctionPointerConverion = false,
2897                       bool Complain = false,
2898                       SourceRange OpRangeForComplaining = SourceRange(),
2899                       QualType DestTypeForComplaining = QualType(),
2900                       unsigned DiagIDForComplaining = 0);
2901 
2902 
2903   Expr *FixOverloadedFunctionReference(Expr *E,
2904                                        DeclAccessPair FoundDecl,
2905                                        FunctionDecl *Fn);
2906   ExprResult FixOverloadedFunctionReference(ExprResult,
2907                                             DeclAccessPair FoundDecl,
2908                                             FunctionDecl *Fn);
2909 
2910   void AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
2911                                    ArrayRef<Expr *> Args,
2912                                    OverloadCandidateSet &CandidateSet,
2913                                    bool PartialOverloading = false);
2914 
2915   // An enum used to represent the different possible results of building a
2916   // range-based for loop.
2917   enum ForRangeStatus {
2918     FRS_Success,
2919     FRS_NoViableFunction,
2920     FRS_DiagnosticIssued
2921   };
2922 
2923   ForRangeStatus BuildForRangeBeginEndCall(SourceLocation Loc,
2924                                            SourceLocation RangeLoc,
2925                                            const DeclarationNameInfo &NameInfo,
2926                                            LookupResult &MemberLookup,
2927                                            OverloadCandidateSet *CandidateSet,
2928                                            Expr *Range, ExprResult *CallExpr);
2929 
2930   ExprResult BuildOverloadedCallExpr(Scope *S, Expr *Fn,
2931                                      UnresolvedLookupExpr *ULE,
2932                                      SourceLocation LParenLoc,
2933                                      MultiExprArg Args,
2934                                      SourceLocation RParenLoc,
2935                                      Expr *ExecConfig,
2936                                      bool AllowTypoCorrection=true,
2937                                      bool CalleesAddressIsTaken=false);
2938 
2939   bool buildOverloadedCallSet(Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE,
2940                               MultiExprArg Args, SourceLocation RParenLoc,
2941                               OverloadCandidateSet *CandidateSet,
2942                               ExprResult *Result);
2943 
2944   ExprResult CreateOverloadedUnaryOp(SourceLocation OpLoc,
2945                                      UnaryOperatorKind Opc,
2946                                      const UnresolvedSetImpl &Fns,
2947                                      Expr *input, bool RequiresADL = true);
2948 
2949   ExprResult CreateOverloadedBinOp(SourceLocation OpLoc,
2950                                    BinaryOperatorKind Opc,
2951                                    const UnresolvedSetImpl &Fns,
2952                                    Expr *LHS, Expr *RHS,
2953                                    bool RequiresADL = true);
2954 
2955   ExprResult CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
2956                                                 SourceLocation RLoc,
2957                                                 Expr *Base,Expr *Idx);
2958 
2959   ExprResult
2960   BuildCallToMemberFunction(Scope *S, Expr *MemExpr,
2961                             SourceLocation LParenLoc,
2962                             MultiExprArg Args,
2963                             SourceLocation RParenLoc);
2964   ExprResult
2965   BuildCallToObjectOfClassType(Scope *S, Expr *Object, SourceLocation LParenLoc,
2966                                MultiExprArg Args,
2967                                SourceLocation RParenLoc);
2968 
2969   ExprResult BuildOverloadedArrowExpr(Scope *S, Expr *Base,
2970                                       SourceLocation OpLoc,
2971                                       bool *NoArrowOperatorFound = nullptr);
2972 
2973   /// CheckCallReturnType - Checks that a call expression's return type is
2974   /// complete. Returns true on failure. The location passed in is the location
2975   /// that best represents the call.
2976   bool CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
2977                            CallExpr *CE, FunctionDecl *FD);
2978 
2979   /// Helpers for dealing with blocks and functions.
2980   bool CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters,
2981                                 bool CheckParameterNames);
2982   void CheckCXXDefaultArguments(FunctionDecl *FD);
2983   void CheckExtraCXXDefaultArguments(Declarator &D);
2984   Scope *getNonFieldDeclScope(Scope *S);
2985 
2986   /// \name Name lookup
2987   ///
2988   /// These routines provide name lookup that is used during semantic
2989   /// analysis to resolve the various kinds of names (identifiers,
2990   /// overloaded operator names, constructor names, etc.) into zero or
2991   /// more declarations within a particular scope. The major entry
2992   /// points are LookupName, which performs unqualified name lookup,
2993   /// and LookupQualifiedName, which performs qualified name lookup.
2994   ///
2995   /// All name lookup is performed based on some specific criteria,
2996   /// which specify what names will be visible to name lookup and how
2997   /// far name lookup should work. These criteria are important both
2998   /// for capturing language semantics (certain lookups will ignore
2999   /// certain names, for example) and for performance, since name
3000   /// lookup is often a bottleneck in the compilation of C++. Name
3001   /// lookup criteria is specified via the LookupCriteria enumeration.
3002   ///
3003   /// The results of name lookup can vary based on the kind of name
3004   /// lookup performed, the current language, and the translation
3005   /// unit. In C, for example, name lookup will either return nothing
3006   /// (no entity found) or a single declaration. In C++, name lookup
3007   /// can additionally refer to a set of overloaded functions or
3008   /// result in an ambiguity. All of the possible results of name
3009   /// lookup are captured by the LookupResult class, which provides
3010   /// the ability to distinguish among them.
3011   //@{
3012 
3013   /// Describes the kind of name lookup to perform.
3014   enum LookupNameKind {
3015     /// Ordinary name lookup, which finds ordinary names (functions,
3016     /// variables, typedefs, etc.) in C and most kinds of names
3017     /// (functions, variables, members, types, etc.) in C++.
3018     LookupOrdinaryName = 0,
3019     /// Tag name lookup, which finds the names of enums, classes,
3020     /// structs, and unions.
3021     LookupTagName,
3022     /// Label name lookup.
3023     LookupLabel,
3024     /// Member name lookup, which finds the names of
3025     /// class/struct/union members.
3026     LookupMemberName,
3027     /// Look up of an operator name (e.g., operator+) for use with
3028     /// operator overloading. This lookup is similar to ordinary name
3029     /// lookup, but will ignore any declarations that are class members.
3030     LookupOperatorName,
3031     /// Look up of a name that precedes the '::' scope resolution
3032     /// operator in C++. This lookup completely ignores operator, object,
3033     /// function, and enumerator names (C++ [basic.lookup.qual]p1).
3034     LookupNestedNameSpecifierName,
3035     /// Look up a namespace name within a C++ using directive or
3036     /// namespace alias definition, ignoring non-namespace names (C++
3037     /// [basic.lookup.udir]p1).
3038     LookupNamespaceName,
3039     /// Look up all declarations in a scope with the given name,
3040     /// including resolved using declarations.  This is appropriate
3041     /// for checking redeclarations for a using declaration.
3042     LookupUsingDeclName,
3043     /// Look up an ordinary name that is going to be redeclared as a
3044     /// name with linkage. This lookup ignores any declarations that
3045     /// are outside of the current scope unless they have linkage. See
3046     /// C99 6.2.2p4-5 and C++ [basic.link]p6.
3047     LookupRedeclarationWithLinkage,
3048     /// Look up a friend of a local class. This lookup does not look
3049     /// outside the innermost non-class scope. See C++11 [class.friend]p11.
3050     LookupLocalFriendName,
3051     /// Look up the name of an Objective-C protocol.
3052     LookupObjCProtocolName,
3053     /// Look up implicit 'self' parameter of an objective-c method.
3054     LookupObjCImplicitSelfParam,
3055     /// Look up the name of an OpenMP user-defined reduction operation.
3056     LookupOMPReductionName,
3057     /// Look up any declaration with any name.
3058     LookupAnyName
3059   };
3060 
3061   /// Specifies whether (or how) name lookup is being performed for a
3062   /// redeclaration (vs. a reference).
3063   enum RedeclarationKind {
3064     /// The lookup is a reference to this name that is not for the
3065     /// purpose of redeclaring the name.
3066     NotForRedeclaration = 0,
3067     /// The lookup results will be used for redeclaration of a name,
3068     /// if an entity by that name already exists and is visible.
3069     ForVisibleRedeclaration,
3070     /// The lookup results will be used for redeclaration of a name
3071     /// with external linkage; non-visible lookup results with external linkage
3072     /// may also be found.
3073     ForExternalRedeclaration
3074   };
3075 
forRedeclarationInCurContext()3076   RedeclarationKind forRedeclarationInCurContext() {
3077     // A declaration with an owning module for linkage can never link against
3078     // anything that is not visible. We don't need to check linkage here; if
3079     // the context has internal linkage, redeclaration lookup won't find things
3080     // from other TUs, and we can't safely compute linkage yet in general.
3081     if (cast<Decl>(CurContext)
3082             ->getOwningModuleForLinkage(/*IgnoreLinkage*/true))
3083       return ForVisibleRedeclaration;
3084     return ForExternalRedeclaration;
3085   }
3086 
3087   /// The possible outcomes of name lookup for a literal operator.
3088   enum LiteralOperatorLookupResult {
3089     /// The lookup resulted in an error.
3090     LOLR_Error,
3091     /// The lookup found no match but no diagnostic was issued.
3092     LOLR_ErrorNoDiagnostic,
3093     /// The lookup found a single 'cooked' literal operator, which
3094     /// expects a normal literal to be built and passed to it.
3095     LOLR_Cooked,
3096     /// The lookup found a single 'raw' literal operator, which expects
3097     /// a string literal containing the spelling of the literal token.
3098     LOLR_Raw,
3099     /// The lookup found an overload set of literal operator templates,
3100     /// which expect the characters of the spelling of the literal token to be
3101     /// passed as a non-type template argument pack.
3102     LOLR_Template,
3103     /// The lookup found an overload set of literal operator templates,
3104     /// which expect the character type and characters of the spelling of the
3105     /// string literal token to be passed as template arguments.
3106     LOLR_StringTemplate
3107   };
3108 
3109   SpecialMemberOverloadResult LookupSpecialMember(CXXRecordDecl *D,
3110                                                   CXXSpecialMember SM,
3111                                                   bool ConstArg,
3112                                                   bool VolatileArg,
3113                                                   bool RValueThis,
3114                                                   bool ConstThis,
3115                                                   bool VolatileThis);
3116 
3117   typedef std::function<void(const TypoCorrection &)> TypoDiagnosticGenerator;
3118   typedef std::function<ExprResult(Sema &, TypoExpr *, TypoCorrection)>
3119       TypoRecoveryCallback;
3120 
3121 private:
3122   bool CppLookupName(LookupResult &R, Scope *S);
3123 
3124   struct TypoExprState {
3125     std::unique_ptr<TypoCorrectionConsumer> Consumer;
3126     TypoDiagnosticGenerator DiagHandler;
3127     TypoRecoveryCallback RecoveryHandler;
3128     TypoExprState();
3129     TypoExprState(TypoExprState &&other) noexcept;
3130     TypoExprState &operator=(TypoExprState &&other) noexcept;
3131   };
3132 
3133   /// The set of unhandled TypoExprs and their associated state.
3134   llvm::MapVector<TypoExpr *, TypoExprState> DelayedTypos;
3135 
3136   /// Creates a new TypoExpr AST node.
3137   TypoExpr *createDelayedTypo(std::unique_ptr<TypoCorrectionConsumer> TCC,
3138                               TypoDiagnosticGenerator TDG,
3139                               TypoRecoveryCallback TRC);
3140 
3141   // The set of known/encountered (unique, canonicalized) NamespaceDecls.
3142   //
3143   // The boolean value will be true to indicate that the namespace was loaded
3144   // from an AST/PCH file, or false otherwise.
3145   llvm::MapVector<NamespaceDecl*, bool> KnownNamespaces;
3146 
3147   /// Whether we have already loaded known namespaces from an extenal
3148   /// source.
3149   bool LoadedExternalKnownNamespaces;
3150 
3151   /// Helper for CorrectTypo and CorrectTypoDelayed used to create and
3152   /// populate a new TypoCorrectionConsumer. Returns nullptr if typo correction
3153   /// should be skipped entirely.
3154   std::unique_ptr<TypoCorrectionConsumer>
3155   makeTypoCorrectionConsumer(const DeclarationNameInfo &Typo,
3156                              Sema::LookupNameKind LookupKind, Scope *S,
3157                              CXXScopeSpec *SS,
3158                              std::unique_ptr<CorrectionCandidateCallback> CCC,
3159                              DeclContext *MemberContext, bool EnteringContext,
3160                              const ObjCObjectPointerType *OPT,
3161                              bool ErrorRecovery);
3162 
3163 public:
3164   const TypoExprState &getTypoExprState(TypoExpr *TE) const;
3165 
3166   /// Clears the state of the given TypoExpr.
3167   void clearDelayedTypo(TypoExpr *TE);
3168 
3169   /// Look up a name, looking for a single declaration.  Return
3170   /// null if the results were absent, ambiguous, or overloaded.
3171   ///
3172   /// It is preferable to use the elaborated form and explicitly handle
3173   /// ambiguity and overloaded.
3174   NamedDecl *LookupSingleName(Scope *S, DeclarationName Name,
3175                               SourceLocation Loc,
3176                               LookupNameKind NameKind,
3177                               RedeclarationKind Redecl
3178                                 = NotForRedeclaration);
3179   bool LookupName(LookupResult &R, Scope *S,
3180                   bool AllowBuiltinCreation = false);
3181   bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
3182                            bool InUnqualifiedLookup = false);
3183   bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
3184                            CXXScopeSpec &SS);
3185   bool LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS,
3186                         bool AllowBuiltinCreation = false,
3187                         bool EnteringContext = false);
3188   ObjCProtocolDecl *LookupProtocol(IdentifierInfo *II, SourceLocation IdLoc,
3189                                    RedeclarationKind Redecl
3190                                      = NotForRedeclaration);
3191   bool LookupInSuper(LookupResult &R, CXXRecordDecl *Class);
3192 
3193   void LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S,
3194                                     QualType T1, QualType T2,
3195                                     UnresolvedSetImpl &Functions);
3196 
3197   LabelDecl *LookupOrCreateLabel(IdentifierInfo *II, SourceLocation IdentLoc,
3198                                  SourceLocation GnuLabelLoc = SourceLocation());
3199 
3200   DeclContextLookupResult LookupConstructors(CXXRecordDecl *Class);
3201   CXXConstructorDecl *LookupDefaultConstructor(CXXRecordDecl *Class);
3202   CXXConstructorDecl *LookupCopyingConstructor(CXXRecordDecl *Class,
3203                                                unsigned Quals);
3204   CXXMethodDecl *LookupCopyingAssignment(CXXRecordDecl *Class, unsigned Quals,
3205                                          bool RValueThis, unsigned ThisQuals);
3206   CXXConstructorDecl *LookupMovingConstructor(CXXRecordDecl *Class,
3207                                               unsigned Quals);
3208   CXXMethodDecl *LookupMovingAssignment(CXXRecordDecl *Class, unsigned Quals,
3209                                         bool RValueThis, unsigned ThisQuals);
3210   CXXDestructorDecl *LookupDestructor(CXXRecordDecl *Class);
3211 
3212   bool checkLiteralOperatorId(const CXXScopeSpec &SS, const UnqualifiedId &Id);
3213   LiteralOperatorLookupResult LookupLiteralOperator(Scope *S, LookupResult &R,
3214                                                     ArrayRef<QualType> ArgTys,
3215                                                     bool AllowRaw,
3216                                                     bool AllowTemplate,
3217                                                     bool AllowStringTemplate,
3218                                                     bool DiagnoseMissing);
3219   bool isKnownName(StringRef name);
3220 
3221   void ArgumentDependentLookup(DeclarationName Name, SourceLocation Loc,
3222                                ArrayRef<Expr *> Args, ADLResult &Functions);
3223 
3224   void LookupVisibleDecls(Scope *S, LookupNameKind Kind,
3225                           VisibleDeclConsumer &Consumer,
3226                           bool IncludeGlobalScope = true,
3227                           bool LoadExternal = true);
3228   void LookupVisibleDecls(DeclContext *Ctx, LookupNameKind Kind,
3229                           VisibleDeclConsumer &Consumer,
3230                           bool IncludeGlobalScope = true,
3231                           bool IncludeDependentBases = false,
3232                           bool LoadExternal = true);
3233 
3234   enum CorrectTypoKind {
3235     CTK_NonError,     // CorrectTypo used in a non error recovery situation.
3236     CTK_ErrorRecovery // CorrectTypo used in normal error recovery.
3237   };
3238 
3239   TypoCorrection CorrectTypo(const DeclarationNameInfo &Typo,
3240                              Sema::LookupNameKind LookupKind,
3241                              Scope *S, CXXScopeSpec *SS,
3242                              std::unique_ptr<CorrectionCandidateCallback> CCC,
3243                              CorrectTypoKind Mode,
3244                              DeclContext *MemberContext = nullptr,
3245                              bool EnteringContext = false,
3246                              const ObjCObjectPointerType *OPT = nullptr,
3247                              bool RecordFailure = true);
3248 
3249   TypoExpr *CorrectTypoDelayed(const DeclarationNameInfo &Typo,
3250                                Sema::LookupNameKind LookupKind, Scope *S,
3251                                CXXScopeSpec *SS,
3252                                std::unique_ptr<CorrectionCandidateCallback> CCC,
3253                                TypoDiagnosticGenerator TDG,
3254                                TypoRecoveryCallback TRC, CorrectTypoKind Mode,
3255                                DeclContext *MemberContext = nullptr,
3256                                bool EnteringContext = false,
3257                                const ObjCObjectPointerType *OPT = nullptr);
3258 
3259   /// Process any TypoExprs in the given Expr and its children,
3260   /// generating diagnostics as appropriate and returning a new Expr if there
3261   /// were typos that were all successfully corrected and ExprError if one or
3262   /// more typos could not be corrected.
3263   ///
3264   /// \param E The Expr to check for TypoExprs.
3265   ///
3266   /// \param InitDecl A VarDecl to avoid because the Expr being corrected is its
3267   /// initializer.
3268   ///
3269   /// \param Filter A function applied to a newly rebuilt Expr to determine if
3270   /// it is an acceptable/usable result from a single combination of typo
3271   /// corrections. As long as the filter returns ExprError, different
3272   /// combinations of corrections will be tried until all are exhausted.
3273   ExprResult
3274   CorrectDelayedTyposInExpr(Expr *E, VarDecl *InitDecl = nullptr,
3275                             llvm::function_ref<ExprResult(Expr *)> Filter =
3276                                 [](Expr *E) -> ExprResult { return E; });
3277 
3278   ExprResult
CorrectDelayedTyposInExpr(Expr * E,llvm::function_ref<ExprResult (Expr *)> Filter)3279   CorrectDelayedTyposInExpr(Expr *E,
3280                             llvm::function_ref<ExprResult(Expr *)> Filter) {
3281     return CorrectDelayedTyposInExpr(E, nullptr, Filter);
3282   }
3283 
3284   ExprResult
3285   CorrectDelayedTyposInExpr(ExprResult ER, VarDecl *InitDecl = nullptr,
3286                             llvm::function_ref<ExprResult(Expr *)> Filter =
3287                                 [](Expr *E) -> ExprResult { return E; }) {
3288     return ER.isInvalid() ? ER : CorrectDelayedTyposInExpr(ER.get(), Filter);
3289   }
3290 
3291   ExprResult
CorrectDelayedTyposInExpr(ExprResult ER,llvm::function_ref<ExprResult (Expr *)> Filter)3292   CorrectDelayedTyposInExpr(ExprResult ER,
3293                             llvm::function_ref<ExprResult(Expr *)> Filter) {
3294     return CorrectDelayedTyposInExpr(ER, nullptr, Filter);
3295   }
3296 
3297   void diagnoseTypo(const TypoCorrection &Correction,
3298                     const PartialDiagnostic &TypoDiag,
3299                     bool ErrorRecovery = true);
3300 
3301   void diagnoseTypo(const TypoCorrection &Correction,
3302                     const PartialDiagnostic &TypoDiag,
3303                     const PartialDiagnostic &PrevNote,
3304                     bool ErrorRecovery = true);
3305 
3306   void MarkTypoCorrectedFunctionDefinition(const NamedDecl *F);
3307 
3308   void FindAssociatedClassesAndNamespaces(SourceLocation InstantiationLoc,
3309                                           ArrayRef<Expr *> Args,
3310                                    AssociatedNamespaceSet &AssociatedNamespaces,
3311                                    AssociatedClassSet &AssociatedClasses);
3312 
3313   void FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S,
3314                             bool ConsiderLinkage, bool AllowInlineNamespace);
3315 
3316   bool CheckRedeclarationModuleOwnership(NamedDecl *New, NamedDecl *Old);
3317 
3318   void DiagnoseAmbiguousLookup(LookupResult &Result);
3319   //@}
3320 
3321   ObjCInterfaceDecl *getObjCInterfaceDecl(IdentifierInfo *&Id,
3322                                           SourceLocation IdLoc,
3323                                           bool TypoCorrection = false);
3324   NamedDecl *LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID,
3325                                  Scope *S, bool ForRedeclaration,
3326                                  SourceLocation Loc);
3327   NamedDecl *ImplicitlyDefineFunction(SourceLocation Loc, IdentifierInfo &II,
3328                                       Scope *S);
3329   void AddKnownFunctionAttributes(FunctionDecl *FD);
3330 
3331   // More parsing and symbol table subroutines.
3332 
3333   void ProcessPragmaWeak(Scope *S, Decl *D);
3334   // Decl attributes - this routine is the top level dispatcher.
3335   void ProcessDeclAttributes(Scope *S, Decl *D, const Declarator &PD);
3336   // Helper for delayed processing of attributes.
3337   void ProcessDeclAttributeDelayed(Decl *D,
3338                                    const ParsedAttributesView &AttrList);
3339   void ProcessDeclAttributeList(Scope *S, Decl *D, const ParsedAttributesView &AL,
3340                              bool IncludeCXX11Attributes = true);
3341   bool ProcessAccessDeclAttributeList(AccessSpecDecl *ASDecl,
3342                                    const ParsedAttributesView &AttrList);
3343 
3344   void checkUnusedDeclAttributes(Declarator &D);
3345 
3346   /// Determine if type T is a valid subject for a nonnull and similar
3347   /// attributes. By default, we look through references (the behavior used by
3348   /// nonnull), but if the second parameter is true, then we treat a reference
3349   /// type as valid.
3350   bool isValidPointerAttrType(QualType T, bool RefOkay = false);
3351 
3352   bool CheckRegparmAttr(const ParsedAttr &attr, unsigned &value);
3353   bool CheckCallingConvAttr(const ParsedAttr &attr, CallingConv &CC,
3354                             const FunctionDecl *FD = nullptr);
3355   bool CheckAttrTarget(const ParsedAttr &CurrAttr);
3356   bool CheckAttrNoArgs(const ParsedAttr &CurrAttr);
3357   bool checkStringLiteralArgumentAttr(const ParsedAttr &Attr, unsigned ArgNum,
3358                                       StringRef &Str,
3359                                       SourceLocation *ArgLocation = nullptr);
3360   bool checkSectionName(SourceLocation LiteralLoc, StringRef Str);
3361   bool checkTargetAttr(SourceLocation LiteralLoc, StringRef Str);
3362   bool checkMSInheritanceAttrOnDefinition(
3363       CXXRecordDecl *RD, SourceRange Range, bool BestCase,
3364       MSInheritanceAttr::Spelling SemanticSpelling);
3365 
3366   void CheckAlignasUnderalignment(Decl *D);
3367 
3368   /// Adjust the calling convention of a method to be the ABI default if it
3369   /// wasn't specified explicitly.  This handles method types formed from
3370   /// function type typedefs and typename template arguments.
3371   void adjustMemberFunctionCC(QualType &T, bool IsStatic, bool IsCtorOrDtor,
3372                               SourceLocation Loc);
3373 
3374   // Check if there is an explicit attribute, but only look through parens.
3375   // The intent is to look for an attribute on the current declarator, but not
3376   // one that came from a typedef.
3377   bool hasExplicitCallingConv(QualType &T);
3378 
3379   /// Get the outermost AttributedType node that sets a calling convention.
3380   /// Valid types should not have multiple attributes with different CCs.
3381   const AttributedType *getCallingConvAttributedType(QualType T) const;
3382 
3383   /// Check whether a nullability type specifier can be added to the given
3384   /// type.
3385   ///
3386   /// \param type The type to which the nullability specifier will be
3387   /// added. On success, this type will be updated appropriately.
3388   ///
3389   /// \param nullability The nullability specifier to add.
3390   ///
3391   /// \param nullabilityLoc The location of the nullability specifier.
3392   ///
3393   /// \param isContextSensitive Whether this nullability specifier was
3394   /// written as a context-sensitive keyword (in an Objective-C
3395   /// method) or an Objective-C property attribute, rather than as an
3396   /// underscored type specifier.
3397   ///
3398   /// \param allowArrayTypes Whether to accept nullability specifiers on an
3399   /// array type (e.g., because it will decay to a pointer).
3400   ///
3401   /// \returns true if nullability cannot be applied, false otherwise.
3402   bool checkNullabilityTypeSpecifier(QualType &type, NullabilityKind nullability,
3403                                      SourceLocation nullabilityLoc,
3404                                      bool isContextSensitive,
3405                                      bool allowArrayTypes);
3406 
3407   /// Stmt attributes - this routine is the top level dispatcher.
3408   StmtResult ProcessStmtAttributes(Stmt *Stmt,
3409                                    const ParsedAttributesView &Attrs,
3410                                    SourceRange Range);
3411 
3412   void WarnConflictingTypedMethods(ObjCMethodDecl *Method,
3413                                    ObjCMethodDecl *MethodDecl,
3414                                    bool IsProtocolMethodDecl);
3415 
3416   void CheckConflictingOverridingMethod(ObjCMethodDecl *Method,
3417                                    ObjCMethodDecl *Overridden,
3418                                    bool IsProtocolMethodDecl);
3419 
3420   /// WarnExactTypedMethods - This routine issues a warning if method
3421   /// implementation declaration matches exactly that of its declaration.
3422   void WarnExactTypedMethods(ObjCMethodDecl *Method,
3423                              ObjCMethodDecl *MethodDecl,
3424                              bool IsProtocolMethodDecl);
3425 
3426   typedef llvm::SmallPtrSet<Selector, 8> SelectorSet;
3427 
3428   /// CheckImplementationIvars - This routine checks if the instance variables
3429   /// listed in the implelementation match those listed in the interface.
3430   void CheckImplementationIvars(ObjCImplementationDecl *ImpDecl,
3431                                 ObjCIvarDecl **Fields, unsigned nIvars,
3432                                 SourceLocation Loc);
3433 
3434   /// ImplMethodsVsClassMethods - This is main routine to warn if any method
3435   /// remains unimplemented in the class or category \@implementation.
3436   void ImplMethodsVsClassMethods(Scope *S, ObjCImplDecl* IMPDecl,
3437                                  ObjCContainerDecl* IDecl,
3438                                  bool IncompleteImpl = false);
3439 
3440   /// DiagnoseUnimplementedProperties - This routine warns on those properties
3441   /// which must be implemented by this implementation.
3442   void DiagnoseUnimplementedProperties(Scope *S, ObjCImplDecl* IMPDecl,
3443                                        ObjCContainerDecl *CDecl,
3444                                        bool SynthesizeProperties);
3445 
3446   /// Diagnose any null-resettable synthesized setters.
3447   void diagnoseNullResettableSynthesizedSetters(const ObjCImplDecl *impDecl);
3448 
3449   /// DefaultSynthesizeProperties - This routine default synthesizes all
3450   /// properties which must be synthesized in the class's \@implementation.
3451   void DefaultSynthesizeProperties(Scope *S, ObjCImplDecl *IMPDecl,
3452                                    ObjCInterfaceDecl *IDecl,
3453                                    SourceLocation AtEnd);
3454   void DefaultSynthesizeProperties(Scope *S, Decl *D, SourceLocation AtEnd);
3455 
3456   /// IvarBacksCurrentMethodAccessor - This routine returns 'true' if 'IV' is
3457   /// an ivar synthesized for 'Method' and 'Method' is a property accessor
3458   /// declared in class 'IFace'.
3459   bool IvarBacksCurrentMethodAccessor(ObjCInterfaceDecl *IFace,
3460                                       ObjCMethodDecl *Method, ObjCIvarDecl *IV);
3461 
3462   /// DiagnoseUnusedBackingIvarInAccessor - Issue an 'unused' warning if ivar which
3463   /// backs the property is not used in the property's accessor.
3464   void DiagnoseUnusedBackingIvarInAccessor(Scope *S,
3465                                            const ObjCImplementationDecl *ImplD);
3466 
3467   /// GetIvarBackingPropertyAccessor - If method is a property setter/getter and
3468   /// it property has a backing ivar, returns this ivar; otherwise, returns NULL.
3469   /// It also returns ivar's property on success.
3470   ObjCIvarDecl *GetIvarBackingPropertyAccessor(const ObjCMethodDecl *Method,
3471                                                const ObjCPropertyDecl *&PDecl) const;
3472 
3473   /// Called by ActOnProperty to handle \@property declarations in
3474   /// class extensions.
3475   ObjCPropertyDecl *HandlePropertyInClassExtension(Scope *S,
3476                       SourceLocation AtLoc,
3477                       SourceLocation LParenLoc,
3478                       FieldDeclarator &FD,
3479                       Selector GetterSel,
3480                       SourceLocation GetterNameLoc,
3481                       Selector SetterSel,
3482                       SourceLocation SetterNameLoc,
3483                       const bool isReadWrite,
3484                       unsigned &Attributes,
3485                       const unsigned AttributesAsWritten,
3486                       QualType T,
3487                       TypeSourceInfo *TSI,
3488                       tok::ObjCKeywordKind MethodImplKind);
3489 
3490   /// Called by ActOnProperty and HandlePropertyInClassExtension to
3491   /// handle creating the ObjcPropertyDecl for a category or \@interface.
3492   ObjCPropertyDecl *CreatePropertyDecl(Scope *S,
3493                                        ObjCContainerDecl *CDecl,
3494                                        SourceLocation AtLoc,
3495                                        SourceLocation LParenLoc,
3496                                        FieldDeclarator &FD,
3497                                        Selector GetterSel,
3498                                        SourceLocation GetterNameLoc,
3499                                        Selector SetterSel,
3500                                        SourceLocation SetterNameLoc,
3501                                        const bool isReadWrite,
3502                                        const unsigned Attributes,
3503                                        const unsigned AttributesAsWritten,
3504                                        QualType T,
3505                                        TypeSourceInfo *TSI,
3506                                        tok::ObjCKeywordKind MethodImplKind,
3507                                        DeclContext *lexicalDC = nullptr);
3508 
3509   /// AtomicPropertySetterGetterRules - This routine enforces the rule (via
3510   /// warning) when atomic property has one but not the other user-declared
3511   /// setter or getter.
3512   void AtomicPropertySetterGetterRules(ObjCImplDecl* IMPDecl,
3513                                        ObjCInterfaceDecl* IDecl);
3514 
3515   void DiagnoseOwningPropertyGetterSynthesis(const ObjCImplementationDecl *D);
3516 
3517   void DiagnoseMissingDesignatedInitOverrides(
3518                                           const ObjCImplementationDecl *ImplD,
3519                                           const ObjCInterfaceDecl *IFD);
3520 
3521   void DiagnoseDuplicateIvars(ObjCInterfaceDecl *ID, ObjCInterfaceDecl *SID);
3522 
3523   enum MethodMatchStrategy {
3524     MMS_loose,
3525     MMS_strict
3526   };
3527 
3528   /// MatchTwoMethodDeclarations - Checks if two methods' type match and returns
3529   /// true, or false, accordingly.
3530   bool MatchTwoMethodDeclarations(const ObjCMethodDecl *Method,
3531                                   const ObjCMethodDecl *PrevMethod,
3532                                   MethodMatchStrategy strategy = MMS_strict);
3533 
3534   /// MatchAllMethodDeclarations - Check methods declaraed in interface or
3535   /// or protocol against those declared in their implementations.
3536   void MatchAllMethodDeclarations(const SelectorSet &InsMap,
3537                                   const SelectorSet &ClsMap,
3538                                   SelectorSet &InsMapSeen,
3539                                   SelectorSet &ClsMapSeen,
3540                                   ObjCImplDecl* IMPDecl,
3541                                   ObjCContainerDecl* IDecl,
3542                                   bool &IncompleteImpl,
3543                                   bool ImmediateClass,
3544                                   bool WarnCategoryMethodImpl=false);
3545 
3546   /// CheckCategoryVsClassMethodMatches - Checks that methods implemented in
3547   /// category matches with those implemented in its primary class and
3548   /// warns each time an exact match is found.
3549   void CheckCategoryVsClassMethodMatches(ObjCCategoryImplDecl *CatIMP);
3550 
3551   /// Add the given method to the list of globally-known methods.
3552   void addMethodToGlobalList(ObjCMethodList *List, ObjCMethodDecl *Method);
3553 
3554 private:
3555   /// AddMethodToGlobalPool - Add an instance or factory method to the global
3556   /// pool. See descriptoin of AddInstanceMethodToGlobalPool.
3557   void AddMethodToGlobalPool(ObjCMethodDecl *Method, bool impl, bool instance);
3558 
3559   /// LookupMethodInGlobalPool - Returns the instance or factory method and
3560   /// optionally warns if there are multiple signatures.
3561   ObjCMethodDecl *LookupMethodInGlobalPool(Selector Sel, SourceRange R,
3562                                            bool receiverIdOrClass,
3563                                            bool instance);
3564 
3565 public:
3566   /// - Returns instance or factory methods in global method pool for
3567   /// given selector. It checks the desired kind first, if none is found, and
3568   /// parameter checkTheOther is set, it then checks the other kind. If no such
3569   /// method or only one method is found, function returns false; otherwise, it
3570   /// returns true.
3571   bool
3572   CollectMultipleMethodsInGlobalPool(Selector Sel,
3573                                      SmallVectorImpl<ObjCMethodDecl*>& Methods,
3574                                      bool InstanceFirst, bool CheckTheOther,
3575                                      const ObjCObjectType *TypeBound = nullptr);
3576 
3577   bool
3578   AreMultipleMethodsInGlobalPool(Selector Sel, ObjCMethodDecl *BestMethod,
3579                                  SourceRange R, bool receiverIdOrClass,
3580                                  SmallVectorImpl<ObjCMethodDecl*>& Methods);
3581 
3582   void
3583   DiagnoseMultipleMethodInGlobalPool(SmallVectorImpl<ObjCMethodDecl*> &Methods,
3584                                      Selector Sel, SourceRange R,
3585                                      bool receiverIdOrClass);
3586 
3587 private:
3588   /// - Returns a selector which best matches given argument list or
3589   /// nullptr if none could be found
3590   ObjCMethodDecl *SelectBestMethod(Selector Sel, MultiExprArg Args,
3591                                    bool IsInstance,
3592                                    SmallVectorImpl<ObjCMethodDecl*>& Methods);
3593 
3594 
3595   /// Record the typo correction failure and return an empty correction.
3596   TypoCorrection FailedCorrection(IdentifierInfo *Typo, SourceLocation TypoLoc,
3597                                   bool RecordFailure = true) {
3598     if (RecordFailure)
3599       TypoCorrectionFailures[Typo].insert(TypoLoc);
3600     return TypoCorrection();
3601   }
3602 
3603 public:
3604   /// AddInstanceMethodToGlobalPool - All instance methods in a translation
3605   /// unit are added to a global pool. This allows us to efficiently associate
3606   /// a selector with a method declaraation for purposes of typechecking
3607   /// messages sent to "id" (where the class of the object is unknown).
3608   void AddInstanceMethodToGlobalPool(ObjCMethodDecl *Method, bool impl=false) {
3609     AddMethodToGlobalPool(Method, impl, /*instance*/true);
3610   }
3611 
3612   /// AddFactoryMethodToGlobalPool - Same as above, but for factory methods.
3613   void AddFactoryMethodToGlobalPool(ObjCMethodDecl *Method, bool impl=false) {
3614     AddMethodToGlobalPool(Method, impl, /*instance*/false);
3615   }
3616 
3617   /// AddAnyMethodToGlobalPool - Add any method, instance or factory to global
3618   /// pool.
3619   void AddAnyMethodToGlobalPool(Decl *D);
3620 
3621   /// LookupInstanceMethodInGlobalPool - Returns the method and warns if
3622   /// there are multiple signatures.
3623   ObjCMethodDecl *LookupInstanceMethodInGlobalPool(Selector Sel, SourceRange R,
3624                                                    bool receiverIdOrClass=false) {
3625     return LookupMethodInGlobalPool(Sel, R, receiverIdOrClass,
3626                                     /*instance*/true);
3627   }
3628 
3629   /// LookupFactoryMethodInGlobalPool - Returns the method and warns if
3630   /// there are multiple signatures.
3631   ObjCMethodDecl *LookupFactoryMethodInGlobalPool(Selector Sel, SourceRange R,
3632                                                   bool receiverIdOrClass=false) {
3633     return LookupMethodInGlobalPool(Sel, R, receiverIdOrClass,
3634                                     /*instance*/false);
3635   }
3636 
3637   const ObjCMethodDecl *SelectorsForTypoCorrection(Selector Sel,
3638                               QualType ObjectType=QualType());
3639   /// LookupImplementedMethodInGlobalPool - Returns the method which has an
3640   /// implementation.
3641   ObjCMethodDecl *LookupImplementedMethodInGlobalPool(Selector Sel);
3642 
3643   /// CollectIvarsToConstructOrDestruct - Collect those ivars which require
3644   /// initialization.
3645   void CollectIvarsToConstructOrDestruct(ObjCInterfaceDecl *OI,
3646                                   SmallVectorImpl<ObjCIvarDecl*> &Ivars);
3647 
3648   //===--------------------------------------------------------------------===//
3649   // Statement Parsing Callbacks: SemaStmt.cpp.
3650 public:
3651   class FullExprArg {
3652   public:
FullExprArg()3653     FullExprArg() : E(nullptr) { }
FullExprArg(Sema & actions)3654     FullExprArg(Sema &actions) : E(nullptr) { }
3655 
release()3656     ExprResult release() {
3657       return E;
3658     }
3659 
get()3660     Expr *get() const { return E; }
3661 
3662     Expr *operator->() {
3663       return E;
3664     }
3665 
3666   private:
3667     // FIXME: No need to make the entire Sema class a friend when it's just
3668     // Sema::MakeFullExpr that needs access to the constructor below.
3669     friend class Sema;
3670 
FullExprArg(Expr * expr)3671     explicit FullExprArg(Expr *expr) : E(expr) {}
3672 
3673     Expr *E;
3674   };
3675 
MakeFullExpr(Expr * Arg)3676   FullExprArg MakeFullExpr(Expr *Arg) {
3677     return MakeFullExpr(Arg, Arg ? Arg->getExprLoc() : SourceLocation());
3678   }
MakeFullExpr(Expr * Arg,SourceLocation CC)3679   FullExprArg MakeFullExpr(Expr *Arg, SourceLocation CC) {
3680     return FullExprArg(ActOnFinishFullExpr(Arg, CC).get());
3681   }
MakeFullDiscardedValueExpr(Expr * Arg)3682   FullExprArg MakeFullDiscardedValueExpr(Expr *Arg) {
3683     ExprResult FE =
3684       ActOnFinishFullExpr(Arg, Arg ? Arg->getExprLoc() : SourceLocation(),
3685                           /*DiscardedValue*/ true);
3686     return FullExprArg(FE.get());
3687   }
3688 
3689   StmtResult ActOnExprStmt(ExprResult Arg);
3690   StmtResult ActOnExprStmtError();
3691 
3692   StmtResult ActOnNullStmt(SourceLocation SemiLoc,
3693                            bool HasLeadingEmptyMacro = false);
3694 
3695   void ActOnStartOfCompoundStmt(bool IsStmtExpr);
3696   void ActOnFinishOfCompoundStmt();
3697   StmtResult ActOnCompoundStmt(SourceLocation L, SourceLocation R,
3698                                ArrayRef<Stmt *> Elts, bool isStmtExpr);
3699 
3700   /// A RAII object to enter scope of a compound statement.
3701   class CompoundScopeRAII {
3702   public:
S(S)3703     CompoundScopeRAII(Sema &S, bool IsStmtExpr = false) : S(S) {
3704       S.ActOnStartOfCompoundStmt(IsStmtExpr);
3705     }
3706 
~CompoundScopeRAII()3707     ~CompoundScopeRAII() {
3708       S.ActOnFinishOfCompoundStmt();
3709     }
3710 
3711   private:
3712     Sema &S;
3713   };
3714 
3715   /// An RAII helper that pops function a function scope on exit.
3716   struct FunctionScopeRAII {
3717     Sema &S;
3718     bool Active;
FunctionScopeRAIIFunctionScopeRAII3719     FunctionScopeRAII(Sema &S) : S(S), Active(true) {}
~FunctionScopeRAIIFunctionScopeRAII3720     ~FunctionScopeRAII() {
3721       if (Active)
3722         S.PopFunctionScopeInfo();
3723     }
disableFunctionScopeRAII3724     void disable() { Active = false; }
3725   };
3726 
3727   StmtResult ActOnDeclStmt(DeclGroupPtrTy Decl,
3728                                    SourceLocation StartLoc,
3729                                    SourceLocation EndLoc);
3730   void ActOnForEachDeclStmt(DeclGroupPtrTy Decl);
3731   StmtResult ActOnForEachLValueExpr(Expr *E);
3732   ExprResult ActOnCaseExpr(SourceLocation CaseLoc, ExprResult Val);
3733   StmtResult ActOnCaseStmt(SourceLocation CaseLoc, ExprResult LHS,
3734                            SourceLocation DotDotDotLoc, ExprResult RHS,
3735                            SourceLocation ColonLoc);
3736   void ActOnCaseStmtBody(Stmt *CaseStmt, Stmt *SubStmt);
3737 
3738   StmtResult ActOnDefaultStmt(SourceLocation DefaultLoc,
3739                                       SourceLocation ColonLoc,
3740                                       Stmt *SubStmt, Scope *CurScope);
3741   StmtResult ActOnLabelStmt(SourceLocation IdentLoc, LabelDecl *TheDecl,
3742                             SourceLocation ColonLoc, Stmt *SubStmt);
3743 
3744   StmtResult ActOnAttributedStmt(SourceLocation AttrLoc,
3745                                  ArrayRef<const Attr*> Attrs,
3746                                  Stmt *SubStmt);
3747 
3748   class ConditionResult;
3749   StmtResult ActOnIfStmt(SourceLocation IfLoc, bool IsConstexpr,
3750                          Stmt *InitStmt,
3751                          ConditionResult Cond, Stmt *ThenVal,
3752                          SourceLocation ElseLoc, Stmt *ElseVal);
3753   StmtResult BuildIfStmt(SourceLocation IfLoc, bool IsConstexpr,
3754                          Stmt *InitStmt,
3755                          ConditionResult Cond, Stmt *ThenVal,
3756                          SourceLocation ElseLoc, Stmt *ElseVal);
3757   StmtResult ActOnStartOfSwitchStmt(SourceLocation SwitchLoc,
3758                                     Stmt *InitStmt,
3759                                     ConditionResult Cond);
3760   StmtResult ActOnFinishSwitchStmt(SourceLocation SwitchLoc,
3761                                            Stmt *Switch, Stmt *Body);
3762   StmtResult ActOnWhileStmt(SourceLocation WhileLoc, ConditionResult Cond,
3763                             Stmt *Body);
3764   StmtResult ActOnDoStmt(SourceLocation DoLoc, Stmt *Body,
3765                          SourceLocation WhileLoc, SourceLocation CondLParen,
3766                          Expr *Cond, SourceLocation CondRParen);
3767 
3768   StmtResult ActOnForStmt(SourceLocation ForLoc,
3769                           SourceLocation LParenLoc,
3770                           Stmt *First,
3771                           ConditionResult Second,
3772                           FullExprArg Third,
3773                           SourceLocation RParenLoc,
3774                           Stmt *Body);
3775   ExprResult CheckObjCForCollectionOperand(SourceLocation forLoc,
3776                                            Expr *collection);
3777   StmtResult ActOnObjCForCollectionStmt(SourceLocation ForColLoc,
3778                                         Stmt *First, Expr *collection,
3779                                         SourceLocation RParenLoc);
3780   StmtResult FinishObjCForCollectionStmt(Stmt *ForCollection, Stmt *Body);
3781 
3782   enum BuildForRangeKind {
3783     /// Initial building of a for-range statement.
3784     BFRK_Build,
3785     /// Instantiation or recovery rebuild of a for-range statement. Don't
3786     /// attempt any typo-correction.
3787     BFRK_Rebuild,
3788     /// Determining whether a for-range statement could be built. Avoid any
3789     /// unnecessary or irreversible actions.
3790     BFRK_Check
3791   };
3792 
3793   StmtResult ActOnCXXForRangeStmt(Scope *S, SourceLocation ForLoc,
3794                                   SourceLocation CoawaitLoc,
3795                                   Stmt *LoopVar,
3796                                   SourceLocation ColonLoc, Expr *Collection,
3797                                   SourceLocation RParenLoc,
3798                                   BuildForRangeKind Kind);
3799   StmtResult BuildCXXForRangeStmt(SourceLocation ForLoc,
3800                                   SourceLocation CoawaitLoc,
3801                                   SourceLocation ColonLoc,
3802                                   Stmt *RangeDecl, Stmt *Begin, Stmt *End,
3803                                   Expr *Cond, Expr *Inc,
3804                                   Stmt *LoopVarDecl,
3805                                   SourceLocation RParenLoc,
3806                                   BuildForRangeKind Kind);
3807   StmtResult FinishCXXForRangeStmt(Stmt *ForRange, Stmt *Body);
3808 
3809   StmtResult ActOnGotoStmt(SourceLocation GotoLoc,
3810                            SourceLocation LabelLoc,
3811                            LabelDecl *TheDecl);
3812   StmtResult ActOnIndirectGotoStmt(SourceLocation GotoLoc,
3813                                    SourceLocation StarLoc,
3814                                    Expr *DestExp);
3815   StmtResult ActOnContinueStmt(SourceLocation ContinueLoc, Scope *CurScope);
3816   StmtResult ActOnBreakStmt(SourceLocation BreakLoc, Scope *CurScope);
3817 
3818   void ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope,
3819                                 CapturedRegionKind Kind, unsigned NumParams);
3820   typedef std::pair<StringRef, QualType> CapturedParamNameType;
3821   void ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope,
3822                                 CapturedRegionKind Kind,
3823                                 ArrayRef<CapturedParamNameType> Params);
3824   StmtResult ActOnCapturedRegionEnd(Stmt *S);
3825   void ActOnCapturedRegionError();
3826   RecordDecl *CreateCapturedStmtRecordDecl(CapturedDecl *&CD,
3827                                            SourceLocation Loc,
3828                                            unsigned NumParams);
3829 
3830   enum CopyElisionSemanticsKind {
3831     CES_Strict = 0,
3832     CES_AllowParameters = 1,
3833     CES_AllowDifferentTypes = 2,
3834     CES_AllowExceptionVariables = 4,
3835     CES_FormerDefault = (CES_AllowParameters),
3836     CES_Default = (CES_AllowParameters | CES_AllowDifferentTypes),
3837     CES_AsIfByStdMove = (CES_AllowParameters | CES_AllowDifferentTypes |
3838                          CES_AllowExceptionVariables),
3839   };
3840 
3841   VarDecl *getCopyElisionCandidate(QualType ReturnType, Expr *E,
3842                                    CopyElisionSemanticsKind CESK);
3843   bool isCopyElisionCandidate(QualType ReturnType, const VarDecl *VD,
3844                               CopyElisionSemanticsKind CESK);
3845 
3846   StmtResult ActOnReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp,
3847                              Scope *CurScope);
3848   StmtResult BuildReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp);
3849   StmtResult ActOnCapScopeReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp);
3850 
3851   StmtResult ActOnGCCAsmStmt(SourceLocation AsmLoc, bool IsSimple,
3852                              bool IsVolatile, unsigned NumOutputs,
3853                              unsigned NumInputs, IdentifierInfo **Names,
3854                              MultiExprArg Constraints, MultiExprArg Exprs,
3855                              Expr *AsmString, MultiExprArg Clobbers,
3856                              SourceLocation RParenLoc);
3857 
3858   void FillInlineAsmIdentifierInfo(Expr *Res,
3859                                    llvm::InlineAsmIdentifierInfo &Info);
3860   ExprResult LookupInlineAsmIdentifier(CXXScopeSpec &SS,
3861                                        SourceLocation TemplateKWLoc,
3862                                        UnqualifiedId &Id,
3863                                        bool IsUnevaluatedContext);
3864   bool LookupInlineAsmField(StringRef Base, StringRef Member,
3865                             unsigned &Offset, SourceLocation AsmLoc);
3866   ExprResult LookupInlineAsmVarDeclField(Expr *RefExpr, StringRef Member,
3867                                          SourceLocation AsmLoc);
3868   StmtResult ActOnMSAsmStmt(SourceLocation AsmLoc, SourceLocation LBraceLoc,
3869                             ArrayRef<Token> AsmToks,
3870                             StringRef AsmString,
3871                             unsigned NumOutputs, unsigned NumInputs,
3872                             ArrayRef<StringRef> Constraints,
3873                             ArrayRef<StringRef> Clobbers,
3874                             ArrayRef<Expr*> Exprs,
3875                             SourceLocation EndLoc);
3876   LabelDecl *GetOrCreateMSAsmLabel(StringRef ExternalLabelName,
3877                                    SourceLocation Location,
3878                                    bool AlwaysCreate);
3879 
3880   VarDecl *BuildObjCExceptionDecl(TypeSourceInfo *TInfo, QualType ExceptionType,
3881                                   SourceLocation StartLoc,
3882                                   SourceLocation IdLoc, IdentifierInfo *Id,
3883                                   bool Invalid = false);
3884 
3885   Decl *ActOnObjCExceptionDecl(Scope *S, Declarator &D);
3886 
3887   StmtResult ActOnObjCAtCatchStmt(SourceLocation AtLoc, SourceLocation RParen,
3888                                   Decl *Parm, Stmt *Body);
3889 
3890   StmtResult ActOnObjCAtFinallyStmt(SourceLocation AtLoc, Stmt *Body);
3891 
3892   StmtResult ActOnObjCAtTryStmt(SourceLocation AtLoc, Stmt *Try,
3893                                 MultiStmtArg Catch, Stmt *Finally);
3894 
3895   StmtResult BuildObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw);
3896   StmtResult ActOnObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw,
3897                                   Scope *CurScope);
3898   ExprResult ActOnObjCAtSynchronizedOperand(SourceLocation atLoc,
3899                                             Expr *operand);
3900   StmtResult ActOnObjCAtSynchronizedStmt(SourceLocation AtLoc,
3901                                          Expr *SynchExpr,
3902                                          Stmt *SynchBody);
3903 
3904   StmtResult ActOnObjCAutoreleasePoolStmt(SourceLocation AtLoc, Stmt *Body);
3905 
3906   VarDecl *BuildExceptionDeclaration(Scope *S, TypeSourceInfo *TInfo,
3907                                      SourceLocation StartLoc,
3908                                      SourceLocation IdLoc,
3909                                      IdentifierInfo *Id);
3910 
3911   Decl *ActOnExceptionDeclarator(Scope *S, Declarator &D);
3912 
3913   StmtResult ActOnCXXCatchBlock(SourceLocation CatchLoc,
3914                                 Decl *ExDecl, Stmt *HandlerBlock);
3915   StmtResult ActOnCXXTryBlock(SourceLocation TryLoc, Stmt *TryBlock,
3916                               ArrayRef<Stmt *> Handlers);
3917 
3918   StmtResult ActOnSEHTryBlock(bool IsCXXTry, // try (true) or __try (false) ?
3919                               SourceLocation TryLoc, Stmt *TryBlock,
3920                               Stmt *Handler);
3921   StmtResult ActOnSEHExceptBlock(SourceLocation Loc,
3922                                  Expr *FilterExpr,
3923                                  Stmt *Block);
3924   void ActOnStartSEHFinallyBlock();
3925   void ActOnAbortSEHFinallyBlock();
3926   StmtResult ActOnFinishSEHFinallyBlock(SourceLocation Loc, Stmt *Block);
3927   StmtResult ActOnSEHLeaveStmt(SourceLocation Loc, Scope *CurScope);
3928 
3929   void DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock);
3930 
3931   bool ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const;
3932 
3933   /// If it's a file scoped decl that must warn if not used, keep track
3934   /// of it.
3935   void MarkUnusedFileScopedDecl(const DeclaratorDecl *D);
3936 
3937   /// DiagnoseUnusedExprResult - If the statement passed in is an expression
3938   /// whose result is unused, warn.
3939   void DiagnoseUnusedExprResult(const Stmt *S);
3940   void DiagnoseUnusedNestedTypedefs(const RecordDecl *D);
3941   void DiagnoseUnusedDecl(const NamedDecl *ND);
3942 
3943   /// Emit \p DiagID if statement located on \p StmtLoc has a suspicious null
3944   /// statement as a \p Body, and it is located on the same line.
3945   ///
3946   /// This helps prevent bugs due to typos, such as:
3947   ///     if (condition);
3948   ///       do_stuff();
3949   void DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
3950                              const Stmt *Body,
3951                              unsigned DiagID);
3952 
3953   /// Warn if a for/while loop statement \p S, which is followed by
3954   /// \p PossibleBody, has a suspicious null statement as a body.
3955   void DiagnoseEmptyLoopBody(const Stmt *S,
3956                              const Stmt *PossibleBody);
3957 
3958   /// Warn if a value is moved to itself.
3959   void DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
3960                         SourceLocation OpLoc);
3961 
3962   /// Warn if we're implicitly casting from a _Nullable pointer type to a
3963   /// _Nonnull one.
3964   void diagnoseNullableToNonnullConversion(QualType DstType, QualType SrcType,
3965                                            SourceLocation Loc);
3966 
3967   /// Warn when implicitly casting 0 to nullptr.
3968   void diagnoseZeroToNullptrConversion(CastKind Kind, const Expr *E);
3969 
PushParsingDeclaration(sema::DelayedDiagnosticPool & pool)3970   ParsingDeclState PushParsingDeclaration(sema::DelayedDiagnosticPool &pool) {
3971     return DelayedDiagnostics.push(pool);
3972   }
3973   void PopParsingDeclaration(ParsingDeclState state, Decl *decl);
3974 
3975   typedef ProcessingContextState ParsingClassState;
PushParsingClass()3976   ParsingClassState PushParsingClass() {
3977     return DelayedDiagnostics.pushUndelayed();
3978   }
PopParsingClass(ParsingClassState state)3979   void PopParsingClass(ParsingClassState state) {
3980     DelayedDiagnostics.popUndelayed(state);
3981   }
3982 
3983   void redelayDiagnostics(sema::DelayedDiagnosticPool &pool);
3984 
3985   void DiagnoseAvailabilityOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs,
3986                                   const ObjCInterfaceDecl *UnknownObjCClass,
3987                                   bool ObjCPropertyAccess,
3988                                   bool AvoidPartialAvailabilityChecks = false);
3989 
3990   bool makeUnavailableInSystemHeader(SourceLocation loc,
3991                                      UnavailableAttr::ImplicitReason reason);
3992 
3993   /// Issue any -Wunguarded-availability warnings in \c FD
3994   void DiagnoseUnguardedAvailabilityViolations(Decl *FD);
3995 
3996   //===--------------------------------------------------------------------===//
3997   // Expression Parsing Callbacks: SemaExpr.cpp.
3998 
3999   bool CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid);
4000   bool DiagnoseUseOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs,
4001                          const ObjCInterfaceDecl *UnknownObjCClass = nullptr,
4002                          bool ObjCPropertyAccess = false,
4003                          bool AvoidPartialAvailabilityChecks = false);
4004   void NoteDeletedFunction(FunctionDecl *FD);
4005   void NoteDeletedInheritingConstructor(CXXConstructorDecl *CD);
4006   std::string getDeletedOrUnavailableSuffix(const FunctionDecl *FD);
4007   bool DiagnosePropertyAccessorMismatch(ObjCPropertyDecl *PD,
4008                                         ObjCMethodDecl *Getter,
4009                                         SourceLocation Loc);
4010   void DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
4011                              ArrayRef<Expr *> Args);
4012 
4013   void PushExpressionEvaluationContext(
4014       ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl = nullptr,
4015       ExpressionEvaluationContextRecord::ExpressionKind Type =
4016           ExpressionEvaluationContextRecord::EK_Other);
4017   enum ReuseLambdaContextDecl_t { ReuseLambdaContextDecl };
4018   void PushExpressionEvaluationContext(
4019       ExpressionEvaluationContext NewContext, ReuseLambdaContextDecl_t,
4020       ExpressionEvaluationContextRecord::ExpressionKind Type =
4021           ExpressionEvaluationContextRecord::EK_Other);
4022   void PopExpressionEvaluationContext();
4023 
4024   void DiscardCleanupsInEvaluationContext();
4025 
4026   ExprResult TransformToPotentiallyEvaluated(Expr *E);
4027   ExprResult HandleExprEvaluationContextForTypeof(Expr *E);
4028 
4029   ExprResult ActOnConstantExpression(ExprResult Res);
4030 
4031   // Functions for marking a declaration referenced.  These functions also
4032   // contain the relevant logic for marking if a reference to a function or
4033   // variable is an odr-use (in the C++11 sense).  There are separate variants
4034   // for expressions referring to a decl; these exist because odr-use marking
4035   // needs to be delayed for some constant variables when we build one of the
4036   // named expressions.
4037   //
4038   // MightBeOdrUse indicates whether the use could possibly be an odr-use, and
4039   // should usually be true. This only needs to be set to false if the lack of
4040   // odr-use cannot be determined from the current context (for instance,
4041   // because the name denotes a virtual function and was written without an
4042   // explicit nested-name-specifier).
4043   void MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, bool MightBeOdrUse);
4044   void MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func,
4045                               bool MightBeOdrUse = true);
4046   void MarkVariableReferenced(SourceLocation Loc, VarDecl *Var);
4047   void MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base = nullptr);
4048   void MarkMemberReferenced(MemberExpr *E);
4049 
4050   void UpdateMarkingForLValueToRValue(Expr *E);
4051   void CleanupVarDeclMarking();
4052 
4053   enum TryCaptureKind {
4054     TryCapture_Implicit, TryCapture_ExplicitByVal, TryCapture_ExplicitByRef
4055   };
4056 
4057   /// Try to capture the given variable.
4058   ///
4059   /// \param Var The variable to capture.
4060   ///
4061   /// \param Loc The location at which the capture occurs.
4062   ///
4063   /// \param Kind The kind of capture, which may be implicit (for either a
4064   /// block or a lambda), or explicit by-value or by-reference (for a lambda).
4065   ///
4066   /// \param EllipsisLoc The location of the ellipsis, if one is provided in
4067   /// an explicit lambda capture.
4068   ///
4069   /// \param BuildAndDiagnose Whether we are actually supposed to add the
4070   /// captures or diagnose errors. If false, this routine merely check whether
4071   /// the capture can occur without performing the capture itself or complaining
4072   /// if the variable cannot be captured.
4073   ///
4074   /// \param CaptureType Will be set to the type of the field used to capture
4075   /// this variable in the innermost block or lambda. Only valid when the
4076   /// variable can be captured.
4077   ///
4078   /// \param DeclRefType Will be set to the type of a reference to the capture
4079   /// from within the current scope. Only valid when the variable can be
4080   /// captured.
4081   ///
4082   /// \param FunctionScopeIndexToStopAt If non-null, it points to the index
4083   /// of the FunctionScopeInfo stack beyond which we do not attempt to capture.
4084   /// This is useful when enclosing lambdas must speculatively capture
4085   /// variables that may or may not be used in certain specializations of
4086   /// a nested generic lambda.
4087   ///
4088   /// \returns true if an error occurred (i.e., the variable cannot be
4089   /// captured) and false if the capture succeeded.
4090   bool tryCaptureVariable(VarDecl *Var, SourceLocation Loc, TryCaptureKind Kind,
4091                           SourceLocation EllipsisLoc, bool BuildAndDiagnose,
4092                           QualType &CaptureType,
4093                           QualType &DeclRefType,
4094                           const unsigned *const FunctionScopeIndexToStopAt);
4095 
4096   /// Try to capture the given variable.
4097   bool tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
4098                           TryCaptureKind Kind = TryCapture_Implicit,
4099                           SourceLocation EllipsisLoc = SourceLocation());
4100 
4101   /// Checks if the variable must be captured.
4102   bool NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc);
4103 
4104   /// Given a variable, determine the type that a reference to that
4105   /// variable will have in the given scope.
4106   QualType getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc);
4107 
4108   /// Mark all of the declarations referenced within a particular AST node as
4109   /// referenced. Used when template instantiation instantiates a non-dependent
4110   /// type -- entities referenced by the type are now referenced.
4111   void MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T);
4112   void MarkDeclarationsReferencedInExpr(Expr *E,
4113                                         bool SkipLocalVariables = false);
4114 
4115   /// Try to recover by turning the given expression into a
4116   /// call.  Returns true if recovery was attempted or an error was
4117   /// emitted; this may also leave the ExprResult invalid.
4118   bool tryToRecoverWithCall(ExprResult &E, const PartialDiagnostic &PD,
4119                             bool ForceComplain = false,
4120                             bool (*IsPlausibleResult)(QualType) = nullptr);
4121 
4122   /// Figure out if an expression could be turned into a call.
4123   bool tryExprAsCall(Expr &E, QualType &ZeroArgCallReturnTy,
4124                      UnresolvedSetImpl &NonTemplateOverloads);
4125 
4126   /// Conditionally issue a diagnostic based on the current
4127   /// evaluation context.
4128   ///
4129   /// \param Statement If Statement is non-null, delay reporting the
4130   /// diagnostic until the function body is parsed, and then do a basic
4131   /// reachability analysis to determine if the statement is reachable.
4132   /// If it is unreachable, the diagnostic will not be emitted.
4133   bool DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
4134                            const PartialDiagnostic &PD);
4135 
4136   // Primary Expressions.
4137   SourceRange getExprRange(Expr *E) const;
4138 
4139   ExprResult ActOnIdExpression(
4140       Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
4141       UnqualifiedId &Id, bool HasTrailingLParen, bool IsAddressOfOperand,
4142       std::unique_ptr<CorrectionCandidateCallback> CCC = nullptr,
4143       bool IsInlineAsmIdentifier = false, Token *KeywordReplacement = nullptr);
4144 
4145   void DecomposeUnqualifiedId(const UnqualifiedId &Id,
4146                               TemplateArgumentListInfo &Buffer,
4147                               DeclarationNameInfo &NameInfo,
4148                               const TemplateArgumentListInfo *&TemplateArgs);
4149 
4150   bool
4151   DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
4152                       std::unique_ptr<CorrectionCandidateCallback> CCC,
4153                       TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr,
4154                       ArrayRef<Expr *> Args = None, TypoExpr **Out = nullptr);
4155 
4156   ExprResult LookupInObjCMethod(LookupResult &LookUp, Scope *S,
4157                                 IdentifierInfo *II,
4158                                 bool AllowBuiltinCreation=false);
4159 
4160   ExprResult ActOnDependentIdExpression(const CXXScopeSpec &SS,
4161                                         SourceLocation TemplateKWLoc,
4162                                         const DeclarationNameInfo &NameInfo,
4163                                         bool isAddressOfOperand,
4164                                 const TemplateArgumentListInfo *TemplateArgs);
4165 
4166   ExprResult BuildDeclRefExpr(ValueDecl *D, QualType Ty,
4167                               ExprValueKind VK,
4168                               SourceLocation Loc,
4169                               const CXXScopeSpec *SS = nullptr);
4170   ExprResult
4171   BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
4172                    const DeclarationNameInfo &NameInfo,
4173                    const CXXScopeSpec *SS = nullptr,
4174                    NamedDecl *FoundD = nullptr,
4175                    const TemplateArgumentListInfo *TemplateArgs = nullptr);
4176   ExprResult
4177   BuildAnonymousStructUnionMemberReference(
4178       const CXXScopeSpec &SS,
4179       SourceLocation nameLoc,
4180       IndirectFieldDecl *indirectField,
4181       DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_none),
4182       Expr *baseObjectExpr = nullptr,
4183       SourceLocation opLoc = SourceLocation());
4184 
4185   ExprResult BuildPossibleImplicitMemberExpr(const CXXScopeSpec &SS,
4186                                              SourceLocation TemplateKWLoc,
4187                                              LookupResult &R,
4188                                 const TemplateArgumentListInfo *TemplateArgs,
4189                                              const Scope *S);
4190   ExprResult BuildImplicitMemberExpr(const CXXScopeSpec &SS,
4191                                      SourceLocation TemplateKWLoc,
4192                                      LookupResult &R,
4193                                 const TemplateArgumentListInfo *TemplateArgs,
4194                                      bool IsDefiniteInstance,
4195                                      const Scope *S);
4196   bool UseArgumentDependentLookup(const CXXScopeSpec &SS,
4197                                   const LookupResult &R,
4198                                   bool HasTrailingLParen);
4199 
4200   ExprResult
4201   BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS,
4202                                     const DeclarationNameInfo &NameInfo,
4203                                     bool IsAddressOfOperand, const Scope *S,
4204                                     TypeSourceInfo **RecoveryTSI = nullptr);
4205 
4206   ExprResult BuildDependentDeclRefExpr(const CXXScopeSpec &SS,
4207                                        SourceLocation TemplateKWLoc,
4208                                 const DeclarationNameInfo &NameInfo,
4209                                 const TemplateArgumentListInfo *TemplateArgs);
4210 
4211   ExprResult BuildDeclarationNameExpr(const CXXScopeSpec &SS,
4212                                       LookupResult &R,
4213                                       bool NeedsADL,
4214                                       bool AcceptInvalidDecl = false);
4215   ExprResult BuildDeclarationNameExpr(
4216       const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
4217       NamedDecl *FoundD = nullptr,
4218       const TemplateArgumentListInfo *TemplateArgs = nullptr,
4219       bool AcceptInvalidDecl = false);
4220 
4221   ExprResult BuildLiteralOperatorCall(LookupResult &R,
4222                       DeclarationNameInfo &SuffixInfo,
4223                       ArrayRef<Expr *> Args,
4224                       SourceLocation LitEndLoc,
4225                       TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr);
4226 
4227   ExprResult BuildPredefinedExpr(SourceLocation Loc,
4228                                  PredefinedExpr::IdentType IT);
4229   ExprResult ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind);
4230   ExprResult ActOnIntegerConstant(SourceLocation Loc, uint64_t Val);
4231 
4232   bool CheckLoopHintExpr(Expr *E, SourceLocation Loc);
4233 
4234   ExprResult ActOnNumericConstant(const Token &Tok, Scope *UDLScope = nullptr);
4235   ExprResult ActOnCharacterConstant(const Token &Tok,
4236                                     Scope *UDLScope = nullptr);
4237   ExprResult ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E);
4238   ExprResult ActOnParenListExpr(SourceLocation L,
4239                                 SourceLocation R,
4240                                 MultiExprArg Val);
4241 
4242   /// ActOnStringLiteral - The specified tokens were lexed as pasted string
4243   /// fragments (e.g. "foo" "bar" L"baz").
4244   ExprResult ActOnStringLiteral(ArrayRef<Token> StringToks,
4245                                 Scope *UDLScope = nullptr);
4246 
4247   ExprResult ActOnGenericSelectionExpr(SourceLocation KeyLoc,
4248                                        SourceLocation DefaultLoc,
4249                                        SourceLocation RParenLoc,
4250                                        Expr *ControllingExpr,
4251                                        ArrayRef<ParsedType> ArgTypes,
4252                                        ArrayRef<Expr *> ArgExprs);
4253   ExprResult CreateGenericSelectionExpr(SourceLocation KeyLoc,
4254                                         SourceLocation DefaultLoc,
4255                                         SourceLocation RParenLoc,
4256                                         Expr *ControllingExpr,
4257                                         ArrayRef<TypeSourceInfo *> Types,
4258                                         ArrayRef<Expr *> Exprs);
4259 
4260   // Binary/Unary Operators.  'Tok' is the token for the operator.
4261   ExprResult CreateBuiltinUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc,
4262                                   Expr *InputExpr);
4263   ExprResult BuildUnaryOp(Scope *S, SourceLocation OpLoc,
4264                           UnaryOperatorKind Opc, Expr *Input);
4265   ExprResult ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
4266                           tok::TokenKind Op, Expr *Input);
4267 
4268   bool isQualifiedMemberAccess(Expr *E);
4269   QualType CheckAddressOfOperand(ExprResult &Operand, SourceLocation OpLoc);
4270 
4271   ExprResult CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
4272                                             SourceLocation OpLoc,
4273                                             UnaryExprOrTypeTrait ExprKind,
4274                                             SourceRange R);
4275   ExprResult CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
4276                                             UnaryExprOrTypeTrait ExprKind);
4277   ExprResult
4278     ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
4279                                   UnaryExprOrTypeTrait ExprKind,
4280                                   bool IsType, void *TyOrEx,
4281                                   SourceRange ArgRange);
4282 
4283   ExprResult CheckPlaceholderExpr(Expr *E);
4284   bool CheckVecStepExpr(Expr *E);
4285 
4286   bool CheckUnaryExprOrTypeTraitOperand(Expr *E, UnaryExprOrTypeTrait ExprKind);
4287   bool CheckUnaryExprOrTypeTraitOperand(QualType ExprType, SourceLocation OpLoc,
4288                                         SourceRange ExprRange,
4289                                         UnaryExprOrTypeTrait ExprKind);
4290   ExprResult ActOnSizeofParameterPackExpr(Scope *S,
4291                                           SourceLocation OpLoc,
4292                                           IdentifierInfo &Name,
4293                                           SourceLocation NameLoc,
4294                                           SourceLocation RParenLoc);
4295   ExprResult ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
4296                                  tok::TokenKind Kind, Expr *Input);
4297 
4298   ExprResult ActOnArraySubscriptExpr(Scope *S, Expr *Base, SourceLocation LLoc,
4299                                      Expr *Idx, SourceLocation RLoc);
4300   ExprResult CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
4301                                              Expr *Idx, SourceLocation RLoc);
4302   ExprResult ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc,
4303                                       Expr *LowerBound, SourceLocation ColonLoc,
4304                                       Expr *Length, SourceLocation RBLoc);
4305 
4306   // This struct is for use by ActOnMemberAccess to allow
4307   // BuildMemberReferenceExpr to be able to reinvoke ActOnMemberAccess after
4308   // changing the access operator from a '.' to a '->' (to see if that is the
4309   // change needed to fix an error about an unknown member, e.g. when the class
4310   // defines a custom operator->).
4311   struct ActOnMemberAccessExtraArgs {
4312     Scope *S;
4313     UnqualifiedId &Id;
4314     Decl *ObjCImpDecl;
4315   };
4316 
4317   ExprResult BuildMemberReferenceExpr(
4318       Expr *Base, QualType BaseType, SourceLocation OpLoc, bool IsArrow,
4319       CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
4320       NamedDecl *FirstQualifierInScope, const DeclarationNameInfo &NameInfo,
4321       const TemplateArgumentListInfo *TemplateArgs,
4322       const Scope *S,
4323       ActOnMemberAccessExtraArgs *ExtraArgs = nullptr);
4324 
4325   ExprResult
4326   BuildMemberReferenceExpr(Expr *Base, QualType BaseType, SourceLocation OpLoc,
4327                            bool IsArrow, const CXXScopeSpec &SS,
4328                            SourceLocation TemplateKWLoc,
4329                            NamedDecl *FirstQualifierInScope, LookupResult &R,
4330                            const TemplateArgumentListInfo *TemplateArgs,
4331                            const Scope *S,
4332                            bool SuppressQualifierCheck = false,
4333                            ActOnMemberAccessExtraArgs *ExtraArgs = nullptr);
4334 
4335   ExprResult BuildFieldReferenceExpr(Expr *BaseExpr, bool IsArrow,
4336                                      SourceLocation OpLoc,
4337                                      const CXXScopeSpec &SS, FieldDecl *Field,
4338                                      DeclAccessPair FoundDecl,
4339                                      const DeclarationNameInfo &MemberNameInfo);
4340 
4341   ExprResult PerformMemberExprBaseConversion(Expr *Base, bool IsArrow);
4342 
4343   bool CheckQualifiedMemberReference(Expr *BaseExpr, QualType BaseType,
4344                                      const CXXScopeSpec &SS,
4345                                      const LookupResult &R);
4346 
4347   ExprResult ActOnDependentMemberExpr(Expr *Base, QualType BaseType,
4348                                       bool IsArrow, SourceLocation OpLoc,
4349                                       const CXXScopeSpec &SS,
4350                                       SourceLocation TemplateKWLoc,
4351                                       NamedDecl *FirstQualifierInScope,
4352                                const DeclarationNameInfo &NameInfo,
4353                                const TemplateArgumentListInfo *TemplateArgs);
4354 
4355   ExprResult ActOnMemberAccessExpr(Scope *S, Expr *Base,
4356                                    SourceLocation OpLoc,
4357                                    tok::TokenKind OpKind,
4358                                    CXXScopeSpec &SS,
4359                                    SourceLocation TemplateKWLoc,
4360                                    UnqualifiedId &Member,
4361                                    Decl *ObjCImpDecl);
4362 
4363   void ActOnDefaultCtorInitializers(Decl *CDtorDecl);
4364   bool ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
4365                                FunctionDecl *FDecl,
4366                                const FunctionProtoType *Proto,
4367                                ArrayRef<Expr *> Args,
4368                                SourceLocation RParenLoc,
4369                                bool ExecConfig = false);
4370   void CheckStaticArrayArgument(SourceLocation CallLoc,
4371                                 ParmVarDecl *Param,
4372                                 const Expr *ArgExpr);
4373 
4374   /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
4375   /// This provides the location of the left/right parens and a list of comma
4376   /// locations.
4377   ExprResult ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
4378                            MultiExprArg ArgExprs, SourceLocation RParenLoc,
4379                            Expr *ExecConfig = nullptr,
4380                            bool IsExecConfig = false);
4381   ExprResult BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
4382                                    SourceLocation LParenLoc,
4383                                    ArrayRef<Expr *> Arg,
4384                                    SourceLocation RParenLoc,
4385                                    Expr *Config = nullptr,
4386                                    bool IsExecConfig = false);
4387 
4388   ExprResult ActOnCUDAExecConfigExpr(Scope *S, SourceLocation LLLLoc,
4389                                      MultiExprArg ExecConfig,
4390                                      SourceLocation GGGLoc);
4391 
4392   ExprResult ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
4393                            Declarator &D, ParsedType &Ty,
4394                            SourceLocation RParenLoc, Expr *CastExpr);
4395   ExprResult BuildCStyleCastExpr(SourceLocation LParenLoc,
4396                                  TypeSourceInfo *Ty,
4397                                  SourceLocation RParenLoc,
4398                                  Expr *Op);
4399   CastKind PrepareScalarCast(ExprResult &src, QualType destType);
4400 
4401   /// Build an altivec or OpenCL literal.
4402   ExprResult BuildVectorLiteral(SourceLocation LParenLoc,
4403                                 SourceLocation RParenLoc, Expr *E,
4404                                 TypeSourceInfo *TInfo);
4405 
4406   ExprResult MaybeConvertParenListExprToParenExpr(Scope *S, Expr *ME);
4407 
4408   ExprResult ActOnCompoundLiteral(SourceLocation LParenLoc,
4409                                   ParsedType Ty,
4410                                   SourceLocation RParenLoc,
4411                                   Expr *InitExpr);
4412 
4413   ExprResult BuildCompoundLiteralExpr(SourceLocation LParenLoc,
4414                                       TypeSourceInfo *TInfo,
4415                                       SourceLocation RParenLoc,
4416                                       Expr *LiteralExpr);
4417 
4418   ExprResult ActOnInitList(SourceLocation LBraceLoc,
4419                            MultiExprArg InitArgList,
4420                            SourceLocation RBraceLoc);
4421 
4422   ExprResult ActOnDesignatedInitializer(Designation &Desig,
4423                                         SourceLocation Loc,
4424                                         bool GNUSyntax,
4425                                         ExprResult Init);
4426 
4427 private:
4428   static BinaryOperatorKind ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind);
4429 
4430 public:
4431   ExprResult ActOnBinOp(Scope *S, SourceLocation TokLoc,
4432                         tok::TokenKind Kind, Expr *LHSExpr, Expr *RHSExpr);
4433   ExprResult BuildBinOp(Scope *S, SourceLocation OpLoc,
4434                         BinaryOperatorKind Opc, Expr *LHSExpr, Expr *RHSExpr);
4435   ExprResult CreateBuiltinBinOp(SourceLocation OpLoc, BinaryOperatorKind Opc,
4436                                 Expr *LHSExpr, Expr *RHSExpr);
4437 
4438   void DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc);
4439 
4440   /// ActOnConditionalOp - Parse a ?: operation.  Note that 'LHS' may be null
4441   /// in the case of a the GNU conditional expr extension.
4442   ExprResult ActOnConditionalOp(SourceLocation QuestionLoc,
4443                                 SourceLocation ColonLoc,
4444                                 Expr *CondExpr, Expr *LHSExpr, Expr *RHSExpr);
4445 
4446   /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
4447   ExprResult ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
4448                             LabelDecl *TheDecl);
4449 
4450   void ActOnStartStmtExpr();
4451   ExprResult ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
4452                            SourceLocation RPLoc); // "({..})"
4453   void ActOnStmtExprError();
4454 
4455   // __builtin_offsetof(type, identifier(.identifier|[expr])*)
4456   struct OffsetOfComponent {
4457     SourceLocation LocStart, LocEnd;
4458     bool isBrackets;  // true if [expr], false if .ident
4459     union {
4460       IdentifierInfo *IdentInfo;
4461       Expr *E;
4462     } U;
4463   };
4464 
4465   /// __builtin_offsetof(type, a.b[123][456].c)
4466   ExprResult BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
4467                                   TypeSourceInfo *TInfo,
4468                                   ArrayRef<OffsetOfComponent> Components,
4469                                   SourceLocation RParenLoc);
4470   ExprResult ActOnBuiltinOffsetOf(Scope *S,
4471                                   SourceLocation BuiltinLoc,
4472                                   SourceLocation TypeLoc,
4473                                   ParsedType ParsedArgTy,
4474                                   ArrayRef<OffsetOfComponent> Components,
4475                                   SourceLocation RParenLoc);
4476 
4477   // __builtin_choose_expr(constExpr, expr1, expr2)
4478   ExprResult ActOnChooseExpr(SourceLocation BuiltinLoc,
4479                              Expr *CondExpr, Expr *LHSExpr,
4480                              Expr *RHSExpr, SourceLocation RPLoc);
4481 
4482   // __builtin_va_arg(expr, type)
4483   ExprResult ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty,
4484                         SourceLocation RPLoc);
4485   ExprResult BuildVAArgExpr(SourceLocation BuiltinLoc, Expr *E,
4486                             TypeSourceInfo *TInfo, SourceLocation RPLoc);
4487 
4488   // __null
4489   ExprResult ActOnGNUNullExpr(SourceLocation TokenLoc);
4490 
4491   bool CheckCaseExpression(Expr *E);
4492 
4493   /// Describes the result of an "if-exists" condition check.
4494   enum IfExistsResult {
4495     /// The symbol exists.
4496     IER_Exists,
4497 
4498     /// The symbol does not exist.
4499     IER_DoesNotExist,
4500 
4501     /// The name is a dependent name, so the results will differ
4502     /// from one instantiation to the next.
4503     IER_Dependent,
4504 
4505     /// An error occurred.
4506     IER_Error
4507   };
4508 
4509   IfExistsResult
4510   CheckMicrosoftIfExistsSymbol(Scope *S, CXXScopeSpec &SS,
4511                                const DeclarationNameInfo &TargetNameInfo);
4512 
4513   IfExistsResult
4514   CheckMicrosoftIfExistsSymbol(Scope *S, SourceLocation KeywordLoc,
4515                                bool IsIfExists, CXXScopeSpec &SS,
4516                                UnqualifiedId &Name);
4517 
4518   StmtResult BuildMSDependentExistsStmt(SourceLocation KeywordLoc,
4519                                         bool IsIfExists,
4520                                         NestedNameSpecifierLoc QualifierLoc,
4521                                         DeclarationNameInfo NameInfo,
4522                                         Stmt *Nested);
4523   StmtResult ActOnMSDependentExistsStmt(SourceLocation KeywordLoc,
4524                                         bool IsIfExists,
4525                                         CXXScopeSpec &SS, UnqualifiedId &Name,
4526                                         Stmt *Nested);
4527 
4528   //===------------------------- "Block" Extension ------------------------===//
4529 
4530   /// ActOnBlockStart - This callback is invoked when a block literal is
4531   /// started.
4532   void ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope);
4533 
4534   /// ActOnBlockArguments - This callback allows processing of block arguments.
4535   /// If there are no arguments, this is still invoked.
4536   void ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
4537                            Scope *CurScope);
4538 
4539   /// ActOnBlockError - If there is an error parsing a block, this callback
4540   /// is invoked to pop the information about the block from the action impl.
4541   void ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope);
4542 
4543   /// ActOnBlockStmtExpr - This is called when the body of a block statement
4544   /// literal was successfully completed.  ^(int x){...}
4545   ExprResult ActOnBlockStmtExpr(SourceLocation CaretLoc, Stmt *Body,
4546                                 Scope *CurScope);
4547 
4548   //===---------------------------- Clang Extensions ----------------------===//
4549 
4550   /// __builtin_convertvector(...)
4551   ExprResult ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy,
4552                                     SourceLocation BuiltinLoc,
4553                                     SourceLocation RParenLoc);
4554 
4555   //===---------------------------- OpenCL Features -----------------------===//
4556 
4557   /// __builtin_astype(...)
4558   ExprResult ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
4559                              SourceLocation BuiltinLoc,
4560                              SourceLocation RParenLoc);
4561 
4562   //===---------------------------- C++ Features --------------------------===//
4563 
4564   // Act on C++ namespaces
4565   Decl *ActOnStartNamespaceDef(Scope *S, SourceLocation InlineLoc,
4566                                SourceLocation NamespaceLoc,
4567                                SourceLocation IdentLoc, IdentifierInfo *Ident,
4568                                SourceLocation LBrace,
4569                                const ParsedAttributesView &AttrList,
4570                                UsingDirectiveDecl *&UsingDecl);
4571   void ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace);
4572 
4573   NamespaceDecl *getStdNamespace() const;
4574   NamespaceDecl *getOrCreateStdNamespace();
4575 
4576   NamespaceDecl *lookupStdExperimentalNamespace();
4577 
4578   CXXRecordDecl *getStdBadAlloc() const;
4579   EnumDecl *getStdAlignValT() const;
4580 
4581 private:
4582   // A cache representing if we've fully checked the various comparison category
4583   // types stored in ASTContext. The bit-index corresponds to the integer value
4584   // of a ComparisonCategoryType enumerator.
4585   llvm::SmallBitVector FullyCheckedComparisonCategories;
4586 
4587 public:
4588   /// Lookup the specified comparison category types in the standard
4589   ///   library, an check the VarDecls possibly returned by the operator<=>
4590   ///   builtins for that type.
4591   ///
4592   /// \return The type of the comparison category type corresponding to the
4593   ///   specified Kind, or a null type if an error occurs
4594   QualType CheckComparisonCategoryType(ComparisonCategoryType Kind,
4595                                        SourceLocation Loc);
4596 
4597   /// Tests whether Ty is an instance of std::initializer_list and, if
4598   /// it is and Element is not NULL, assigns the element type to Element.
4599   bool isStdInitializerList(QualType Ty, QualType *Element);
4600 
4601   /// Looks for the std::initializer_list template and instantiates it
4602   /// with Element, or emits an error if it's not found.
4603   ///
4604   /// \returns The instantiated template, or null on error.
4605   QualType BuildStdInitializerList(QualType Element, SourceLocation Loc);
4606 
4607   /// Determine whether Ctor is an initializer-list constructor, as
4608   /// defined in [dcl.init.list]p2.
4609   bool isInitListConstructor(const FunctionDecl *Ctor);
4610 
4611   Decl *ActOnUsingDirective(Scope *CurScope, SourceLocation UsingLoc,
4612                             SourceLocation NamespcLoc, CXXScopeSpec &SS,
4613                             SourceLocation IdentLoc,
4614                             IdentifierInfo *NamespcName,
4615                             const ParsedAttributesView &AttrList);
4616 
4617   void PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir);
4618 
4619   Decl *ActOnNamespaceAliasDef(Scope *CurScope,
4620                                SourceLocation NamespaceLoc,
4621                                SourceLocation AliasLoc,
4622                                IdentifierInfo *Alias,
4623                                CXXScopeSpec &SS,
4624                                SourceLocation IdentLoc,
4625                                IdentifierInfo *Ident);
4626 
4627   void HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow);
4628   bool CheckUsingShadowDecl(UsingDecl *UD, NamedDecl *Target,
4629                             const LookupResult &PreviousDecls,
4630                             UsingShadowDecl *&PrevShadow);
4631   UsingShadowDecl *BuildUsingShadowDecl(Scope *S, UsingDecl *UD,
4632                                         NamedDecl *Target,
4633                                         UsingShadowDecl *PrevDecl);
4634 
4635   bool CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
4636                                    bool HasTypenameKeyword,
4637                                    const CXXScopeSpec &SS,
4638                                    SourceLocation NameLoc,
4639                                    const LookupResult &Previous);
4640   bool CheckUsingDeclQualifier(SourceLocation UsingLoc,
4641                                bool HasTypename,
4642                                const CXXScopeSpec &SS,
4643                                const DeclarationNameInfo &NameInfo,
4644                                SourceLocation NameLoc);
4645 
4646   NamedDecl *BuildUsingDeclaration(
4647       Scope *S, AccessSpecifier AS, SourceLocation UsingLoc,
4648       bool HasTypenameKeyword, SourceLocation TypenameLoc, CXXScopeSpec &SS,
4649       DeclarationNameInfo NameInfo, SourceLocation EllipsisLoc,
4650       const ParsedAttributesView &AttrList, bool IsInstantiation);
4651   NamedDecl *BuildUsingPackDecl(NamedDecl *InstantiatedFrom,
4652                                 ArrayRef<NamedDecl *> Expansions);
4653 
4654   bool CheckInheritingConstructorUsingDecl(UsingDecl *UD);
4655 
4656   /// Given a derived-class using shadow declaration for a constructor and the
4657   /// correspnding base class constructor, find or create the implicit
4658   /// synthesized derived class constructor to use for this initialization.
4659   CXXConstructorDecl *
4660   findInheritingConstructor(SourceLocation Loc, CXXConstructorDecl *BaseCtor,
4661                             ConstructorUsingShadowDecl *DerivedShadow);
4662 
4663   Decl *ActOnUsingDeclaration(Scope *CurScope, AccessSpecifier AS,
4664                               SourceLocation UsingLoc,
4665                               SourceLocation TypenameLoc, CXXScopeSpec &SS,
4666                               UnqualifiedId &Name, SourceLocation EllipsisLoc,
4667                               const ParsedAttributesView &AttrList);
4668   Decl *ActOnAliasDeclaration(Scope *CurScope, AccessSpecifier AS,
4669                               MultiTemplateParamsArg TemplateParams,
4670                               SourceLocation UsingLoc, UnqualifiedId &Name,
4671                               const ParsedAttributesView &AttrList,
4672                               TypeResult Type, Decl *DeclFromDeclSpec);
4673 
4674   /// BuildCXXConstructExpr - Creates a complete call to a constructor,
4675   /// including handling of its default argument expressions.
4676   ///
4677   /// \param ConstructKind - a CXXConstructExpr::ConstructionKind
4678   ExprResult
4679   BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
4680                         NamedDecl *FoundDecl,
4681                         CXXConstructorDecl *Constructor, MultiExprArg Exprs,
4682                         bool HadMultipleCandidates, bool IsListInitialization,
4683                         bool IsStdInitListInitialization,
4684                         bool RequiresZeroInit, unsigned ConstructKind,
4685                         SourceRange ParenRange);
4686 
4687   /// Build a CXXConstructExpr whose constructor has already been resolved if
4688   /// it denotes an inherited constructor.
4689   ExprResult
4690   BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
4691                         CXXConstructorDecl *Constructor, bool Elidable,
4692                         MultiExprArg Exprs,
4693                         bool HadMultipleCandidates, bool IsListInitialization,
4694                         bool IsStdInitListInitialization,
4695                         bool RequiresZeroInit, unsigned ConstructKind,
4696                         SourceRange ParenRange);
4697 
4698   // FIXME: Can we remove this and have the above BuildCXXConstructExpr check if
4699   // the constructor can be elidable?
4700   ExprResult
4701   BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
4702                         NamedDecl *FoundDecl,
4703                         CXXConstructorDecl *Constructor, bool Elidable,
4704                         MultiExprArg Exprs, bool HadMultipleCandidates,
4705                         bool IsListInitialization,
4706                         bool IsStdInitListInitialization, bool RequiresZeroInit,
4707                         unsigned ConstructKind, SourceRange ParenRange);
4708 
4709   ExprResult BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field);
4710 
4711 
4712   /// Instantiate or parse a C++ default argument expression as necessary.
4713   /// Return true on error.
4714   bool CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD,
4715                               ParmVarDecl *Param);
4716 
4717   /// BuildCXXDefaultArgExpr - Creates a CXXDefaultArgExpr, instantiating
4718   /// the default expr if needed.
4719   ExprResult BuildCXXDefaultArgExpr(SourceLocation CallLoc,
4720                                     FunctionDecl *FD,
4721                                     ParmVarDecl *Param);
4722 
4723   /// FinalizeVarWithDestructor - Prepare for calling destructor on the
4724   /// constructed variable.
4725   void FinalizeVarWithDestructor(VarDecl *VD, const RecordType *DeclInitType);
4726 
4727   /// Helper class that collects exception specifications for
4728   /// implicitly-declared special member functions.
4729   class ImplicitExceptionSpecification {
4730     // Pointer to allow copying
4731     Sema *Self;
4732     // We order exception specifications thus:
4733     // noexcept is the most restrictive, but is only used in C++11.
4734     // throw() comes next.
4735     // Then a throw(collected exceptions)
4736     // Finally no specification, which is expressed as noexcept(false).
4737     // throw(...) is used instead if any called function uses it.
4738     ExceptionSpecificationType ComputedEST;
4739     llvm::SmallPtrSet<CanQualType, 4> ExceptionsSeen;
4740     SmallVector<QualType, 4> Exceptions;
4741 
ClearExceptions()4742     void ClearExceptions() {
4743       ExceptionsSeen.clear();
4744       Exceptions.clear();
4745     }
4746 
4747   public:
ImplicitExceptionSpecification(Sema & Self)4748     explicit ImplicitExceptionSpecification(Sema &Self)
4749       : Self(&Self), ComputedEST(EST_BasicNoexcept) {
4750       if (!Self.getLangOpts().CPlusPlus11)
4751         ComputedEST = EST_DynamicNone;
4752     }
4753 
4754     /// Get the computed exception specification type.
getExceptionSpecType()4755     ExceptionSpecificationType getExceptionSpecType() const {
4756       assert(!isComputedNoexcept(ComputedEST) &&
4757              "noexcept(expr) should not be a possible result");
4758       return ComputedEST;
4759     }
4760 
4761     /// The number of exceptions in the exception specification.
size()4762     unsigned size() const { return Exceptions.size(); }
4763 
4764     /// The set of exceptions in the exception specification.
data()4765     const QualType *data() const { return Exceptions.data(); }
4766 
4767     /// Integrate another called method into the collected data.
4768     void CalledDecl(SourceLocation CallLoc, const CXXMethodDecl *Method);
4769 
4770     /// Integrate an invoked expression into the collected data.
4771     void CalledExpr(Expr *E);
4772 
4773     /// Overwrite an EPI's exception specification with this
4774     /// computed exception specification.
getExceptionSpec()4775     FunctionProtoType::ExceptionSpecInfo getExceptionSpec() const {
4776       FunctionProtoType::ExceptionSpecInfo ESI;
4777       ESI.Type = getExceptionSpecType();
4778       if (ESI.Type == EST_Dynamic) {
4779         ESI.Exceptions = Exceptions;
4780       } else if (ESI.Type == EST_None) {
4781         /// C++11 [except.spec]p14:
4782         ///   The exception-specification is noexcept(false) if the set of
4783         ///   potential exceptions of the special member function contains "any"
4784         ESI.Type = EST_NoexceptFalse;
4785         ESI.NoexceptExpr = Self->ActOnCXXBoolLiteral(SourceLocation(),
4786                                                      tok::kw_false).get();
4787       }
4788       return ESI;
4789     }
4790   };
4791 
4792   /// Determine what sort of exception specification a defaulted
4793   /// copy constructor of a class will have.
4794   ImplicitExceptionSpecification
4795   ComputeDefaultedDefaultCtorExceptionSpec(SourceLocation Loc,
4796                                            CXXMethodDecl *MD);
4797 
4798   /// Determine what sort of exception specification a defaulted
4799   /// default constructor of a class will have, and whether the parameter
4800   /// will be const.
4801   ImplicitExceptionSpecification
4802   ComputeDefaultedCopyCtorExceptionSpec(CXXMethodDecl *MD);
4803 
4804   /// Determine what sort of exception specification a defautled
4805   /// copy assignment operator of a class will have, and whether the
4806   /// parameter will be const.
4807   ImplicitExceptionSpecification
4808   ComputeDefaultedCopyAssignmentExceptionSpec(CXXMethodDecl *MD);
4809 
4810   /// Determine what sort of exception specification a defaulted move
4811   /// constructor of a class will have.
4812   ImplicitExceptionSpecification
4813   ComputeDefaultedMoveCtorExceptionSpec(CXXMethodDecl *MD);
4814 
4815   /// Determine what sort of exception specification a defaulted move
4816   /// assignment operator of a class will have.
4817   ImplicitExceptionSpecification
4818   ComputeDefaultedMoveAssignmentExceptionSpec(CXXMethodDecl *MD);
4819 
4820   /// Determine what sort of exception specification a defaulted
4821   /// destructor of a class will have.
4822   ImplicitExceptionSpecification
4823   ComputeDefaultedDtorExceptionSpec(CXXMethodDecl *MD);
4824 
4825   /// Determine what sort of exception specification an inheriting
4826   /// constructor of a class will have.
4827   ImplicitExceptionSpecification
4828   ComputeInheritingCtorExceptionSpec(SourceLocation Loc,
4829                                      CXXConstructorDecl *CD);
4830 
4831   /// Evaluate the implicit exception specification for a defaulted
4832   /// special member function.
4833   void EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD);
4834 
4835   /// Check the given noexcept-specifier, convert its expression, and compute
4836   /// the appropriate ExceptionSpecificationType.
4837   ExprResult ActOnNoexceptSpec(SourceLocation NoexceptLoc, Expr *NoexceptExpr,
4838                                ExceptionSpecificationType &EST);
4839 
4840   /// Check the given exception-specification and update the
4841   /// exception specification information with the results.
4842   void checkExceptionSpecification(bool IsTopLevel,
4843                                    ExceptionSpecificationType EST,
4844                                    ArrayRef<ParsedType> DynamicExceptions,
4845                                    ArrayRef<SourceRange> DynamicExceptionRanges,
4846                                    Expr *NoexceptExpr,
4847                                    SmallVectorImpl<QualType> &Exceptions,
4848                                    FunctionProtoType::ExceptionSpecInfo &ESI);
4849 
4850   /// Determine if we're in a case where we need to (incorrectly) eagerly
4851   /// parse an exception specification to work around a libstdc++ bug.
4852   bool isLibstdcxxEagerExceptionSpecHack(const Declarator &D);
4853 
4854   /// Add an exception-specification to the given member function
4855   /// (or member function template). The exception-specification was parsed
4856   /// after the method itself was declared.
4857   void actOnDelayedExceptionSpecification(Decl *Method,
4858          ExceptionSpecificationType EST,
4859          SourceRange SpecificationRange,
4860          ArrayRef<ParsedType> DynamicExceptions,
4861          ArrayRef<SourceRange> DynamicExceptionRanges,
4862          Expr *NoexceptExpr);
4863 
4864   class InheritedConstructorInfo;
4865 
4866   /// Determine if a special member function should have a deleted
4867   /// definition when it is defaulted.
4868   bool ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
4869                                  InheritedConstructorInfo *ICI = nullptr,
4870                                  bool Diagnose = false);
4871 
4872   /// Declare the implicit default constructor for the given class.
4873   ///
4874   /// \param ClassDecl The class declaration into which the implicit
4875   /// default constructor will be added.
4876   ///
4877   /// \returns The implicitly-declared default constructor.
4878   CXXConstructorDecl *DeclareImplicitDefaultConstructor(
4879                                                      CXXRecordDecl *ClassDecl);
4880 
4881   /// DefineImplicitDefaultConstructor - Checks for feasibility of
4882   /// defining this constructor as the default constructor.
4883   void DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
4884                                         CXXConstructorDecl *Constructor);
4885 
4886   /// Declare the implicit destructor for the given class.
4887   ///
4888   /// \param ClassDecl The class declaration into which the implicit
4889   /// destructor will be added.
4890   ///
4891   /// \returns The implicitly-declared destructor.
4892   CXXDestructorDecl *DeclareImplicitDestructor(CXXRecordDecl *ClassDecl);
4893 
4894   /// DefineImplicitDestructor - Checks for feasibility of
4895   /// defining this destructor as the default destructor.
4896   void DefineImplicitDestructor(SourceLocation CurrentLocation,
4897                                 CXXDestructorDecl *Destructor);
4898 
4899   /// Build an exception spec for destructors that don't have one.
4900   ///
4901   /// C++11 says that user-defined destructors with no exception spec get one
4902   /// that looks as if the destructor was implicitly declared.
4903   void AdjustDestructorExceptionSpec(CXXRecordDecl *ClassDecl,
4904                                      CXXDestructorDecl *Destructor);
4905 
4906   /// Define the specified inheriting constructor.
4907   void DefineInheritingConstructor(SourceLocation UseLoc,
4908                                    CXXConstructorDecl *Constructor);
4909 
4910   /// Declare the implicit copy constructor for the given class.
4911   ///
4912   /// \param ClassDecl The class declaration into which the implicit
4913   /// copy constructor will be added.
4914   ///
4915   /// \returns The implicitly-declared copy constructor.
4916   CXXConstructorDecl *DeclareImplicitCopyConstructor(CXXRecordDecl *ClassDecl);
4917 
4918   /// DefineImplicitCopyConstructor - Checks for feasibility of
4919   /// defining this constructor as the copy constructor.
4920   void DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
4921                                      CXXConstructorDecl *Constructor);
4922 
4923   /// Declare the implicit move constructor for the given class.
4924   ///
4925   /// \param ClassDecl The Class declaration into which the implicit
4926   /// move constructor will be added.
4927   ///
4928   /// \returns The implicitly-declared move constructor, or NULL if it wasn't
4929   /// declared.
4930   CXXConstructorDecl *DeclareImplicitMoveConstructor(CXXRecordDecl *ClassDecl);
4931 
4932   /// DefineImplicitMoveConstructor - Checks for feasibility of
4933   /// defining this constructor as the move constructor.
4934   void DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
4935                                      CXXConstructorDecl *Constructor);
4936 
4937   /// Declare the implicit copy assignment operator for the given class.
4938   ///
4939   /// \param ClassDecl The class declaration into which the implicit
4940   /// copy assignment operator will be added.
4941   ///
4942   /// \returns The implicitly-declared copy assignment operator.
4943   CXXMethodDecl *DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl);
4944 
4945   /// Defines an implicitly-declared copy assignment operator.
4946   void DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
4947                                     CXXMethodDecl *MethodDecl);
4948 
4949   /// Declare the implicit move assignment operator for the given class.
4950   ///
4951   /// \param ClassDecl The Class declaration into which the implicit
4952   /// move assignment operator will be added.
4953   ///
4954   /// \returns The implicitly-declared move assignment operator, or NULL if it
4955   /// wasn't declared.
4956   CXXMethodDecl *DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl);
4957 
4958   /// Defines an implicitly-declared move assignment operator.
4959   void DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
4960                                     CXXMethodDecl *MethodDecl);
4961 
4962   /// Force the declaration of any implicitly-declared members of this
4963   /// class.
4964   void ForceDeclarationOfImplicitMembers(CXXRecordDecl *Class);
4965 
4966   /// Check a completed declaration of an implicit special member.
4967   void CheckImplicitSpecialMemberDeclaration(Scope *S, FunctionDecl *FD);
4968 
4969   /// Determine whether the given function is an implicitly-deleted
4970   /// special member function.
4971   bool isImplicitlyDeleted(FunctionDecl *FD);
4972 
4973   /// Check whether 'this' shows up in the type of a static member
4974   /// function after the (naturally empty) cv-qualifier-seq would be.
4975   ///
4976   /// \returns true if an error occurred.
4977   bool checkThisInStaticMemberFunctionType(CXXMethodDecl *Method);
4978 
4979   /// Whether this' shows up in the exception specification of a static
4980   /// member function.
4981   bool checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method);
4982 
4983   /// Check whether 'this' shows up in the attributes of the given
4984   /// static member function.
4985   ///
4986   /// \returns true if an error occurred.
4987   bool checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method);
4988 
4989   /// MaybeBindToTemporary - If the passed in expression has a record type with
4990   /// a non-trivial destructor, this will return CXXBindTemporaryExpr. Otherwise
4991   /// it simply returns the passed in expression.
4992   ExprResult MaybeBindToTemporary(Expr *E);
4993 
4994   bool CompleteConstructorCall(CXXConstructorDecl *Constructor,
4995                                MultiExprArg ArgsPtr,
4996                                SourceLocation Loc,
4997                                SmallVectorImpl<Expr*> &ConvertedArgs,
4998                                bool AllowExplicit = false,
4999                                bool IsListInitialization = false);
5000 
5001   ParsedType getInheritingConstructorName(CXXScopeSpec &SS,
5002                                           SourceLocation NameLoc,
5003                                           IdentifierInfo &Name);
5004 
5005   ParsedType getConstructorName(IdentifierInfo &II, SourceLocation NameLoc,
5006                                 Scope *S, CXXScopeSpec &SS,
5007                                 bool EnteringContext);
5008   ParsedType getDestructorName(SourceLocation TildeLoc,
5009                                IdentifierInfo &II, SourceLocation NameLoc,
5010                                Scope *S, CXXScopeSpec &SS,
5011                                ParsedType ObjectType,
5012                                bool EnteringContext);
5013 
5014   ParsedType getDestructorTypeForDecltype(const DeclSpec &DS,
5015                                           ParsedType ObjectType);
5016 
5017   // Checks that reinterpret casts don't have undefined behavior.
5018   void CheckCompatibleReinterpretCast(QualType SrcType, QualType DestType,
5019                                       bool IsDereference, SourceRange Range);
5020 
5021   /// ActOnCXXNamedCast - Parse {dynamic,static,reinterpret,const}_cast's.
5022   ExprResult ActOnCXXNamedCast(SourceLocation OpLoc,
5023                                tok::TokenKind Kind,
5024                                SourceLocation LAngleBracketLoc,
5025                                Declarator &D,
5026                                SourceLocation RAngleBracketLoc,
5027                                SourceLocation LParenLoc,
5028                                Expr *E,
5029                                SourceLocation RParenLoc);
5030 
5031   ExprResult BuildCXXNamedCast(SourceLocation OpLoc,
5032                                tok::TokenKind Kind,
5033                                TypeSourceInfo *Ty,
5034                                Expr *E,
5035                                SourceRange AngleBrackets,
5036                                SourceRange Parens);
5037 
5038   ExprResult BuildCXXTypeId(QualType TypeInfoType,
5039                             SourceLocation TypeidLoc,
5040                             TypeSourceInfo *Operand,
5041                             SourceLocation RParenLoc);
5042   ExprResult BuildCXXTypeId(QualType TypeInfoType,
5043                             SourceLocation TypeidLoc,
5044                             Expr *Operand,
5045                             SourceLocation RParenLoc);
5046 
5047   /// ActOnCXXTypeid - Parse typeid( something ).
5048   ExprResult ActOnCXXTypeid(SourceLocation OpLoc,
5049                             SourceLocation LParenLoc, bool isType,
5050                             void *TyOrExpr,
5051                             SourceLocation RParenLoc);
5052 
5053   ExprResult BuildCXXUuidof(QualType TypeInfoType,
5054                             SourceLocation TypeidLoc,
5055                             TypeSourceInfo *Operand,
5056                             SourceLocation RParenLoc);
5057   ExprResult BuildCXXUuidof(QualType TypeInfoType,
5058                             SourceLocation TypeidLoc,
5059                             Expr *Operand,
5060                             SourceLocation RParenLoc);
5061 
5062   /// ActOnCXXUuidof - Parse __uuidof( something ).
5063   ExprResult ActOnCXXUuidof(SourceLocation OpLoc,
5064                             SourceLocation LParenLoc, bool isType,
5065                             void *TyOrExpr,
5066                             SourceLocation RParenLoc);
5067 
5068   /// Handle a C++1z fold-expression: ( expr op ... op expr ).
5069   ExprResult ActOnCXXFoldExpr(SourceLocation LParenLoc, Expr *LHS,
5070                               tok::TokenKind Operator,
5071                               SourceLocation EllipsisLoc, Expr *RHS,
5072                               SourceLocation RParenLoc);
5073   ExprResult BuildCXXFoldExpr(SourceLocation LParenLoc, Expr *LHS,
5074                               BinaryOperatorKind Operator,
5075                               SourceLocation EllipsisLoc, Expr *RHS,
5076                               SourceLocation RParenLoc);
5077   ExprResult BuildEmptyCXXFoldExpr(SourceLocation EllipsisLoc,
5078                                    BinaryOperatorKind Operator);
5079 
5080   //// ActOnCXXThis -  Parse 'this' pointer.
5081   ExprResult ActOnCXXThis(SourceLocation loc);
5082 
5083   /// Try to retrieve the type of the 'this' pointer.
5084   ///
5085   /// \returns The type of 'this', if possible. Otherwise, returns a NULL type.
5086   QualType getCurrentThisType();
5087 
5088   /// When non-NULL, the C++ 'this' expression is allowed despite the
5089   /// current context not being a non-static member function. In such cases,
5090   /// this provides the type used for 'this'.
5091   QualType CXXThisTypeOverride;
5092 
5093   /// RAII object used to temporarily allow the C++ 'this' expression
5094   /// to be used, with the given qualifiers on the current class type.
5095   class CXXThisScopeRAII {
5096     Sema &S;
5097     QualType OldCXXThisTypeOverride;
5098     bool Enabled;
5099 
5100   public:
5101     /// Introduce a new scope where 'this' may be allowed (when enabled),
5102     /// using the given declaration (which is either a class template or a
5103     /// class) along with the given qualifiers.
5104     /// along with the qualifiers placed on '*this'.
5105     CXXThisScopeRAII(Sema &S, Decl *ContextDecl, unsigned CXXThisTypeQuals,
5106                      bool Enabled = true);
5107 
5108     ~CXXThisScopeRAII();
5109   };
5110 
5111   /// Make sure the value of 'this' is actually available in the current
5112   /// context, if it is a potentially evaluated context.
5113   ///
5114   /// \param Loc The location at which the capture of 'this' occurs.
5115   ///
5116   /// \param Explicit Whether 'this' is explicitly captured in a lambda
5117   /// capture list.
5118   ///
5119   /// \param FunctionScopeIndexToStopAt If non-null, it points to the index
5120   /// of the FunctionScopeInfo stack beyond which we do not attempt to capture.
5121   /// This is useful when enclosing lambdas must speculatively capture
5122   /// 'this' that may or may not be used in certain specializations of
5123   /// a nested generic lambda (depending on whether the name resolves to
5124   /// a non-static member function or a static function).
5125   /// \return returns 'true' if failed, 'false' if success.
5126   bool CheckCXXThisCapture(SourceLocation Loc, bool Explicit = false,
5127       bool BuildAndDiagnose = true,
5128       const unsigned *const FunctionScopeIndexToStopAt = nullptr,
5129       bool ByCopy = false);
5130 
5131   /// Determine whether the given type is the type of *this that is used
5132   /// outside of the body of a member function for a type that is currently
5133   /// being defined.
5134   bool isThisOutsideMemberFunctionBody(QualType BaseType);
5135 
5136   /// ActOnCXXBoolLiteral - Parse {true,false} literals.
5137   ExprResult ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind);
5138 
5139 
5140   /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
5141   ExprResult ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind);
5142 
5143   ExprResult
5144   ActOnObjCAvailabilityCheckExpr(llvm::ArrayRef<AvailabilitySpec> AvailSpecs,
5145                                  SourceLocation AtLoc, SourceLocation RParen);
5146 
5147   /// ActOnCXXNullPtrLiteral - Parse 'nullptr'.
5148   ExprResult ActOnCXXNullPtrLiteral(SourceLocation Loc);
5149 
5150   //// ActOnCXXThrow -  Parse throw expressions.
5151   ExprResult ActOnCXXThrow(Scope *S, SourceLocation OpLoc, Expr *expr);
5152   ExprResult BuildCXXThrow(SourceLocation OpLoc, Expr *Ex,
5153                            bool IsThrownVarInScope);
5154   bool CheckCXXThrowOperand(SourceLocation ThrowLoc, QualType ThrowTy, Expr *E);
5155 
5156   /// ActOnCXXTypeConstructExpr - Parse construction of a specified type.
5157   /// Can be interpreted either as function-style casting ("int(x)")
5158   /// or class type construction ("ClassType(x,y,z)")
5159   /// or creation of a value-initialized type ("int()").
5160   ExprResult ActOnCXXTypeConstructExpr(ParsedType TypeRep,
5161                                        SourceLocation LParenOrBraceLoc,
5162                                        MultiExprArg Exprs,
5163                                        SourceLocation RParenOrBraceLoc,
5164                                        bool ListInitialization);
5165 
5166   ExprResult BuildCXXTypeConstructExpr(TypeSourceInfo *Type,
5167                                        SourceLocation LParenLoc,
5168                                        MultiExprArg Exprs,
5169                                        SourceLocation RParenLoc,
5170                                        bool ListInitialization);
5171 
5172   /// ActOnCXXNew - Parsed a C++ 'new' expression.
5173   ExprResult ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
5174                          SourceLocation PlacementLParen,
5175                          MultiExprArg PlacementArgs,
5176                          SourceLocation PlacementRParen,
5177                          SourceRange TypeIdParens, Declarator &D,
5178                          Expr *Initializer);
5179   ExprResult BuildCXXNew(SourceRange Range, bool UseGlobal,
5180                          SourceLocation PlacementLParen,
5181                          MultiExprArg PlacementArgs,
5182                          SourceLocation PlacementRParen,
5183                          SourceRange TypeIdParens,
5184                          QualType AllocType,
5185                          TypeSourceInfo *AllocTypeInfo,
5186                          Expr *ArraySize,
5187                          SourceRange DirectInitRange,
5188                          Expr *Initializer);
5189 
5190   bool CheckAllocatedType(QualType AllocType, SourceLocation Loc,
5191                           SourceRange R);
5192 
5193   /// The scope in which to find allocation functions.
5194   enum AllocationFunctionScope {
5195     /// Only look for allocation functions in the global scope.
5196     AFS_Global,
5197     /// Only look for allocation functions in the scope of the
5198     /// allocated class.
5199     AFS_Class,
5200     /// Look for allocation functions in both the global scope
5201     /// and in the scope of the allocated class.
5202     AFS_Both
5203   };
5204 
5205   /// Finds the overloads of operator new and delete that are appropriate
5206   /// for the allocation.
5207   bool FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,
5208                                AllocationFunctionScope NewScope,
5209                                AllocationFunctionScope DeleteScope,
5210                                QualType AllocType, bool IsArray,
5211                                bool &PassAlignment, MultiExprArg PlaceArgs,
5212                                FunctionDecl *&OperatorNew,
5213                                FunctionDecl *&OperatorDelete,
5214                                bool Diagnose = true);
5215   void DeclareGlobalNewDelete();
5216   void DeclareGlobalAllocationFunction(DeclarationName Name, QualType Return,
5217                                        ArrayRef<QualType> Params);
5218 
5219   bool FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD,
5220                                 DeclarationName Name, FunctionDecl* &Operator,
5221                                 bool Diagnose = true);
5222   FunctionDecl *FindUsualDeallocationFunction(SourceLocation StartLoc,
5223                                               bool CanProvideSize,
5224                                               bool Overaligned,
5225                                               DeclarationName Name);
5226   FunctionDecl *FindDeallocationFunctionForDestructor(SourceLocation StartLoc,
5227                                                       CXXRecordDecl *RD);
5228 
5229   /// ActOnCXXDelete - Parsed a C++ 'delete' expression
5230   ExprResult ActOnCXXDelete(SourceLocation StartLoc,
5231                             bool UseGlobal, bool ArrayForm,
5232                             Expr *Operand);
5233   void CheckVirtualDtorCall(CXXDestructorDecl *dtor, SourceLocation Loc,
5234                             bool IsDelete, bool CallCanBeVirtual,
5235                             bool WarnOnNonAbstractTypes,
5236                             SourceLocation DtorLoc);
5237 
5238   ExprResult ActOnNoexceptExpr(SourceLocation KeyLoc, SourceLocation LParen,
5239                                Expr *Operand, SourceLocation RParen);
5240   ExprResult BuildCXXNoexceptExpr(SourceLocation KeyLoc, Expr *Operand,
5241                                   SourceLocation RParen);
5242 
5243   /// Parsed one of the type trait support pseudo-functions.
5244   ExprResult ActOnTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
5245                             ArrayRef<ParsedType> Args,
5246                             SourceLocation RParenLoc);
5247   ExprResult BuildTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
5248                             ArrayRef<TypeSourceInfo *> Args,
5249                             SourceLocation RParenLoc);
5250 
5251   /// ActOnArrayTypeTrait - Parsed one of the binary type trait support
5252   /// pseudo-functions.
5253   ExprResult ActOnArrayTypeTrait(ArrayTypeTrait ATT,
5254                                  SourceLocation KWLoc,
5255                                  ParsedType LhsTy,
5256                                  Expr *DimExpr,
5257                                  SourceLocation RParen);
5258 
5259   ExprResult BuildArrayTypeTrait(ArrayTypeTrait ATT,
5260                                  SourceLocation KWLoc,
5261                                  TypeSourceInfo *TSInfo,
5262                                  Expr *DimExpr,
5263                                  SourceLocation RParen);
5264 
5265   /// ActOnExpressionTrait - Parsed one of the unary type trait support
5266   /// pseudo-functions.
5267   ExprResult ActOnExpressionTrait(ExpressionTrait OET,
5268                                   SourceLocation KWLoc,
5269                                   Expr *Queried,
5270                                   SourceLocation RParen);
5271 
5272   ExprResult BuildExpressionTrait(ExpressionTrait OET,
5273                                   SourceLocation KWLoc,
5274                                   Expr *Queried,
5275                                   SourceLocation RParen);
5276 
5277   ExprResult ActOnStartCXXMemberReference(Scope *S,
5278                                           Expr *Base,
5279                                           SourceLocation OpLoc,
5280                                           tok::TokenKind OpKind,
5281                                           ParsedType &ObjectType,
5282                                           bool &MayBePseudoDestructor);
5283 
5284   ExprResult BuildPseudoDestructorExpr(Expr *Base,
5285                                        SourceLocation OpLoc,
5286                                        tok::TokenKind OpKind,
5287                                        const CXXScopeSpec &SS,
5288                                        TypeSourceInfo *ScopeType,
5289                                        SourceLocation CCLoc,
5290                                        SourceLocation TildeLoc,
5291                                      PseudoDestructorTypeStorage DestroyedType);
5292 
5293   ExprResult ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
5294                                        SourceLocation OpLoc,
5295                                        tok::TokenKind OpKind,
5296                                        CXXScopeSpec &SS,
5297                                        UnqualifiedId &FirstTypeName,
5298                                        SourceLocation CCLoc,
5299                                        SourceLocation TildeLoc,
5300                                        UnqualifiedId &SecondTypeName);
5301 
5302   ExprResult ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
5303                                        SourceLocation OpLoc,
5304                                        tok::TokenKind OpKind,
5305                                        SourceLocation TildeLoc,
5306                                        const DeclSpec& DS);
5307 
5308   /// MaybeCreateExprWithCleanups - If the current full-expression
5309   /// requires any cleanups, surround it with a ExprWithCleanups node.
5310   /// Otherwise, just returns the passed-in expression.
5311   Expr *MaybeCreateExprWithCleanups(Expr *SubExpr);
5312   Stmt *MaybeCreateStmtWithCleanups(Stmt *SubStmt);
5313   ExprResult MaybeCreateExprWithCleanups(ExprResult SubExpr);
5314 
5315   MaterializeTemporaryExpr *
5316   CreateMaterializeTemporaryExpr(QualType T, Expr *Temporary,
5317                                  bool BoundToLvalueReference);
5318 
ActOnFinishFullExpr(Expr * Expr)5319   ExprResult ActOnFinishFullExpr(Expr *Expr) {
5320     return ActOnFinishFullExpr(Expr, Expr ? Expr->getExprLoc()
5321                                           : SourceLocation());
5322   }
5323   ExprResult ActOnFinishFullExpr(Expr *Expr, SourceLocation CC,
5324                                  bool DiscardedValue = false,
5325                                  bool IsConstexpr = false,
5326                                  bool IsLambdaInitCaptureInitializer = false);
5327   StmtResult ActOnFinishFullStmt(Stmt *Stmt);
5328 
5329   // Marks SS invalid if it represents an incomplete type.
5330   bool RequireCompleteDeclContext(CXXScopeSpec &SS, DeclContext *DC);
5331 
5332   DeclContext *computeDeclContext(QualType T);
5333   DeclContext *computeDeclContext(const CXXScopeSpec &SS,
5334                                   bool EnteringContext = false);
5335   bool isDependentScopeSpecifier(const CXXScopeSpec &SS);
5336   CXXRecordDecl *getCurrentInstantiationOf(NestedNameSpecifier *NNS);
5337 
5338   /// The parser has parsed a global nested-name-specifier '::'.
5339   ///
5340   /// \param CCLoc The location of the '::'.
5341   ///
5342   /// \param SS The nested-name-specifier, which will be updated in-place
5343   /// to reflect the parsed nested-name-specifier.
5344   ///
5345   /// \returns true if an error occurred, false otherwise.
5346   bool ActOnCXXGlobalScopeSpecifier(SourceLocation CCLoc, CXXScopeSpec &SS);
5347 
5348   /// The parser has parsed a '__super' nested-name-specifier.
5349   ///
5350   /// \param SuperLoc The location of the '__super' keyword.
5351   ///
5352   /// \param ColonColonLoc The location of the '::'.
5353   ///
5354   /// \param SS The nested-name-specifier, which will be updated in-place
5355   /// to reflect the parsed nested-name-specifier.
5356   ///
5357   /// \returns true if an error occurred, false otherwise.
5358   bool ActOnSuperScopeSpecifier(SourceLocation SuperLoc,
5359                                 SourceLocation ColonColonLoc, CXXScopeSpec &SS);
5360 
5361   bool isAcceptableNestedNameSpecifier(const NamedDecl *SD,
5362                                        bool *CanCorrect = nullptr);
5363   NamedDecl *FindFirstQualifierInScope(Scope *S, NestedNameSpecifier *NNS);
5364 
5365   /// Keeps information about an identifier in a nested-name-spec.
5366   ///
5367   struct NestedNameSpecInfo {
5368     /// The type of the object, if we're parsing nested-name-specifier in
5369     /// a member access expression.
5370     ParsedType ObjectType;
5371 
5372     /// The identifier preceding the '::'.
5373     IdentifierInfo *Identifier;
5374 
5375     /// The location of the identifier.
5376     SourceLocation IdentifierLoc;
5377 
5378     /// The location of the '::'.
5379     SourceLocation CCLoc;
5380 
5381     /// Creates info object for the most typical case.
5382     NestedNameSpecInfo(IdentifierInfo *II, SourceLocation IdLoc,
5383              SourceLocation ColonColonLoc, ParsedType ObjectType = ParsedType())
ObjectTypeNestedNameSpecInfo5384       : ObjectType(ObjectType), Identifier(II), IdentifierLoc(IdLoc),
5385         CCLoc(ColonColonLoc) {
5386     }
5387 
NestedNameSpecInfoNestedNameSpecInfo5388     NestedNameSpecInfo(IdentifierInfo *II, SourceLocation IdLoc,
5389                        SourceLocation ColonColonLoc, QualType ObjectType)
5390       : ObjectType(ParsedType::make(ObjectType)), Identifier(II),
5391         IdentifierLoc(IdLoc), CCLoc(ColonColonLoc) {
5392     }
5393   };
5394 
5395   bool isNonTypeNestedNameSpecifier(Scope *S, CXXScopeSpec &SS,
5396                                     NestedNameSpecInfo &IdInfo);
5397 
5398   bool BuildCXXNestedNameSpecifier(Scope *S,
5399                                    NestedNameSpecInfo &IdInfo,
5400                                    bool EnteringContext,
5401                                    CXXScopeSpec &SS,
5402                                    NamedDecl *ScopeLookupResult,
5403                                    bool ErrorRecoveryLookup,
5404                                    bool *IsCorrectedToColon = nullptr,
5405                                    bool OnlyNamespace = false);
5406 
5407   /// The parser has parsed a nested-name-specifier 'identifier::'.
5408   ///
5409   /// \param S The scope in which this nested-name-specifier occurs.
5410   ///
5411   /// \param IdInfo Parser information about an identifier in the
5412   /// nested-name-spec.
5413   ///
5414   /// \param EnteringContext Whether we're entering the context nominated by
5415   /// this nested-name-specifier.
5416   ///
5417   /// \param SS The nested-name-specifier, which is both an input
5418   /// parameter (the nested-name-specifier before this type) and an
5419   /// output parameter (containing the full nested-name-specifier,
5420   /// including this new type).
5421   ///
5422   /// \param ErrorRecoveryLookup If true, then this method is called to improve
5423   /// error recovery. In this case do not emit error message.
5424   ///
5425   /// \param IsCorrectedToColon If not null, suggestions to replace '::' -> ':'
5426   /// are allowed.  The bool value pointed by this parameter is set to 'true'
5427   /// if the identifier is treated as if it was followed by ':', not '::'.
5428   ///
5429   /// \param OnlyNamespace If true, only considers namespaces in lookup.
5430   ///
5431   /// \returns true if an error occurred, false otherwise.
5432   bool ActOnCXXNestedNameSpecifier(Scope *S,
5433                                    NestedNameSpecInfo &IdInfo,
5434                                    bool EnteringContext,
5435                                    CXXScopeSpec &SS,
5436                                    bool ErrorRecoveryLookup = false,
5437                                    bool *IsCorrectedToColon = nullptr,
5438                                    bool OnlyNamespace = false);
5439 
5440   ExprResult ActOnDecltypeExpression(Expr *E);
5441 
5442   bool ActOnCXXNestedNameSpecifierDecltype(CXXScopeSpec &SS,
5443                                            const DeclSpec &DS,
5444                                            SourceLocation ColonColonLoc);
5445 
5446   bool IsInvalidUnlessNestedName(Scope *S, CXXScopeSpec &SS,
5447                                  NestedNameSpecInfo &IdInfo,
5448                                  bool EnteringContext);
5449 
5450   /// The parser has parsed a nested-name-specifier
5451   /// 'template[opt] template-name < template-args >::'.
5452   ///
5453   /// \param S The scope in which this nested-name-specifier occurs.
5454   ///
5455   /// \param SS The nested-name-specifier, which is both an input
5456   /// parameter (the nested-name-specifier before this type) and an
5457   /// output parameter (containing the full nested-name-specifier,
5458   /// including this new type).
5459   ///
5460   /// \param TemplateKWLoc the location of the 'template' keyword, if any.
5461   /// \param TemplateName the template name.
5462   /// \param TemplateNameLoc The location of the template name.
5463   /// \param LAngleLoc The location of the opening angle bracket  ('<').
5464   /// \param TemplateArgs The template arguments.
5465   /// \param RAngleLoc The location of the closing angle bracket  ('>').
5466   /// \param CCLoc The location of the '::'.
5467   ///
5468   /// \param EnteringContext Whether we're entering the context of the
5469   /// nested-name-specifier.
5470   ///
5471   ///
5472   /// \returns true if an error occurred, false otherwise.
5473   bool ActOnCXXNestedNameSpecifier(Scope *S,
5474                                    CXXScopeSpec &SS,
5475                                    SourceLocation TemplateKWLoc,
5476                                    TemplateTy TemplateName,
5477                                    SourceLocation TemplateNameLoc,
5478                                    SourceLocation LAngleLoc,
5479                                    ASTTemplateArgsPtr TemplateArgs,
5480                                    SourceLocation RAngleLoc,
5481                                    SourceLocation CCLoc,
5482                                    bool EnteringContext);
5483 
5484   /// Given a C++ nested-name-specifier, produce an annotation value
5485   /// that the parser can use later to reconstruct the given
5486   /// nested-name-specifier.
5487   ///
5488   /// \param SS A nested-name-specifier.
5489   ///
5490   /// \returns A pointer containing all of the information in the
5491   /// nested-name-specifier \p SS.
5492   void *SaveNestedNameSpecifierAnnotation(CXXScopeSpec &SS);
5493 
5494   /// Given an annotation pointer for a nested-name-specifier, restore
5495   /// the nested-name-specifier structure.
5496   ///
5497   /// \param Annotation The annotation pointer, produced by
5498   /// \c SaveNestedNameSpecifierAnnotation().
5499   ///
5500   /// \param AnnotationRange The source range corresponding to the annotation.
5501   ///
5502   /// \param SS The nested-name-specifier that will be updated with the contents
5503   /// of the annotation pointer.
5504   void RestoreNestedNameSpecifierAnnotation(void *Annotation,
5505                                             SourceRange AnnotationRange,
5506                                             CXXScopeSpec &SS);
5507 
5508   bool ShouldEnterDeclaratorScope(Scope *S, const CXXScopeSpec &SS);
5509 
5510   /// ActOnCXXEnterDeclaratorScope - Called when a C++ scope specifier (global
5511   /// scope or nested-name-specifier) is parsed, part of a declarator-id.
5512   /// After this method is called, according to [C++ 3.4.3p3], names should be
5513   /// looked up in the declarator-id's scope, until the declarator is parsed and
5514   /// ActOnCXXExitDeclaratorScope is called.
5515   /// The 'SS' should be a non-empty valid CXXScopeSpec.
5516   bool ActOnCXXEnterDeclaratorScope(Scope *S, CXXScopeSpec &SS);
5517 
5518   /// ActOnCXXExitDeclaratorScope - Called when a declarator that previously
5519   /// invoked ActOnCXXEnterDeclaratorScope(), is finished. 'SS' is the same
5520   /// CXXScopeSpec that was passed to ActOnCXXEnterDeclaratorScope as well.
5521   /// Used to indicate that names should revert to being looked up in the
5522   /// defining scope.
5523   void ActOnCXXExitDeclaratorScope(Scope *S, const CXXScopeSpec &SS);
5524 
5525   /// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse an
5526   /// initializer for the declaration 'Dcl'.
5527   /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
5528   /// static data member of class X, names should be looked up in the scope of
5529   /// class X.
5530   void ActOnCXXEnterDeclInitializer(Scope *S, Decl *Dcl);
5531 
5532   /// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
5533   /// initializer for the declaration 'Dcl'.
5534   void ActOnCXXExitDeclInitializer(Scope *S, Decl *Dcl);
5535 
5536   /// Create a new lambda closure type.
5537   CXXRecordDecl *createLambdaClosureType(SourceRange IntroducerRange,
5538                                          TypeSourceInfo *Info,
5539                                          bool KnownDependent,
5540                                          LambdaCaptureDefault CaptureDefault);
5541 
5542   /// Start the definition of a lambda expression.
5543   CXXMethodDecl *startLambdaDefinition(CXXRecordDecl *Class,
5544                                        SourceRange IntroducerRange,
5545                                        TypeSourceInfo *MethodType,
5546                                        SourceLocation EndLoc,
5547                                        ArrayRef<ParmVarDecl *> Params,
5548                                        bool IsConstexprSpecified);
5549 
5550   /// Endow the lambda scope info with the relevant properties.
5551   void buildLambdaScope(sema::LambdaScopeInfo *LSI,
5552                         CXXMethodDecl *CallOperator,
5553                         SourceRange IntroducerRange,
5554                         LambdaCaptureDefault CaptureDefault,
5555                         SourceLocation CaptureDefaultLoc,
5556                         bool ExplicitParams,
5557                         bool ExplicitResultType,
5558                         bool Mutable);
5559 
5560   /// Perform initialization analysis of the init-capture and perform
5561   /// any implicit conversions such as an lvalue-to-rvalue conversion if
5562   /// not being used to initialize a reference.
actOnLambdaInitCaptureInitialization(SourceLocation Loc,bool ByRef,IdentifierInfo * Id,LambdaCaptureInitKind InitKind,Expr * & Init)5563   ParsedType actOnLambdaInitCaptureInitialization(
5564       SourceLocation Loc, bool ByRef, IdentifierInfo *Id,
5565       LambdaCaptureInitKind InitKind, Expr *&Init) {
5566     return ParsedType::make(buildLambdaInitCaptureInitialization(
5567         Loc, ByRef, Id, InitKind != LambdaCaptureInitKind::CopyInit, Init));
5568   }
5569   QualType buildLambdaInitCaptureInitialization(SourceLocation Loc, bool ByRef,
5570                                                 IdentifierInfo *Id,
5571                                                 bool DirectInit, Expr *&Init);
5572 
5573   /// Create a dummy variable within the declcontext of the lambda's
5574   ///  call operator, for name lookup purposes for a lambda init capture.
5575   ///
5576   ///  CodeGen handles emission of lambda captures, ignoring these dummy
5577   ///  variables appropriately.
5578   VarDecl *createLambdaInitCaptureVarDecl(SourceLocation Loc,
5579                                           QualType InitCaptureType,
5580                                           IdentifierInfo *Id,
5581                                           unsigned InitStyle, Expr *Init);
5582 
5583   /// Build the implicit field for an init-capture.
5584   FieldDecl *buildInitCaptureField(sema::LambdaScopeInfo *LSI, VarDecl *Var);
5585 
5586   /// Note that we have finished the explicit captures for the
5587   /// given lambda.
5588   void finishLambdaExplicitCaptures(sema::LambdaScopeInfo *LSI);
5589 
5590   /// Introduce the lambda parameters into scope.
5591   void addLambdaParameters(CXXMethodDecl *CallOperator, Scope *CurScope);
5592 
5593   /// Deduce a block or lambda's return type based on the return
5594   /// statements present in the body.
5595   void deduceClosureReturnType(sema::CapturingScopeInfo &CSI);
5596 
5597   /// ActOnStartOfLambdaDefinition - This is called just before we start
5598   /// parsing the body of a lambda; it analyzes the explicit captures and
5599   /// arguments, and sets up various data-structures for the body of the
5600   /// lambda.
5601   void ActOnStartOfLambdaDefinition(LambdaIntroducer &Intro,
5602                                     Declarator &ParamInfo, Scope *CurScope);
5603 
5604   /// ActOnLambdaError - If there is an error parsing a lambda, this callback
5605   /// is invoked to pop the information about the lambda.
5606   void ActOnLambdaError(SourceLocation StartLoc, Scope *CurScope,
5607                         bool IsInstantiation = false);
5608 
5609   /// ActOnLambdaExpr - This is called when the body of a lambda expression
5610   /// was successfully completed.
5611   ExprResult ActOnLambdaExpr(SourceLocation StartLoc, Stmt *Body,
5612                              Scope *CurScope);
5613 
5614   /// Does copying/destroying the captured variable have side effects?
5615   bool CaptureHasSideEffects(const sema::Capture &From);
5616 
5617   /// Diagnose if an explicit lambda capture is unused. Returns true if a
5618   /// diagnostic is emitted.
5619   bool DiagnoseUnusedLambdaCapture(SourceRange CaptureRange,
5620                                    const sema::Capture &From);
5621 
5622   /// Complete a lambda-expression having processed and attached the
5623   /// lambda body.
5624   ExprResult BuildLambdaExpr(SourceLocation StartLoc, SourceLocation EndLoc,
5625                              sema::LambdaScopeInfo *LSI);
5626 
5627   /// Get the return type to use for a lambda's conversion function(s) to
5628   /// function pointer type, given the type of the call operator.
5629   QualType
5630   getLambdaConversionFunctionResultType(const FunctionProtoType *CallOpType);
5631 
5632   /// Define the "body" of the conversion from a lambda object to a
5633   /// function pointer.
5634   ///
5635   /// This routine doesn't actually define a sensible body; rather, it fills
5636   /// in the initialization expression needed to copy the lambda object into
5637   /// the block, and IR generation actually generates the real body of the
5638   /// block pointer conversion.
5639   void DefineImplicitLambdaToFunctionPointerConversion(
5640          SourceLocation CurrentLoc, CXXConversionDecl *Conv);
5641 
5642   /// Define the "body" of the conversion from a lambda object to a
5643   /// block pointer.
5644   ///
5645   /// This routine doesn't actually define a sensible body; rather, it fills
5646   /// in the initialization expression needed to copy the lambda object into
5647   /// the block, and IR generation actually generates the real body of the
5648   /// block pointer conversion.
5649   void DefineImplicitLambdaToBlockPointerConversion(SourceLocation CurrentLoc,
5650                                                     CXXConversionDecl *Conv);
5651 
5652   ExprResult BuildBlockForLambdaConversion(SourceLocation CurrentLocation,
5653                                            SourceLocation ConvLocation,
5654                                            CXXConversionDecl *Conv,
5655                                            Expr *Src);
5656 
5657   // ParseObjCStringLiteral - Parse Objective-C string literals.
5658   ExprResult ParseObjCStringLiteral(SourceLocation *AtLocs,
5659                                     ArrayRef<Expr *> Strings);
5660 
5661   ExprResult BuildObjCStringLiteral(SourceLocation AtLoc, StringLiteral *S);
5662 
5663   /// BuildObjCNumericLiteral - builds an ObjCBoxedExpr AST node for the
5664   /// numeric literal expression. Type of the expression will be "NSNumber *"
5665   /// or "id" if NSNumber is unavailable.
5666   ExprResult BuildObjCNumericLiteral(SourceLocation AtLoc, Expr *Number);
5667   ExprResult ActOnObjCBoolLiteral(SourceLocation AtLoc, SourceLocation ValueLoc,
5668                                   bool Value);
5669   ExprResult BuildObjCArrayLiteral(SourceRange SR, MultiExprArg Elements);
5670 
5671   /// BuildObjCBoxedExpr - builds an ObjCBoxedExpr AST node for the
5672   /// '@' prefixed parenthesized expression. The type of the expression will
5673   /// either be "NSNumber *", "NSString *" or "NSValue *" depending on the type
5674   /// of ValueType, which is allowed to be a built-in numeric type, "char *",
5675   /// "const char *" or C structure with attribute 'objc_boxable'.
5676   ExprResult BuildObjCBoxedExpr(SourceRange SR, Expr *ValueExpr);
5677 
5678   ExprResult BuildObjCSubscriptExpression(SourceLocation RB, Expr *BaseExpr,
5679                                           Expr *IndexExpr,
5680                                           ObjCMethodDecl *getterMethod,
5681                                           ObjCMethodDecl *setterMethod);
5682 
5683   ExprResult BuildObjCDictionaryLiteral(SourceRange SR,
5684                                MutableArrayRef<ObjCDictionaryElement> Elements);
5685 
5686   ExprResult BuildObjCEncodeExpression(SourceLocation AtLoc,
5687                                   TypeSourceInfo *EncodedTypeInfo,
5688                                   SourceLocation RParenLoc);
5689   ExprResult BuildCXXMemberCallExpr(Expr *Exp, NamedDecl *FoundDecl,
5690                                     CXXConversionDecl *Method,
5691                                     bool HadMultipleCandidates);
5692 
5693   ExprResult ParseObjCEncodeExpression(SourceLocation AtLoc,
5694                                        SourceLocation EncodeLoc,
5695                                        SourceLocation LParenLoc,
5696                                        ParsedType Ty,
5697                                        SourceLocation RParenLoc);
5698 
5699   /// ParseObjCSelectorExpression - Build selector expression for \@selector
5700   ExprResult ParseObjCSelectorExpression(Selector Sel,
5701                                          SourceLocation AtLoc,
5702                                          SourceLocation SelLoc,
5703                                          SourceLocation LParenLoc,
5704                                          SourceLocation RParenLoc,
5705                                          bool WarnMultipleSelectors);
5706 
5707   /// ParseObjCProtocolExpression - Build protocol expression for \@protocol
5708   ExprResult ParseObjCProtocolExpression(IdentifierInfo * ProtocolName,
5709                                          SourceLocation AtLoc,
5710                                          SourceLocation ProtoLoc,
5711                                          SourceLocation LParenLoc,
5712                                          SourceLocation ProtoIdLoc,
5713                                          SourceLocation RParenLoc);
5714 
5715   //===--------------------------------------------------------------------===//
5716   // C++ Declarations
5717   //
5718   Decl *ActOnStartLinkageSpecification(Scope *S,
5719                                        SourceLocation ExternLoc,
5720                                        Expr *LangStr,
5721                                        SourceLocation LBraceLoc);
5722   Decl *ActOnFinishLinkageSpecification(Scope *S,
5723                                         Decl *LinkageSpec,
5724                                         SourceLocation RBraceLoc);
5725 
5726 
5727   //===--------------------------------------------------------------------===//
5728   // C++ Classes
5729   //
5730   CXXRecordDecl *getCurrentClass(Scope *S, const CXXScopeSpec *SS);
5731   bool isCurrentClassName(const IdentifierInfo &II, Scope *S,
5732                           const CXXScopeSpec *SS = nullptr);
5733   bool isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS);
5734 
5735   bool ActOnAccessSpecifier(AccessSpecifier Access, SourceLocation ASLoc,
5736                             SourceLocation ColonLoc,
5737                             const ParsedAttributesView &Attrs);
5738 
5739   NamedDecl *ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS,
5740                                  Declarator &D,
5741                                  MultiTemplateParamsArg TemplateParameterLists,
5742                                  Expr *BitfieldWidth, const VirtSpecifiers &VS,
5743                                  InClassInitStyle InitStyle);
5744 
5745   void ActOnStartCXXInClassMemberInitializer();
5746   void ActOnFinishCXXInClassMemberInitializer(Decl *VarDecl,
5747                                               SourceLocation EqualLoc,
5748                                               Expr *Init);
5749 
5750   MemInitResult ActOnMemInitializer(Decl *ConstructorD,
5751                                     Scope *S,
5752                                     CXXScopeSpec &SS,
5753                                     IdentifierInfo *MemberOrBase,
5754                                     ParsedType TemplateTypeTy,
5755                                     const DeclSpec &DS,
5756                                     SourceLocation IdLoc,
5757                                     SourceLocation LParenLoc,
5758                                     ArrayRef<Expr *> Args,
5759                                     SourceLocation RParenLoc,
5760                                     SourceLocation EllipsisLoc);
5761 
5762   MemInitResult ActOnMemInitializer(Decl *ConstructorD,
5763                                     Scope *S,
5764                                     CXXScopeSpec &SS,
5765                                     IdentifierInfo *MemberOrBase,
5766                                     ParsedType TemplateTypeTy,
5767                                     const DeclSpec &DS,
5768                                     SourceLocation IdLoc,
5769                                     Expr *InitList,
5770                                     SourceLocation EllipsisLoc);
5771 
5772   MemInitResult BuildMemInitializer(Decl *ConstructorD,
5773                                     Scope *S,
5774                                     CXXScopeSpec &SS,
5775                                     IdentifierInfo *MemberOrBase,
5776                                     ParsedType TemplateTypeTy,
5777                                     const DeclSpec &DS,
5778                                     SourceLocation IdLoc,
5779                                     Expr *Init,
5780                                     SourceLocation EllipsisLoc);
5781 
5782   MemInitResult BuildMemberInitializer(ValueDecl *Member,
5783                                        Expr *Init,
5784                                        SourceLocation IdLoc);
5785 
5786   MemInitResult BuildBaseInitializer(QualType BaseType,
5787                                      TypeSourceInfo *BaseTInfo,
5788                                      Expr *Init,
5789                                      CXXRecordDecl *ClassDecl,
5790                                      SourceLocation EllipsisLoc);
5791 
5792   MemInitResult BuildDelegatingInitializer(TypeSourceInfo *TInfo,
5793                                            Expr *Init,
5794                                            CXXRecordDecl *ClassDecl);
5795 
5796   bool SetDelegatingInitializer(CXXConstructorDecl *Constructor,
5797                                 CXXCtorInitializer *Initializer);
5798 
5799   bool SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
5800                            ArrayRef<CXXCtorInitializer *> Initializers = None);
5801 
5802   void SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation);
5803 
5804 
5805   /// MarkBaseAndMemberDestructorsReferenced - Given a record decl,
5806   /// mark all the non-trivial destructors of its members and bases as
5807   /// referenced.
5808   void MarkBaseAndMemberDestructorsReferenced(SourceLocation Loc,
5809                                               CXXRecordDecl *Record);
5810 
5811   /// The list of classes whose vtables have been used within
5812   /// this translation unit, and the source locations at which the
5813   /// first use occurred.
5814   typedef std::pair<CXXRecordDecl*, SourceLocation> VTableUse;
5815 
5816   /// The list of vtables that are required but have not yet been
5817   /// materialized.
5818   SmallVector<VTableUse, 16> VTableUses;
5819 
5820   /// The set of classes whose vtables have been used within
5821   /// this translation unit, and a bit that will be true if the vtable is
5822   /// required to be emitted (otherwise, it should be emitted only if needed
5823   /// by code generation).
5824   llvm::DenseMap<CXXRecordDecl *, bool> VTablesUsed;
5825 
5826   /// Load any externally-stored vtable uses.
5827   void LoadExternalVTableUses();
5828 
5829   /// Note that the vtable for the given class was used at the
5830   /// given location.
5831   void MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
5832                       bool DefinitionRequired = false);
5833 
5834   /// Mark the exception specifications of all virtual member functions
5835   /// in the given class as needed.
5836   void MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
5837                                              const CXXRecordDecl *RD);
5838 
5839   /// MarkVirtualMembersReferenced - Will mark all members of the given
5840   /// CXXRecordDecl referenced.
5841   void MarkVirtualMembersReferenced(SourceLocation Loc,
5842                                     const CXXRecordDecl *RD);
5843 
5844   /// Define all of the vtables that have been used in this
5845   /// translation unit and reference any virtual members used by those
5846   /// vtables.
5847   ///
5848   /// \returns true if any work was done, false otherwise.
5849   bool DefineUsedVTables();
5850 
5851   void AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl);
5852 
5853   void ActOnMemInitializers(Decl *ConstructorDecl,
5854                             SourceLocation ColonLoc,
5855                             ArrayRef<CXXCtorInitializer*> MemInits,
5856                             bool AnyErrors);
5857 
5858   /// Check class-level dllimport/dllexport attribute. The caller must
5859   /// ensure that referenceDLLExportedClassMethods is called some point later
5860   /// when all outer classes of Class are complete.
5861   void checkClassLevelDLLAttribute(CXXRecordDecl *Class);
5862   void checkClassLevelCodeSegAttribute(CXXRecordDecl *Class);
5863 
5864   void referenceDLLExportedClassMethods();
5865 
5866   void propagateDLLAttrToBaseClassTemplate(
5867       CXXRecordDecl *Class, Attr *ClassAttr,
5868       ClassTemplateSpecializationDecl *BaseTemplateSpec,
5869       SourceLocation BaseLoc);
5870 
5871   void CheckCompletedCXXClass(CXXRecordDecl *Record);
5872 
5873   /// Check that the C++ class annoated with "trivial_abi" satisfies all the
5874   /// conditions that are needed for the attribute to have an effect.
5875   void checkIllFormedTrivialABIStruct(CXXRecordDecl &RD);
5876 
5877   void ActOnFinishCXXMemberSpecification(Scope *S, SourceLocation RLoc,
5878                                          Decl *TagDecl, SourceLocation LBrac,
5879                                          SourceLocation RBrac,
5880                                          const ParsedAttributesView &AttrList);
5881   void ActOnFinishCXXMemberDecls();
5882   void ActOnFinishCXXNonNestedClass(Decl *D);
5883 
5884   void ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param);
5885   unsigned ActOnReenterTemplateScope(Scope *S, Decl *Template);
5886   void ActOnStartDelayedMemberDeclarations(Scope *S, Decl *Record);
5887   void ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *Method);
5888   void ActOnDelayedCXXMethodParameter(Scope *S, Decl *Param);
5889   void ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *Record);
5890   void ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *Method);
5891   void ActOnFinishDelayedMemberInitializers(Decl *Record);
5892   void MarkAsLateParsedTemplate(FunctionDecl *FD, Decl *FnD,
5893                                 CachedTokens &Toks);
5894   void UnmarkAsLateParsedTemplate(FunctionDecl *FD);
5895   bool IsInsideALocalClassWithinATemplateFunction();
5896 
5897   Decl *ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
5898                                      Expr *AssertExpr,
5899                                      Expr *AssertMessageExpr,
5900                                      SourceLocation RParenLoc);
5901   Decl *BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
5902                                      Expr *AssertExpr,
5903                                      StringLiteral *AssertMessageExpr,
5904                                      SourceLocation RParenLoc,
5905                                      bool Failed);
5906 
5907   FriendDecl *CheckFriendTypeDecl(SourceLocation LocStart,
5908                                   SourceLocation FriendLoc,
5909                                   TypeSourceInfo *TSInfo);
5910   Decl *ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
5911                             MultiTemplateParamsArg TemplateParams);
5912   NamedDecl *ActOnFriendFunctionDecl(Scope *S, Declarator &D,
5913                                      MultiTemplateParamsArg TemplateParams);
5914 
5915   QualType CheckConstructorDeclarator(Declarator &D, QualType R,
5916                                       StorageClass& SC);
5917   void CheckConstructor(CXXConstructorDecl *Constructor);
5918   QualType CheckDestructorDeclarator(Declarator &D, QualType R,
5919                                      StorageClass& SC);
5920   bool CheckDestructor(CXXDestructorDecl *Destructor);
5921   void CheckConversionDeclarator(Declarator &D, QualType &R,
5922                                  StorageClass& SC);
5923   Decl *ActOnConversionDeclarator(CXXConversionDecl *Conversion);
5924   void CheckDeductionGuideDeclarator(Declarator &D, QualType &R,
5925                                      StorageClass &SC);
5926   void CheckDeductionGuideTemplate(FunctionTemplateDecl *TD);
5927 
5928   void CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD);
5929   void CheckExplicitlyDefaultedMemberExceptionSpec(CXXMethodDecl *MD,
5930                                                    const FunctionProtoType *T);
5931   void CheckDelayedMemberExceptionSpecs();
5932 
5933   //===--------------------------------------------------------------------===//
5934   // C++ Derived Classes
5935   //
5936 
5937   /// ActOnBaseSpecifier - Parsed a base specifier
5938   CXXBaseSpecifier *CheckBaseSpecifier(CXXRecordDecl *Class,
5939                                        SourceRange SpecifierRange,
5940                                        bool Virtual, AccessSpecifier Access,
5941                                        TypeSourceInfo *TInfo,
5942                                        SourceLocation EllipsisLoc);
5943 
5944   BaseResult ActOnBaseSpecifier(Decl *classdecl,
5945                                 SourceRange SpecifierRange,
5946                                 ParsedAttributes &Attrs,
5947                                 bool Virtual, AccessSpecifier Access,
5948                                 ParsedType basetype,
5949                                 SourceLocation BaseLoc,
5950                                 SourceLocation EllipsisLoc);
5951 
5952   bool AttachBaseSpecifiers(CXXRecordDecl *Class,
5953                             MutableArrayRef<CXXBaseSpecifier *> Bases);
5954   void ActOnBaseSpecifiers(Decl *ClassDecl,
5955                            MutableArrayRef<CXXBaseSpecifier *> Bases);
5956 
5957   bool IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base);
5958   bool IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base,
5959                      CXXBasePaths &Paths);
5960 
5961   // FIXME: I don't like this name.
5962   void BuildBasePathArray(const CXXBasePaths &Paths, CXXCastPath &BasePath);
5963 
5964   bool CheckDerivedToBaseConversion(QualType Derived, QualType Base,
5965                                     SourceLocation Loc, SourceRange Range,
5966                                     CXXCastPath *BasePath = nullptr,
5967                                     bool IgnoreAccess = false);
5968   bool CheckDerivedToBaseConversion(QualType Derived, QualType Base,
5969                                     unsigned InaccessibleBaseID,
5970                                     unsigned AmbigiousBaseConvID,
5971                                     SourceLocation Loc, SourceRange Range,
5972                                     DeclarationName Name,
5973                                     CXXCastPath *BasePath,
5974                                     bool IgnoreAccess = false);
5975 
5976   std::string getAmbiguousPathsDisplayString(CXXBasePaths &Paths);
5977 
5978   bool CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
5979                                          const CXXMethodDecl *Old);
5980 
5981   /// CheckOverridingFunctionReturnType - Checks whether the return types are
5982   /// covariant, according to C++ [class.virtual]p5.
5983   bool CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
5984                                          const CXXMethodDecl *Old);
5985 
5986   /// CheckOverridingFunctionExceptionSpec - Checks whether the exception
5987   /// spec is a subset of base spec.
5988   bool CheckOverridingFunctionExceptionSpec(const CXXMethodDecl *New,
5989                                             const CXXMethodDecl *Old);
5990 
5991   bool CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange);
5992 
5993   /// CheckOverrideControl - Check C++11 override control semantics.
5994   void CheckOverrideControl(NamedDecl *D);
5995 
5996   /// DiagnoseAbsenceOfOverrideControl - Diagnose if 'override' keyword was
5997   /// not used in the declaration of an overriding method.
5998   void DiagnoseAbsenceOfOverrideControl(NamedDecl *D);
5999 
6000   /// CheckForFunctionMarkedFinal - Checks whether a virtual member function
6001   /// overrides a virtual member function marked 'final', according to
6002   /// C++11 [class.virtual]p4.
6003   bool CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
6004                                               const CXXMethodDecl *Old);
6005 
6006 
6007   //===--------------------------------------------------------------------===//
6008   // C++ Access Control
6009   //
6010 
6011   enum AccessResult {
6012     AR_accessible,
6013     AR_inaccessible,
6014     AR_dependent,
6015     AR_delayed
6016   };
6017 
6018   bool SetMemberAccessSpecifier(NamedDecl *MemberDecl,
6019                                 NamedDecl *PrevMemberDecl,
6020                                 AccessSpecifier LexicalAS);
6021 
6022   AccessResult CheckUnresolvedMemberAccess(UnresolvedMemberExpr *E,
6023                                            DeclAccessPair FoundDecl);
6024   AccessResult CheckUnresolvedLookupAccess(UnresolvedLookupExpr *E,
6025                                            DeclAccessPair FoundDecl);
6026   AccessResult CheckAllocationAccess(SourceLocation OperatorLoc,
6027                                      SourceRange PlacementRange,
6028                                      CXXRecordDecl *NamingClass,
6029                                      DeclAccessPair FoundDecl,
6030                                      bool Diagnose = true);
6031   AccessResult CheckConstructorAccess(SourceLocation Loc,
6032                                       CXXConstructorDecl *D,
6033                                       DeclAccessPair FoundDecl,
6034                                       const InitializedEntity &Entity,
6035                                       bool IsCopyBindingRefToTemp = false);
6036   AccessResult CheckConstructorAccess(SourceLocation Loc,
6037                                       CXXConstructorDecl *D,
6038                                       DeclAccessPair FoundDecl,
6039                                       const InitializedEntity &Entity,
6040                                       const PartialDiagnostic &PDiag);
6041   AccessResult CheckDestructorAccess(SourceLocation Loc,
6042                                      CXXDestructorDecl *Dtor,
6043                                      const PartialDiagnostic &PDiag,
6044                                      QualType objectType = QualType());
6045   AccessResult CheckFriendAccess(NamedDecl *D);
6046   AccessResult CheckMemberAccess(SourceLocation UseLoc,
6047                                  CXXRecordDecl *NamingClass,
6048                                  DeclAccessPair Found);
6049   AccessResult CheckMemberOperatorAccess(SourceLocation Loc,
6050                                          Expr *ObjectExpr,
6051                                          Expr *ArgExpr,
6052                                          DeclAccessPair FoundDecl);
6053   AccessResult CheckAddressOfMemberAccess(Expr *OvlExpr,
6054                                           DeclAccessPair FoundDecl);
6055   AccessResult CheckBaseClassAccess(SourceLocation AccessLoc,
6056                                     QualType Base, QualType Derived,
6057                                     const CXXBasePath &Path,
6058                                     unsigned DiagID,
6059                                     bool ForceCheck = false,
6060                                     bool ForceUnprivileged = false);
6061   void CheckLookupAccess(const LookupResult &R);
6062   bool IsSimplyAccessible(NamedDecl *decl, DeclContext *Ctx);
6063   bool isSpecialMemberAccessibleForDeletion(CXXMethodDecl *decl,
6064                                             AccessSpecifier access,
6065                                             QualType objectType);
6066 
6067   void HandleDependentAccessCheck(const DependentDiagnostic &DD,
6068                          const MultiLevelTemplateArgumentList &TemplateArgs);
6069   void PerformDependentDiagnostics(const DeclContext *Pattern,
6070                         const MultiLevelTemplateArgumentList &TemplateArgs);
6071 
6072   void HandleDelayedAccessCheck(sema::DelayedDiagnostic &DD, Decl *Ctx);
6073 
6074   /// When true, access checking violations are treated as SFINAE
6075   /// failures rather than hard errors.
6076   bool AccessCheckingSFINAE;
6077 
6078   enum AbstractDiagSelID {
6079     AbstractNone = -1,
6080     AbstractReturnType,
6081     AbstractParamType,
6082     AbstractVariableType,
6083     AbstractFieldType,
6084     AbstractIvarType,
6085     AbstractSynthesizedIvarType,
6086     AbstractArrayType
6087   };
6088 
6089   bool isAbstractType(SourceLocation Loc, QualType T);
6090   bool RequireNonAbstractType(SourceLocation Loc, QualType T,
6091                               TypeDiagnoser &Diagnoser);
6092   template <typename... Ts>
RequireNonAbstractType(SourceLocation Loc,QualType T,unsigned DiagID,const Ts &...Args)6093   bool RequireNonAbstractType(SourceLocation Loc, QualType T, unsigned DiagID,
6094                               const Ts &...Args) {
6095     BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
6096     return RequireNonAbstractType(Loc, T, Diagnoser);
6097   }
6098 
6099   void DiagnoseAbstractType(const CXXRecordDecl *RD);
6100 
6101   //===--------------------------------------------------------------------===//
6102   // C++ Overloaded Operators [C++ 13.5]
6103   //
6104 
6105   bool CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl);
6106 
6107   bool CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl);
6108 
6109   //===--------------------------------------------------------------------===//
6110   // C++ Templates [C++ 14]
6111   //
6112   void FilterAcceptableTemplateNames(LookupResult &R,
6113                                      bool AllowFunctionTemplates = true);
6114   bool hasAnyAcceptableTemplateNames(LookupResult &R,
6115                                      bool AllowFunctionTemplates = true);
6116 
6117   bool LookupTemplateName(LookupResult &R, Scope *S, CXXScopeSpec &SS,
6118                           QualType ObjectType, bool EnteringContext,
6119                           bool &MemberOfUnknownSpecialization,
6120                           SourceLocation TemplateKWLoc = SourceLocation());
6121 
6122   TemplateNameKind isTemplateName(Scope *S,
6123                                   CXXScopeSpec &SS,
6124                                   bool hasTemplateKeyword,
6125                                   const UnqualifiedId &Name,
6126                                   ParsedType ObjectType,
6127                                   bool EnteringContext,
6128                                   TemplateTy &Template,
6129                                   bool &MemberOfUnknownSpecialization);
6130 
6131   /// Determine whether a particular identifier might be the name in a C++1z
6132   /// deduction-guide declaration.
6133   bool isDeductionGuideName(Scope *S, const IdentifierInfo &Name,
6134                             SourceLocation NameLoc,
6135                             ParsedTemplateTy *Template = nullptr);
6136 
6137   bool DiagnoseUnknownTemplateName(const IdentifierInfo &II,
6138                                    SourceLocation IILoc,
6139                                    Scope *S,
6140                                    const CXXScopeSpec *SS,
6141                                    TemplateTy &SuggestedTemplate,
6142                                    TemplateNameKind &SuggestedKind);
6143 
6144   bool DiagnoseUninstantiableTemplate(SourceLocation PointOfInstantiation,
6145                                       NamedDecl *Instantiation,
6146                                       bool InstantiatedFromMember,
6147                                       const NamedDecl *Pattern,
6148                                       const NamedDecl *PatternDef,
6149                                       TemplateSpecializationKind TSK,
6150                                       bool Complain = true);
6151 
6152   void DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl);
6153   TemplateDecl *AdjustDeclIfTemplate(Decl *&Decl);
6154 
6155   NamedDecl *ActOnTypeParameter(Scope *S, bool Typename,
6156                            SourceLocation EllipsisLoc,
6157                            SourceLocation KeyLoc,
6158                            IdentifierInfo *ParamName,
6159                            SourceLocation ParamNameLoc,
6160                            unsigned Depth, unsigned Position,
6161                            SourceLocation EqualLoc,
6162                            ParsedType DefaultArg);
6163 
6164   QualType CheckNonTypeTemplateParameterType(TypeSourceInfo *&TSI,
6165                                              SourceLocation Loc);
6166   QualType CheckNonTypeTemplateParameterType(QualType T, SourceLocation Loc);
6167 
6168   NamedDecl *ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
6169                                       unsigned Depth,
6170                                       unsigned Position,
6171                                       SourceLocation EqualLoc,
6172                                       Expr *DefaultArg);
6173   NamedDecl *ActOnTemplateTemplateParameter(Scope *S,
6174                                        SourceLocation TmpLoc,
6175                                        TemplateParameterList *Params,
6176                                        SourceLocation EllipsisLoc,
6177                                        IdentifierInfo *ParamName,
6178                                        SourceLocation ParamNameLoc,
6179                                        unsigned Depth,
6180                                        unsigned Position,
6181                                        SourceLocation EqualLoc,
6182                                        ParsedTemplateArgument DefaultArg);
6183 
6184   TemplateParameterList *
6185   ActOnTemplateParameterList(unsigned Depth,
6186                              SourceLocation ExportLoc,
6187                              SourceLocation TemplateLoc,
6188                              SourceLocation LAngleLoc,
6189                              ArrayRef<NamedDecl *> Params,
6190                              SourceLocation RAngleLoc,
6191                              Expr *RequiresClause);
6192 
6193   /// The context in which we are checking a template parameter list.
6194   enum TemplateParamListContext {
6195     TPC_ClassTemplate,
6196     TPC_VarTemplate,
6197     TPC_FunctionTemplate,
6198     TPC_ClassTemplateMember,
6199     TPC_FriendClassTemplate,
6200     TPC_FriendFunctionTemplate,
6201     TPC_FriendFunctionTemplateDefinition,
6202     TPC_TypeAliasTemplate
6203   };
6204 
6205   bool CheckTemplateParameterList(TemplateParameterList *NewParams,
6206                                   TemplateParameterList *OldParams,
6207                                   TemplateParamListContext TPC);
6208   TemplateParameterList *MatchTemplateParametersToScopeSpecifier(
6209       SourceLocation DeclStartLoc, SourceLocation DeclLoc,
6210       const CXXScopeSpec &SS, TemplateIdAnnotation *TemplateId,
6211       ArrayRef<TemplateParameterList *> ParamLists,
6212       bool IsFriend, bool &IsMemberSpecialization, bool &Invalid);
6213 
6214   DeclResult CheckClassTemplate(
6215       Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc,
6216       CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc,
6217       const ParsedAttributesView &Attr, TemplateParameterList *TemplateParams,
6218       AccessSpecifier AS, SourceLocation ModulePrivateLoc,
6219       SourceLocation FriendLoc, unsigned NumOuterTemplateParamLists,
6220       TemplateParameterList **OuterTemplateParamLists,
6221       SkipBodyInfo *SkipBody = nullptr);
6222 
6223   TemplateArgumentLoc getTrivialTemplateArgumentLoc(const TemplateArgument &Arg,
6224                                                     QualType NTTPType,
6225                                                     SourceLocation Loc);
6226 
6227   void translateTemplateArguments(const ASTTemplateArgsPtr &In,
6228                                   TemplateArgumentListInfo &Out);
6229 
6230   ParsedTemplateArgument ActOnTemplateTypeArgument(TypeResult ParsedType);
6231 
6232   void NoteAllFoundTemplates(TemplateName Name);
6233 
6234   QualType CheckTemplateIdType(TemplateName Template,
6235                                SourceLocation TemplateLoc,
6236                               TemplateArgumentListInfo &TemplateArgs);
6237 
6238   TypeResult
6239   ActOnTemplateIdType(CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
6240                       TemplateTy Template, IdentifierInfo *TemplateII,
6241                       SourceLocation TemplateIILoc,
6242                       SourceLocation LAngleLoc,
6243                       ASTTemplateArgsPtr TemplateArgs,
6244                       SourceLocation RAngleLoc,
6245                       bool IsCtorOrDtorName = false,
6246                       bool IsClassName = false);
6247 
6248   /// Parsed an elaborated-type-specifier that refers to a template-id,
6249   /// such as \c class T::template apply<U>.
6250   TypeResult ActOnTagTemplateIdType(TagUseKind TUK,
6251                                     TypeSpecifierType TagSpec,
6252                                     SourceLocation TagLoc,
6253                                     CXXScopeSpec &SS,
6254                                     SourceLocation TemplateKWLoc,
6255                                     TemplateTy TemplateD,
6256                                     SourceLocation TemplateLoc,
6257                                     SourceLocation LAngleLoc,
6258                                     ASTTemplateArgsPtr TemplateArgsIn,
6259                                     SourceLocation RAngleLoc);
6260 
6261   DeclResult ActOnVarTemplateSpecialization(
6262       Scope *S, Declarator &D, TypeSourceInfo *DI,
6263       SourceLocation TemplateKWLoc, TemplateParameterList *TemplateParams,
6264       StorageClass SC, bool IsPartialSpecialization);
6265 
6266   DeclResult CheckVarTemplateId(VarTemplateDecl *Template,
6267                                 SourceLocation TemplateLoc,
6268                                 SourceLocation TemplateNameLoc,
6269                                 const TemplateArgumentListInfo &TemplateArgs);
6270 
6271   ExprResult CheckVarTemplateId(const CXXScopeSpec &SS,
6272                                 const DeclarationNameInfo &NameInfo,
6273                                 VarTemplateDecl *Template,
6274                                 SourceLocation TemplateLoc,
6275                                 const TemplateArgumentListInfo *TemplateArgs);
6276 
6277   void diagnoseMissingTemplateArguments(TemplateName Name, SourceLocation Loc);
6278 
6279   ExprResult BuildTemplateIdExpr(const CXXScopeSpec &SS,
6280                                  SourceLocation TemplateKWLoc,
6281                                  LookupResult &R,
6282                                  bool RequiresADL,
6283                                const TemplateArgumentListInfo *TemplateArgs);
6284 
6285   ExprResult BuildQualifiedTemplateIdExpr(CXXScopeSpec &SS,
6286                                           SourceLocation TemplateKWLoc,
6287                                const DeclarationNameInfo &NameInfo,
6288                                const TemplateArgumentListInfo *TemplateArgs);
6289 
6290   TemplateNameKind ActOnDependentTemplateName(
6291       Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
6292       const UnqualifiedId &Name, ParsedType ObjectType, bool EnteringContext,
6293       TemplateTy &Template, bool AllowInjectedClassName = false);
6294 
6295   DeclResult ActOnClassTemplateSpecialization(
6296       Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc,
6297       SourceLocation ModulePrivateLoc, TemplateIdAnnotation &TemplateId,
6298       const ParsedAttributesView &Attr,
6299       MultiTemplateParamsArg TemplateParameterLists,
6300       SkipBodyInfo *SkipBody = nullptr);
6301 
6302   bool CheckTemplatePartialSpecializationArgs(SourceLocation Loc,
6303                                               TemplateDecl *PrimaryTemplate,
6304                                               unsigned NumExplicitArgs,
6305                                               ArrayRef<TemplateArgument> Args);
6306   void CheckTemplatePartialSpecialization(
6307       ClassTemplatePartialSpecializationDecl *Partial);
6308   void CheckTemplatePartialSpecialization(
6309       VarTemplatePartialSpecializationDecl *Partial);
6310 
6311   Decl *ActOnTemplateDeclarator(Scope *S,
6312                                 MultiTemplateParamsArg TemplateParameterLists,
6313                                 Declarator &D);
6314 
6315   bool
6316   CheckSpecializationInstantiationRedecl(SourceLocation NewLoc,
6317                                          TemplateSpecializationKind NewTSK,
6318                                          NamedDecl *PrevDecl,
6319                                          TemplateSpecializationKind PrevTSK,
6320                                          SourceLocation PrevPtOfInstantiation,
6321                                          bool &SuppressNew);
6322 
6323   bool CheckDependentFunctionTemplateSpecialization(FunctionDecl *FD,
6324                     const TemplateArgumentListInfo &ExplicitTemplateArgs,
6325                                                     LookupResult &Previous);
6326 
6327   bool CheckFunctionTemplateSpecialization(FunctionDecl *FD,
6328                          TemplateArgumentListInfo *ExplicitTemplateArgs,
6329                                            LookupResult &Previous);
6330   bool CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous);
6331   void CompleteMemberSpecialization(NamedDecl *Member, LookupResult &Previous);
6332 
6333   DeclResult ActOnExplicitInstantiation(
6334       Scope *S, SourceLocation ExternLoc, SourceLocation TemplateLoc,
6335       unsigned TagSpec, SourceLocation KWLoc, const CXXScopeSpec &SS,
6336       TemplateTy Template, SourceLocation TemplateNameLoc,
6337       SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgs,
6338       SourceLocation RAngleLoc, const ParsedAttributesView &Attr);
6339 
6340   DeclResult ActOnExplicitInstantiation(Scope *S, SourceLocation ExternLoc,
6341                                         SourceLocation TemplateLoc,
6342                                         unsigned TagSpec, SourceLocation KWLoc,
6343                                         CXXScopeSpec &SS, IdentifierInfo *Name,
6344                                         SourceLocation NameLoc,
6345                                         const ParsedAttributesView &Attr);
6346 
6347   DeclResult ActOnExplicitInstantiation(Scope *S,
6348                                         SourceLocation ExternLoc,
6349                                         SourceLocation TemplateLoc,
6350                                         Declarator &D);
6351 
6352   TemplateArgumentLoc
6353   SubstDefaultTemplateArgumentIfAvailable(TemplateDecl *Template,
6354                                           SourceLocation TemplateLoc,
6355                                           SourceLocation RAngleLoc,
6356                                           Decl *Param,
6357                                           SmallVectorImpl<TemplateArgument>
6358                                             &Converted,
6359                                           bool &HasDefaultArg);
6360 
6361   /// Specifies the context in which a particular template
6362   /// argument is being checked.
6363   enum CheckTemplateArgumentKind {
6364     /// The template argument was specified in the code or was
6365     /// instantiated with some deduced template arguments.
6366     CTAK_Specified,
6367 
6368     /// The template argument was deduced via template argument
6369     /// deduction.
6370     CTAK_Deduced,
6371 
6372     /// The template argument was deduced from an array bound
6373     /// via template argument deduction.
6374     CTAK_DeducedFromArrayBound
6375   };
6376 
6377   bool CheckTemplateArgument(NamedDecl *Param,
6378                              TemplateArgumentLoc &Arg,
6379                              NamedDecl *Template,
6380                              SourceLocation TemplateLoc,
6381                              SourceLocation RAngleLoc,
6382                              unsigned ArgumentPackIndex,
6383                            SmallVectorImpl<TemplateArgument> &Converted,
6384                              CheckTemplateArgumentKind CTAK = CTAK_Specified);
6385 
6386   /// Check that the given template arguments can be be provided to
6387   /// the given template, converting the arguments along the way.
6388   ///
6389   /// \param Template The template to which the template arguments are being
6390   /// provided.
6391   ///
6392   /// \param TemplateLoc The location of the template name in the source.
6393   ///
6394   /// \param TemplateArgs The list of template arguments. If the template is
6395   /// a template template parameter, this function may extend the set of
6396   /// template arguments to also include substituted, defaulted template
6397   /// arguments.
6398   ///
6399   /// \param PartialTemplateArgs True if the list of template arguments is
6400   /// intentionally partial, e.g., because we're checking just the initial
6401   /// set of template arguments.
6402   ///
6403   /// \param Converted Will receive the converted, canonicalized template
6404   /// arguments.
6405   ///
6406   /// \param UpdateArgsWithConversions If \c true, update \p TemplateArgs to
6407   /// contain the converted forms of the template arguments as written.
6408   /// Otherwise, \p TemplateArgs will not be modified.
6409   ///
6410   /// \returns true if an error occurred, false otherwise.
6411   bool CheckTemplateArgumentList(TemplateDecl *Template,
6412                                  SourceLocation TemplateLoc,
6413                                  TemplateArgumentListInfo &TemplateArgs,
6414                                  bool PartialTemplateArgs,
6415                                  SmallVectorImpl<TemplateArgument> &Converted,
6416                                  bool UpdateArgsWithConversions = true);
6417 
6418   bool CheckTemplateTypeArgument(TemplateTypeParmDecl *Param,
6419                                  TemplateArgumentLoc &Arg,
6420                            SmallVectorImpl<TemplateArgument> &Converted);
6421 
6422   bool CheckTemplateArgument(TemplateTypeParmDecl *Param,
6423                              TypeSourceInfo *Arg);
6424   ExprResult CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
6425                                    QualType InstantiatedParamType, Expr *Arg,
6426                                    TemplateArgument &Converted,
6427                                CheckTemplateArgumentKind CTAK = CTAK_Specified);
6428   bool CheckTemplateTemplateArgument(TemplateParameterList *Params,
6429                                      TemplateArgumentLoc &Arg);
6430 
6431   ExprResult
6432   BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg,
6433                                           QualType ParamType,
6434                                           SourceLocation Loc);
6435   ExprResult
6436   BuildExpressionFromIntegralTemplateArgument(const TemplateArgument &Arg,
6437                                               SourceLocation Loc);
6438 
6439   /// Enumeration describing how template parameter lists are compared
6440   /// for equality.
6441   enum TemplateParameterListEqualKind {
6442     /// We are matching the template parameter lists of two templates
6443     /// that might be redeclarations.
6444     ///
6445     /// \code
6446     /// template<typename T> struct X;
6447     /// template<typename T> struct X;
6448     /// \endcode
6449     TPL_TemplateMatch,
6450 
6451     /// We are matching the template parameter lists of two template
6452     /// template parameters as part of matching the template parameter lists
6453     /// of two templates that might be redeclarations.
6454     ///
6455     /// \code
6456     /// template<template<int I> class TT> struct X;
6457     /// template<template<int Value> class Other> struct X;
6458     /// \endcode
6459     TPL_TemplateTemplateParmMatch,
6460 
6461     /// We are matching the template parameter lists of a template
6462     /// template argument against the template parameter lists of a template
6463     /// template parameter.
6464     ///
6465     /// \code
6466     /// template<template<int Value> class Metafun> struct X;
6467     /// template<int Value> struct integer_c;
6468     /// X<integer_c> xic;
6469     /// \endcode
6470     TPL_TemplateTemplateArgumentMatch
6471   };
6472 
6473   bool TemplateParameterListsAreEqual(TemplateParameterList *New,
6474                                       TemplateParameterList *Old,
6475                                       bool Complain,
6476                                       TemplateParameterListEqualKind Kind,
6477                                       SourceLocation TemplateArgLoc
6478                                         = SourceLocation());
6479 
6480   bool CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams);
6481 
6482   /// Called when the parser has parsed a C++ typename
6483   /// specifier, e.g., "typename T::type".
6484   ///
6485   /// \param S The scope in which this typename type occurs.
6486   /// \param TypenameLoc the location of the 'typename' keyword
6487   /// \param SS the nested-name-specifier following the typename (e.g., 'T::').
6488   /// \param II the identifier we're retrieving (e.g., 'type' in the example).
6489   /// \param IdLoc the location of the identifier.
6490   TypeResult
6491   ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
6492                     const CXXScopeSpec &SS, const IdentifierInfo &II,
6493                     SourceLocation IdLoc);
6494 
6495   /// Called when the parser has parsed a C++ typename
6496   /// specifier that ends in a template-id, e.g.,
6497   /// "typename MetaFun::template apply<T1, T2>".
6498   ///
6499   /// \param S The scope in which this typename type occurs.
6500   /// \param TypenameLoc the location of the 'typename' keyword
6501   /// \param SS the nested-name-specifier following the typename (e.g., 'T::').
6502   /// \param TemplateLoc the location of the 'template' keyword, if any.
6503   /// \param TemplateName The template name.
6504   /// \param TemplateII The identifier used to name the template.
6505   /// \param TemplateIILoc The location of the template name.
6506   /// \param LAngleLoc The location of the opening angle bracket  ('<').
6507   /// \param TemplateArgs The template arguments.
6508   /// \param RAngleLoc The location of the closing angle bracket  ('>').
6509   TypeResult
6510   ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
6511                     const CXXScopeSpec &SS,
6512                     SourceLocation TemplateLoc,
6513                     TemplateTy TemplateName,
6514                     IdentifierInfo *TemplateII,
6515                     SourceLocation TemplateIILoc,
6516                     SourceLocation LAngleLoc,
6517                     ASTTemplateArgsPtr TemplateArgs,
6518                     SourceLocation RAngleLoc);
6519 
6520   QualType CheckTypenameType(ElaboratedTypeKeyword Keyword,
6521                              SourceLocation KeywordLoc,
6522                              NestedNameSpecifierLoc QualifierLoc,
6523                              const IdentifierInfo &II,
6524                              SourceLocation IILoc);
6525 
6526   TypeSourceInfo *RebuildTypeInCurrentInstantiation(TypeSourceInfo *T,
6527                                                     SourceLocation Loc,
6528                                                     DeclarationName Name);
6529   bool RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS);
6530 
6531   ExprResult RebuildExprInCurrentInstantiation(Expr *E);
6532   bool RebuildTemplateParamsInCurrentInstantiation(
6533                                                 TemplateParameterList *Params);
6534 
6535   std::string
6536   getTemplateArgumentBindingsText(const TemplateParameterList *Params,
6537                                   const TemplateArgumentList &Args);
6538 
6539   std::string
6540   getTemplateArgumentBindingsText(const TemplateParameterList *Params,
6541                                   const TemplateArgument *Args,
6542                                   unsigned NumArgs);
6543 
6544   //===--------------------------------------------------------------------===//
6545   // C++ Variadic Templates (C++0x [temp.variadic])
6546   //===--------------------------------------------------------------------===//
6547 
6548   /// Determine whether an unexpanded parameter pack might be permitted in this
6549   /// location. Useful for error recovery.
6550   bool isUnexpandedParameterPackPermitted();
6551 
6552   /// The context in which an unexpanded parameter pack is
6553   /// being diagnosed.
6554   ///
6555   /// Note that the values of this enumeration line up with the first
6556   /// argument to the \c err_unexpanded_parameter_pack diagnostic.
6557   enum UnexpandedParameterPackContext {
6558     /// An arbitrary expression.
6559     UPPC_Expression = 0,
6560 
6561     /// The base type of a class type.
6562     UPPC_BaseType,
6563 
6564     /// The type of an arbitrary declaration.
6565     UPPC_DeclarationType,
6566 
6567     /// The type of a data member.
6568     UPPC_DataMemberType,
6569 
6570     /// The size of a bit-field.
6571     UPPC_BitFieldWidth,
6572 
6573     /// The expression in a static assertion.
6574     UPPC_StaticAssertExpression,
6575 
6576     /// The fixed underlying type of an enumeration.
6577     UPPC_FixedUnderlyingType,
6578 
6579     /// The enumerator value.
6580     UPPC_EnumeratorValue,
6581 
6582     /// A using declaration.
6583     UPPC_UsingDeclaration,
6584 
6585     /// A friend declaration.
6586     UPPC_FriendDeclaration,
6587 
6588     /// A declaration qualifier.
6589     UPPC_DeclarationQualifier,
6590 
6591     /// An initializer.
6592     UPPC_Initializer,
6593 
6594     /// A default argument.
6595     UPPC_DefaultArgument,
6596 
6597     /// The type of a non-type template parameter.
6598     UPPC_NonTypeTemplateParameterType,
6599 
6600     /// The type of an exception.
6601     UPPC_ExceptionType,
6602 
6603     /// Partial specialization.
6604     UPPC_PartialSpecialization,
6605 
6606     /// Microsoft __if_exists.
6607     UPPC_IfExists,
6608 
6609     /// Microsoft __if_not_exists.
6610     UPPC_IfNotExists,
6611 
6612     /// Lambda expression.
6613     UPPC_Lambda,
6614 
6615     /// Block expression,
6616     UPPC_Block
6617   };
6618 
6619   /// Diagnose unexpanded parameter packs.
6620   ///
6621   /// \param Loc The location at which we should emit the diagnostic.
6622   ///
6623   /// \param UPPC The context in which we are diagnosing unexpanded
6624   /// parameter packs.
6625   ///
6626   /// \param Unexpanded the set of unexpanded parameter packs.
6627   ///
6628   /// \returns true if an error occurred, false otherwise.
6629   bool DiagnoseUnexpandedParameterPacks(SourceLocation Loc,
6630                                         UnexpandedParameterPackContext UPPC,
6631                                   ArrayRef<UnexpandedParameterPack> Unexpanded);
6632 
6633   /// If the given type contains an unexpanded parameter pack,
6634   /// diagnose the error.
6635   ///
6636   /// \param Loc The source location where a diagnostc should be emitted.
6637   ///
6638   /// \param T The type that is being checked for unexpanded parameter
6639   /// packs.
6640   ///
6641   /// \returns true if an error occurred, false otherwise.
6642   bool DiagnoseUnexpandedParameterPack(SourceLocation Loc, TypeSourceInfo *T,
6643                                        UnexpandedParameterPackContext UPPC);
6644 
6645   /// If the given expression contains an unexpanded parameter
6646   /// pack, diagnose the error.
6647   ///
6648   /// \param E The expression that is being checked for unexpanded
6649   /// parameter packs.
6650   ///
6651   /// \returns true if an error occurred, false otherwise.
6652   bool DiagnoseUnexpandedParameterPack(Expr *E,
6653                        UnexpandedParameterPackContext UPPC = UPPC_Expression);
6654 
6655   /// If the given nested-name-specifier contains an unexpanded
6656   /// parameter pack, diagnose the error.
6657   ///
6658   /// \param SS The nested-name-specifier that is being checked for
6659   /// unexpanded parameter packs.
6660   ///
6661   /// \returns true if an error occurred, false otherwise.
6662   bool DiagnoseUnexpandedParameterPack(const CXXScopeSpec &SS,
6663                                        UnexpandedParameterPackContext UPPC);
6664 
6665   /// If the given name contains an unexpanded parameter pack,
6666   /// diagnose the error.
6667   ///
6668   /// \param NameInfo The name (with source location information) that
6669   /// is being checked for unexpanded parameter packs.
6670   ///
6671   /// \returns true if an error occurred, false otherwise.
6672   bool DiagnoseUnexpandedParameterPack(const DeclarationNameInfo &NameInfo,
6673                                        UnexpandedParameterPackContext UPPC);
6674 
6675   /// If the given template name contains an unexpanded parameter pack,
6676   /// diagnose the error.
6677   ///
6678   /// \param Loc The location of the template name.
6679   ///
6680   /// \param Template The template name that is being checked for unexpanded
6681   /// parameter packs.
6682   ///
6683   /// \returns true if an error occurred, false otherwise.
6684   bool DiagnoseUnexpandedParameterPack(SourceLocation Loc,
6685                                        TemplateName Template,
6686                                        UnexpandedParameterPackContext UPPC);
6687 
6688   /// If the given template argument contains an unexpanded parameter
6689   /// pack, diagnose the error.
6690   ///
6691   /// \param Arg The template argument that is being checked for unexpanded
6692   /// parameter packs.
6693   ///
6694   /// \returns true if an error occurred, false otherwise.
6695   bool DiagnoseUnexpandedParameterPack(TemplateArgumentLoc Arg,
6696                                        UnexpandedParameterPackContext UPPC);
6697 
6698   /// Collect the set of unexpanded parameter packs within the given
6699   /// template argument.
6700   ///
6701   /// \param Arg The template argument that will be traversed to find
6702   /// unexpanded parameter packs.
6703   void collectUnexpandedParameterPacks(TemplateArgument Arg,
6704                    SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
6705 
6706   /// Collect the set of unexpanded parameter packs within the given
6707   /// template argument.
6708   ///
6709   /// \param Arg The template argument that will be traversed to find
6710   /// unexpanded parameter packs.
6711   void collectUnexpandedParameterPacks(TemplateArgumentLoc Arg,
6712                     SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
6713 
6714   /// Collect the set of unexpanded parameter packs within the given
6715   /// type.
6716   ///
6717   /// \param T The type that will be traversed to find
6718   /// unexpanded parameter packs.
6719   void collectUnexpandedParameterPacks(QualType T,
6720                    SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
6721 
6722   /// Collect the set of unexpanded parameter packs within the given
6723   /// type.
6724   ///
6725   /// \param TL The type that will be traversed to find
6726   /// unexpanded parameter packs.
6727   void collectUnexpandedParameterPacks(TypeLoc TL,
6728                    SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
6729 
6730   /// Collect the set of unexpanded parameter packs within the given
6731   /// nested-name-specifier.
6732   ///
6733   /// \param NNS The nested-name-specifier that will be traversed to find
6734   /// unexpanded parameter packs.
6735   void collectUnexpandedParameterPacks(NestedNameSpecifierLoc NNS,
6736                          SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
6737 
6738   /// Collect the set of unexpanded parameter packs within the given
6739   /// name.
6740   ///
6741   /// \param NameInfo The name that will be traversed to find
6742   /// unexpanded parameter packs.
6743   void collectUnexpandedParameterPacks(const DeclarationNameInfo &NameInfo,
6744                          SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
6745 
6746   /// Invoked when parsing a template argument followed by an
6747   /// ellipsis, which creates a pack expansion.
6748   ///
6749   /// \param Arg The template argument preceding the ellipsis, which
6750   /// may already be invalid.
6751   ///
6752   /// \param EllipsisLoc The location of the ellipsis.
6753   ParsedTemplateArgument ActOnPackExpansion(const ParsedTemplateArgument &Arg,
6754                                             SourceLocation EllipsisLoc);
6755 
6756   /// Invoked when parsing a type followed by an ellipsis, which
6757   /// creates a pack expansion.
6758   ///
6759   /// \param Type The type preceding the ellipsis, which will become
6760   /// the pattern of the pack expansion.
6761   ///
6762   /// \param EllipsisLoc The location of the ellipsis.
6763   TypeResult ActOnPackExpansion(ParsedType Type, SourceLocation EllipsisLoc);
6764 
6765   /// Construct a pack expansion type from the pattern of the pack
6766   /// expansion.
6767   TypeSourceInfo *CheckPackExpansion(TypeSourceInfo *Pattern,
6768                                      SourceLocation EllipsisLoc,
6769                                      Optional<unsigned> NumExpansions);
6770 
6771   /// Construct a pack expansion type from the pattern of the pack
6772   /// expansion.
6773   QualType CheckPackExpansion(QualType Pattern,
6774                               SourceRange PatternRange,
6775                               SourceLocation EllipsisLoc,
6776                               Optional<unsigned> NumExpansions);
6777 
6778   /// Invoked when parsing an expression followed by an ellipsis, which
6779   /// creates a pack expansion.
6780   ///
6781   /// \param Pattern The expression preceding the ellipsis, which will become
6782   /// the pattern of the pack expansion.
6783   ///
6784   /// \param EllipsisLoc The location of the ellipsis.
6785   ExprResult ActOnPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc);
6786 
6787   /// Invoked when parsing an expression followed by an ellipsis, which
6788   /// creates a pack expansion.
6789   ///
6790   /// \param Pattern The expression preceding the ellipsis, which will become
6791   /// the pattern of the pack expansion.
6792   ///
6793   /// \param EllipsisLoc The location of the ellipsis.
6794   ExprResult CheckPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc,
6795                                 Optional<unsigned> NumExpansions);
6796 
6797   /// Determine whether we could expand a pack expansion with the
6798   /// given set of parameter packs into separate arguments by repeatedly
6799   /// transforming the pattern.
6800   ///
6801   /// \param EllipsisLoc The location of the ellipsis that identifies the
6802   /// pack expansion.
6803   ///
6804   /// \param PatternRange The source range that covers the entire pattern of
6805   /// the pack expansion.
6806   ///
6807   /// \param Unexpanded The set of unexpanded parameter packs within the
6808   /// pattern.
6809   ///
6810   /// \param ShouldExpand Will be set to \c true if the transformer should
6811   /// expand the corresponding pack expansions into separate arguments. When
6812   /// set, \c NumExpansions must also be set.
6813   ///
6814   /// \param RetainExpansion Whether the caller should add an unexpanded
6815   /// pack expansion after all of the expanded arguments. This is used
6816   /// when extending explicitly-specified template argument packs per
6817   /// C++0x [temp.arg.explicit]p9.
6818   ///
6819   /// \param NumExpansions The number of separate arguments that will be in
6820   /// the expanded form of the corresponding pack expansion. This is both an
6821   /// input and an output parameter, which can be set by the caller if the
6822   /// number of expansions is known a priori (e.g., due to a prior substitution)
6823   /// and will be set by the callee when the number of expansions is known.
6824   /// The callee must set this value when \c ShouldExpand is \c true; it may
6825   /// set this value in other cases.
6826   ///
6827   /// \returns true if an error occurred (e.g., because the parameter packs
6828   /// are to be instantiated with arguments of different lengths), false
6829   /// otherwise. If false, \c ShouldExpand (and possibly \c NumExpansions)
6830   /// must be set.
6831   bool CheckParameterPacksForExpansion(SourceLocation EllipsisLoc,
6832                                        SourceRange PatternRange,
6833                              ArrayRef<UnexpandedParameterPack> Unexpanded,
6834                              const MultiLevelTemplateArgumentList &TemplateArgs,
6835                                        bool &ShouldExpand,
6836                                        bool &RetainExpansion,
6837                                        Optional<unsigned> &NumExpansions);
6838 
6839   /// Determine the number of arguments in the given pack expansion
6840   /// type.
6841   ///
6842   /// This routine assumes that the number of arguments in the expansion is
6843   /// consistent across all of the unexpanded parameter packs in its pattern.
6844   ///
6845   /// Returns an empty Optional if the type can't be expanded.
6846   Optional<unsigned> getNumArgumentsInExpansion(QualType T,
6847       const MultiLevelTemplateArgumentList &TemplateArgs);
6848 
6849   /// Determine whether the given declarator contains any unexpanded
6850   /// parameter packs.
6851   ///
6852   /// This routine is used by the parser to disambiguate function declarators
6853   /// with an ellipsis prior to the ')', e.g.,
6854   ///
6855   /// \code
6856   ///   void f(T...);
6857   /// \endcode
6858   ///
6859   /// To determine whether we have an (unnamed) function parameter pack or
6860   /// a variadic function.
6861   ///
6862   /// \returns true if the declarator contains any unexpanded parameter packs,
6863   /// false otherwise.
6864   bool containsUnexpandedParameterPacks(Declarator &D);
6865 
6866   /// Returns the pattern of the pack expansion for a template argument.
6867   ///
6868   /// \param OrigLoc The template argument to expand.
6869   ///
6870   /// \param Ellipsis Will be set to the location of the ellipsis.
6871   ///
6872   /// \param NumExpansions Will be set to the number of expansions that will
6873   /// be generated from this pack expansion, if known a priori.
6874   TemplateArgumentLoc getTemplateArgumentPackExpansionPattern(
6875       TemplateArgumentLoc OrigLoc,
6876       SourceLocation &Ellipsis,
6877       Optional<unsigned> &NumExpansions) const;
6878 
6879   /// Given a template argument that contains an unexpanded parameter pack, but
6880   /// which has already been substituted, attempt to determine the number of
6881   /// elements that will be produced once this argument is fully-expanded.
6882   ///
6883   /// This is intended for use when transforming 'sizeof...(Arg)' in order to
6884   /// avoid actually expanding the pack where possible.
6885   Optional<unsigned> getFullyPackExpandedSize(TemplateArgument Arg);
6886 
6887   //===--------------------------------------------------------------------===//
6888   // C++ Template Argument Deduction (C++ [temp.deduct])
6889   //===--------------------------------------------------------------------===//
6890 
6891   /// Adjust the type \p ArgFunctionType to match the calling convention,
6892   /// noreturn, and optionally the exception specification of \p FunctionType.
6893   /// Deduction often wants to ignore these properties when matching function
6894   /// types.
6895   QualType adjustCCAndNoReturn(QualType ArgFunctionType, QualType FunctionType,
6896                                bool AdjustExceptionSpec = false);
6897 
6898   /// Describes the result of template argument deduction.
6899   ///
6900   /// The TemplateDeductionResult enumeration describes the result of
6901   /// template argument deduction, as returned from
6902   /// DeduceTemplateArguments(). The separate TemplateDeductionInfo
6903   /// structure provides additional information about the results of
6904   /// template argument deduction, e.g., the deduced template argument
6905   /// list (if successful) or the specific template parameters or
6906   /// deduced arguments that were involved in the failure.
6907   enum TemplateDeductionResult {
6908     /// Template argument deduction was successful.
6909     TDK_Success = 0,
6910     /// The declaration was invalid; do nothing.
6911     TDK_Invalid,
6912     /// Template argument deduction exceeded the maximum template
6913     /// instantiation depth (which has already been diagnosed).
6914     TDK_InstantiationDepth,
6915     /// Template argument deduction did not deduce a value
6916     /// for every template parameter.
6917     TDK_Incomplete,
6918     /// Template argument deduction did not deduce a value for every
6919     /// expansion of an expanded template parameter pack.
6920     TDK_IncompletePack,
6921     /// Template argument deduction produced inconsistent
6922     /// deduced values for the given template parameter.
6923     TDK_Inconsistent,
6924     /// Template argument deduction failed due to inconsistent
6925     /// cv-qualifiers on a template parameter type that would
6926     /// otherwise be deduced, e.g., we tried to deduce T in "const T"
6927     /// but were given a non-const "X".
6928     TDK_Underqualified,
6929     /// Substitution of the deduced template argument values
6930     /// resulted in an error.
6931     TDK_SubstitutionFailure,
6932     /// After substituting deduced template arguments, a dependent
6933     /// parameter type did not match the corresponding argument.
6934     TDK_DeducedMismatch,
6935     /// After substituting deduced template arguments, an element of
6936     /// a dependent parameter type did not match the corresponding element
6937     /// of the corresponding argument (when deducing from an initializer list).
6938     TDK_DeducedMismatchNested,
6939     /// A non-depnedent component of the parameter did not match the
6940     /// corresponding component of the argument.
6941     TDK_NonDeducedMismatch,
6942     /// When performing template argument deduction for a function
6943     /// template, there were too many call arguments.
6944     TDK_TooManyArguments,
6945     /// When performing template argument deduction for a function
6946     /// template, there were too few call arguments.
6947     TDK_TooFewArguments,
6948     /// The explicitly-specified template arguments were not valid
6949     /// template arguments for the given template.
6950     TDK_InvalidExplicitArguments,
6951     /// Checking non-dependent argument conversions failed.
6952     TDK_NonDependentConversionFailure,
6953     /// Deduction failed; that's all we know.
6954     TDK_MiscellaneousDeductionFailure,
6955     /// CUDA Target attributes do not match.
6956     TDK_CUDATargetMismatch
6957   };
6958 
6959   TemplateDeductionResult
6960   DeduceTemplateArguments(ClassTemplatePartialSpecializationDecl *Partial,
6961                           const TemplateArgumentList &TemplateArgs,
6962                           sema::TemplateDeductionInfo &Info);
6963 
6964   TemplateDeductionResult
6965   DeduceTemplateArguments(VarTemplatePartialSpecializationDecl *Partial,
6966                           const TemplateArgumentList &TemplateArgs,
6967                           sema::TemplateDeductionInfo &Info);
6968 
6969   TemplateDeductionResult SubstituteExplicitTemplateArguments(
6970       FunctionTemplateDecl *FunctionTemplate,
6971       TemplateArgumentListInfo &ExplicitTemplateArgs,
6972       SmallVectorImpl<DeducedTemplateArgument> &Deduced,
6973       SmallVectorImpl<QualType> &ParamTypes, QualType *FunctionType,
6974       sema::TemplateDeductionInfo &Info);
6975 
6976   /// brief A function argument from which we performed template argument
6977   // deduction for a call.
6978   struct OriginalCallArg {
OriginalCallArgOriginalCallArg6979     OriginalCallArg(QualType OriginalParamType, bool DecomposedParam,
6980                     unsigned ArgIdx, QualType OriginalArgType)
6981         : OriginalParamType(OriginalParamType),
6982           DecomposedParam(DecomposedParam), ArgIdx(ArgIdx),
6983           OriginalArgType(OriginalArgType) {}
6984 
6985     QualType OriginalParamType;
6986     bool DecomposedParam;
6987     unsigned ArgIdx;
6988     QualType OriginalArgType;
6989   };
6990 
6991   TemplateDeductionResult FinishTemplateArgumentDeduction(
6992       FunctionTemplateDecl *FunctionTemplate,
6993       SmallVectorImpl<DeducedTemplateArgument> &Deduced,
6994       unsigned NumExplicitlySpecified, FunctionDecl *&Specialization,
6995       sema::TemplateDeductionInfo &Info,
6996       SmallVectorImpl<OriginalCallArg> const *OriginalCallArgs = nullptr,
6997       bool PartialOverloading = false,
6998       llvm::function_ref<bool()> CheckNonDependent = []{ return false; });
6999 
7000   TemplateDeductionResult DeduceTemplateArguments(
7001       FunctionTemplateDecl *FunctionTemplate,
7002       TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
7003       FunctionDecl *&Specialization, sema::TemplateDeductionInfo &Info,
7004       bool PartialOverloading,
7005       llvm::function_ref<bool(ArrayRef<QualType>)> CheckNonDependent);
7006 
7007   TemplateDeductionResult
7008   DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
7009                           TemplateArgumentListInfo *ExplicitTemplateArgs,
7010                           QualType ArgFunctionType,
7011                           FunctionDecl *&Specialization,
7012                           sema::TemplateDeductionInfo &Info,
7013                           bool IsAddressOfFunction = false);
7014 
7015   TemplateDeductionResult
7016   DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
7017                           QualType ToType,
7018                           CXXConversionDecl *&Specialization,
7019                           sema::TemplateDeductionInfo &Info);
7020 
7021   TemplateDeductionResult
7022   DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
7023                           TemplateArgumentListInfo *ExplicitTemplateArgs,
7024                           FunctionDecl *&Specialization,
7025                           sema::TemplateDeductionInfo &Info,
7026                           bool IsAddressOfFunction = false);
7027 
7028   /// Substitute Replacement for \p auto in \p TypeWithAuto
7029   QualType SubstAutoType(QualType TypeWithAuto, QualType Replacement);
7030   /// Substitute Replacement for auto in TypeWithAuto
7031   TypeSourceInfo* SubstAutoTypeSourceInfo(TypeSourceInfo *TypeWithAuto,
7032                                           QualType Replacement);
7033   /// Completely replace the \c auto in \p TypeWithAuto by
7034   /// \p Replacement. This does not retain any \c auto type sugar.
7035   QualType ReplaceAutoType(QualType TypeWithAuto, QualType Replacement);
7036 
7037   /// Result type of DeduceAutoType.
7038   enum DeduceAutoResult {
7039     DAR_Succeeded,
7040     DAR_Failed,
7041     DAR_FailedAlreadyDiagnosed
7042   };
7043 
7044   DeduceAutoResult
7045   DeduceAutoType(TypeSourceInfo *AutoType, Expr *&Initializer, QualType &Result,
7046                  Optional<unsigned> DependentDeductionDepth = None);
7047   DeduceAutoResult
7048   DeduceAutoType(TypeLoc AutoTypeLoc, Expr *&Initializer, QualType &Result,
7049                  Optional<unsigned> DependentDeductionDepth = None);
7050   void DiagnoseAutoDeductionFailure(VarDecl *VDecl, Expr *Init);
7051   bool DeduceReturnType(FunctionDecl *FD, SourceLocation Loc,
7052                         bool Diagnose = true);
7053 
7054   /// Declare implicit deduction guides for a class template if we've
7055   /// not already done so.
7056   void DeclareImplicitDeductionGuides(TemplateDecl *Template,
7057                                       SourceLocation Loc);
7058 
7059   QualType DeduceTemplateSpecializationFromInitializer(
7060       TypeSourceInfo *TInfo, const InitializedEntity &Entity,
7061       const InitializationKind &Kind, MultiExprArg Init);
7062 
7063   QualType deduceVarTypeFromInitializer(VarDecl *VDecl, DeclarationName Name,
7064                                         QualType Type, TypeSourceInfo *TSI,
7065                                         SourceRange Range, bool DirectInit,
7066                                         Expr *Init);
7067 
7068   TypeLoc getReturnTypeLoc(FunctionDecl *FD) const;
7069 
7070   bool DeduceFunctionTypeFromReturnExpr(FunctionDecl *FD,
7071                                         SourceLocation ReturnLoc,
7072                                         Expr *&RetExpr, AutoType *AT);
7073 
7074   FunctionTemplateDecl *getMoreSpecializedTemplate(FunctionTemplateDecl *FT1,
7075                                                    FunctionTemplateDecl *FT2,
7076                                                    SourceLocation Loc,
7077                                            TemplatePartialOrderingContext TPOC,
7078                                                    unsigned NumCallArguments1,
7079                                                    unsigned NumCallArguments2);
7080   UnresolvedSetIterator
7081   getMostSpecialized(UnresolvedSetIterator SBegin, UnresolvedSetIterator SEnd,
7082                      TemplateSpecCandidateSet &FailedCandidates,
7083                      SourceLocation Loc,
7084                      const PartialDiagnostic &NoneDiag,
7085                      const PartialDiagnostic &AmbigDiag,
7086                      const PartialDiagnostic &CandidateDiag,
7087                      bool Complain = true, QualType TargetType = QualType());
7088 
7089   ClassTemplatePartialSpecializationDecl *
7090   getMoreSpecializedPartialSpecialization(
7091                                   ClassTemplatePartialSpecializationDecl *PS1,
7092                                   ClassTemplatePartialSpecializationDecl *PS2,
7093                                   SourceLocation Loc);
7094 
7095   bool isMoreSpecializedThanPrimary(ClassTemplatePartialSpecializationDecl *T,
7096                                     sema::TemplateDeductionInfo &Info);
7097 
7098   VarTemplatePartialSpecializationDecl *getMoreSpecializedPartialSpecialization(
7099       VarTemplatePartialSpecializationDecl *PS1,
7100       VarTemplatePartialSpecializationDecl *PS2, SourceLocation Loc);
7101 
7102   bool isMoreSpecializedThanPrimary(VarTemplatePartialSpecializationDecl *T,
7103                                     sema::TemplateDeductionInfo &Info);
7104 
7105   bool isTemplateTemplateParameterAtLeastAsSpecializedAs(
7106       TemplateParameterList *P, TemplateDecl *AArg, SourceLocation Loc);
7107 
7108   void MarkUsedTemplateParameters(const TemplateArgumentList &TemplateArgs,
7109                                   bool OnlyDeduced,
7110                                   unsigned Depth,
7111                                   llvm::SmallBitVector &Used);
MarkDeducedTemplateParameters(const FunctionTemplateDecl * FunctionTemplate,llvm::SmallBitVector & Deduced)7112   void MarkDeducedTemplateParameters(
7113                                   const FunctionTemplateDecl *FunctionTemplate,
7114                                   llvm::SmallBitVector &Deduced) {
7115     return MarkDeducedTemplateParameters(Context, FunctionTemplate, Deduced);
7116   }
7117   static void MarkDeducedTemplateParameters(ASTContext &Ctx,
7118                                   const FunctionTemplateDecl *FunctionTemplate,
7119                                   llvm::SmallBitVector &Deduced);
7120 
7121   //===--------------------------------------------------------------------===//
7122   // C++ Template Instantiation
7123   //
7124 
7125   MultiLevelTemplateArgumentList
7126   getTemplateInstantiationArgs(NamedDecl *D,
7127                                const TemplateArgumentList *Innermost = nullptr,
7128                                bool RelativeToPrimary = false,
7129                                const FunctionDecl *Pattern = nullptr);
7130 
7131   /// A context in which code is being synthesized (where a source location
7132   /// alone is not sufficient to identify the context). This covers template
7133   /// instantiation and various forms of implicitly-generated functions.
7134   struct CodeSynthesisContext {
7135     /// The kind of template instantiation we are performing
7136     enum SynthesisKind {
7137       /// We are instantiating a template declaration. The entity is
7138       /// the declaration we're instantiating (e.g., a CXXRecordDecl).
7139       TemplateInstantiation,
7140 
7141       /// We are instantiating a default argument for a template
7142       /// parameter. The Entity is the template parameter whose argument is
7143       /// being instantiated, the Template is the template, and the
7144       /// TemplateArgs/NumTemplateArguments provide the template arguments as
7145       /// specified.
7146       DefaultTemplateArgumentInstantiation,
7147 
7148       /// We are instantiating a default argument for a function.
7149       /// The Entity is the ParmVarDecl, and TemplateArgs/NumTemplateArgs
7150       /// provides the template arguments as specified.
7151       DefaultFunctionArgumentInstantiation,
7152 
7153       /// We are substituting explicit template arguments provided for
7154       /// a function template. The entity is a FunctionTemplateDecl.
7155       ExplicitTemplateArgumentSubstitution,
7156 
7157       /// We are substituting template argument determined as part of
7158       /// template argument deduction for either a class template
7159       /// partial specialization or a function template. The
7160       /// Entity is either a {Class|Var}TemplatePartialSpecializationDecl or
7161       /// a TemplateDecl.
7162       DeducedTemplateArgumentSubstitution,
7163 
7164       /// We are substituting prior template arguments into a new
7165       /// template parameter. The template parameter itself is either a
7166       /// NonTypeTemplateParmDecl or a TemplateTemplateParmDecl.
7167       PriorTemplateArgumentSubstitution,
7168 
7169       /// We are checking the validity of a default template argument that
7170       /// has been used when naming a template-id.
7171       DefaultTemplateArgumentChecking,
7172 
7173       /// We are instantiating the exception specification for a function
7174       /// template which was deferred until it was needed.
7175       ExceptionSpecInstantiation,
7176 
7177       /// We are declaring an implicit special member function.
7178       DeclaringSpecialMember,
7179 
7180       /// We are defining a synthesized function (such as a defaulted special
7181       /// member).
7182       DefiningSynthesizedFunction,
7183 
7184       /// Added for Template instantiation observation.
7185       /// Memoization means we are _not_ instantiating a template because
7186       /// it is already instantiated (but we entered a context where we
7187       /// would have had to if it was not already instantiated).
7188       Memoization
7189     } Kind;
7190 
7191     /// Was the enclosing context a non-instantiation SFINAE context?
7192     bool SavedInNonInstantiationSFINAEContext;
7193 
7194     /// The point of instantiation or synthesis within the source code.
7195     SourceLocation PointOfInstantiation;
7196 
7197     /// The entity that is being synthesized.
7198     Decl *Entity;
7199 
7200     /// The template (or partial specialization) in which we are
7201     /// performing the instantiation, for substitutions of prior template
7202     /// arguments.
7203     NamedDecl *Template;
7204 
7205     /// The list of template arguments we are substituting, if they
7206     /// are not part of the entity.
7207     const TemplateArgument *TemplateArgs;
7208 
7209     // FIXME: Wrap this union around more members, or perhaps store the
7210     // kind-specific members in the RAII object owning the context.
7211     union {
7212       /// The number of template arguments in TemplateArgs.
7213       unsigned NumTemplateArgs;
7214 
7215       /// The special member being declared or defined.
7216       CXXSpecialMember SpecialMember;
7217     };
7218 
template_argumentsCodeSynthesisContext7219     ArrayRef<TemplateArgument> template_arguments() const {
7220       assert(Kind != DeclaringSpecialMember);
7221       return {TemplateArgs, NumTemplateArgs};
7222     }
7223 
7224     /// The template deduction info object associated with the
7225     /// substitution or checking of explicit or deduced template arguments.
7226     sema::TemplateDeductionInfo *DeductionInfo;
7227 
7228     /// The source range that covers the construct that cause
7229     /// the instantiation, e.g., the template-id that causes a class
7230     /// template instantiation.
7231     SourceRange InstantiationRange;
7232 
CodeSynthesisContextCodeSynthesisContext7233     CodeSynthesisContext()
7234       : Kind(TemplateInstantiation), Entity(nullptr), Template(nullptr),
7235         TemplateArgs(nullptr), NumTemplateArgs(0), DeductionInfo(nullptr) {}
7236 
7237     /// Determines whether this template is an actual instantiation
7238     /// that should be counted toward the maximum instantiation depth.
7239     bool isInstantiationRecord() const;
7240   };
7241 
7242   /// List of active code synthesis contexts.
7243   ///
7244   /// This vector is treated as a stack. As synthesis of one entity requires
7245   /// synthesis of another, additional contexts are pushed onto the stack.
7246   SmallVector<CodeSynthesisContext, 16> CodeSynthesisContexts;
7247 
7248   /// Specializations whose definitions are currently being instantiated.
7249   llvm::DenseSet<std::pair<Decl *, unsigned>> InstantiatingSpecializations;
7250 
7251   /// Non-dependent types used in templates that have already been instantiated
7252   /// by some template instantiation.
7253   llvm::DenseSet<QualType> InstantiatedNonDependentTypes;
7254 
7255   /// Extra modules inspected when performing a lookup during a template
7256   /// instantiation. Computed lazily.
7257   SmallVector<Module*, 16> CodeSynthesisContextLookupModules;
7258 
7259   /// Cache of additional modules that should be used for name lookup
7260   /// within the current template instantiation. Computed lazily; use
7261   /// getLookupModules() to get a complete set.
7262   llvm::DenseSet<Module*> LookupModulesCache;
7263 
7264   /// Get the set of additional modules that should be checked during
7265   /// name lookup. A module and its imports become visible when instanting a
7266   /// template defined within it.
7267   llvm::DenseSet<Module*> &getLookupModules();
7268 
7269   /// Map from the most recent declaration of a namespace to the most
7270   /// recent visible declaration of that namespace.
7271   llvm::DenseMap<NamedDecl*, NamedDecl*> VisibleNamespaceCache;
7272 
7273   /// Whether we are in a SFINAE context that is not associated with
7274   /// template instantiation.
7275   ///
7276   /// This is used when setting up a SFINAE trap (\c see SFINAETrap) outside
7277   /// of a template instantiation or template argument deduction.
7278   bool InNonInstantiationSFINAEContext;
7279 
7280   /// The number of \p CodeSynthesisContexts that are not template
7281   /// instantiations and, therefore, should not be counted as part of the
7282   /// instantiation depth.
7283   ///
7284   /// When the instantiation depth reaches the user-configurable limit
7285   /// \p LangOptions::InstantiationDepth we will abort instantiation.
7286   // FIXME: Should we have a similar limit for other forms of synthesis?
7287   unsigned NonInstantiationEntries;
7288 
7289   /// The depth of the context stack at the point when the most recent
7290   /// error or warning was produced.
7291   ///
7292   /// This value is used to suppress printing of redundant context stacks
7293   /// when there are multiple errors or warnings in the same instantiation.
7294   // FIXME: Does this belong in Sema? It's tough to implement it anywhere else.
7295   unsigned LastEmittedCodeSynthesisContextDepth = 0;
7296 
7297   /// The template instantiation callbacks to trace or track
7298   /// instantiations (objects can be chained).
7299   ///
7300   /// This callbacks is used to print, trace or track template
7301   /// instantiations as they are being constructed.
7302   std::vector<std::unique_ptr<TemplateInstantiationCallback>>
7303       TemplateInstCallbacks;
7304 
7305   /// The current index into pack expansion arguments that will be
7306   /// used for substitution of parameter packs.
7307   ///
7308   /// The pack expansion index will be -1 to indicate that parameter packs
7309   /// should be instantiated as themselves. Otherwise, the index specifies
7310   /// which argument within the parameter pack will be used for substitution.
7311   int ArgumentPackSubstitutionIndex;
7312 
7313   /// RAII object used to change the argument pack substitution index
7314   /// within a \c Sema object.
7315   ///
7316   /// See \c ArgumentPackSubstitutionIndex for more information.
7317   class ArgumentPackSubstitutionIndexRAII {
7318     Sema &Self;
7319     int OldSubstitutionIndex;
7320 
7321   public:
ArgumentPackSubstitutionIndexRAII(Sema & Self,int NewSubstitutionIndex)7322     ArgumentPackSubstitutionIndexRAII(Sema &Self, int NewSubstitutionIndex)
7323       : Self(Self), OldSubstitutionIndex(Self.ArgumentPackSubstitutionIndex) {
7324       Self.ArgumentPackSubstitutionIndex = NewSubstitutionIndex;
7325     }
7326 
~ArgumentPackSubstitutionIndexRAII()7327     ~ArgumentPackSubstitutionIndexRAII() {
7328       Self.ArgumentPackSubstitutionIndex = OldSubstitutionIndex;
7329     }
7330   };
7331 
7332   friend class ArgumentPackSubstitutionRAII;
7333 
7334   /// For each declaration that involved template argument deduction, the
7335   /// set of diagnostics that were suppressed during that template argument
7336   /// deduction.
7337   ///
7338   /// FIXME: Serialize this structure to the AST file.
7339   typedef llvm::DenseMap<Decl *, SmallVector<PartialDiagnosticAt, 1> >
7340     SuppressedDiagnosticsMap;
7341   SuppressedDiagnosticsMap SuppressedDiagnostics;
7342 
7343   /// A stack object to be created when performing template
7344   /// instantiation.
7345   ///
7346   /// Construction of an object of type \c InstantiatingTemplate
7347   /// pushes the current instantiation onto the stack of active
7348   /// instantiations. If the size of this stack exceeds the maximum
7349   /// number of recursive template instantiations, construction
7350   /// produces an error and evaluates true.
7351   ///
7352   /// Destruction of this object will pop the named instantiation off
7353   /// the stack.
7354   struct InstantiatingTemplate {
7355     /// Note that we are instantiating a class template,
7356     /// function template, variable template, alias template,
7357     /// or a member thereof.
7358     InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
7359                           Decl *Entity,
7360                           SourceRange InstantiationRange = SourceRange());
7361 
7362     struct ExceptionSpecification {};
7363     /// Note that we are instantiating an exception specification
7364     /// of a function template.
7365     InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
7366                           FunctionDecl *Entity, ExceptionSpecification,
7367                           SourceRange InstantiationRange = SourceRange());
7368 
7369     /// Note that we are instantiating a default argument in a
7370     /// template-id.
7371     InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
7372                           TemplateParameter Param, TemplateDecl *Template,
7373                           ArrayRef<TemplateArgument> TemplateArgs,
7374                           SourceRange InstantiationRange = SourceRange());
7375 
7376     /// Note that we are substituting either explicitly-specified or
7377     /// deduced template arguments during function template argument deduction.
7378     InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
7379                           FunctionTemplateDecl *FunctionTemplate,
7380                           ArrayRef<TemplateArgument> TemplateArgs,
7381                           CodeSynthesisContext::SynthesisKind Kind,
7382                           sema::TemplateDeductionInfo &DeductionInfo,
7383                           SourceRange InstantiationRange = SourceRange());
7384 
7385     /// Note that we are instantiating as part of template
7386     /// argument deduction for a class template declaration.
7387     InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
7388                           TemplateDecl *Template,
7389                           ArrayRef<TemplateArgument> TemplateArgs,
7390                           sema::TemplateDeductionInfo &DeductionInfo,
7391                           SourceRange InstantiationRange = SourceRange());
7392 
7393     /// Note that we are instantiating as part of template
7394     /// argument deduction for a class template partial
7395     /// specialization.
7396     InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
7397                           ClassTemplatePartialSpecializationDecl *PartialSpec,
7398                           ArrayRef<TemplateArgument> TemplateArgs,
7399                           sema::TemplateDeductionInfo &DeductionInfo,
7400                           SourceRange InstantiationRange = SourceRange());
7401 
7402     /// Note that we are instantiating as part of template
7403     /// argument deduction for a variable template partial
7404     /// specialization.
7405     InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
7406                           VarTemplatePartialSpecializationDecl *PartialSpec,
7407                           ArrayRef<TemplateArgument> TemplateArgs,
7408                           sema::TemplateDeductionInfo &DeductionInfo,
7409                           SourceRange InstantiationRange = SourceRange());
7410 
7411     /// Note that we are instantiating a default argument for a function
7412     /// parameter.
7413     InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
7414                           ParmVarDecl *Param,
7415                           ArrayRef<TemplateArgument> TemplateArgs,
7416                           SourceRange InstantiationRange = SourceRange());
7417 
7418     /// Note that we are substituting prior template arguments into a
7419     /// non-type parameter.
7420     InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
7421                           NamedDecl *Template,
7422                           NonTypeTemplateParmDecl *Param,
7423                           ArrayRef<TemplateArgument> TemplateArgs,
7424                           SourceRange InstantiationRange);
7425 
7426     /// Note that we are substituting prior template arguments into a
7427     /// template template parameter.
7428     InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
7429                           NamedDecl *Template,
7430                           TemplateTemplateParmDecl *Param,
7431                           ArrayRef<TemplateArgument> TemplateArgs,
7432                           SourceRange InstantiationRange);
7433 
7434     /// Note that we are checking the default template argument
7435     /// against the template parameter for a given template-id.
7436     InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
7437                           TemplateDecl *Template,
7438                           NamedDecl *Param,
7439                           ArrayRef<TemplateArgument> TemplateArgs,
7440                           SourceRange InstantiationRange);
7441 
7442 
7443     /// Note that we have finished instantiating this template.
7444     void Clear();
7445 
~InstantiatingTemplateInstantiatingTemplate7446     ~InstantiatingTemplate() { Clear(); }
7447 
7448     /// Determines whether we have exceeded the maximum
7449     /// recursive template instantiations.
isInvalidInstantiatingTemplate7450     bool isInvalid() const { return Invalid; }
7451 
7452     /// Determine whether we are already instantiating this
7453     /// specialization in some surrounding active instantiation.
isAlreadyInstantiatingInstantiatingTemplate7454     bool isAlreadyInstantiating() const { return AlreadyInstantiating; }
7455 
7456   private:
7457     Sema &SemaRef;
7458     bool Invalid;
7459     bool AlreadyInstantiating;
7460     bool CheckInstantiationDepth(SourceLocation PointOfInstantiation,
7461                                  SourceRange InstantiationRange);
7462 
7463     InstantiatingTemplate(
7464         Sema &SemaRef, CodeSynthesisContext::SynthesisKind Kind,
7465         SourceLocation PointOfInstantiation, SourceRange InstantiationRange,
7466         Decl *Entity, NamedDecl *Template = nullptr,
7467         ArrayRef<TemplateArgument> TemplateArgs = None,
7468         sema::TemplateDeductionInfo *DeductionInfo = nullptr);
7469 
7470     InstantiatingTemplate(const InstantiatingTemplate&) = delete;
7471 
7472     InstantiatingTemplate&
7473     operator=(const InstantiatingTemplate&) = delete;
7474   };
7475 
7476   void pushCodeSynthesisContext(CodeSynthesisContext Ctx);
7477   void popCodeSynthesisContext();
7478 
7479   /// Determine whether we are currently performing template instantiation.
inTemplateInstantiation()7480   bool inTemplateInstantiation() const {
7481     return CodeSynthesisContexts.size() > NonInstantiationEntries;
7482   }
7483 
PrintContextStack()7484   void PrintContextStack() {
7485     if (!CodeSynthesisContexts.empty() &&
7486         CodeSynthesisContexts.size() != LastEmittedCodeSynthesisContextDepth) {
7487       PrintInstantiationStack();
7488       LastEmittedCodeSynthesisContextDepth = CodeSynthesisContexts.size();
7489     }
7490     if (PragmaAttributeCurrentTargetDecl)
7491       PrintPragmaAttributeInstantiationPoint();
7492   }
7493   void PrintInstantiationStack();
7494 
7495   void PrintPragmaAttributeInstantiationPoint();
7496 
7497   /// Determines whether we are currently in a context where
7498   /// template argument substitution failures are not considered
7499   /// errors.
7500   ///
7501   /// \returns An empty \c Optional if we're not in a SFINAE context.
7502   /// Otherwise, contains a pointer that, if non-NULL, contains the nearest
7503   /// template-deduction context object, which can be used to capture
7504   /// diagnostics that will be suppressed.
7505   Optional<sema::TemplateDeductionInfo *> isSFINAEContext() const;
7506 
7507   /// Determines whether we are currently in a context that
7508   /// is not evaluated as per C++ [expr] p5.
isUnevaluatedContext()7509   bool isUnevaluatedContext() const {
7510     assert(!ExprEvalContexts.empty() &&
7511            "Must be in an expression evaluation context");
7512     return ExprEvalContexts.back().isUnevaluated();
7513   }
7514 
7515   /// RAII class used to determine whether SFINAE has
7516   /// trapped any errors that occur during template argument
7517   /// deduction.
7518   class SFINAETrap {
7519     Sema &SemaRef;
7520     unsigned PrevSFINAEErrors;
7521     bool PrevInNonInstantiationSFINAEContext;
7522     bool PrevAccessCheckingSFINAE;
7523     bool PrevLastDiagnosticIgnored;
7524 
7525   public:
7526     explicit SFINAETrap(Sema &SemaRef, bool AccessCheckingSFINAE = false)
SemaRef(SemaRef)7527       : SemaRef(SemaRef), PrevSFINAEErrors(SemaRef.NumSFINAEErrors),
7528         PrevInNonInstantiationSFINAEContext(
7529                                       SemaRef.InNonInstantiationSFINAEContext),
7530         PrevAccessCheckingSFINAE(SemaRef.AccessCheckingSFINAE),
7531         PrevLastDiagnosticIgnored(
7532             SemaRef.getDiagnostics().isLastDiagnosticIgnored())
7533     {
7534       if (!SemaRef.isSFINAEContext())
7535         SemaRef.InNonInstantiationSFINAEContext = true;
7536       SemaRef.AccessCheckingSFINAE = AccessCheckingSFINAE;
7537     }
7538 
~SFINAETrap()7539     ~SFINAETrap() {
7540       SemaRef.NumSFINAEErrors = PrevSFINAEErrors;
7541       SemaRef.InNonInstantiationSFINAEContext
7542         = PrevInNonInstantiationSFINAEContext;
7543       SemaRef.AccessCheckingSFINAE = PrevAccessCheckingSFINAE;
7544       SemaRef.getDiagnostics().setLastDiagnosticIgnored(
7545           PrevLastDiagnosticIgnored);
7546     }
7547 
7548     /// Determine whether any SFINAE errors have been trapped.
hasErrorOccurred()7549     bool hasErrorOccurred() const {
7550       return SemaRef.NumSFINAEErrors > PrevSFINAEErrors;
7551     }
7552   };
7553 
7554   /// RAII class used to indicate that we are performing provisional
7555   /// semantic analysis to determine the validity of a construct, so
7556   /// typo-correction and diagnostics in the immediate context (not within
7557   /// implicitly-instantiated templates) should be suppressed.
7558   class TentativeAnalysisScope {
7559     Sema &SemaRef;
7560     // FIXME: Using a SFINAETrap for this is a hack.
7561     SFINAETrap Trap;
7562     bool PrevDisableTypoCorrection;
7563   public:
TentativeAnalysisScope(Sema & SemaRef)7564     explicit TentativeAnalysisScope(Sema &SemaRef)
7565         : SemaRef(SemaRef), Trap(SemaRef, true),
7566           PrevDisableTypoCorrection(SemaRef.DisableTypoCorrection) {
7567       SemaRef.DisableTypoCorrection = true;
7568     }
~TentativeAnalysisScope()7569     ~TentativeAnalysisScope() {
7570       SemaRef.DisableTypoCorrection = PrevDisableTypoCorrection;
7571     }
7572   };
7573 
7574   /// The current instantiation scope used to store local
7575   /// variables.
7576   LocalInstantiationScope *CurrentInstantiationScope;
7577 
7578   /// Tracks whether we are in a context where typo correction is
7579   /// disabled.
7580   bool DisableTypoCorrection;
7581 
7582   /// The number of typos corrected by CorrectTypo.
7583   unsigned TyposCorrected;
7584 
7585   typedef llvm::SmallSet<SourceLocation, 2> SrcLocSet;
7586   typedef llvm::DenseMap<IdentifierInfo *, SrcLocSet> IdentifierSourceLocations;
7587 
7588   /// A cache containing identifiers for which typo correction failed and
7589   /// their locations, so that repeated attempts to correct an identifier in a
7590   /// given location are ignored if typo correction already failed for it.
7591   IdentifierSourceLocations TypoCorrectionFailures;
7592 
7593   /// Worker object for performing CFG-based warnings.
7594   sema::AnalysisBasedWarnings AnalysisWarnings;
7595   threadSafety::BeforeSet *ThreadSafetyDeclCache;
7596 
7597   /// An entity for which implicit template instantiation is required.
7598   ///
7599   /// The source location associated with the declaration is the first place in
7600   /// the source code where the declaration was "used". It is not necessarily
7601   /// the point of instantiation (which will be either before or after the
7602   /// namespace-scope declaration that triggered this implicit instantiation),
7603   /// However, it is the location that diagnostics should generally refer to,
7604   /// because users will need to know what code triggered the instantiation.
7605   typedef std::pair<ValueDecl *, SourceLocation> PendingImplicitInstantiation;
7606 
7607   /// The queue of implicit template instantiations that are required
7608   /// but have not yet been performed.
7609   std::deque<PendingImplicitInstantiation> PendingInstantiations;
7610 
7611   /// Queue of implicit template instantiations that cannot be performed
7612   /// eagerly.
7613   SmallVector<PendingImplicitInstantiation, 1> LateParsedInstantiations;
7614 
7615   class GlobalEagerInstantiationScope {
7616   public:
GlobalEagerInstantiationScope(Sema & S,bool Enabled)7617     GlobalEagerInstantiationScope(Sema &S, bool Enabled)
7618         : S(S), Enabled(Enabled) {
7619       if (!Enabled) return;
7620 
7621       SavedPendingInstantiations.swap(S.PendingInstantiations);
7622       SavedVTableUses.swap(S.VTableUses);
7623     }
7624 
perform()7625     void perform() {
7626       if (Enabled) {
7627         S.DefineUsedVTables();
7628         S.PerformPendingInstantiations();
7629       }
7630     }
7631 
~GlobalEagerInstantiationScope()7632     ~GlobalEagerInstantiationScope() {
7633       if (!Enabled) return;
7634 
7635       // Restore the set of pending vtables.
7636       assert(S.VTableUses.empty() &&
7637              "VTableUses should be empty before it is discarded.");
7638       S.VTableUses.swap(SavedVTableUses);
7639 
7640       // Restore the set of pending implicit instantiations.
7641       assert(S.PendingInstantiations.empty() &&
7642              "PendingInstantiations should be empty before it is discarded.");
7643       S.PendingInstantiations.swap(SavedPendingInstantiations);
7644     }
7645 
7646   private:
7647     Sema &S;
7648     SmallVector<VTableUse, 16> SavedVTableUses;
7649     std::deque<PendingImplicitInstantiation> SavedPendingInstantiations;
7650     bool Enabled;
7651   };
7652 
7653   /// The queue of implicit template instantiations that are required
7654   /// and must be performed within the current local scope.
7655   ///
7656   /// This queue is only used for member functions of local classes in
7657   /// templates, which must be instantiated in the same scope as their
7658   /// enclosing function, so that they can reference function-local
7659   /// types, static variables, enumerators, etc.
7660   std::deque<PendingImplicitInstantiation> PendingLocalImplicitInstantiations;
7661 
7662   class LocalEagerInstantiationScope {
7663   public:
LocalEagerInstantiationScope(Sema & S)7664     LocalEagerInstantiationScope(Sema &S) : S(S) {
7665       SavedPendingLocalImplicitInstantiations.swap(
7666           S.PendingLocalImplicitInstantiations);
7667     }
7668 
perform()7669     void perform() { S.PerformPendingInstantiations(/*LocalOnly=*/true); }
7670 
~LocalEagerInstantiationScope()7671     ~LocalEagerInstantiationScope() {
7672       assert(S.PendingLocalImplicitInstantiations.empty() &&
7673              "there shouldn't be any pending local implicit instantiations");
7674       SavedPendingLocalImplicitInstantiations.swap(
7675           S.PendingLocalImplicitInstantiations);
7676     }
7677 
7678   private:
7679     Sema &S;
7680     std::deque<PendingImplicitInstantiation>
7681         SavedPendingLocalImplicitInstantiations;
7682   };
7683 
7684   /// A helper class for building up ExtParameterInfos.
7685   class ExtParameterInfoBuilder {
7686     SmallVector<FunctionProtoType::ExtParameterInfo, 16> Infos;
7687     bool HasInteresting = false;
7688 
7689   public:
7690     /// Set the ExtParameterInfo for the parameter at the given index,
7691     ///
set(unsigned index,FunctionProtoType::ExtParameterInfo info)7692     void set(unsigned index, FunctionProtoType::ExtParameterInfo info) {
7693       assert(Infos.size() <= index);
7694       Infos.resize(index);
7695       Infos.push_back(info);
7696 
7697       if (!HasInteresting)
7698         HasInteresting = (info != FunctionProtoType::ExtParameterInfo());
7699     }
7700 
7701     /// Return a pointer (suitable for setting in an ExtProtoInfo) to the
7702     /// ExtParameterInfo array we've built up.
7703     const FunctionProtoType::ExtParameterInfo *
getPointerOrNull(unsigned numParams)7704     getPointerOrNull(unsigned numParams) {
7705       if (!HasInteresting) return nullptr;
7706       Infos.resize(numParams);
7707       return Infos.data();
7708     }
7709   };
7710 
7711   void PerformPendingInstantiations(bool LocalOnly = false);
7712 
7713   TypeSourceInfo *SubstType(TypeSourceInfo *T,
7714                             const MultiLevelTemplateArgumentList &TemplateArgs,
7715                             SourceLocation Loc, DeclarationName Entity,
7716                             bool AllowDeducedTST = false);
7717 
7718   QualType SubstType(QualType T,
7719                      const MultiLevelTemplateArgumentList &TemplateArgs,
7720                      SourceLocation Loc, DeclarationName Entity);
7721 
7722   TypeSourceInfo *SubstType(TypeLoc TL,
7723                             const MultiLevelTemplateArgumentList &TemplateArgs,
7724                             SourceLocation Loc, DeclarationName Entity);
7725 
7726   TypeSourceInfo *SubstFunctionDeclType(TypeSourceInfo *T,
7727                             const MultiLevelTemplateArgumentList &TemplateArgs,
7728                                         SourceLocation Loc,
7729                                         DeclarationName Entity,
7730                                         CXXRecordDecl *ThisContext,
7731                                         unsigned ThisTypeQuals);
7732   void SubstExceptionSpec(FunctionDecl *New, const FunctionProtoType *Proto,
7733                           const MultiLevelTemplateArgumentList &Args);
7734   bool SubstExceptionSpec(SourceLocation Loc,
7735                           FunctionProtoType::ExceptionSpecInfo &ESI,
7736                           SmallVectorImpl<QualType> &ExceptionStorage,
7737                           const MultiLevelTemplateArgumentList &Args);
7738   ParmVarDecl *SubstParmVarDecl(ParmVarDecl *D,
7739                             const MultiLevelTemplateArgumentList &TemplateArgs,
7740                                 int indexAdjustment,
7741                                 Optional<unsigned> NumExpansions,
7742                                 bool ExpectParameterPack);
7743   bool SubstParmTypes(SourceLocation Loc, ArrayRef<ParmVarDecl *> Params,
7744                       const FunctionProtoType::ExtParameterInfo *ExtParamInfos,
7745                       const MultiLevelTemplateArgumentList &TemplateArgs,
7746                       SmallVectorImpl<QualType> &ParamTypes,
7747                       SmallVectorImpl<ParmVarDecl *> *OutParams,
7748                       ExtParameterInfoBuilder &ParamInfos);
7749   ExprResult SubstExpr(Expr *E,
7750                        const MultiLevelTemplateArgumentList &TemplateArgs);
7751 
7752   /// Substitute the given template arguments into a list of
7753   /// expressions, expanding pack expansions if required.
7754   ///
7755   /// \param Exprs The list of expressions to substitute into.
7756   ///
7757   /// \param IsCall Whether this is some form of call, in which case
7758   /// default arguments will be dropped.
7759   ///
7760   /// \param TemplateArgs The set of template arguments to substitute.
7761   ///
7762   /// \param Outputs Will receive all of the substituted arguments.
7763   ///
7764   /// \returns true if an error occurred, false otherwise.
7765   bool SubstExprs(ArrayRef<Expr *> Exprs, bool IsCall,
7766                   const MultiLevelTemplateArgumentList &TemplateArgs,
7767                   SmallVectorImpl<Expr *> &Outputs);
7768 
7769   StmtResult SubstStmt(Stmt *S,
7770                        const MultiLevelTemplateArgumentList &TemplateArgs);
7771 
7772   TemplateParameterList *
7773   SubstTemplateParams(TemplateParameterList *Params, DeclContext *Owner,
7774                       const MultiLevelTemplateArgumentList &TemplateArgs);
7775 
7776   Decl *SubstDecl(Decl *D, DeclContext *Owner,
7777                   const MultiLevelTemplateArgumentList &TemplateArgs);
7778 
7779   ExprResult SubstInitializer(Expr *E,
7780                        const MultiLevelTemplateArgumentList &TemplateArgs,
7781                        bool CXXDirectInit);
7782 
7783   bool
7784   SubstBaseSpecifiers(CXXRecordDecl *Instantiation,
7785                       CXXRecordDecl *Pattern,
7786                       const MultiLevelTemplateArgumentList &TemplateArgs);
7787 
7788   bool
7789   InstantiateClass(SourceLocation PointOfInstantiation,
7790                    CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern,
7791                    const MultiLevelTemplateArgumentList &TemplateArgs,
7792                    TemplateSpecializationKind TSK,
7793                    bool Complain = true);
7794 
7795   bool InstantiateEnum(SourceLocation PointOfInstantiation,
7796                        EnumDecl *Instantiation, EnumDecl *Pattern,
7797                        const MultiLevelTemplateArgumentList &TemplateArgs,
7798                        TemplateSpecializationKind TSK);
7799 
7800   bool InstantiateInClassInitializer(
7801       SourceLocation PointOfInstantiation, FieldDecl *Instantiation,
7802       FieldDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs);
7803 
7804   struct LateInstantiatedAttribute {
7805     const Attr *TmplAttr;
7806     LocalInstantiationScope *Scope;
7807     Decl *NewDecl;
7808 
LateInstantiatedAttributeLateInstantiatedAttribute7809     LateInstantiatedAttribute(const Attr *A, LocalInstantiationScope *S,
7810                               Decl *D)
7811       : TmplAttr(A), Scope(S), NewDecl(D)
7812     { }
7813   };
7814   typedef SmallVector<LateInstantiatedAttribute, 16> LateInstantiatedAttrVec;
7815 
7816   void InstantiateAttrs(const MultiLevelTemplateArgumentList &TemplateArgs,
7817                         const Decl *Pattern, Decl *Inst,
7818                         LateInstantiatedAttrVec *LateAttrs = nullptr,
7819                         LocalInstantiationScope *OuterMostScope = nullptr);
7820 
7821   void
7822   InstantiateAttrsForDecl(const MultiLevelTemplateArgumentList &TemplateArgs,
7823                           const Decl *Pattern, Decl *Inst,
7824                           LateInstantiatedAttrVec *LateAttrs = nullptr,
7825                           LocalInstantiationScope *OuterMostScope = nullptr);
7826 
7827   bool usesPartialOrExplicitSpecialization(
7828       SourceLocation Loc, ClassTemplateSpecializationDecl *ClassTemplateSpec);
7829 
7830   bool
7831   InstantiateClassTemplateSpecialization(SourceLocation PointOfInstantiation,
7832                            ClassTemplateSpecializationDecl *ClassTemplateSpec,
7833                            TemplateSpecializationKind TSK,
7834                            bool Complain = true);
7835 
7836   void InstantiateClassMembers(SourceLocation PointOfInstantiation,
7837                                CXXRecordDecl *Instantiation,
7838                             const MultiLevelTemplateArgumentList &TemplateArgs,
7839                                TemplateSpecializationKind TSK);
7840 
7841   void InstantiateClassTemplateSpecializationMembers(
7842                                           SourceLocation PointOfInstantiation,
7843                            ClassTemplateSpecializationDecl *ClassTemplateSpec,
7844                                                 TemplateSpecializationKind TSK);
7845 
7846   NestedNameSpecifierLoc
7847   SubstNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS,
7848                            const MultiLevelTemplateArgumentList &TemplateArgs);
7849 
7850   DeclarationNameInfo
7851   SubstDeclarationNameInfo(const DeclarationNameInfo &NameInfo,
7852                            const MultiLevelTemplateArgumentList &TemplateArgs);
7853   TemplateName
7854   SubstTemplateName(NestedNameSpecifierLoc QualifierLoc, TemplateName Name,
7855                     SourceLocation Loc,
7856                     const MultiLevelTemplateArgumentList &TemplateArgs);
7857   bool Subst(const TemplateArgumentLoc *Args, unsigned NumArgs,
7858              TemplateArgumentListInfo &Result,
7859              const MultiLevelTemplateArgumentList &TemplateArgs);
7860 
7861   void InstantiateExceptionSpec(SourceLocation PointOfInstantiation,
7862                                 FunctionDecl *Function);
7863   FunctionDecl *InstantiateFunctionDeclaration(FunctionTemplateDecl *FTD,
7864                                                const TemplateArgumentList *Args,
7865                                                SourceLocation Loc);
7866   void InstantiateFunctionDefinition(SourceLocation PointOfInstantiation,
7867                                      FunctionDecl *Function,
7868                                      bool Recursive = false,
7869                                      bool DefinitionRequired = false,
7870                                      bool AtEndOfTU = false);
7871   VarTemplateSpecializationDecl *BuildVarTemplateInstantiation(
7872       VarTemplateDecl *VarTemplate, VarDecl *FromVar,
7873       const TemplateArgumentList &TemplateArgList,
7874       const TemplateArgumentListInfo &TemplateArgsInfo,
7875       SmallVectorImpl<TemplateArgument> &Converted,
7876       SourceLocation PointOfInstantiation, void *InsertPos,
7877       LateInstantiatedAttrVec *LateAttrs = nullptr,
7878       LocalInstantiationScope *StartingScope = nullptr);
7879   VarTemplateSpecializationDecl *CompleteVarTemplateSpecializationDecl(
7880       VarTemplateSpecializationDecl *VarSpec, VarDecl *PatternDecl,
7881       const MultiLevelTemplateArgumentList &TemplateArgs);
7882   void
7883   BuildVariableInstantiation(VarDecl *NewVar, VarDecl *OldVar,
7884                              const MultiLevelTemplateArgumentList &TemplateArgs,
7885                              LateInstantiatedAttrVec *LateAttrs,
7886                              DeclContext *Owner,
7887                              LocalInstantiationScope *StartingScope,
7888                              bool InstantiatingVarTemplate = false);
7889   void InstantiateVariableInitializer(
7890       VarDecl *Var, VarDecl *OldVar,
7891       const MultiLevelTemplateArgumentList &TemplateArgs);
7892   void InstantiateVariableDefinition(SourceLocation PointOfInstantiation,
7893                                      VarDecl *Var, bool Recursive = false,
7894                                      bool DefinitionRequired = false,
7895                                      bool AtEndOfTU = false);
7896 
7897   void InstantiateMemInitializers(CXXConstructorDecl *New,
7898                                   const CXXConstructorDecl *Tmpl,
7899                             const MultiLevelTemplateArgumentList &TemplateArgs);
7900 
7901   NamedDecl *FindInstantiatedDecl(SourceLocation Loc, NamedDecl *D,
7902                           const MultiLevelTemplateArgumentList &TemplateArgs,
7903                           bool FindingInstantiatedContext = false);
7904   DeclContext *FindInstantiatedContext(SourceLocation Loc, DeclContext *DC,
7905                           const MultiLevelTemplateArgumentList &TemplateArgs);
7906 
7907   // Objective-C declarations.
7908   enum ObjCContainerKind {
7909     OCK_None = -1,
7910     OCK_Interface = 0,
7911     OCK_Protocol,
7912     OCK_Category,
7913     OCK_ClassExtension,
7914     OCK_Implementation,
7915     OCK_CategoryImplementation
7916   };
7917   ObjCContainerKind getObjCContainerKind() const;
7918 
7919   DeclResult actOnObjCTypeParam(Scope *S,
7920                                 ObjCTypeParamVariance variance,
7921                                 SourceLocation varianceLoc,
7922                                 unsigned index,
7923                                 IdentifierInfo *paramName,
7924                                 SourceLocation paramLoc,
7925                                 SourceLocation colonLoc,
7926                                 ParsedType typeBound);
7927 
7928   ObjCTypeParamList *actOnObjCTypeParamList(Scope *S, SourceLocation lAngleLoc,
7929                                             ArrayRef<Decl *> typeParams,
7930                                             SourceLocation rAngleLoc);
7931   void popObjCTypeParamList(Scope *S, ObjCTypeParamList *typeParamList);
7932 
7933   Decl *ActOnStartClassInterface(
7934       Scope *S, SourceLocation AtInterfaceLoc, IdentifierInfo *ClassName,
7935       SourceLocation ClassLoc, ObjCTypeParamList *typeParamList,
7936       IdentifierInfo *SuperName, SourceLocation SuperLoc,
7937       ArrayRef<ParsedType> SuperTypeArgs, SourceRange SuperTypeArgsRange,
7938       Decl *const *ProtoRefs, unsigned NumProtoRefs,
7939       const SourceLocation *ProtoLocs, SourceLocation EndProtoLoc,
7940       const ParsedAttributesView &AttrList);
7941 
7942   void ActOnSuperClassOfClassInterface(Scope *S,
7943                                        SourceLocation AtInterfaceLoc,
7944                                        ObjCInterfaceDecl *IDecl,
7945                                        IdentifierInfo *ClassName,
7946                                        SourceLocation ClassLoc,
7947                                        IdentifierInfo *SuperName,
7948                                        SourceLocation SuperLoc,
7949                                        ArrayRef<ParsedType> SuperTypeArgs,
7950                                        SourceRange SuperTypeArgsRange);
7951 
7952   void ActOnTypedefedProtocols(SmallVectorImpl<Decl *> &ProtocolRefs,
7953                                SmallVectorImpl<SourceLocation> &ProtocolLocs,
7954                                IdentifierInfo *SuperName,
7955                                SourceLocation SuperLoc);
7956 
7957   Decl *ActOnCompatibilityAlias(
7958                     SourceLocation AtCompatibilityAliasLoc,
7959                     IdentifierInfo *AliasName,  SourceLocation AliasLocation,
7960                     IdentifierInfo *ClassName, SourceLocation ClassLocation);
7961 
7962   bool CheckForwardProtocolDeclarationForCircularDependency(
7963     IdentifierInfo *PName,
7964     SourceLocation &PLoc, SourceLocation PrevLoc,
7965     const ObjCList<ObjCProtocolDecl> &PList);
7966 
7967   Decl *ActOnStartProtocolInterface(
7968       SourceLocation AtProtoInterfaceLoc, IdentifierInfo *ProtocolName,
7969       SourceLocation ProtocolLoc, Decl *const *ProtoRefNames,
7970       unsigned NumProtoRefs, const SourceLocation *ProtoLocs,
7971       SourceLocation EndProtoLoc, const ParsedAttributesView &AttrList);
7972 
7973   Decl *ActOnStartCategoryInterface(
7974       SourceLocation AtInterfaceLoc, IdentifierInfo *ClassName,
7975       SourceLocation ClassLoc, ObjCTypeParamList *typeParamList,
7976       IdentifierInfo *CategoryName, SourceLocation CategoryLoc,
7977       Decl *const *ProtoRefs, unsigned NumProtoRefs,
7978       const SourceLocation *ProtoLocs, SourceLocation EndProtoLoc,
7979       const ParsedAttributesView &AttrList);
7980 
7981   Decl *ActOnStartClassImplementation(
7982                     SourceLocation AtClassImplLoc,
7983                     IdentifierInfo *ClassName, SourceLocation ClassLoc,
7984                     IdentifierInfo *SuperClassname,
7985                     SourceLocation SuperClassLoc);
7986 
7987   Decl *ActOnStartCategoryImplementation(SourceLocation AtCatImplLoc,
7988                                          IdentifierInfo *ClassName,
7989                                          SourceLocation ClassLoc,
7990                                          IdentifierInfo *CatName,
7991                                          SourceLocation CatLoc);
7992 
7993   DeclGroupPtrTy ActOnFinishObjCImplementation(Decl *ObjCImpDecl,
7994                                                ArrayRef<Decl *> Decls);
7995 
7996   DeclGroupPtrTy ActOnForwardClassDeclaration(SourceLocation Loc,
7997                    IdentifierInfo **IdentList,
7998                    SourceLocation *IdentLocs,
7999                    ArrayRef<ObjCTypeParamList *> TypeParamLists,
8000                    unsigned NumElts);
8001 
8002   DeclGroupPtrTy
8003   ActOnForwardProtocolDeclaration(SourceLocation AtProtoclLoc,
8004                                   ArrayRef<IdentifierLocPair> IdentList,
8005                                   const ParsedAttributesView &attrList);
8006 
8007   void FindProtocolDeclaration(bool WarnOnDeclarations, bool ForObjCContainer,
8008                                ArrayRef<IdentifierLocPair> ProtocolId,
8009                                SmallVectorImpl<Decl *> &Protocols);
8010 
8011   void DiagnoseTypeArgsAndProtocols(IdentifierInfo *ProtocolId,
8012                                     SourceLocation ProtocolLoc,
8013                                     IdentifierInfo *TypeArgId,
8014                                     SourceLocation TypeArgLoc,
8015                                     bool SelectProtocolFirst = false);
8016 
8017   /// Given a list of identifiers (and their locations), resolve the
8018   /// names to either Objective-C protocol qualifiers or type
8019   /// arguments, as appropriate.
8020   void actOnObjCTypeArgsOrProtocolQualifiers(
8021          Scope *S,
8022          ParsedType baseType,
8023          SourceLocation lAngleLoc,
8024          ArrayRef<IdentifierInfo *> identifiers,
8025          ArrayRef<SourceLocation> identifierLocs,
8026          SourceLocation rAngleLoc,
8027          SourceLocation &typeArgsLAngleLoc,
8028          SmallVectorImpl<ParsedType> &typeArgs,
8029          SourceLocation &typeArgsRAngleLoc,
8030          SourceLocation &protocolLAngleLoc,
8031          SmallVectorImpl<Decl *> &protocols,
8032          SourceLocation &protocolRAngleLoc,
8033          bool warnOnIncompleteProtocols);
8034 
8035   /// Build a an Objective-C protocol-qualified 'id' type where no
8036   /// base type was specified.
8037   TypeResult actOnObjCProtocolQualifierType(
8038                SourceLocation lAngleLoc,
8039                ArrayRef<Decl *> protocols,
8040                ArrayRef<SourceLocation> protocolLocs,
8041                SourceLocation rAngleLoc);
8042 
8043   /// Build a specialized and/or protocol-qualified Objective-C type.
8044   TypeResult actOnObjCTypeArgsAndProtocolQualifiers(
8045                Scope *S,
8046                SourceLocation Loc,
8047                ParsedType BaseType,
8048                SourceLocation TypeArgsLAngleLoc,
8049                ArrayRef<ParsedType> TypeArgs,
8050                SourceLocation TypeArgsRAngleLoc,
8051                SourceLocation ProtocolLAngleLoc,
8052                ArrayRef<Decl *> Protocols,
8053                ArrayRef<SourceLocation> ProtocolLocs,
8054                SourceLocation ProtocolRAngleLoc);
8055 
8056   /// Build an Objective-C type parameter type.
8057   QualType BuildObjCTypeParamType(const ObjCTypeParamDecl *Decl,
8058                                   SourceLocation ProtocolLAngleLoc,
8059                                   ArrayRef<ObjCProtocolDecl *> Protocols,
8060                                   ArrayRef<SourceLocation> ProtocolLocs,
8061                                   SourceLocation ProtocolRAngleLoc,
8062                                   bool FailOnError = false);
8063 
8064   /// Build an Objective-C object pointer type.
8065   QualType BuildObjCObjectType(QualType BaseType,
8066                                SourceLocation Loc,
8067                                SourceLocation TypeArgsLAngleLoc,
8068                                ArrayRef<TypeSourceInfo *> TypeArgs,
8069                                SourceLocation TypeArgsRAngleLoc,
8070                                SourceLocation ProtocolLAngleLoc,
8071                                ArrayRef<ObjCProtocolDecl *> Protocols,
8072                                ArrayRef<SourceLocation> ProtocolLocs,
8073                                SourceLocation ProtocolRAngleLoc,
8074                                bool FailOnError = false);
8075 
8076   /// Check the application of the Objective-C '__kindof' qualifier to
8077   /// the given type.
8078   bool checkObjCKindOfType(QualType &type, SourceLocation loc);
8079 
8080   /// Ensure attributes are consistent with type.
8081   /// \param [in, out] Attributes The attributes to check; they will
8082   /// be modified to be consistent with \p PropertyTy.
8083   void CheckObjCPropertyAttributes(Decl *PropertyPtrTy,
8084                                    SourceLocation Loc,
8085                                    unsigned &Attributes,
8086                                    bool propertyInPrimaryClass);
8087 
8088   /// Process the specified property declaration and create decls for the
8089   /// setters and getters as needed.
8090   /// \param property The property declaration being processed
8091   void ProcessPropertyDecl(ObjCPropertyDecl *property);
8092 
8093 
8094   void DiagnosePropertyMismatch(ObjCPropertyDecl *Property,
8095                                 ObjCPropertyDecl *SuperProperty,
8096                                 const IdentifierInfo *Name,
8097                                 bool OverridingProtocolProperty);
8098 
8099   void DiagnoseClassExtensionDupMethods(ObjCCategoryDecl *CAT,
8100                                         ObjCInterfaceDecl *ID);
8101 
8102   Decl *ActOnAtEnd(Scope *S, SourceRange AtEnd,
8103                    ArrayRef<Decl *> allMethods = None,
8104                    ArrayRef<DeclGroupPtrTy> allTUVars = None);
8105 
8106   Decl *ActOnProperty(Scope *S, SourceLocation AtLoc,
8107                       SourceLocation LParenLoc,
8108                       FieldDeclarator &FD, ObjCDeclSpec &ODS,
8109                       Selector GetterSel, Selector SetterSel,
8110                       tok::ObjCKeywordKind MethodImplKind,
8111                       DeclContext *lexicalDC = nullptr);
8112 
8113   Decl *ActOnPropertyImplDecl(Scope *S,
8114                               SourceLocation AtLoc,
8115                               SourceLocation PropertyLoc,
8116                               bool ImplKind,
8117                               IdentifierInfo *PropertyId,
8118                               IdentifierInfo *PropertyIvar,
8119                               SourceLocation PropertyIvarLoc,
8120                               ObjCPropertyQueryKind QueryKind);
8121 
8122   enum ObjCSpecialMethodKind {
8123     OSMK_None,
8124     OSMK_Alloc,
8125     OSMK_New,
8126     OSMK_Copy,
8127     OSMK_RetainingInit,
8128     OSMK_NonRetainingInit
8129   };
8130 
8131   struct ObjCArgInfo {
8132     IdentifierInfo *Name;
8133     SourceLocation NameLoc;
8134     // The Type is null if no type was specified, and the DeclSpec is invalid
8135     // in this case.
8136     ParsedType Type;
8137     ObjCDeclSpec DeclSpec;
8138 
8139     /// ArgAttrs - Attribute list for this argument.
8140     ParsedAttributesView ArgAttrs;
8141   };
8142 
8143   Decl *ActOnMethodDeclaration(
8144       Scope *S,
8145       SourceLocation BeginLoc, // location of the + or -.
8146       SourceLocation EndLoc,   // location of the ; or {.
8147       tok::TokenKind MethodType, ObjCDeclSpec &ReturnQT, ParsedType ReturnType,
8148       ArrayRef<SourceLocation> SelectorLocs, Selector Sel,
8149       // optional arguments. The number of types/arguments is obtained
8150       // from the Sel.getNumArgs().
8151       ObjCArgInfo *ArgInfo, DeclaratorChunk::ParamInfo *CParamInfo,
8152       unsigned CNumArgs, // c-style args
8153       const ParsedAttributesView &AttrList, tok::ObjCKeywordKind MethodImplKind,
8154       bool isVariadic, bool MethodDefinition);
8155 
8156   ObjCMethodDecl *LookupMethodInQualifiedType(Selector Sel,
8157                                               const ObjCObjectPointerType *OPT,
8158                                               bool IsInstance);
8159   ObjCMethodDecl *LookupMethodInObjectType(Selector Sel, QualType Ty,
8160                                            bool IsInstance);
8161 
8162   bool CheckARCMethodDecl(ObjCMethodDecl *method);
8163   bool inferObjCARCLifetime(ValueDecl *decl);
8164 
8165   ExprResult
8166   HandleExprPropertyRefExpr(const ObjCObjectPointerType *OPT,
8167                             Expr *BaseExpr,
8168                             SourceLocation OpLoc,
8169                             DeclarationName MemberName,
8170                             SourceLocation MemberLoc,
8171                             SourceLocation SuperLoc, QualType SuperType,
8172                             bool Super);
8173 
8174   ExprResult
8175   ActOnClassPropertyRefExpr(IdentifierInfo &receiverName,
8176                             IdentifierInfo &propertyName,
8177                             SourceLocation receiverNameLoc,
8178                             SourceLocation propertyNameLoc);
8179 
8180   ObjCMethodDecl *tryCaptureObjCSelf(SourceLocation Loc);
8181 
8182   /// Describes the kind of message expression indicated by a message
8183   /// send that starts with an identifier.
8184   enum ObjCMessageKind {
8185     /// The message is sent to 'super'.
8186     ObjCSuperMessage,
8187     /// The message is an instance message.
8188     ObjCInstanceMessage,
8189     /// The message is a class message, and the identifier is a type
8190     /// name.
8191     ObjCClassMessage
8192   };
8193 
8194   ObjCMessageKind getObjCMessageKind(Scope *S,
8195                                      IdentifierInfo *Name,
8196                                      SourceLocation NameLoc,
8197                                      bool IsSuper,
8198                                      bool HasTrailingDot,
8199                                      ParsedType &ReceiverType);
8200 
8201   ExprResult ActOnSuperMessage(Scope *S, SourceLocation SuperLoc,
8202                                Selector Sel,
8203                                SourceLocation LBracLoc,
8204                                ArrayRef<SourceLocation> SelectorLocs,
8205                                SourceLocation RBracLoc,
8206                                MultiExprArg Args);
8207 
8208   ExprResult BuildClassMessage(TypeSourceInfo *ReceiverTypeInfo,
8209                                QualType ReceiverType,
8210                                SourceLocation SuperLoc,
8211                                Selector Sel,
8212                                ObjCMethodDecl *Method,
8213                                SourceLocation LBracLoc,
8214                                ArrayRef<SourceLocation> SelectorLocs,
8215                                SourceLocation RBracLoc,
8216                                MultiExprArg Args,
8217                                bool isImplicit = false);
8218 
8219   ExprResult BuildClassMessageImplicit(QualType ReceiverType,
8220                                        bool isSuperReceiver,
8221                                        SourceLocation Loc,
8222                                        Selector Sel,
8223                                        ObjCMethodDecl *Method,
8224                                        MultiExprArg Args);
8225 
8226   ExprResult ActOnClassMessage(Scope *S,
8227                                ParsedType Receiver,
8228                                Selector Sel,
8229                                SourceLocation LBracLoc,
8230                                ArrayRef<SourceLocation> SelectorLocs,
8231                                SourceLocation RBracLoc,
8232                                MultiExprArg Args);
8233 
8234   ExprResult BuildInstanceMessage(Expr *Receiver,
8235                                   QualType ReceiverType,
8236                                   SourceLocation SuperLoc,
8237                                   Selector Sel,
8238                                   ObjCMethodDecl *Method,
8239                                   SourceLocation LBracLoc,
8240                                   ArrayRef<SourceLocation> SelectorLocs,
8241                                   SourceLocation RBracLoc,
8242                                   MultiExprArg Args,
8243                                   bool isImplicit = false);
8244 
8245   ExprResult BuildInstanceMessageImplicit(Expr *Receiver,
8246                                           QualType ReceiverType,
8247                                           SourceLocation Loc,
8248                                           Selector Sel,
8249                                           ObjCMethodDecl *Method,
8250                                           MultiExprArg Args);
8251 
8252   ExprResult ActOnInstanceMessage(Scope *S,
8253                                   Expr *Receiver,
8254                                   Selector Sel,
8255                                   SourceLocation LBracLoc,
8256                                   ArrayRef<SourceLocation> SelectorLocs,
8257                                   SourceLocation RBracLoc,
8258                                   MultiExprArg Args);
8259 
8260   ExprResult BuildObjCBridgedCast(SourceLocation LParenLoc,
8261                                   ObjCBridgeCastKind Kind,
8262                                   SourceLocation BridgeKeywordLoc,
8263                                   TypeSourceInfo *TSInfo,
8264                                   Expr *SubExpr);
8265 
8266   ExprResult ActOnObjCBridgedCast(Scope *S,
8267                                   SourceLocation LParenLoc,
8268                                   ObjCBridgeCastKind Kind,
8269                                   SourceLocation BridgeKeywordLoc,
8270                                   ParsedType Type,
8271                                   SourceLocation RParenLoc,
8272                                   Expr *SubExpr);
8273 
8274   void CheckTollFreeBridgeCast(QualType castType, Expr *castExpr);
8275 
8276   void CheckObjCBridgeRelatedCast(QualType castType, Expr *castExpr);
8277 
8278   bool CheckTollFreeBridgeStaticCast(QualType castType, Expr *castExpr,
8279                                      CastKind &Kind);
8280 
8281   bool checkObjCBridgeRelatedComponents(SourceLocation Loc,
8282                                         QualType DestType, QualType SrcType,
8283                                         ObjCInterfaceDecl *&RelatedClass,
8284                                         ObjCMethodDecl *&ClassMethod,
8285                                         ObjCMethodDecl *&InstanceMethod,
8286                                         TypedefNameDecl *&TDNDecl,
8287                                         bool CfToNs, bool Diagnose = true);
8288 
8289   bool CheckObjCBridgeRelatedConversions(SourceLocation Loc,
8290                                          QualType DestType, QualType SrcType,
8291                                          Expr *&SrcExpr, bool Diagnose = true);
8292 
8293   bool ConversionToObjCStringLiteralCheck(QualType DstType, Expr *&SrcExpr,
8294                                           bool Diagnose = true);
8295 
8296   bool checkInitMethod(ObjCMethodDecl *method, QualType receiverTypeIfCall);
8297 
8298   /// Check whether the given new method is a valid override of the
8299   /// given overridden method, and set any properties that should be inherited.
8300   void CheckObjCMethodOverride(ObjCMethodDecl *NewMethod,
8301                                const ObjCMethodDecl *Overridden);
8302 
8303   /// Describes the compatibility of a result type with its method.
8304   enum ResultTypeCompatibilityKind {
8305     RTC_Compatible,
8306     RTC_Incompatible,
8307     RTC_Unknown
8308   };
8309 
8310   void CheckObjCMethodOverrides(ObjCMethodDecl *ObjCMethod,
8311                                 ObjCInterfaceDecl *CurrentClass,
8312                                 ResultTypeCompatibilityKind RTC);
8313 
8314   enum PragmaOptionsAlignKind {
8315     POAK_Native,  // #pragma options align=native
8316     POAK_Natural, // #pragma options align=natural
8317     POAK_Packed,  // #pragma options align=packed
8318     POAK_Power,   // #pragma options align=power
8319     POAK_Mac68k,  // #pragma options align=mac68k
8320     POAK_Reset    // #pragma options align=reset
8321   };
8322 
8323   /// ActOnPragmaClangSection - Called on well formed \#pragma clang section
8324   void ActOnPragmaClangSection(SourceLocation PragmaLoc,
8325                                PragmaClangSectionAction Action,
8326                                PragmaClangSectionKind SecKind, StringRef SecName);
8327 
8328   /// ActOnPragmaOptionsAlign - Called on well formed \#pragma options align.
8329   void ActOnPragmaOptionsAlign(PragmaOptionsAlignKind Kind,
8330                                SourceLocation PragmaLoc);
8331 
8332   /// ActOnPragmaPack - Called on well formed \#pragma pack(...).
8333   void ActOnPragmaPack(SourceLocation PragmaLoc, PragmaMsStackAction Action,
8334                        StringRef SlotLabel, Expr *Alignment);
8335 
8336   enum class PragmaPackDiagnoseKind {
8337     NonDefaultStateAtInclude,
8338     ChangedStateAtExit
8339   };
8340 
8341   void DiagnoseNonDefaultPragmaPack(PragmaPackDiagnoseKind Kind,
8342                                     SourceLocation IncludeLoc);
8343   void DiagnoseUnterminatedPragmaPack();
8344 
8345   /// ActOnPragmaMSStruct - Called on well formed \#pragma ms_struct [on|off].
8346   void ActOnPragmaMSStruct(PragmaMSStructKind Kind);
8347 
8348   /// ActOnPragmaMSComment - Called on well formed
8349   /// \#pragma comment(kind, "arg").
8350   void ActOnPragmaMSComment(SourceLocation CommentLoc, PragmaMSCommentKind Kind,
8351                             StringRef Arg);
8352 
8353   /// ActOnPragmaMSPointersToMembers - called on well formed \#pragma
8354   /// pointers_to_members(representation method[, general purpose
8355   /// representation]).
8356   void ActOnPragmaMSPointersToMembers(
8357       LangOptions::PragmaMSPointersToMembersKind Kind,
8358       SourceLocation PragmaLoc);
8359 
8360   /// Called on well formed \#pragma vtordisp().
8361   void ActOnPragmaMSVtorDisp(PragmaMsStackAction Action,
8362                              SourceLocation PragmaLoc,
8363                              MSVtorDispAttr::Mode Value);
8364 
8365   enum PragmaSectionKind {
8366     PSK_DataSeg,
8367     PSK_BSSSeg,
8368     PSK_ConstSeg,
8369     PSK_CodeSeg,
8370   };
8371 
8372   bool UnifySection(StringRef SectionName,
8373                     int SectionFlags,
8374                     DeclaratorDecl *TheDecl);
8375   bool UnifySection(StringRef SectionName,
8376                     int SectionFlags,
8377                     SourceLocation PragmaSectionLocation);
8378 
8379   /// Called on well formed \#pragma bss_seg/data_seg/const_seg/code_seg.
8380   void ActOnPragmaMSSeg(SourceLocation PragmaLocation,
8381                         PragmaMsStackAction Action,
8382                         llvm::StringRef StackSlotLabel,
8383                         StringLiteral *SegmentName,
8384                         llvm::StringRef PragmaName);
8385 
8386   /// Called on well formed \#pragma section().
8387   void ActOnPragmaMSSection(SourceLocation PragmaLocation,
8388                             int SectionFlags, StringLiteral *SegmentName);
8389 
8390   /// Called on well-formed \#pragma init_seg().
8391   void ActOnPragmaMSInitSeg(SourceLocation PragmaLocation,
8392                             StringLiteral *SegmentName);
8393 
8394   /// Called on #pragma clang __debug dump II
8395   void ActOnPragmaDump(Scope *S, SourceLocation Loc, IdentifierInfo *II);
8396 
8397   /// ActOnPragmaDetectMismatch - Call on well-formed \#pragma detect_mismatch
8398   void ActOnPragmaDetectMismatch(SourceLocation Loc, StringRef Name,
8399                                  StringRef Value);
8400 
8401   /// ActOnPragmaUnused - Called on well-formed '\#pragma unused'.
8402   void ActOnPragmaUnused(const Token &Identifier,
8403                          Scope *curScope,
8404                          SourceLocation PragmaLoc);
8405 
8406   /// ActOnPragmaVisibility - Called on well formed \#pragma GCC visibility... .
8407   void ActOnPragmaVisibility(const IdentifierInfo* VisType,
8408                              SourceLocation PragmaLoc);
8409 
8410   NamedDecl *DeclClonePragmaWeak(NamedDecl *ND, IdentifierInfo *II,
8411                                  SourceLocation Loc);
8412   void DeclApplyPragmaWeak(Scope *S, NamedDecl *ND, WeakInfo &W);
8413 
8414   /// ActOnPragmaWeakID - Called on well formed \#pragma weak ident.
8415   void ActOnPragmaWeakID(IdentifierInfo* WeakName,
8416                          SourceLocation PragmaLoc,
8417                          SourceLocation WeakNameLoc);
8418 
8419   /// ActOnPragmaRedefineExtname - Called on well formed
8420   /// \#pragma redefine_extname oldname newname.
8421   void ActOnPragmaRedefineExtname(IdentifierInfo* WeakName,
8422                                   IdentifierInfo* AliasName,
8423                                   SourceLocation PragmaLoc,
8424                                   SourceLocation WeakNameLoc,
8425                                   SourceLocation AliasNameLoc);
8426 
8427   /// ActOnPragmaWeakAlias - Called on well formed \#pragma weak ident = ident.
8428   void ActOnPragmaWeakAlias(IdentifierInfo* WeakName,
8429                             IdentifierInfo* AliasName,
8430                             SourceLocation PragmaLoc,
8431                             SourceLocation WeakNameLoc,
8432                             SourceLocation AliasNameLoc);
8433 
8434   /// ActOnPragmaFPContract - Called on well formed
8435   /// \#pragma {STDC,OPENCL} FP_CONTRACT and
8436   /// \#pragma clang fp contract
8437   void ActOnPragmaFPContract(LangOptions::FPContractModeKind FPC);
8438 
8439   /// AddAlignmentAttributesForRecord - Adds any needed alignment attributes to
8440   /// a the record decl, to handle '\#pragma pack' and '\#pragma options align'.
8441   void AddAlignmentAttributesForRecord(RecordDecl *RD);
8442 
8443   /// AddMsStructLayoutForRecord - Adds ms_struct layout attribute to record.
8444   void AddMsStructLayoutForRecord(RecordDecl *RD);
8445 
8446   /// FreePackedContext - Deallocate and null out PackContext.
8447   void FreePackedContext();
8448 
8449   /// PushNamespaceVisibilityAttr - Note that we've entered a
8450   /// namespace with a visibility attribute.
8451   void PushNamespaceVisibilityAttr(const VisibilityAttr *Attr,
8452                                    SourceLocation Loc);
8453 
8454   /// AddPushedVisibilityAttribute - If '\#pragma GCC visibility' was used,
8455   /// add an appropriate visibility attribute.
8456   void AddPushedVisibilityAttribute(Decl *RD);
8457 
8458   /// PopPragmaVisibility - Pop the top element of the visibility stack; used
8459   /// for '\#pragma GCC visibility' and visibility attributes on namespaces.
8460   void PopPragmaVisibility(bool IsNamespaceEnd, SourceLocation EndLoc);
8461 
8462   /// FreeVisContext - Deallocate and null out VisContext.
8463   void FreeVisContext();
8464 
8465   /// AddCFAuditedAttribute - Check whether we're currently within
8466   /// '\#pragma clang arc_cf_code_audited' and, if so, consider adding
8467   /// the appropriate attribute.
8468   void AddCFAuditedAttribute(Decl *D);
8469 
8470   /// Called on well-formed '\#pragma clang attribute push'.
8471   void ActOnPragmaAttributePush(ParsedAttr &Attribute, SourceLocation PragmaLoc,
8472                                 attr::ParsedSubjectMatchRuleSet Rules);
8473 
8474   /// Called on well-formed '\#pragma clang attribute pop'.
8475   void ActOnPragmaAttributePop(SourceLocation PragmaLoc);
8476 
8477   /// Adds the attributes that have been specified using the
8478   /// '\#pragma clang attribute push' directives to the given declaration.
8479   void AddPragmaAttributes(Scope *S, Decl *D);
8480 
8481   void DiagnoseUnterminatedPragmaAttribute();
8482 
8483   /// Called on well formed \#pragma clang optimize.
8484   void ActOnPragmaOptimize(bool On, SourceLocation PragmaLoc);
8485 
8486   /// Get the location for the currently active "\#pragma clang optimize
8487   /// off". If this location is invalid, then the state of the pragma is "on".
getOptimizeOffPragmaLocation()8488   SourceLocation getOptimizeOffPragmaLocation() const {
8489     return OptimizeOffPragmaLocation;
8490   }
8491 
8492   /// Only called on function definitions; if there is a pragma in scope
8493   /// with the effect of a range-based optnone, consider marking the function
8494   /// with attribute optnone.
8495   void AddRangeBasedOptnone(FunctionDecl *FD);
8496 
8497   /// Adds the 'optnone' attribute to the function declaration if there
8498   /// are no conflicts; Loc represents the location causing the 'optnone'
8499   /// attribute to be added (usually because of a pragma).
8500   void AddOptnoneAttributeIfNoConflicts(FunctionDecl *FD, SourceLocation Loc);
8501 
8502   /// AddAlignedAttr - Adds an aligned attribute to a particular declaration.
8503   void AddAlignedAttr(SourceRange AttrRange, Decl *D, Expr *E,
8504                       unsigned SpellingListIndex, bool IsPackExpansion);
8505   void AddAlignedAttr(SourceRange AttrRange, Decl *D, TypeSourceInfo *T,
8506                       unsigned SpellingListIndex, bool IsPackExpansion);
8507 
8508   /// AddAssumeAlignedAttr - Adds an assume_aligned attribute to a particular
8509   /// declaration.
8510   void AddAssumeAlignedAttr(SourceRange AttrRange, Decl *D, Expr *E, Expr *OE,
8511                             unsigned SpellingListIndex);
8512 
8513   /// AddAllocAlignAttr - Adds an alloc_align attribute to a particular
8514   /// declaration.
8515   void AddAllocAlignAttr(SourceRange AttrRange, Decl *D, Expr *ParamExpr,
8516                          unsigned SpellingListIndex);
8517 
8518   /// AddAlignValueAttr - Adds an align_value attribute to a particular
8519   /// declaration.
8520   void AddAlignValueAttr(SourceRange AttrRange, Decl *D, Expr *E,
8521                          unsigned SpellingListIndex);
8522 
8523   /// AddLaunchBoundsAttr - Adds a launch_bounds attribute to a particular
8524   /// declaration.
8525   void AddLaunchBoundsAttr(SourceRange AttrRange, Decl *D, Expr *MaxThreads,
8526                            Expr *MinBlocks, unsigned SpellingListIndex);
8527 
8528   /// AddModeAttr - Adds a mode attribute to a particular declaration.
8529   void AddModeAttr(SourceRange AttrRange, Decl *D, IdentifierInfo *Name,
8530                    unsigned SpellingListIndex, bool InInstantiation = false);
8531 
8532   void AddParameterABIAttr(SourceRange AttrRange, Decl *D,
8533                            ParameterABI ABI, unsigned SpellingListIndex);
8534 
8535   void AddNSConsumedAttr(SourceRange AttrRange, Decl *D,
8536                          unsigned SpellingListIndex, bool isNSConsumed,
8537                          bool isTemplateInstantiation);
8538 
8539   bool checkNSReturnsRetainedReturnType(SourceLocation loc, QualType type);
8540 
8541   //===--------------------------------------------------------------------===//
8542   // C++ Coroutines TS
8543   //
8544   bool ActOnCoroutineBodyStart(Scope *S, SourceLocation KwLoc,
8545                                StringRef Keyword);
8546   ExprResult ActOnCoawaitExpr(Scope *S, SourceLocation KwLoc, Expr *E);
8547   ExprResult ActOnCoyieldExpr(Scope *S, SourceLocation KwLoc, Expr *E);
8548   StmtResult ActOnCoreturnStmt(Scope *S, SourceLocation KwLoc, Expr *E);
8549 
8550   ExprResult BuildResolvedCoawaitExpr(SourceLocation KwLoc, Expr *E,
8551                                       bool IsImplicit = false);
8552   ExprResult BuildUnresolvedCoawaitExpr(SourceLocation KwLoc, Expr *E,
8553                                         UnresolvedLookupExpr* Lookup);
8554   ExprResult BuildCoyieldExpr(SourceLocation KwLoc, Expr *E);
8555   StmtResult BuildCoreturnStmt(SourceLocation KwLoc, Expr *E,
8556                                bool IsImplicit = false);
8557   StmtResult BuildCoroutineBodyStmt(CoroutineBodyStmt::CtorArgs);
8558   bool buildCoroutineParameterMoves(SourceLocation Loc);
8559   VarDecl *buildCoroutinePromise(SourceLocation Loc);
8560   void CheckCompletedCoroutineBody(FunctionDecl *FD, Stmt *&Body);
8561   ClassTemplateDecl *lookupCoroutineTraits(SourceLocation KwLoc,
8562                                            SourceLocation FuncLoc);
8563 
8564   //===--------------------------------------------------------------------===//
8565   // OpenCL extensions.
8566   //
8567 private:
8568   std::string CurrOpenCLExtension;
8569   /// Extensions required by an OpenCL type.
8570   llvm::DenseMap<const Type*, std::set<std::string>> OpenCLTypeExtMap;
8571   /// Extensions required by an OpenCL declaration.
8572   llvm::DenseMap<const Decl*, std::set<std::string>> OpenCLDeclExtMap;
8573 public:
getCurrentOpenCLExtension()8574   llvm::StringRef getCurrentOpenCLExtension() const {
8575     return CurrOpenCLExtension;
8576   }
setCurrentOpenCLExtension(llvm::StringRef Ext)8577   void setCurrentOpenCLExtension(llvm::StringRef Ext) {
8578     CurrOpenCLExtension = Ext;
8579   }
8580 
8581   /// Set OpenCL extensions for a type which can only be used when these
8582   /// OpenCL extensions are enabled. If \p Exts is empty, do nothing.
8583   /// \param Exts A space separated list of OpenCL extensions.
8584   void setOpenCLExtensionForType(QualType T, llvm::StringRef Exts);
8585 
8586   /// Set OpenCL extensions for a declaration which can only be
8587   /// used when these OpenCL extensions are enabled. If \p Exts is empty, do
8588   /// nothing.
8589   /// \param Exts A space separated list of OpenCL extensions.
8590   void setOpenCLExtensionForDecl(Decl *FD, llvm::StringRef Exts);
8591 
8592   /// Set current OpenCL extensions for a type which can only be used
8593   /// when these OpenCL extensions are enabled. If current OpenCL extension is
8594   /// empty, do nothing.
8595   void setCurrentOpenCLExtensionForType(QualType T);
8596 
8597   /// Set current OpenCL extensions for a declaration which
8598   /// can only be used when these OpenCL extensions are enabled. If current
8599   /// OpenCL extension is empty, do nothing.
8600   void setCurrentOpenCLExtensionForDecl(Decl *FD);
8601 
8602   bool isOpenCLDisabledDecl(Decl *FD);
8603 
8604   /// Check if type \p T corresponding to declaration specifier \p DS
8605   /// is disabled due to required OpenCL extensions being disabled. If so,
8606   /// emit diagnostics.
8607   /// \return true if type is disabled.
8608   bool checkOpenCLDisabledTypeDeclSpec(const DeclSpec &DS, QualType T);
8609 
8610   /// Check if declaration \p D used by expression \p E
8611   /// is disabled due to required OpenCL extensions being disabled. If so,
8612   /// emit diagnostics.
8613   /// \return true if type is disabled.
8614   bool checkOpenCLDisabledDecl(const NamedDecl &D, const Expr &E);
8615 
8616   //===--------------------------------------------------------------------===//
8617   // OpenMP directives and clauses.
8618   //
8619 private:
8620   void *VarDataSharingAttributesStack;
8621   /// Set to true inside '#pragma omp declare target' region.
8622   bool IsInOpenMPDeclareTargetContext = false;
8623   /// Initialization of data-sharing attributes stack.
8624   void InitDataSharingAttributesStack();
8625   void DestroyDataSharingAttributesStack();
8626   ExprResult
8627   VerifyPositiveIntegerConstantInClause(Expr *Op, OpenMPClauseKind CKind,
8628                                         bool StrictlyPositive = true);
8629   /// Returns OpenMP nesting level for current directive.
8630   unsigned getOpenMPNestingLevel() const;
8631 
8632   /// Adjusts the function scopes index for the target-based regions.
8633   void adjustOpenMPTargetScopeIndex(unsigned &FunctionScopesIndex,
8634                                     unsigned Level) const;
8635 
8636   /// Push new OpenMP function region for non-capturing function.
8637   void pushOpenMPFunctionRegion();
8638 
8639   /// Pop OpenMP function region for non-capturing function.
8640   void popOpenMPFunctionRegion(const sema::FunctionScopeInfo *OldFSI);
8641 
8642   /// Checks if a type or a declaration is disabled due to the owning extension
8643   /// being disabled, and emits diagnostic messages if it is disabled.
8644   /// \param D type or declaration to be checked.
8645   /// \param DiagLoc source location for the diagnostic message.
8646   /// \param DiagInfo information to be emitted for the diagnostic message.
8647   /// \param SrcRange source range of the declaration.
8648   /// \param Map maps type or declaration to the extensions.
8649   /// \param Selector selects diagnostic message: 0 for type and 1 for
8650   ///        declaration.
8651   /// \return true if the type or declaration is disabled.
8652   template <typename T, typename DiagLocT, typename DiagInfoT, typename MapT>
8653   bool checkOpenCLDisabledTypeOrDecl(T D, DiagLocT DiagLoc, DiagInfoT DiagInfo,
8654                                      MapT &Map, unsigned Selector = 0,
8655                                      SourceRange SrcRange = SourceRange());
8656 
8657 public:
8658   /// Return true if the provided declaration \a VD should be captured by
8659   /// reference.
8660   /// \param Level Relative level of nested OpenMP construct for that the check
8661   /// is performed.
8662   bool isOpenMPCapturedByRef(const ValueDecl *D, unsigned Level) const;
8663 
8664   /// Check if the specified variable is used in one of the private
8665   /// clauses (private, firstprivate, lastprivate, reduction etc.) in OpenMP
8666   /// constructs.
8667   VarDecl *isOpenMPCapturedDecl(ValueDecl *D) const;
8668   ExprResult getOpenMPCapturedExpr(VarDecl *Capture, ExprValueKind VK,
8669                                    ExprObjectKind OK, SourceLocation Loc);
8670 
8671   /// Check if the specified variable is used in 'private' clause.
8672   /// \param Level Relative level of nested OpenMP construct for that the check
8673   /// is performed.
8674   bool isOpenMPPrivateDecl(const ValueDecl *D, unsigned Level) const;
8675 
8676   /// Sets OpenMP capture kind (OMPC_private, OMPC_firstprivate, OMPC_map etc.)
8677   /// for \p FD based on DSA for the provided corresponding captured declaration
8678   /// \p D.
8679   void setOpenMPCaptureKind(FieldDecl *FD, const ValueDecl *D, unsigned Level);
8680 
8681   /// Check if the specified variable is captured  by 'target' directive.
8682   /// \param Level Relative level of nested OpenMP construct for that the check
8683   /// is performed.
8684   bool isOpenMPTargetCapturedDecl(const ValueDecl *D, unsigned Level) const;
8685 
8686   ExprResult PerformOpenMPImplicitIntegerConversion(SourceLocation OpLoc,
8687                                                     Expr *Op);
8688   /// Called on start of new data sharing attribute block.
8689   void StartOpenMPDSABlock(OpenMPDirectiveKind K,
8690                            const DeclarationNameInfo &DirName, Scope *CurScope,
8691                            SourceLocation Loc);
8692   /// Start analysis of clauses.
8693   void StartOpenMPClause(OpenMPClauseKind K);
8694   /// End analysis of clauses.
8695   void EndOpenMPClause();
8696   /// Called on end of data sharing attribute block.
8697   void EndOpenMPDSABlock(Stmt *CurDirective);
8698 
8699   /// Check if the current region is an OpenMP loop region and if it is,
8700   /// mark loop control variable, used in \p Init for loop initialization, as
8701   /// private by default.
8702   /// \param Init First part of the for loop.
8703   void ActOnOpenMPLoopInitialization(SourceLocation ForLoc, Stmt *Init);
8704 
8705   // OpenMP directives and clauses.
8706   /// Called on correct id-expression from the '#pragma omp
8707   /// threadprivate'.
8708   ExprResult ActOnOpenMPIdExpression(Scope *CurScope,
8709                                      CXXScopeSpec &ScopeSpec,
8710                                      const DeclarationNameInfo &Id);
8711   /// Called on well-formed '#pragma omp threadprivate'.
8712   DeclGroupPtrTy ActOnOpenMPThreadprivateDirective(
8713                                      SourceLocation Loc,
8714                                      ArrayRef<Expr *> VarList);
8715   /// Builds a new OpenMPThreadPrivateDecl and checks its correctness.
8716   OMPThreadPrivateDecl *CheckOMPThreadPrivateDecl(SourceLocation Loc,
8717                                                   ArrayRef<Expr *> VarList);
8718   /// Check if the specified type is allowed to be used in 'omp declare
8719   /// reduction' construct.
8720   QualType ActOnOpenMPDeclareReductionType(SourceLocation TyLoc,
8721                                            TypeResult ParsedType);
8722   /// Called on start of '#pragma omp declare reduction'.
8723   DeclGroupPtrTy ActOnOpenMPDeclareReductionDirectiveStart(
8724       Scope *S, DeclContext *DC, DeclarationName Name,
8725       ArrayRef<std::pair<QualType, SourceLocation>> ReductionTypes,
8726       AccessSpecifier AS, Decl *PrevDeclInScope = nullptr);
8727   /// Initialize declare reduction construct initializer.
8728   void ActOnOpenMPDeclareReductionCombinerStart(Scope *S, Decl *D);
8729   /// Finish current declare reduction construct initializer.
8730   void ActOnOpenMPDeclareReductionCombinerEnd(Decl *D, Expr *Combiner);
8731   /// Initialize declare reduction construct initializer.
8732   /// \return omp_priv variable.
8733   VarDecl *ActOnOpenMPDeclareReductionInitializerStart(Scope *S, Decl *D);
8734   /// Finish current declare reduction construct initializer.
8735   void ActOnOpenMPDeclareReductionInitializerEnd(Decl *D, Expr *Initializer,
8736                                                  VarDecl *OmpPrivParm);
8737   /// Called at the end of '#pragma omp declare reduction'.
8738   DeclGroupPtrTy ActOnOpenMPDeclareReductionDirectiveEnd(
8739       Scope *S, DeclGroupPtrTy DeclReductions, bool IsValid);
8740 
8741   /// Called on the start of target region i.e. '#pragma omp declare target'.
8742   bool ActOnStartOpenMPDeclareTargetDirective(SourceLocation Loc);
8743   /// Called at the end of target region i.e. '#pragme omp end declare target'.
8744   void ActOnFinishOpenMPDeclareTargetDirective();
8745   /// Called on correct id-expression from the '#pragma omp declare target'.
8746   void ActOnOpenMPDeclareTargetName(Scope *CurScope, CXXScopeSpec &ScopeSpec,
8747                                     const DeclarationNameInfo &Id,
8748                                     OMPDeclareTargetDeclAttr::MapTypeTy MT,
8749                                     NamedDeclSetType &SameDirectiveDecls);
8750   /// Check declaration inside target region.
8751   void checkDeclIsAllowedInOpenMPTarget(Expr *E, Decl *D,
8752                                         SourceLocation IdLoc = SourceLocation());
8753   /// Return true inside OpenMP declare target region.
isInOpenMPDeclareTargetContext()8754   bool isInOpenMPDeclareTargetContext() const {
8755     return IsInOpenMPDeclareTargetContext;
8756   }
8757   /// Return true inside OpenMP target region.
8758   bool isInOpenMPTargetExecutionDirective() const;
8759   /// Return true if (un)supported features for the current target should be
8760   /// diagnosed if OpenMP (offloading) is enabled.
shouldDiagnoseTargetSupportFromOpenMP()8761   bool shouldDiagnoseTargetSupportFromOpenMP() const {
8762     return !getLangOpts().OpenMPIsDevice || isInOpenMPDeclareTargetContext() ||
8763       isInOpenMPTargetExecutionDirective();
8764   }
8765 
8766   /// Return the number of captured regions created for an OpenMP directive.
8767   static int getOpenMPCaptureLevels(OpenMPDirectiveKind Kind);
8768 
8769   /// Initialization of captured region for OpenMP region.
8770   void ActOnOpenMPRegionStart(OpenMPDirectiveKind DKind, Scope *CurScope);
8771   /// End of OpenMP region.
8772   ///
8773   /// \param S Statement associated with the current OpenMP region.
8774   /// \param Clauses List of clauses for the current OpenMP region.
8775   ///
8776   /// \returns Statement for finished OpenMP region.
8777   StmtResult ActOnOpenMPRegionEnd(StmtResult S, ArrayRef<OMPClause *> Clauses);
8778   StmtResult ActOnOpenMPExecutableDirective(
8779       OpenMPDirectiveKind Kind, const DeclarationNameInfo &DirName,
8780       OpenMPDirectiveKind CancelRegion, ArrayRef<OMPClause *> Clauses,
8781       Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc);
8782   /// Called on well-formed '\#pragma omp parallel' after parsing
8783   /// of the  associated statement.
8784   StmtResult ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses,
8785                                           Stmt *AStmt,
8786                                           SourceLocation StartLoc,
8787                                           SourceLocation EndLoc);
8788   using VarsWithInheritedDSAType =
8789       llvm::SmallDenseMap<const ValueDecl *, const Expr *, 4>;
8790   /// Called on well-formed '\#pragma omp simd' after parsing
8791   /// of the associated statement.
8792   StmtResult
8793   ActOnOpenMPSimdDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
8794                            SourceLocation StartLoc, SourceLocation EndLoc,
8795                            VarsWithInheritedDSAType &VarsWithImplicitDSA);
8796   /// Called on well-formed '\#pragma omp for' after parsing
8797   /// of the associated statement.
8798   StmtResult
8799   ActOnOpenMPForDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
8800                           SourceLocation StartLoc, SourceLocation EndLoc,
8801                           VarsWithInheritedDSAType &VarsWithImplicitDSA);
8802   /// Called on well-formed '\#pragma omp for simd' after parsing
8803   /// of the associated statement.
8804   StmtResult
8805   ActOnOpenMPForSimdDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
8806                               SourceLocation StartLoc, SourceLocation EndLoc,
8807                               VarsWithInheritedDSAType &VarsWithImplicitDSA);
8808   /// Called on well-formed '\#pragma omp sections' after parsing
8809   /// of the associated statement.
8810   StmtResult ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses,
8811                                           Stmt *AStmt, SourceLocation StartLoc,
8812                                           SourceLocation EndLoc);
8813   /// Called on well-formed '\#pragma omp section' after parsing of the
8814   /// associated statement.
8815   StmtResult ActOnOpenMPSectionDirective(Stmt *AStmt, SourceLocation StartLoc,
8816                                          SourceLocation EndLoc);
8817   /// Called on well-formed '\#pragma omp single' after parsing of the
8818   /// associated statement.
8819   StmtResult ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses,
8820                                         Stmt *AStmt, SourceLocation StartLoc,
8821                                         SourceLocation EndLoc);
8822   /// Called on well-formed '\#pragma omp master' after parsing of the
8823   /// associated statement.
8824   StmtResult ActOnOpenMPMasterDirective(Stmt *AStmt, SourceLocation StartLoc,
8825                                         SourceLocation EndLoc);
8826   /// Called on well-formed '\#pragma omp critical' after parsing of the
8827   /// associated statement.
8828   StmtResult ActOnOpenMPCriticalDirective(const DeclarationNameInfo &DirName,
8829                                           ArrayRef<OMPClause *> Clauses,
8830                                           Stmt *AStmt, SourceLocation StartLoc,
8831                                           SourceLocation EndLoc);
8832   /// Called on well-formed '\#pragma omp parallel for' after parsing
8833   /// of the  associated statement.
8834   StmtResult ActOnOpenMPParallelForDirective(
8835       ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8836       SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
8837   /// Called on well-formed '\#pragma omp parallel for simd' after
8838   /// parsing of the  associated statement.
8839   StmtResult ActOnOpenMPParallelForSimdDirective(
8840       ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8841       SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
8842   /// Called on well-formed '\#pragma omp parallel sections' after
8843   /// parsing of the  associated statement.
8844   StmtResult ActOnOpenMPParallelSectionsDirective(ArrayRef<OMPClause *> Clauses,
8845                                                   Stmt *AStmt,
8846                                                   SourceLocation StartLoc,
8847                                                   SourceLocation EndLoc);
8848   /// Called on well-formed '\#pragma omp task' after parsing of the
8849   /// associated statement.
8850   StmtResult ActOnOpenMPTaskDirective(ArrayRef<OMPClause *> Clauses,
8851                                       Stmt *AStmt, SourceLocation StartLoc,
8852                                       SourceLocation EndLoc);
8853   /// Called on well-formed '\#pragma omp taskyield'.
8854   StmtResult ActOnOpenMPTaskyieldDirective(SourceLocation StartLoc,
8855                                            SourceLocation EndLoc);
8856   /// Called on well-formed '\#pragma omp barrier'.
8857   StmtResult ActOnOpenMPBarrierDirective(SourceLocation StartLoc,
8858                                          SourceLocation EndLoc);
8859   /// Called on well-formed '\#pragma omp taskwait'.
8860   StmtResult ActOnOpenMPTaskwaitDirective(SourceLocation StartLoc,
8861                                           SourceLocation EndLoc);
8862   /// Called on well-formed '\#pragma omp taskgroup'.
8863   StmtResult ActOnOpenMPTaskgroupDirective(ArrayRef<OMPClause *> Clauses,
8864                                            Stmt *AStmt, SourceLocation StartLoc,
8865                                            SourceLocation EndLoc);
8866   /// Called on well-formed '\#pragma omp flush'.
8867   StmtResult ActOnOpenMPFlushDirective(ArrayRef<OMPClause *> Clauses,
8868                                        SourceLocation StartLoc,
8869                                        SourceLocation EndLoc);
8870   /// Called on well-formed '\#pragma omp ordered' after parsing of the
8871   /// associated statement.
8872   StmtResult ActOnOpenMPOrderedDirective(ArrayRef<OMPClause *> Clauses,
8873                                          Stmt *AStmt, SourceLocation StartLoc,
8874                                          SourceLocation EndLoc);
8875   /// Called on well-formed '\#pragma omp atomic' after parsing of the
8876   /// associated statement.
8877   StmtResult ActOnOpenMPAtomicDirective(ArrayRef<OMPClause *> Clauses,
8878                                         Stmt *AStmt, SourceLocation StartLoc,
8879                                         SourceLocation EndLoc);
8880   /// Called on well-formed '\#pragma omp target' after parsing of the
8881   /// associated statement.
8882   StmtResult ActOnOpenMPTargetDirective(ArrayRef<OMPClause *> Clauses,
8883                                         Stmt *AStmt, SourceLocation StartLoc,
8884                                         SourceLocation EndLoc);
8885   /// Called on well-formed '\#pragma omp target data' after parsing of
8886   /// the associated statement.
8887   StmtResult ActOnOpenMPTargetDataDirective(ArrayRef<OMPClause *> Clauses,
8888                                             Stmt *AStmt, SourceLocation StartLoc,
8889                                             SourceLocation EndLoc);
8890   /// Called on well-formed '\#pragma omp target enter data' after
8891   /// parsing of the associated statement.
8892   StmtResult ActOnOpenMPTargetEnterDataDirective(ArrayRef<OMPClause *> Clauses,
8893                                                  SourceLocation StartLoc,
8894                                                  SourceLocation EndLoc,
8895                                                  Stmt *AStmt);
8896   /// Called on well-formed '\#pragma omp target exit data' after
8897   /// parsing of the associated statement.
8898   StmtResult ActOnOpenMPTargetExitDataDirective(ArrayRef<OMPClause *> Clauses,
8899                                                 SourceLocation StartLoc,
8900                                                 SourceLocation EndLoc,
8901                                                 Stmt *AStmt);
8902   /// Called on well-formed '\#pragma omp target parallel' after
8903   /// parsing of the associated statement.
8904   StmtResult ActOnOpenMPTargetParallelDirective(ArrayRef<OMPClause *> Clauses,
8905                                                 Stmt *AStmt,
8906                                                 SourceLocation StartLoc,
8907                                                 SourceLocation EndLoc);
8908   /// Called on well-formed '\#pragma omp target parallel for' after
8909   /// parsing of the  associated statement.
8910   StmtResult ActOnOpenMPTargetParallelForDirective(
8911       ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8912       SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
8913   /// Called on well-formed '\#pragma omp teams' after parsing of the
8914   /// associated statement.
8915   StmtResult ActOnOpenMPTeamsDirective(ArrayRef<OMPClause *> Clauses,
8916                                        Stmt *AStmt, SourceLocation StartLoc,
8917                                        SourceLocation EndLoc);
8918   /// Called on well-formed '\#pragma omp cancellation point'.
8919   StmtResult
8920   ActOnOpenMPCancellationPointDirective(SourceLocation StartLoc,
8921                                         SourceLocation EndLoc,
8922                                         OpenMPDirectiveKind CancelRegion);
8923   /// Called on well-formed '\#pragma omp cancel'.
8924   StmtResult ActOnOpenMPCancelDirective(ArrayRef<OMPClause *> Clauses,
8925                                         SourceLocation StartLoc,
8926                                         SourceLocation EndLoc,
8927                                         OpenMPDirectiveKind CancelRegion);
8928   /// Called on well-formed '\#pragma omp taskloop' after parsing of the
8929   /// associated statement.
8930   StmtResult
8931   ActOnOpenMPTaskLoopDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
8932                                SourceLocation StartLoc, SourceLocation EndLoc,
8933                                VarsWithInheritedDSAType &VarsWithImplicitDSA);
8934   /// Called on well-formed '\#pragma omp taskloop simd' after parsing of
8935   /// the associated statement.
8936   StmtResult ActOnOpenMPTaskLoopSimdDirective(
8937       ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8938       SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
8939   /// Called on well-formed '\#pragma omp distribute' after parsing
8940   /// of the associated statement.
8941   StmtResult
8942   ActOnOpenMPDistributeDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
8943                                  SourceLocation StartLoc, SourceLocation EndLoc,
8944                                  VarsWithInheritedDSAType &VarsWithImplicitDSA);
8945   /// Called on well-formed '\#pragma omp target update'.
8946   StmtResult ActOnOpenMPTargetUpdateDirective(ArrayRef<OMPClause *> Clauses,
8947                                               SourceLocation StartLoc,
8948                                               SourceLocation EndLoc,
8949                                               Stmt *AStmt);
8950   /// Called on well-formed '\#pragma omp distribute parallel for' after
8951   /// parsing of the associated statement.
8952   StmtResult ActOnOpenMPDistributeParallelForDirective(
8953       ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8954       SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
8955   /// Called on well-formed '\#pragma omp distribute parallel for simd'
8956   /// after parsing of the associated statement.
8957   StmtResult ActOnOpenMPDistributeParallelForSimdDirective(
8958       ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8959       SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
8960   /// Called on well-formed '\#pragma omp distribute simd' after
8961   /// parsing of the associated statement.
8962   StmtResult ActOnOpenMPDistributeSimdDirective(
8963       ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8964       SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
8965   /// Called on well-formed '\#pragma omp target parallel for simd' after
8966   /// parsing of the associated statement.
8967   StmtResult ActOnOpenMPTargetParallelForSimdDirective(
8968       ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8969       SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
8970   /// Called on well-formed '\#pragma omp target simd' after parsing of
8971   /// the associated statement.
8972   StmtResult
8973   ActOnOpenMPTargetSimdDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
8974                                  SourceLocation StartLoc, SourceLocation EndLoc,
8975                                  VarsWithInheritedDSAType &VarsWithImplicitDSA);
8976   /// Called on well-formed '\#pragma omp teams distribute' after parsing of
8977   /// the associated statement.
8978   StmtResult ActOnOpenMPTeamsDistributeDirective(
8979       ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8980       SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
8981   /// Called on well-formed '\#pragma omp teams distribute simd' after parsing
8982   /// of the associated statement.
8983   StmtResult ActOnOpenMPTeamsDistributeSimdDirective(
8984       ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8985       SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
8986   /// Called on well-formed '\#pragma omp teams distribute parallel for simd'
8987   /// after parsing of the associated statement.
8988   StmtResult ActOnOpenMPTeamsDistributeParallelForSimdDirective(
8989       ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8990       SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
8991   /// Called on well-formed '\#pragma omp teams distribute parallel for'
8992   /// after parsing of the associated statement.
8993   StmtResult ActOnOpenMPTeamsDistributeParallelForDirective(
8994       ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8995       SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
8996   /// Called on well-formed '\#pragma omp target teams' after parsing of the
8997   /// associated statement.
8998   StmtResult ActOnOpenMPTargetTeamsDirective(ArrayRef<OMPClause *> Clauses,
8999                                              Stmt *AStmt,
9000                                              SourceLocation StartLoc,
9001                                              SourceLocation EndLoc);
9002   /// Called on well-formed '\#pragma omp target teams distribute' after parsing
9003   /// of the associated statement.
9004   StmtResult ActOnOpenMPTargetTeamsDistributeDirective(
9005       ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
9006       SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
9007   /// Called on well-formed '\#pragma omp target teams distribute parallel for'
9008   /// after parsing of the associated statement.
9009   StmtResult ActOnOpenMPTargetTeamsDistributeParallelForDirective(
9010       ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
9011       SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
9012   /// Called on well-formed '\#pragma omp target teams distribute parallel for
9013   /// simd' after parsing of the associated statement.
9014   StmtResult ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective(
9015       ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
9016       SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
9017   /// Called on well-formed '\#pragma omp target teams distribute simd' after
9018   /// parsing of the associated statement.
9019   StmtResult ActOnOpenMPTargetTeamsDistributeSimdDirective(
9020       ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
9021       SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
9022 
9023   /// Checks correctness of linear modifiers.
9024   bool CheckOpenMPLinearModifier(OpenMPLinearClauseKind LinKind,
9025                                  SourceLocation LinLoc);
9026   /// Checks that the specified declaration matches requirements for the linear
9027   /// decls.
9028   bool CheckOpenMPLinearDecl(const ValueDecl *D, SourceLocation ELoc,
9029                              OpenMPLinearClauseKind LinKind, QualType Type);
9030 
9031   /// Called on well-formed '\#pragma omp declare simd' after parsing of
9032   /// the associated method/function.
9033   DeclGroupPtrTy ActOnOpenMPDeclareSimdDirective(
9034       DeclGroupPtrTy DG, OMPDeclareSimdDeclAttr::BranchStateTy BS,
9035       Expr *Simdlen, ArrayRef<Expr *> Uniforms, ArrayRef<Expr *> Aligneds,
9036       ArrayRef<Expr *> Alignments, ArrayRef<Expr *> Linears,
9037       ArrayRef<unsigned> LinModifiers, ArrayRef<Expr *> Steps, SourceRange SR);
9038 
9039   OMPClause *ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind,
9040                                          Expr *Expr,
9041                                          SourceLocation StartLoc,
9042                                          SourceLocation LParenLoc,
9043                                          SourceLocation EndLoc);
9044   /// Called on well-formed 'if' clause.
9045   OMPClause *ActOnOpenMPIfClause(OpenMPDirectiveKind NameModifier,
9046                                  Expr *Condition, SourceLocation StartLoc,
9047                                  SourceLocation LParenLoc,
9048                                  SourceLocation NameModifierLoc,
9049                                  SourceLocation ColonLoc,
9050                                  SourceLocation EndLoc);
9051   /// Called on well-formed 'final' clause.
9052   OMPClause *ActOnOpenMPFinalClause(Expr *Condition, SourceLocation StartLoc,
9053                                     SourceLocation LParenLoc,
9054                                     SourceLocation EndLoc);
9055   /// Called on well-formed 'num_threads' clause.
9056   OMPClause *ActOnOpenMPNumThreadsClause(Expr *NumThreads,
9057                                          SourceLocation StartLoc,
9058                                          SourceLocation LParenLoc,
9059                                          SourceLocation EndLoc);
9060   /// Called on well-formed 'safelen' clause.
9061   OMPClause *ActOnOpenMPSafelenClause(Expr *Length,
9062                                       SourceLocation StartLoc,
9063                                       SourceLocation LParenLoc,
9064                                       SourceLocation EndLoc);
9065   /// Called on well-formed 'simdlen' clause.
9066   OMPClause *ActOnOpenMPSimdlenClause(Expr *Length, SourceLocation StartLoc,
9067                                       SourceLocation LParenLoc,
9068                                       SourceLocation EndLoc);
9069   /// Called on well-formed 'collapse' clause.
9070   OMPClause *ActOnOpenMPCollapseClause(Expr *NumForLoops,
9071                                        SourceLocation StartLoc,
9072                                        SourceLocation LParenLoc,
9073                                        SourceLocation EndLoc);
9074   /// Called on well-formed 'ordered' clause.
9075   OMPClause *
9076   ActOnOpenMPOrderedClause(SourceLocation StartLoc, SourceLocation EndLoc,
9077                            SourceLocation LParenLoc = SourceLocation(),
9078                            Expr *NumForLoops = nullptr);
9079   /// Called on well-formed 'grainsize' clause.
9080   OMPClause *ActOnOpenMPGrainsizeClause(Expr *Size, SourceLocation StartLoc,
9081                                         SourceLocation LParenLoc,
9082                                         SourceLocation EndLoc);
9083   /// Called on well-formed 'num_tasks' clause.
9084   OMPClause *ActOnOpenMPNumTasksClause(Expr *NumTasks, SourceLocation StartLoc,
9085                                        SourceLocation LParenLoc,
9086                                        SourceLocation EndLoc);
9087   /// Called on well-formed 'hint' clause.
9088   OMPClause *ActOnOpenMPHintClause(Expr *Hint, SourceLocation StartLoc,
9089                                    SourceLocation LParenLoc,
9090                                    SourceLocation EndLoc);
9091 
9092   OMPClause *ActOnOpenMPSimpleClause(OpenMPClauseKind Kind,
9093                                      unsigned Argument,
9094                                      SourceLocation ArgumentLoc,
9095                                      SourceLocation StartLoc,
9096                                      SourceLocation LParenLoc,
9097                                      SourceLocation EndLoc);
9098   /// Called on well-formed 'default' clause.
9099   OMPClause *ActOnOpenMPDefaultClause(OpenMPDefaultClauseKind Kind,
9100                                       SourceLocation KindLoc,
9101                                       SourceLocation StartLoc,
9102                                       SourceLocation LParenLoc,
9103                                       SourceLocation EndLoc);
9104   /// Called on well-formed 'proc_bind' clause.
9105   OMPClause *ActOnOpenMPProcBindClause(OpenMPProcBindClauseKind Kind,
9106                                        SourceLocation KindLoc,
9107                                        SourceLocation StartLoc,
9108                                        SourceLocation LParenLoc,
9109                                        SourceLocation EndLoc);
9110 
9111   OMPClause *ActOnOpenMPSingleExprWithArgClause(
9112       OpenMPClauseKind Kind, ArrayRef<unsigned> Arguments, Expr *Expr,
9113       SourceLocation StartLoc, SourceLocation LParenLoc,
9114       ArrayRef<SourceLocation> ArgumentsLoc, SourceLocation DelimLoc,
9115       SourceLocation EndLoc);
9116   /// Called on well-formed 'schedule' clause.
9117   OMPClause *ActOnOpenMPScheduleClause(
9118       OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2,
9119       OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
9120       SourceLocation LParenLoc, SourceLocation M1Loc, SourceLocation M2Loc,
9121       SourceLocation KindLoc, SourceLocation CommaLoc, SourceLocation EndLoc);
9122 
9123   OMPClause *ActOnOpenMPClause(OpenMPClauseKind Kind, SourceLocation StartLoc,
9124                                SourceLocation EndLoc);
9125   /// Called on well-formed 'nowait' clause.
9126   OMPClause *ActOnOpenMPNowaitClause(SourceLocation StartLoc,
9127                                      SourceLocation EndLoc);
9128   /// Called on well-formed 'untied' clause.
9129   OMPClause *ActOnOpenMPUntiedClause(SourceLocation StartLoc,
9130                                      SourceLocation EndLoc);
9131   /// Called on well-formed 'mergeable' clause.
9132   OMPClause *ActOnOpenMPMergeableClause(SourceLocation StartLoc,
9133                                         SourceLocation EndLoc);
9134   /// Called on well-formed 'read' clause.
9135   OMPClause *ActOnOpenMPReadClause(SourceLocation StartLoc,
9136                                    SourceLocation EndLoc);
9137   /// Called on well-formed 'write' clause.
9138   OMPClause *ActOnOpenMPWriteClause(SourceLocation StartLoc,
9139                                     SourceLocation EndLoc);
9140   /// Called on well-formed 'update' clause.
9141   OMPClause *ActOnOpenMPUpdateClause(SourceLocation StartLoc,
9142                                      SourceLocation EndLoc);
9143   /// Called on well-formed 'capture' clause.
9144   OMPClause *ActOnOpenMPCaptureClause(SourceLocation StartLoc,
9145                                       SourceLocation EndLoc);
9146   /// Called on well-formed 'seq_cst' clause.
9147   OMPClause *ActOnOpenMPSeqCstClause(SourceLocation StartLoc,
9148                                      SourceLocation EndLoc);
9149   /// Called on well-formed 'threads' clause.
9150   OMPClause *ActOnOpenMPThreadsClause(SourceLocation StartLoc,
9151                                       SourceLocation EndLoc);
9152   /// Called on well-formed 'simd' clause.
9153   OMPClause *ActOnOpenMPSIMDClause(SourceLocation StartLoc,
9154                                    SourceLocation EndLoc);
9155   /// Called on well-formed 'nogroup' clause.
9156   OMPClause *ActOnOpenMPNogroupClause(SourceLocation StartLoc,
9157                                       SourceLocation EndLoc);
9158 
9159   OMPClause *ActOnOpenMPVarListClause(
9160       OpenMPClauseKind Kind, ArrayRef<Expr *> Vars, Expr *TailExpr,
9161       SourceLocation StartLoc, SourceLocation LParenLoc,
9162       SourceLocation ColonLoc, SourceLocation EndLoc,
9163       CXXScopeSpec &ReductionIdScopeSpec,
9164       const DeclarationNameInfo &ReductionId, OpenMPDependClauseKind DepKind,
9165       OpenMPLinearClauseKind LinKind, OpenMPMapClauseKind MapTypeModifier,
9166       OpenMPMapClauseKind MapType, bool IsMapTypeImplicit,
9167       SourceLocation DepLinMapLoc);
9168   /// Called on well-formed 'private' clause.
9169   OMPClause *ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList,
9170                                       SourceLocation StartLoc,
9171                                       SourceLocation LParenLoc,
9172                                       SourceLocation EndLoc);
9173   /// Called on well-formed 'firstprivate' clause.
9174   OMPClause *ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList,
9175                                            SourceLocation StartLoc,
9176                                            SourceLocation LParenLoc,
9177                                            SourceLocation EndLoc);
9178   /// Called on well-formed 'lastprivate' clause.
9179   OMPClause *ActOnOpenMPLastprivateClause(ArrayRef<Expr *> VarList,
9180                                           SourceLocation StartLoc,
9181                                           SourceLocation LParenLoc,
9182                                           SourceLocation EndLoc);
9183   /// Called on well-formed 'shared' clause.
9184   OMPClause *ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList,
9185                                      SourceLocation StartLoc,
9186                                      SourceLocation LParenLoc,
9187                                      SourceLocation EndLoc);
9188   /// Called on well-formed 'reduction' clause.
9189   OMPClause *ActOnOpenMPReductionClause(
9190       ArrayRef<Expr *> VarList, SourceLocation StartLoc,
9191       SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc,
9192       CXXScopeSpec &ReductionIdScopeSpec,
9193       const DeclarationNameInfo &ReductionId,
9194       ArrayRef<Expr *> UnresolvedReductions = llvm::None);
9195   /// Called on well-formed 'task_reduction' clause.
9196   OMPClause *ActOnOpenMPTaskReductionClause(
9197       ArrayRef<Expr *> VarList, SourceLocation StartLoc,
9198       SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc,
9199       CXXScopeSpec &ReductionIdScopeSpec,
9200       const DeclarationNameInfo &ReductionId,
9201       ArrayRef<Expr *> UnresolvedReductions = llvm::None);
9202   /// Called on well-formed 'in_reduction' clause.
9203   OMPClause *ActOnOpenMPInReductionClause(
9204       ArrayRef<Expr *> VarList, SourceLocation StartLoc,
9205       SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc,
9206       CXXScopeSpec &ReductionIdScopeSpec,
9207       const DeclarationNameInfo &ReductionId,
9208       ArrayRef<Expr *> UnresolvedReductions = llvm::None);
9209   /// Called on well-formed 'linear' clause.
9210   OMPClause *
9211   ActOnOpenMPLinearClause(ArrayRef<Expr *> VarList, Expr *Step,
9212                           SourceLocation StartLoc, SourceLocation LParenLoc,
9213                           OpenMPLinearClauseKind LinKind, SourceLocation LinLoc,
9214                           SourceLocation ColonLoc, SourceLocation EndLoc);
9215   /// Called on well-formed 'aligned' clause.
9216   OMPClause *ActOnOpenMPAlignedClause(ArrayRef<Expr *> VarList,
9217                                       Expr *Alignment,
9218                                       SourceLocation StartLoc,
9219                                       SourceLocation LParenLoc,
9220                                       SourceLocation ColonLoc,
9221                                       SourceLocation EndLoc);
9222   /// Called on well-formed 'copyin' clause.
9223   OMPClause *ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList,
9224                                      SourceLocation StartLoc,
9225                                      SourceLocation LParenLoc,
9226                                      SourceLocation EndLoc);
9227   /// Called on well-formed 'copyprivate' clause.
9228   OMPClause *ActOnOpenMPCopyprivateClause(ArrayRef<Expr *> VarList,
9229                                           SourceLocation StartLoc,
9230                                           SourceLocation LParenLoc,
9231                                           SourceLocation EndLoc);
9232   /// Called on well-formed 'flush' pseudo clause.
9233   OMPClause *ActOnOpenMPFlushClause(ArrayRef<Expr *> VarList,
9234                                     SourceLocation StartLoc,
9235                                     SourceLocation LParenLoc,
9236                                     SourceLocation EndLoc);
9237   /// Called on well-formed 'depend' clause.
9238   OMPClause *
9239   ActOnOpenMPDependClause(OpenMPDependClauseKind DepKind, SourceLocation DepLoc,
9240                           SourceLocation ColonLoc, ArrayRef<Expr *> VarList,
9241                           SourceLocation StartLoc, SourceLocation LParenLoc,
9242                           SourceLocation EndLoc);
9243   /// Called on well-formed 'device' clause.
9244   OMPClause *ActOnOpenMPDeviceClause(Expr *Device, SourceLocation StartLoc,
9245                                      SourceLocation LParenLoc,
9246                                      SourceLocation EndLoc);
9247   /// Called on well-formed 'map' clause.
9248   OMPClause *
9249   ActOnOpenMPMapClause(OpenMPMapClauseKind MapTypeModifier,
9250                        OpenMPMapClauseKind MapType, bool IsMapTypeImplicit,
9251                        SourceLocation MapLoc, SourceLocation ColonLoc,
9252                        ArrayRef<Expr *> VarList, SourceLocation StartLoc,
9253                        SourceLocation LParenLoc, SourceLocation EndLoc);
9254   /// Called on well-formed 'num_teams' clause.
9255   OMPClause *ActOnOpenMPNumTeamsClause(Expr *NumTeams, SourceLocation StartLoc,
9256                                        SourceLocation LParenLoc,
9257                                        SourceLocation EndLoc);
9258   /// Called on well-formed 'thread_limit' clause.
9259   OMPClause *ActOnOpenMPThreadLimitClause(Expr *ThreadLimit,
9260                                           SourceLocation StartLoc,
9261                                           SourceLocation LParenLoc,
9262                                           SourceLocation EndLoc);
9263   /// Called on well-formed 'priority' clause.
9264   OMPClause *ActOnOpenMPPriorityClause(Expr *Priority, SourceLocation StartLoc,
9265                                        SourceLocation LParenLoc,
9266                                        SourceLocation EndLoc);
9267   /// Called on well-formed 'dist_schedule' clause.
9268   OMPClause *ActOnOpenMPDistScheduleClause(
9269       OpenMPDistScheduleClauseKind Kind, Expr *ChunkSize,
9270       SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation KindLoc,
9271       SourceLocation CommaLoc, SourceLocation EndLoc);
9272   /// Called on well-formed 'defaultmap' clause.
9273   OMPClause *ActOnOpenMPDefaultmapClause(
9274       OpenMPDefaultmapClauseModifier M, OpenMPDefaultmapClauseKind Kind,
9275       SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation MLoc,
9276       SourceLocation KindLoc, SourceLocation EndLoc);
9277   /// Called on well-formed 'to' clause.
9278   OMPClause *ActOnOpenMPToClause(ArrayRef<Expr *> VarList,
9279                                  SourceLocation StartLoc,
9280                                  SourceLocation LParenLoc,
9281                                  SourceLocation EndLoc);
9282   /// Called on well-formed 'from' clause.
9283   OMPClause *ActOnOpenMPFromClause(ArrayRef<Expr *> VarList,
9284                                    SourceLocation StartLoc,
9285                                    SourceLocation LParenLoc,
9286                                    SourceLocation EndLoc);
9287   /// Called on well-formed 'use_device_ptr' clause.
9288   OMPClause *ActOnOpenMPUseDevicePtrClause(ArrayRef<Expr *> VarList,
9289                                            SourceLocation StartLoc,
9290                                            SourceLocation LParenLoc,
9291                                            SourceLocation EndLoc);
9292   /// Called on well-formed 'is_device_ptr' clause.
9293   OMPClause *ActOnOpenMPIsDevicePtrClause(ArrayRef<Expr *> VarList,
9294                                           SourceLocation StartLoc,
9295                                           SourceLocation LParenLoc,
9296                                           SourceLocation EndLoc);
9297 
9298   /// The kind of conversion being performed.
9299   enum CheckedConversionKind {
9300     /// An implicit conversion.
9301     CCK_ImplicitConversion,
9302     /// A C-style cast.
9303     CCK_CStyleCast,
9304     /// A functional-style cast.
9305     CCK_FunctionalCast,
9306     /// A cast other than a C-style cast.
9307     CCK_OtherCast,
9308     /// A conversion for an operand of a builtin overloaded operator.
9309     CCK_ForBuiltinOverloadedOp
9310   };
9311 
isCast(CheckedConversionKind CCK)9312   static bool isCast(CheckedConversionKind CCK) {
9313     return CCK == CCK_CStyleCast || CCK == CCK_FunctionalCast ||
9314            CCK == CCK_OtherCast;
9315   }
9316 
9317   /// ImpCastExprToType - If Expr is not of type 'Type', insert an implicit
9318   /// cast.  If there is already an implicit cast, merge into the existing one.
9319   /// If isLvalue, the result of the cast is an lvalue.
9320   ExprResult ImpCastExprToType(Expr *E, QualType Type, CastKind CK,
9321                                ExprValueKind VK = VK_RValue,
9322                                const CXXCastPath *BasePath = nullptr,
9323                                CheckedConversionKind CCK
9324                                   = CCK_ImplicitConversion);
9325 
9326   /// ScalarTypeToBooleanCastKind - Returns the cast kind corresponding
9327   /// to the conversion from scalar type ScalarTy to the Boolean type.
9328   static CastKind ScalarTypeToBooleanCastKind(QualType ScalarTy);
9329 
9330   /// IgnoredValueConversions - Given that an expression's result is
9331   /// syntactically ignored, perform any conversions that are
9332   /// required.
9333   ExprResult IgnoredValueConversions(Expr *E);
9334 
9335   // UsualUnaryConversions - promotes integers (C99 6.3.1.1p2) and converts
9336   // functions and arrays to their respective pointers (C99 6.3.2.1).
9337   ExprResult UsualUnaryConversions(Expr *E);
9338 
9339   /// CallExprUnaryConversions - a special case of an unary conversion
9340   /// performed on a function designator of a call expression.
9341   ExprResult CallExprUnaryConversions(Expr *E);
9342 
9343   // DefaultFunctionArrayConversion - converts functions and arrays
9344   // to their respective pointers (C99 6.3.2.1).
9345   ExprResult DefaultFunctionArrayConversion(Expr *E, bool Diagnose = true);
9346 
9347   // DefaultFunctionArrayLvalueConversion - converts functions and
9348   // arrays to their respective pointers and performs the
9349   // lvalue-to-rvalue conversion.
9350   ExprResult DefaultFunctionArrayLvalueConversion(Expr *E,
9351                                                   bool Diagnose = true);
9352 
9353   // DefaultLvalueConversion - performs lvalue-to-rvalue conversion on
9354   // the operand.  This is DefaultFunctionArrayLvalueConversion,
9355   // except that it assumes the operand isn't of function or array
9356   // type.
9357   ExprResult DefaultLvalueConversion(Expr *E);
9358 
9359   // DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
9360   // do not have a prototype. Integer promotions are performed on each
9361   // argument, and arguments that have type float are promoted to double.
9362   ExprResult DefaultArgumentPromotion(Expr *E);
9363 
9364   /// If \p E is a prvalue denoting an unmaterialized temporary, materialize
9365   /// it as an xvalue. In C++98, the result will still be a prvalue, because
9366   /// we don't have xvalues there.
9367   ExprResult TemporaryMaterializationConversion(Expr *E);
9368 
9369   // Used for emitting the right warning by DefaultVariadicArgumentPromotion
9370   enum VariadicCallType {
9371     VariadicFunction,
9372     VariadicBlock,
9373     VariadicMethod,
9374     VariadicConstructor,
9375     VariadicDoesNotApply
9376   };
9377 
9378   VariadicCallType getVariadicCallType(FunctionDecl *FDecl,
9379                                        const FunctionProtoType *Proto,
9380                                        Expr *Fn);
9381 
9382   // Used for determining in which context a type is allowed to be passed to a
9383   // vararg function.
9384   enum VarArgKind {
9385     VAK_Valid,
9386     VAK_ValidInCXX11,
9387     VAK_Undefined,
9388     VAK_MSVCUndefined,
9389     VAK_Invalid
9390   };
9391 
9392   // Determines which VarArgKind fits an expression.
9393   VarArgKind isValidVarArgType(const QualType &Ty);
9394 
9395   /// Check to see if the given expression is a valid argument to a variadic
9396   /// function, issuing a diagnostic if not.
9397   void checkVariadicArgument(const Expr *E, VariadicCallType CT);
9398 
9399   /// Check to see if a given expression could have '.c_str()' called on it.
9400   bool hasCStrMethod(const Expr *E);
9401 
9402   /// GatherArgumentsForCall - Collector argument expressions for various
9403   /// form of call prototypes.
9404   bool GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl,
9405                               const FunctionProtoType *Proto,
9406                               unsigned FirstParam, ArrayRef<Expr *> Args,
9407                               SmallVectorImpl<Expr *> &AllArgs,
9408                               VariadicCallType CallType = VariadicDoesNotApply,
9409                               bool AllowExplicit = false,
9410                               bool IsListInitialization = false);
9411 
9412   // DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
9413   // will create a runtime trap if the resulting type is not a POD type.
9414   ExprResult DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
9415                                               FunctionDecl *FDecl);
9416 
9417   // UsualArithmeticConversions - performs the UsualUnaryConversions on it's
9418   // operands and then handles various conversions that are common to binary
9419   // operators (C99 6.3.1.8). If both operands aren't arithmetic, this
9420   // routine returns the first non-arithmetic type found. The client is
9421   // responsible for emitting appropriate error diagnostics.
9422   QualType UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
9423                                       bool IsCompAssign = false);
9424 
9425   /// AssignConvertType - All of the 'assignment' semantic checks return this
9426   /// enum to indicate whether the assignment was allowed.  These checks are
9427   /// done for simple assignments, as well as initialization, return from
9428   /// function, argument passing, etc.  The query is phrased in terms of a
9429   /// source and destination type.
9430   enum AssignConvertType {
9431     /// Compatible - the types are compatible according to the standard.
9432     Compatible,
9433 
9434     /// PointerToInt - The assignment converts a pointer to an int, which we
9435     /// accept as an extension.
9436     PointerToInt,
9437 
9438     /// IntToPointer - The assignment converts an int to a pointer, which we
9439     /// accept as an extension.
9440     IntToPointer,
9441 
9442     /// FunctionVoidPointer - The assignment is between a function pointer and
9443     /// void*, which the standard doesn't allow, but we accept as an extension.
9444     FunctionVoidPointer,
9445 
9446     /// IncompatiblePointer - The assignment is between two pointers types that
9447     /// are not compatible, but we accept them as an extension.
9448     IncompatiblePointer,
9449 
9450     /// IncompatiblePointerSign - The assignment is between two pointers types
9451     /// which point to integers which have a different sign, but are otherwise
9452     /// identical. This is a subset of the above, but broken out because it's by
9453     /// far the most common case of incompatible pointers.
9454     IncompatiblePointerSign,
9455 
9456     /// CompatiblePointerDiscardsQualifiers - The assignment discards
9457     /// c/v/r qualifiers, which we accept as an extension.
9458     CompatiblePointerDiscardsQualifiers,
9459 
9460     /// IncompatiblePointerDiscardsQualifiers - The assignment
9461     /// discards qualifiers that we don't permit to be discarded,
9462     /// like address spaces.
9463     IncompatiblePointerDiscardsQualifiers,
9464 
9465     /// IncompatibleNestedPointerQualifiers - The assignment is between two
9466     /// nested pointer types, and the qualifiers other than the first two
9467     /// levels differ e.g. char ** -> const char **, but we accept them as an
9468     /// extension.
9469     IncompatibleNestedPointerQualifiers,
9470 
9471     /// IncompatibleVectors - The assignment is between two vector types that
9472     /// have the same size, which we accept as an extension.
9473     IncompatibleVectors,
9474 
9475     /// IntToBlockPointer - The assignment converts an int to a block
9476     /// pointer. We disallow this.
9477     IntToBlockPointer,
9478 
9479     /// IncompatibleBlockPointer - The assignment is between two block
9480     /// pointers types that are not compatible.
9481     IncompatibleBlockPointer,
9482 
9483     /// IncompatibleObjCQualifiedId - The assignment is between a qualified
9484     /// id type and something else (that is incompatible with it). For example,
9485     /// "id <XXX>" = "Foo *", where "Foo *" doesn't implement the XXX protocol.
9486     IncompatibleObjCQualifiedId,
9487 
9488     /// IncompatibleObjCWeakRef - Assigning a weak-unavailable object to an
9489     /// object with __weak qualifier.
9490     IncompatibleObjCWeakRef,
9491 
9492     /// Incompatible - We reject this conversion outright, it is invalid to
9493     /// represent it in the AST.
9494     Incompatible
9495   };
9496 
9497   /// DiagnoseAssignmentResult - Emit a diagnostic, if required, for the
9498   /// assignment conversion type specified by ConvTy.  This returns true if the
9499   /// conversion was invalid or false if the conversion was accepted.
9500   bool DiagnoseAssignmentResult(AssignConvertType ConvTy,
9501                                 SourceLocation Loc,
9502                                 QualType DstType, QualType SrcType,
9503                                 Expr *SrcExpr, AssignmentAction Action,
9504                                 bool *Complained = nullptr);
9505 
9506   /// IsValueInFlagEnum - Determine if a value is allowed as part of a flag
9507   /// enum. If AllowMask is true, then we also allow the complement of a valid
9508   /// value, to be used as a mask.
9509   bool IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
9510                          bool AllowMask) const;
9511 
9512   /// DiagnoseAssignmentEnum - Warn if assignment to enum is a constant
9513   /// integer not in the range of enum values.
9514   void DiagnoseAssignmentEnum(QualType DstType, QualType SrcType,
9515                               Expr *SrcExpr);
9516 
9517   /// CheckAssignmentConstraints - Perform type checking for assignment,
9518   /// argument passing, variable initialization, and function return values.
9519   /// C99 6.5.16.
9520   AssignConvertType CheckAssignmentConstraints(SourceLocation Loc,
9521                                                QualType LHSType,
9522                                                QualType RHSType);
9523 
9524   /// Check assignment constraints and optionally prepare for a conversion of
9525   /// the RHS to the LHS type. The conversion is prepared for if ConvertRHS
9526   /// is true.
9527   AssignConvertType CheckAssignmentConstraints(QualType LHSType,
9528                                                ExprResult &RHS,
9529                                                CastKind &Kind,
9530                                                bool ConvertRHS = true);
9531 
9532   /// Check assignment constraints for an assignment of RHS to LHSType.
9533   ///
9534   /// \param LHSType The destination type for the assignment.
9535   /// \param RHS The source expression for the assignment.
9536   /// \param Diagnose If \c true, diagnostics may be produced when checking
9537   ///        for assignability. If a diagnostic is produced, \p RHS will be
9538   ///        set to ExprError(). Note that this function may still return
9539   ///        without producing a diagnostic, even for an invalid assignment.
9540   /// \param DiagnoseCFAudited If \c true, the target is a function parameter
9541   ///        in an audited Core Foundation API and does not need to be checked
9542   ///        for ARC retain issues.
9543   /// \param ConvertRHS If \c true, \p RHS will be updated to model the
9544   ///        conversions necessary to perform the assignment. If \c false,
9545   ///        \p Diagnose must also be \c false.
9546   AssignConvertType CheckSingleAssignmentConstraints(
9547       QualType LHSType, ExprResult &RHS, bool Diagnose = true,
9548       bool DiagnoseCFAudited = false, bool ConvertRHS = true);
9549 
9550   // If the lhs type is a transparent union, check whether we
9551   // can initialize the transparent union with the given expression.
9552   AssignConvertType CheckTransparentUnionArgumentConstraints(QualType ArgType,
9553                                                              ExprResult &RHS);
9554 
9555   bool IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType);
9556 
9557   bool CheckExceptionSpecCompatibility(Expr *From, QualType ToType);
9558 
9559   ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
9560                                        AssignmentAction Action,
9561                                        bool AllowExplicit = false);
9562   ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
9563                                        AssignmentAction Action,
9564                                        bool AllowExplicit,
9565                                        ImplicitConversionSequence& ICS);
9566   ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
9567                                        const ImplicitConversionSequence& ICS,
9568                                        AssignmentAction Action,
9569                                        CheckedConversionKind CCK
9570                                           = CCK_ImplicitConversion);
9571   ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
9572                                        const StandardConversionSequence& SCS,
9573                                        AssignmentAction Action,
9574                                        CheckedConversionKind CCK);
9575 
9576   /// the following "Check" methods will return a valid/converted QualType
9577   /// or a null QualType (indicating an error diagnostic was issued).
9578 
9579   /// type checking binary operators (subroutines of CreateBuiltinBinOp).
9580   QualType InvalidOperands(SourceLocation Loc, ExprResult &LHS,
9581                            ExprResult &RHS);
9582   QualType InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS,
9583                                  ExprResult &RHS);
9584   QualType CheckPointerToMemberOperands( // C++ 5.5
9585     ExprResult &LHS, ExprResult &RHS, ExprValueKind &VK,
9586     SourceLocation OpLoc, bool isIndirect);
9587   QualType CheckMultiplyDivideOperands( // C99 6.5.5
9588     ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign,
9589     bool IsDivide);
9590   QualType CheckRemainderOperands( // C99 6.5.5
9591     ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
9592     bool IsCompAssign = false);
9593   QualType CheckAdditionOperands( // C99 6.5.6
9594     ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
9595     BinaryOperatorKind Opc, QualType* CompLHSTy = nullptr);
9596   QualType CheckSubtractionOperands( // C99 6.5.6
9597     ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
9598     QualType* CompLHSTy = nullptr);
9599   QualType CheckShiftOperands( // C99 6.5.7
9600     ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
9601     BinaryOperatorKind Opc, bool IsCompAssign = false);
9602   QualType CheckCompareOperands( // C99 6.5.8/9
9603       ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
9604       BinaryOperatorKind Opc);
9605   QualType CheckBitwiseOperands( // C99 6.5.[10...12]
9606       ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
9607       BinaryOperatorKind Opc);
9608   QualType CheckLogicalOperands( // C99 6.5.[13,14]
9609     ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
9610     BinaryOperatorKind Opc);
9611   // CheckAssignmentOperands is used for both simple and compound assignment.
9612   // For simple assignment, pass both expressions and a null converted type.
9613   // For compound assignment, pass both expressions and the converted type.
9614   QualType CheckAssignmentOperands( // C99 6.5.16.[1,2]
9615     Expr *LHSExpr, ExprResult &RHS, SourceLocation Loc, QualType CompoundType);
9616 
9617   ExprResult checkPseudoObjectIncDec(Scope *S, SourceLocation OpLoc,
9618                                      UnaryOperatorKind Opcode, Expr *Op);
9619   ExprResult checkPseudoObjectAssignment(Scope *S, SourceLocation OpLoc,
9620                                          BinaryOperatorKind Opcode,
9621                                          Expr *LHS, Expr *RHS);
9622   ExprResult checkPseudoObjectRValue(Expr *E);
9623   Expr *recreateSyntacticForm(PseudoObjectExpr *E);
9624 
9625   QualType CheckConditionalOperands( // C99 6.5.15
9626     ExprResult &Cond, ExprResult &LHS, ExprResult &RHS,
9627     ExprValueKind &VK, ExprObjectKind &OK, SourceLocation QuestionLoc);
9628   QualType CXXCheckConditionalOperands( // C++ 5.16
9629     ExprResult &cond, ExprResult &lhs, ExprResult &rhs,
9630     ExprValueKind &VK, ExprObjectKind &OK, SourceLocation questionLoc);
9631   QualType FindCompositePointerType(SourceLocation Loc, Expr *&E1, Expr *&E2,
9632                                     bool ConvertArgs = true);
9633   QualType FindCompositePointerType(SourceLocation Loc,
9634                                     ExprResult &E1, ExprResult &E2,
9635                                     bool ConvertArgs = true) {
9636     Expr *E1Tmp = E1.get(), *E2Tmp = E2.get();
9637     QualType Composite =
9638         FindCompositePointerType(Loc, E1Tmp, E2Tmp, ConvertArgs);
9639     E1 = E1Tmp;
9640     E2 = E2Tmp;
9641     return Composite;
9642   }
9643 
9644   QualType FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
9645                                         SourceLocation QuestionLoc);
9646 
9647   bool DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
9648                                   SourceLocation QuestionLoc);
9649 
9650   void DiagnoseAlwaysNonNullPointer(Expr *E,
9651                                     Expr::NullPointerConstantKind NullType,
9652                                     bool IsEqual, SourceRange Range);
9653 
9654   /// type checking for vector binary operators.
9655   QualType CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
9656                                SourceLocation Loc, bool IsCompAssign,
9657                                bool AllowBothBool, bool AllowBoolConversion);
9658   QualType GetSignedVectorType(QualType V);
9659   QualType CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
9660                                       SourceLocation Loc,
9661                                       BinaryOperatorKind Opc);
9662   QualType CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
9663                                       SourceLocation Loc);
9664 
9665   bool areLaxCompatibleVectorTypes(QualType srcType, QualType destType);
9666   bool isLaxVectorConversion(QualType srcType, QualType destType);
9667 
9668   /// type checking declaration initializers (C99 6.7.8)
9669   bool CheckForConstantInitializer(Expr *e, QualType t);
9670 
9671   // type checking C++ declaration initializers (C++ [dcl.init]).
9672 
9673   /// ReferenceCompareResult - Expresses the result of comparing two
9674   /// types (cv1 T1 and cv2 T2) to determine their compatibility for the
9675   /// purposes of initialization by reference (C++ [dcl.init.ref]p4).
9676   enum ReferenceCompareResult {
9677     /// Ref_Incompatible - The two types are incompatible, so direct
9678     /// reference binding is not possible.
9679     Ref_Incompatible = 0,
9680     /// Ref_Related - The two types are reference-related, which means
9681     /// that their unqualified forms (T1 and T2) are either the same
9682     /// or T1 is a base class of T2.
9683     Ref_Related,
9684     /// Ref_Compatible - The two types are reference-compatible.
9685     Ref_Compatible
9686   };
9687 
9688   ReferenceCompareResult CompareReferenceRelationship(SourceLocation Loc,
9689                                                       QualType T1, QualType T2,
9690                                                       bool &DerivedToBase,
9691                                                       bool &ObjCConversion,
9692                                                 bool &ObjCLifetimeConversion);
9693 
9694   ExprResult checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
9695                                  Expr *CastExpr, CastKind &CastKind,
9696                                  ExprValueKind &VK, CXXCastPath &Path);
9697 
9698   /// Force an expression with unknown-type to an expression of the
9699   /// given type.
9700   ExprResult forceUnknownAnyToType(Expr *E, QualType ToType);
9701 
9702   /// Type-check an expression that's being passed to an
9703   /// __unknown_anytype parameter.
9704   ExprResult checkUnknownAnyArg(SourceLocation callLoc,
9705                                 Expr *result, QualType &paramType);
9706 
9707   // CheckVectorCast - check type constraints for vectors.
9708   // Since vectors are an extension, there are no C standard reference for this.
9709   // We allow casting between vectors and integer datatypes of the same size.
9710   // returns true if the cast is invalid
9711   bool CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
9712                        CastKind &Kind);
9713 
9714   /// Prepare `SplattedExpr` for a vector splat operation, adding
9715   /// implicit casts if necessary.
9716   ExprResult prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr);
9717 
9718   // CheckExtVectorCast - check type constraints for extended vectors.
9719   // Since vectors are an extension, there are no C standard reference for this.
9720   // We allow casting between vectors and integer datatypes of the same size,
9721   // or vectors and the element type of that vector.
9722   // returns the cast expr
9723   ExprResult CheckExtVectorCast(SourceRange R, QualType DestTy, Expr *CastExpr,
9724                                 CastKind &Kind);
9725 
9726   ExprResult BuildCXXFunctionalCastExpr(TypeSourceInfo *TInfo, QualType Type,
9727                                         SourceLocation LParenLoc,
9728                                         Expr *CastExpr,
9729                                         SourceLocation RParenLoc);
9730 
9731   enum ARCConversionResult { ACR_okay, ACR_unbridged, ACR_error };
9732 
9733   /// Checks for invalid conversions and casts between
9734   /// retainable pointers and other pointer kinds for ARC and Weak.
9735   ARCConversionResult CheckObjCConversion(SourceRange castRange,
9736                                           QualType castType, Expr *&op,
9737                                           CheckedConversionKind CCK,
9738                                           bool Diagnose = true,
9739                                           bool DiagnoseCFAudited = false,
9740                                           BinaryOperatorKind Opc = BO_PtrMemD
9741                                           );
9742 
9743   Expr *stripARCUnbridgedCast(Expr *e);
9744   void diagnoseARCUnbridgedCast(Expr *e);
9745 
9746   bool CheckObjCARCUnavailableWeakConversion(QualType castType,
9747                                              QualType ExprType);
9748 
9749   /// checkRetainCycles - Check whether an Objective-C message send
9750   /// might create an obvious retain cycle.
9751   void checkRetainCycles(ObjCMessageExpr *msg);
9752   void checkRetainCycles(Expr *receiver, Expr *argument);
9753   void checkRetainCycles(VarDecl *Var, Expr *Init);
9754 
9755   /// checkUnsafeAssigns - Check whether +1 expr is being assigned
9756   /// to weak/__unsafe_unretained type.
9757   bool checkUnsafeAssigns(SourceLocation Loc, QualType LHS, Expr *RHS);
9758 
9759   /// checkUnsafeExprAssigns - Check whether +1 expr is being assigned
9760   /// to weak/__unsafe_unretained expression.
9761   void checkUnsafeExprAssigns(SourceLocation Loc, Expr *LHS, Expr *RHS);
9762 
9763   /// CheckMessageArgumentTypes - Check types in an Obj-C message send.
9764   /// \param Method - May be null.
9765   /// \param [out] ReturnType - The return type of the send.
9766   /// \return true iff there were any incompatible types.
9767   bool CheckMessageArgumentTypes(QualType ReceiverType,
9768                                  MultiExprArg Args, Selector Sel,
9769                                  ArrayRef<SourceLocation> SelectorLocs,
9770                                  ObjCMethodDecl *Method, bool isClassMessage,
9771                                  bool isSuperMessage,
9772                                  SourceLocation lbrac, SourceLocation rbrac,
9773                                  SourceRange RecRange,
9774                                  QualType &ReturnType, ExprValueKind &VK);
9775 
9776   /// Determine the result of a message send expression based on
9777   /// the type of the receiver, the method expected to receive the message,
9778   /// and the form of the message send.
9779   QualType getMessageSendResultType(QualType ReceiverType,
9780                                     ObjCMethodDecl *Method,
9781                                     bool isClassMessage, bool isSuperMessage);
9782 
9783   /// If the given expression involves a message send to a method
9784   /// with a related result type, emit a note describing what happened.
9785   void EmitRelatedResultTypeNote(const Expr *E);
9786 
9787   /// Given that we had incompatible pointer types in a return
9788   /// statement, check whether we're in a method with a related result
9789   /// type, and if so, emit a note describing what happened.
9790   void EmitRelatedResultTypeNoteForReturn(QualType destType);
9791 
9792   class ConditionResult {
9793     Decl *ConditionVar;
9794     FullExprArg Condition;
9795     bool Invalid;
9796     bool HasKnownValue;
9797     bool KnownValue;
9798 
9799     friend class Sema;
ConditionResult(Sema & S,Decl * ConditionVar,FullExprArg Condition,bool IsConstexpr)9800     ConditionResult(Sema &S, Decl *ConditionVar, FullExprArg Condition,
9801                     bool IsConstexpr)
9802         : ConditionVar(ConditionVar), Condition(Condition), Invalid(false),
9803           HasKnownValue(IsConstexpr && Condition.get() &&
9804                         !Condition.get()->isValueDependent()),
9805           KnownValue(HasKnownValue &&
9806                      !!Condition.get()->EvaluateKnownConstInt(S.Context)) {}
ConditionResult(bool Invalid)9807     explicit ConditionResult(bool Invalid)
9808         : ConditionVar(nullptr), Condition(nullptr), Invalid(Invalid),
9809           HasKnownValue(false), KnownValue(false) {}
9810 
9811   public:
ConditionResult()9812     ConditionResult() : ConditionResult(false) {}
isInvalid()9813     bool isInvalid() const { return Invalid; }
get()9814     std::pair<VarDecl *, Expr *> get() const {
9815       return std::make_pair(cast_or_null<VarDecl>(ConditionVar),
9816                             Condition.get());
9817     }
getKnownValue()9818     llvm::Optional<bool> getKnownValue() const {
9819       if (!HasKnownValue)
9820         return None;
9821       return KnownValue;
9822     }
9823   };
ConditionError()9824   static ConditionResult ConditionError() { return ConditionResult(true); }
9825 
9826   enum class ConditionKind {
9827     Boolean,     ///< A boolean condition, from 'if', 'while', 'for', or 'do'.
9828     ConstexprIf, ///< A constant boolean condition from 'if constexpr'.
9829     Switch       ///< An integral condition for a 'switch' statement.
9830   };
9831 
9832   ConditionResult ActOnCondition(Scope *S, SourceLocation Loc,
9833                                  Expr *SubExpr, ConditionKind CK);
9834 
9835   ConditionResult ActOnConditionVariable(Decl *ConditionVar,
9836                                          SourceLocation StmtLoc,
9837                                          ConditionKind CK);
9838 
9839   DeclResult ActOnCXXConditionDeclaration(Scope *S, Declarator &D);
9840 
9841   ExprResult CheckConditionVariable(VarDecl *ConditionVar,
9842                                     SourceLocation StmtLoc,
9843                                     ConditionKind CK);
9844   ExprResult CheckSwitchCondition(SourceLocation SwitchLoc, Expr *Cond);
9845 
9846   /// CheckBooleanCondition - Diagnose problems involving the use of
9847   /// the given expression as a boolean condition (e.g. in an if
9848   /// statement).  Also performs the standard function and array
9849   /// decays, possibly changing the input variable.
9850   ///
9851   /// \param Loc - A location associated with the condition, e.g. the
9852   /// 'if' keyword.
9853   /// \return true iff there were any errors
9854   ExprResult CheckBooleanCondition(SourceLocation Loc, Expr *E,
9855                                    bool IsConstexpr = false);
9856 
9857   /// DiagnoseAssignmentAsCondition - Given that an expression is
9858   /// being used as a boolean condition, warn if it's an assignment.
9859   void DiagnoseAssignmentAsCondition(Expr *E);
9860 
9861   /// Redundant parentheses over an equality comparison can indicate
9862   /// that the user intended an assignment used as condition.
9863   void DiagnoseEqualityWithExtraParens(ParenExpr *ParenE);
9864 
9865   /// CheckCXXBooleanCondition - Returns true if conversion to bool is invalid.
9866   ExprResult CheckCXXBooleanCondition(Expr *CondExpr, bool IsConstexpr = false);
9867 
9868   /// ConvertIntegerToTypeWarnOnOverflow - Convert the specified APInt to have
9869   /// the specified width and sign.  If an overflow occurs, detect it and emit
9870   /// the specified diagnostic.
9871   void ConvertIntegerToTypeWarnOnOverflow(llvm::APSInt &OldVal,
9872                                           unsigned NewWidth, bool NewSign,
9873                                           SourceLocation Loc, unsigned DiagID);
9874 
9875   /// Checks that the Objective-C declaration is declared in the global scope.
9876   /// Emits an error and marks the declaration as invalid if it's not declared
9877   /// in the global scope.
9878   bool CheckObjCDeclScope(Decl *D);
9879 
9880   /// Abstract base class used for diagnosing integer constant
9881   /// expression violations.
9882   class VerifyICEDiagnoser {
9883   public:
9884     bool Suppress;
9885 
Suppress(Suppress)9886     VerifyICEDiagnoser(bool Suppress = false) : Suppress(Suppress) { }
9887 
9888     virtual void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) =0;
9889     virtual void diagnoseFold(Sema &S, SourceLocation Loc, SourceRange SR);
~VerifyICEDiagnoser()9890     virtual ~VerifyICEDiagnoser() { }
9891   };
9892 
9893   /// VerifyIntegerConstantExpression - Verifies that an expression is an ICE,
9894   /// and reports the appropriate diagnostics. Returns false on success.
9895   /// Can optionally return the value of the expression.
9896   ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
9897                                              VerifyICEDiagnoser &Diagnoser,
9898                                              bool AllowFold = true);
9899   ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
9900                                              unsigned DiagID,
9901                                              bool AllowFold = true);
9902   ExprResult VerifyIntegerConstantExpression(Expr *E,
9903                                              llvm::APSInt *Result = nullptr);
9904 
9905   /// VerifyBitField - verifies that a bit field expression is an ICE and has
9906   /// the correct width, and that the field type is valid.
9907   /// Returns false on success.
9908   /// Can optionally return whether the bit-field is of width 0
9909   ExprResult VerifyBitField(SourceLocation FieldLoc, IdentifierInfo *FieldName,
9910                             QualType FieldTy, bool IsMsStruct,
9911                             Expr *BitWidth, bool *ZeroWidth = nullptr);
9912 
9913 private:
9914   unsigned ForceCUDAHostDeviceDepth = 0;
9915 
9916 public:
9917   /// Increments our count of the number of times we've seen a pragma forcing
9918   /// functions to be __host__ __device__.  So long as this count is greater
9919   /// than zero, all functions encountered will be __host__ __device__.
9920   void PushForceCUDAHostDevice();
9921 
9922   /// Decrements our count of the number of times we've seen a pragma forcing
9923   /// functions to be __host__ __device__.  Returns false if the count is 0
9924   /// before incrementing, so you can emit an error.
9925   bool PopForceCUDAHostDevice();
9926 
9927   /// Diagnostics that are emitted only if we discover that the given function
9928   /// must be codegen'ed.  Because handling these correctly adds overhead to
9929   /// compilation, this is currently only enabled for CUDA compilations.
9930   llvm::DenseMap<CanonicalDeclPtr<FunctionDecl>,
9931                  std::vector<PartialDiagnosticAt>>
9932       CUDADeferredDiags;
9933 
9934   /// A pair of a canonical FunctionDecl and a SourceLocation.  When used as the
9935   /// key in a hashtable, both the FD and location are hashed.
9936   struct FunctionDeclAndLoc {
9937     CanonicalDeclPtr<FunctionDecl> FD;
9938     SourceLocation Loc;
9939   };
9940 
9941   /// FunctionDecls and SourceLocations for which CheckCUDACall has emitted a
9942   /// (maybe deferred) "bad call" diagnostic.  We use this to avoid emitting the
9943   /// same deferred diag twice.
9944   llvm::DenseSet<FunctionDeclAndLoc> LocsWithCUDACallDiags;
9945 
9946   /// An inverse call graph, mapping known-emitted functions to one of their
9947   /// known-emitted callers (plus the location of the call).
9948   ///
9949   /// Functions that we can tell a priori must be emitted aren't added to this
9950   /// map.
9951   llvm::DenseMap</* Callee = */ CanonicalDeclPtr<FunctionDecl>,
9952                  /* Caller = */ FunctionDeclAndLoc>
9953       CUDAKnownEmittedFns;
9954 
9955   /// A partial call graph maintained during CUDA compilation to support
9956   /// deferred diagnostics.
9957   ///
9958   /// Functions are only added here if, at the time they're considered, they are
9959   /// not known-emitted.  As soon as we discover that a function is
9960   /// known-emitted, we remove it and everything it transitively calls from this
9961   /// set and add those functions to CUDAKnownEmittedFns.
9962   llvm::DenseMap</* Caller = */ CanonicalDeclPtr<FunctionDecl>,
9963                  /* Callees = */ llvm::MapVector<CanonicalDeclPtr<FunctionDecl>,
9964                                                  SourceLocation>>
9965       CUDACallGraph;
9966 
9967   /// Diagnostic builder for CUDA errors which may or may not be deferred.
9968   ///
9969   /// In CUDA, there exist constructs (e.g. variable-length arrays, try/catch)
9970   /// which are not allowed to appear inside __device__ functions and are
9971   /// allowed to appear in __host__ __device__ functions only if the host+device
9972   /// function is never codegen'ed.
9973   ///
9974   /// To handle this, we use the notion of "deferred diagnostics", where we
9975   /// attach a diagnostic to a FunctionDecl that's emitted iff it's codegen'ed.
9976   ///
9977   /// This class lets you emit either a regular diagnostic, a deferred
9978   /// diagnostic, or no diagnostic at all, according to an argument you pass to
9979   /// its constructor, thus simplifying the process of creating these "maybe
9980   /// deferred" diagnostics.
9981   class CUDADiagBuilder {
9982   public:
9983     enum Kind {
9984       /// Emit no diagnostics.
9985       K_Nop,
9986       /// Emit the diagnostic immediately (i.e., behave like Sema::Diag()).
9987       K_Immediate,
9988       /// Emit the diagnostic immediately, and, if it's a warning or error, also
9989       /// emit a call stack showing how this function can be reached by an a
9990       /// priori known-emitted function.
9991       K_ImmediateWithCallStack,
9992       /// Create a deferred diagnostic, which is emitted only if the function
9993       /// it's attached to is codegen'ed.  Also emit a call stack as with
9994       /// K_ImmediateWithCallStack.
9995       K_Deferred
9996     };
9997 
9998     CUDADiagBuilder(Kind K, SourceLocation Loc, unsigned DiagID,
9999                     FunctionDecl *Fn, Sema &S);
10000     ~CUDADiagBuilder();
10001 
10002     /// Convertible to bool: True if we immediately emitted an error, false if
10003     /// we didn't emit an error or we created a deferred error.
10004     ///
10005     /// Example usage:
10006     ///
10007     ///   if (CUDADiagBuilder(...) << foo << bar)
10008     ///     return ExprError();
10009     ///
10010     /// But see CUDADiagIfDeviceCode() and CUDADiagIfHostCode() -- you probably
10011     /// want to use these instead of creating a CUDADiagBuilder yourself.
10012     operator bool() const { return ImmediateDiag.hasValue(); }
10013 
10014     template <typename T>
10015     friend const CUDADiagBuilder &operator<<(const CUDADiagBuilder &Diag,
10016                                              const T &Value) {
10017       if (Diag.ImmediateDiag.hasValue())
10018         *Diag.ImmediateDiag << Value;
10019       else if (Diag.PartialDiag.hasValue())
10020         *Diag.PartialDiag << Value;
10021       return Diag;
10022     }
10023 
10024   private:
10025     Sema &S;
10026     SourceLocation Loc;
10027     unsigned DiagID;
10028     FunctionDecl *Fn;
10029     bool ShowCallStack;
10030 
10031     // Invariant: At most one of these Optionals has a value.
10032     // FIXME: Switch these to a Variant once that exists.
10033     llvm::Optional<SemaDiagnosticBuilder> ImmediateDiag;
10034     llvm::Optional<PartialDiagnostic> PartialDiag;
10035   };
10036 
10037   /// Creates a CUDADiagBuilder that emits the diagnostic if the current context
10038   /// is "used as device code".
10039   ///
10040   /// - If CurContext is a __host__ function, does not emit any diagnostics.
10041   /// - If CurContext is a __device__ or __global__ function, emits the
10042   ///   diagnostics immediately.
10043   /// - If CurContext is a __host__ __device__ function and we are compiling for
10044   ///   the device, creates a diagnostic which is emitted if and when we realize
10045   ///   that the function will be codegen'ed.
10046   ///
10047   /// Example usage:
10048   ///
10049   ///  // Variable-length arrays are not allowed in CUDA device code.
10050   ///  if (CUDADiagIfDeviceCode(Loc, diag::err_cuda_vla) << CurrentCUDATarget())
10051   ///    return ExprError();
10052   ///  // Otherwise, continue parsing as normal.
10053   CUDADiagBuilder CUDADiagIfDeviceCode(SourceLocation Loc, unsigned DiagID);
10054 
10055   /// Creates a CUDADiagBuilder that emits the diagnostic if the current context
10056   /// is "used as host code".
10057   ///
10058   /// Same as CUDADiagIfDeviceCode, with "host" and "device" switched.
10059   CUDADiagBuilder CUDADiagIfHostCode(SourceLocation Loc, unsigned DiagID);
10060 
10061   enum CUDAFunctionTarget {
10062     CFT_Device,
10063     CFT_Global,
10064     CFT_Host,
10065     CFT_HostDevice,
10066     CFT_InvalidTarget
10067   };
10068 
10069   /// Determines whether the given function is a CUDA device/host/kernel/etc.
10070   /// function.
10071   ///
10072   /// Use this rather than examining the function's attributes yourself -- you
10073   /// will get it wrong.  Returns CFT_Host if D is null.
10074   CUDAFunctionTarget IdentifyCUDATarget(const FunctionDecl *D,
10075                                         bool IgnoreImplicitHDAttr = false);
10076   CUDAFunctionTarget IdentifyCUDATarget(const ParsedAttributesView &Attrs);
10077 
10078   /// Gets the CUDA target for the current context.
CurrentCUDATarget()10079   CUDAFunctionTarget CurrentCUDATarget() {
10080     return IdentifyCUDATarget(dyn_cast<FunctionDecl>(CurContext));
10081   }
10082 
10083   // CUDA function call preference. Must be ordered numerically from
10084   // worst to best.
10085   enum CUDAFunctionPreference {
10086     CFP_Never,      // Invalid caller/callee combination.
10087     CFP_WrongSide,  // Calls from host-device to host or device
10088                     // function that do not match current compilation
10089                     // mode.
10090     CFP_HostDevice, // Any calls to host/device functions.
10091     CFP_SameSide,   // Calls from host-device to host or device
10092                     // function matching current compilation mode.
10093     CFP_Native,     // host-to-host or device-to-device calls.
10094   };
10095 
10096   /// Identifies relative preference of a given Caller/Callee
10097   /// combination, based on their host/device attributes.
10098   /// \param Caller function which needs address of \p Callee.
10099   ///               nullptr in case of global context.
10100   /// \param Callee target function
10101   ///
10102   /// \returns preference value for particular Caller/Callee combination.
10103   CUDAFunctionPreference IdentifyCUDAPreference(const FunctionDecl *Caller,
10104                                                 const FunctionDecl *Callee);
10105 
10106   /// Determines whether Caller may invoke Callee, based on their CUDA
10107   /// host/device attributes.  Returns false if the call is not allowed.
10108   ///
10109   /// Note: Will return true for CFP_WrongSide calls.  These may appear in
10110   /// semantically correct CUDA programs, but only if they're never codegen'ed.
IsAllowedCUDACall(const FunctionDecl * Caller,const FunctionDecl * Callee)10111   bool IsAllowedCUDACall(const FunctionDecl *Caller,
10112                          const FunctionDecl *Callee) {
10113     return IdentifyCUDAPreference(Caller, Callee) != CFP_Never;
10114   }
10115 
10116   /// May add implicit CUDAHostAttr and CUDADeviceAttr attributes to FD,
10117   /// depending on FD and the current compilation settings.
10118   void maybeAddCUDAHostDeviceAttrs(FunctionDecl *FD,
10119                                    const LookupResult &Previous);
10120 
10121 public:
10122   /// Check whether we're allowed to call Callee from the current context.
10123   ///
10124   /// - If the call is never allowed in a semantically-correct program
10125   ///   (CFP_Never), emits an error and returns false.
10126   ///
10127   /// - If the call is allowed in semantically-correct programs, but only if
10128   ///   it's never codegen'ed (CFP_WrongSide), creates a deferred diagnostic to
10129   ///   be emitted if and when the caller is codegen'ed, and returns true.
10130   ///
10131   ///   Will only create deferred diagnostics for a given SourceLocation once,
10132   ///   so you can safely call this multiple times without generating duplicate
10133   ///   deferred errors.
10134   ///
10135   /// - Otherwise, returns true without emitting any diagnostics.
10136   bool CheckCUDACall(SourceLocation Loc, FunctionDecl *Callee);
10137 
10138   /// Set __device__ or __host__ __device__ attributes on the given lambda
10139   /// operator() method.
10140   ///
10141   /// CUDA lambdas declared inside __device__ or __global__ functions inherit
10142   /// the __device__ attribute.  Similarly, lambdas inside __host__ __device__
10143   /// functions become __host__ __device__ themselves.
10144   void CUDASetLambdaAttrs(CXXMethodDecl *Method);
10145 
10146   /// Finds a function in \p Matches with highest calling priority
10147   /// from \p Caller context and erases all functions with lower
10148   /// calling priority.
10149   void EraseUnwantedCUDAMatches(
10150       const FunctionDecl *Caller,
10151       SmallVectorImpl<std::pair<DeclAccessPair, FunctionDecl *>> &Matches);
10152 
10153   /// Given a implicit special member, infer its CUDA target from the
10154   /// calls it needs to make to underlying base/field special members.
10155   /// \param ClassDecl the class for which the member is being created.
10156   /// \param CSM the kind of special member.
10157   /// \param MemberDecl the special member itself.
10158   /// \param ConstRHS true if this is a copy operation with a const object on
10159   ///        its RHS.
10160   /// \param Diagnose true if this call should emit diagnostics.
10161   /// \return true if there was an error inferring.
10162   /// The result of this call is implicit CUDA target attribute(s) attached to
10163   /// the member declaration.
10164   bool inferCUDATargetForImplicitSpecialMember(CXXRecordDecl *ClassDecl,
10165                                                CXXSpecialMember CSM,
10166                                                CXXMethodDecl *MemberDecl,
10167                                                bool ConstRHS,
10168                                                bool Diagnose);
10169 
10170   /// \return true if \p CD can be considered empty according to CUDA
10171   /// (E.2.3.1 in CUDA 7.5 Programming guide).
10172   bool isEmptyCudaConstructor(SourceLocation Loc, CXXConstructorDecl *CD);
10173   bool isEmptyCudaDestructor(SourceLocation Loc, CXXDestructorDecl *CD);
10174 
10175   // \brief Checks that initializers of \p Var satisfy CUDA restrictions. In
10176   // case of error emits appropriate diagnostic and invalidates \p Var.
10177   //
10178   // \details CUDA allows only empty constructors as initializers for global
10179   // variables (see E.2.3.1, CUDA 7.5). The same restriction also applies to all
10180   // __shared__ variables whether they are local or not (they all are implicitly
10181   // static in CUDA). One exception is that CUDA allows constant initializers
10182   // for __constant__ and __device__ variables.
10183   void checkAllowedCUDAInitializer(VarDecl *VD);
10184 
10185   /// Check whether NewFD is a valid overload for CUDA. Emits
10186   /// diagnostics and invalidates NewFD if not.
10187   void checkCUDATargetOverload(FunctionDecl *NewFD,
10188                                const LookupResult &Previous);
10189   /// Copies target attributes from the template TD to the function FD.
10190   void inheritCUDATargetAttrs(FunctionDecl *FD, const FunctionTemplateDecl &TD);
10191 
10192   /// \name Code completion
10193   //@{
10194   /// Describes the context in which code completion occurs.
10195   enum ParserCompletionContext {
10196     /// Code completion occurs at top-level or namespace context.
10197     PCC_Namespace,
10198     /// Code completion occurs within a class, struct, or union.
10199     PCC_Class,
10200     /// Code completion occurs within an Objective-C interface, protocol,
10201     /// or category.
10202     PCC_ObjCInterface,
10203     /// Code completion occurs within an Objective-C implementation or
10204     /// category implementation
10205     PCC_ObjCImplementation,
10206     /// Code completion occurs within the list of instance variables
10207     /// in an Objective-C interface, protocol, category, or implementation.
10208     PCC_ObjCInstanceVariableList,
10209     /// Code completion occurs following one or more template
10210     /// headers.
10211     PCC_Template,
10212     /// Code completion occurs following one or more template
10213     /// headers within a class.
10214     PCC_MemberTemplate,
10215     /// Code completion occurs within an expression.
10216     PCC_Expression,
10217     /// Code completion occurs within a statement, which may
10218     /// also be an expression or a declaration.
10219     PCC_Statement,
10220     /// Code completion occurs at the beginning of the
10221     /// initialization statement (or expression) in a for loop.
10222     PCC_ForInit,
10223     /// Code completion occurs within the condition of an if,
10224     /// while, switch, or for statement.
10225     PCC_Condition,
10226     /// Code completion occurs within the body of a function on a
10227     /// recovery path, where we do not have a specific handle on our position
10228     /// in the grammar.
10229     PCC_RecoveryInFunction,
10230     /// Code completion occurs where only a type is permitted.
10231     PCC_Type,
10232     /// Code completion occurs in a parenthesized expression, which
10233     /// might also be a type cast.
10234     PCC_ParenthesizedExpression,
10235     /// Code completion occurs within a sequence of declaration
10236     /// specifiers within a function, method, or block.
10237     PCC_LocalDeclarationSpecifiers
10238   };
10239 
10240   void CodeCompleteModuleImport(SourceLocation ImportLoc, ModuleIdPath Path);
10241   void CodeCompleteOrdinaryName(Scope *S,
10242                                 ParserCompletionContext CompletionContext);
10243   void CodeCompleteDeclSpec(Scope *S, DeclSpec &DS,
10244                             bool AllowNonIdentifiers,
10245                             bool AllowNestedNameSpecifiers);
10246 
10247   struct CodeCompleteExpressionData;
10248   void CodeCompleteExpression(Scope *S,
10249                               const CodeCompleteExpressionData &Data);
10250   void CodeCompleteMemberReferenceExpr(Scope *S, Expr *Base, Expr *OtherOpBase,
10251                                        SourceLocation OpLoc, bool IsArrow,
10252                                        bool IsBaseExprStatement);
10253   void CodeCompletePostfixExpression(Scope *S, ExprResult LHS);
10254   void CodeCompleteTag(Scope *S, unsigned TagSpec);
10255   void CodeCompleteTypeQualifiers(DeclSpec &DS);
10256   void CodeCompleteFunctionQualifiers(DeclSpec &DS, Declarator &D,
10257                                       const VirtSpecifiers *VS = nullptr);
10258   void CodeCompleteBracketDeclarator(Scope *S);
10259   void CodeCompleteCase(Scope *S);
10260   void CodeCompleteCall(Scope *S, Expr *Fn, ArrayRef<Expr *> Args);
10261   void CodeCompleteConstructor(Scope *S, QualType Type, SourceLocation Loc,
10262                                ArrayRef<Expr *> Args);
10263   void CodeCompleteInitializer(Scope *S, Decl *D);
10264   void CodeCompleteReturn(Scope *S);
10265   void CodeCompleteAfterIf(Scope *S);
10266   void CodeCompleteAssignmentRHS(Scope *S, Expr *LHS);
10267 
10268   void CodeCompleteQualifiedId(Scope *S, CXXScopeSpec &SS,
10269                                bool EnteringContext);
10270   void CodeCompleteUsing(Scope *S);
10271   void CodeCompleteUsingDirective(Scope *S);
10272   void CodeCompleteNamespaceDecl(Scope *S);
10273   void CodeCompleteNamespaceAliasDecl(Scope *S);
10274   void CodeCompleteOperatorName(Scope *S);
10275   void CodeCompleteConstructorInitializer(
10276                                 Decl *Constructor,
10277                                 ArrayRef<CXXCtorInitializer *> Initializers);
10278 
10279   void CodeCompleteLambdaIntroducer(Scope *S, LambdaIntroducer &Intro,
10280                                     bool AfterAmpersand);
10281 
10282   void CodeCompleteObjCAtDirective(Scope *S);
10283   void CodeCompleteObjCAtVisibility(Scope *S);
10284   void CodeCompleteObjCAtStatement(Scope *S);
10285   void CodeCompleteObjCAtExpression(Scope *S);
10286   void CodeCompleteObjCPropertyFlags(Scope *S, ObjCDeclSpec &ODS);
10287   void CodeCompleteObjCPropertyGetter(Scope *S);
10288   void CodeCompleteObjCPropertySetter(Scope *S);
10289   void CodeCompleteObjCPassingType(Scope *S, ObjCDeclSpec &DS,
10290                                    bool IsParameter);
10291   void CodeCompleteObjCMessageReceiver(Scope *S);
10292   void CodeCompleteObjCSuperMessage(Scope *S, SourceLocation SuperLoc,
10293                                     ArrayRef<IdentifierInfo *> SelIdents,
10294                                     bool AtArgumentExpression);
10295   void CodeCompleteObjCClassMessage(Scope *S, ParsedType Receiver,
10296                                     ArrayRef<IdentifierInfo *> SelIdents,
10297                                     bool AtArgumentExpression,
10298                                     bool IsSuper = false);
10299   void CodeCompleteObjCInstanceMessage(Scope *S, Expr *Receiver,
10300                                        ArrayRef<IdentifierInfo *> SelIdents,
10301                                        bool AtArgumentExpression,
10302                                        ObjCInterfaceDecl *Super = nullptr);
10303   void CodeCompleteObjCForCollection(Scope *S,
10304                                      DeclGroupPtrTy IterationVar);
10305   void CodeCompleteObjCSelector(Scope *S,
10306                                 ArrayRef<IdentifierInfo *> SelIdents);
10307   void CodeCompleteObjCProtocolReferences(
10308                                          ArrayRef<IdentifierLocPair> Protocols);
10309   void CodeCompleteObjCProtocolDecl(Scope *S);
10310   void CodeCompleteObjCInterfaceDecl(Scope *S);
10311   void CodeCompleteObjCSuperclass(Scope *S,
10312                                   IdentifierInfo *ClassName,
10313                                   SourceLocation ClassNameLoc);
10314   void CodeCompleteObjCImplementationDecl(Scope *S);
10315   void CodeCompleteObjCInterfaceCategory(Scope *S,
10316                                          IdentifierInfo *ClassName,
10317                                          SourceLocation ClassNameLoc);
10318   void CodeCompleteObjCImplementationCategory(Scope *S,
10319                                               IdentifierInfo *ClassName,
10320                                               SourceLocation ClassNameLoc);
10321   void CodeCompleteObjCPropertyDefinition(Scope *S);
10322   void CodeCompleteObjCPropertySynthesizeIvar(Scope *S,
10323                                               IdentifierInfo *PropertyName);
10324   void CodeCompleteObjCMethodDecl(Scope *S, Optional<bool> IsInstanceMethod,
10325                                   ParsedType ReturnType);
10326   void CodeCompleteObjCMethodDeclSelector(Scope *S,
10327                                           bool IsInstanceMethod,
10328                                           bool AtParameterName,
10329                                           ParsedType ReturnType,
10330                                           ArrayRef<IdentifierInfo *> SelIdents);
10331   void CodeCompleteObjCClassPropertyRefExpr(Scope *S, IdentifierInfo &ClassName,
10332                                             SourceLocation ClassNameLoc,
10333                                             bool IsBaseExprStatement);
10334   void CodeCompletePreprocessorDirective(bool InConditional);
10335   void CodeCompleteInPreprocessorConditionalExclusion(Scope *S);
10336   void CodeCompletePreprocessorMacroName(bool IsDefinition);
10337   void CodeCompletePreprocessorExpression();
10338   void CodeCompletePreprocessorMacroArgument(Scope *S,
10339                                              IdentifierInfo *Macro,
10340                                              MacroInfo *MacroInfo,
10341                                              unsigned Argument);
10342   void CodeCompleteNaturalLanguage();
10343   void CodeCompleteAvailabilityPlatformName();
10344   void GatherGlobalCodeCompletions(CodeCompletionAllocator &Allocator,
10345                                    CodeCompletionTUInfo &CCTUInfo,
10346                   SmallVectorImpl<CodeCompletionResult> &Results);
10347   //@}
10348 
10349   //===--------------------------------------------------------------------===//
10350   // Extra semantic analysis beyond the C type system
10351 
10352 public:
10353   SourceLocation getLocationOfStringLiteralByte(const StringLiteral *SL,
10354                                                 unsigned ByteNo) const;
10355 
10356 private:
10357   void CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
10358                         const ArraySubscriptExpr *ASE=nullptr,
10359                         bool AllowOnePastEnd=true, bool IndexNegated=false);
10360   void CheckArrayAccess(const Expr *E);
10361   // Used to grab the relevant information from a FormatAttr and a
10362   // FunctionDeclaration.
10363   struct FormatStringInfo {
10364     unsigned FormatIdx;
10365     unsigned FirstDataArg;
10366     bool HasVAListArg;
10367   };
10368 
10369   static bool getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
10370                                   FormatStringInfo *FSI);
10371   bool CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
10372                          const FunctionProtoType *Proto);
10373   bool CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation loc,
10374                            ArrayRef<const Expr *> Args);
10375   bool CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
10376                         const FunctionProtoType *Proto);
10377   bool CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto);
10378   void CheckConstructorCall(FunctionDecl *FDecl,
10379                             ArrayRef<const Expr *> Args,
10380                             const FunctionProtoType *Proto,
10381                             SourceLocation Loc);
10382 
10383   void checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
10384                  const Expr *ThisArg, ArrayRef<const Expr *> Args,
10385                  bool IsMemberFunction, SourceLocation Loc, SourceRange Range,
10386                  VariadicCallType CallType);
10387 
10388   bool CheckObjCString(Expr *Arg);
10389   ExprResult CheckOSLogFormatStringArg(Expr *Arg);
10390 
10391   ExprResult CheckBuiltinFunctionCall(FunctionDecl *FDecl,
10392                                       unsigned BuiltinID, CallExpr *TheCall);
10393 
10394   bool CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
10395                                     unsigned MaxWidth);
10396   bool CheckNeonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
10397   bool CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
10398 
10399   bool CheckAArch64BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
10400   bool CheckHexagonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
10401   bool CheckHexagonBuiltinCpu(unsigned BuiltinID, CallExpr *TheCall);
10402   bool CheckHexagonBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall);
10403   bool CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
10404   bool CheckSystemZBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
10405   bool CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall);
10406   bool CheckX86BuiltinGatherScatterScale(unsigned BuiltinID, CallExpr *TheCall);
10407   bool CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
10408   bool CheckPPCBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
10409 
10410   bool SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall);
10411   bool SemaBuiltinVAStartARMMicrosoft(CallExpr *Call);
10412   bool SemaBuiltinUnorderedCompare(CallExpr *TheCall);
10413   bool SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs);
10414   bool SemaBuiltinVSX(CallExpr *TheCall);
10415   bool SemaBuiltinOSLogFormat(CallExpr *TheCall);
10416 
10417 public:
10418   // Used by C++ template instantiation.
10419   ExprResult SemaBuiltinShuffleVector(CallExpr *TheCall);
10420   ExprResult SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
10421                                    SourceLocation BuiltinLoc,
10422                                    SourceLocation RParenLoc);
10423 
10424 private:
10425   bool SemaBuiltinPrefetch(CallExpr *TheCall);
10426   bool SemaBuiltinAllocaWithAlign(CallExpr *TheCall);
10427   bool SemaBuiltinAssume(CallExpr *TheCall);
10428   bool SemaBuiltinAssumeAligned(CallExpr *TheCall);
10429   bool SemaBuiltinLongjmp(CallExpr *TheCall);
10430   bool SemaBuiltinSetjmp(CallExpr *TheCall);
10431   ExprResult SemaBuiltinAtomicOverloaded(ExprResult TheCallResult);
10432   ExprResult SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult);
10433   ExprResult SemaAtomicOpsOverloaded(ExprResult TheCallResult,
10434                                      AtomicExpr::AtomicOp Op);
10435   ExprResult SemaBuiltinOperatorNewDeleteOverloaded(ExprResult TheCallResult,
10436                                                     bool IsDelete);
10437   bool SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
10438                               llvm::APSInt &Result);
10439   bool SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum, int Low,
10440                                    int High, bool RangeIsError = true);
10441   bool SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum,
10442                                       unsigned Multiple);
10443   bool SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall,
10444                                 int ArgNum, unsigned ExpectedFieldNum,
10445                                 bool AllowName);
10446 public:
10447   enum FormatStringType {
10448     FST_Scanf,
10449     FST_Printf,
10450     FST_NSString,
10451     FST_Strftime,
10452     FST_Strfmon,
10453     FST_Kprintf,
10454     FST_FreeBSDKPrintf,
10455     FST_OSTrace,
10456     FST_OSLog,
10457     FST_Unknown
10458   };
10459   static FormatStringType GetFormatStringType(const FormatAttr *Format);
10460 
10461   bool FormatStringHasSArg(const StringLiteral *FExpr);
10462 
10463   static bool GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx);
10464 
10465 private:
10466   bool CheckFormatArguments(const FormatAttr *Format,
10467                             ArrayRef<const Expr *> Args,
10468                             bool IsCXXMember,
10469                             VariadicCallType CallType,
10470                             SourceLocation Loc, SourceRange Range,
10471                             llvm::SmallBitVector &CheckedVarArgs);
10472   bool CheckFormatArguments(ArrayRef<const Expr *> Args,
10473                             bool HasVAListArg, unsigned format_idx,
10474                             unsigned firstDataArg, FormatStringType Type,
10475                             VariadicCallType CallType,
10476                             SourceLocation Loc, SourceRange range,
10477                             llvm::SmallBitVector &CheckedVarArgs);
10478 
10479   void CheckAbsoluteValueFunction(const CallExpr *Call,
10480                                   const FunctionDecl *FDecl);
10481 
10482   void CheckMaxUnsignedZero(const CallExpr *Call, const FunctionDecl *FDecl);
10483 
10484   void CheckMemaccessArguments(const CallExpr *Call,
10485                                unsigned BId,
10486                                IdentifierInfo *FnName);
10487 
10488   void CheckStrlcpycatArguments(const CallExpr *Call,
10489                                 IdentifierInfo *FnName);
10490 
10491   void CheckStrncatArguments(const CallExpr *Call,
10492                              IdentifierInfo *FnName);
10493 
10494   void CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
10495                           SourceLocation ReturnLoc,
10496                           bool isObjCMethod = false,
10497                           const AttrVec *Attrs = nullptr,
10498                           const FunctionDecl *FD = nullptr);
10499 
10500 public:
10501   void CheckFloatComparison(SourceLocation Loc, Expr *LHS, Expr *RHS);
10502 
10503 private:
10504   void CheckImplicitConversions(Expr *E, SourceLocation CC = SourceLocation());
10505   void CheckBoolLikeConversion(Expr *E, SourceLocation CC);
10506   void CheckForIntOverflow(Expr *E);
10507   void CheckUnsequencedOperations(Expr *E);
10508 
10509   /// Perform semantic checks on a completed expression. This will either
10510   /// be a full-expression or a default argument expression.
10511   void CheckCompletedExpr(Expr *E, SourceLocation CheckLoc = SourceLocation(),
10512                           bool IsConstexpr = false);
10513 
10514   void CheckBitFieldInitialization(SourceLocation InitLoc, FieldDecl *Field,
10515                                    Expr *Init);
10516 
10517   /// Check if there is a field shadowing.
10518   void CheckShadowInheritedFields(const SourceLocation &Loc,
10519                                   DeclarationName FieldName,
10520                                   const CXXRecordDecl *RD);
10521 
10522   /// Check if the given expression contains 'break' or 'continue'
10523   /// statement that produces control flow different from GCC.
10524   void CheckBreakContinueBinding(Expr *E);
10525 
10526   /// Check whether receiver is mutable ObjC container which
10527   /// attempts to add itself into the container
10528   void CheckObjCCircularContainer(ObjCMessageExpr *Message);
10529 
10530   void AnalyzeDeleteExprMismatch(const CXXDeleteExpr *DE);
10531   void AnalyzeDeleteExprMismatch(FieldDecl *Field, SourceLocation DeleteLoc,
10532                                  bool DeleteWasArrayForm);
10533 public:
10534   /// Register a magic integral constant to be used as a type tag.
10535   void RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
10536                                   uint64_t MagicValue, QualType Type,
10537                                   bool LayoutCompatible, bool MustBeNull);
10538 
10539   struct TypeTagData {
TypeTagDataTypeTagData10540     TypeTagData() {}
10541 
TypeTagDataTypeTagData10542     TypeTagData(QualType Type, bool LayoutCompatible, bool MustBeNull) :
10543         Type(Type), LayoutCompatible(LayoutCompatible),
10544         MustBeNull(MustBeNull)
10545     {}
10546 
10547     QualType Type;
10548 
10549     /// If true, \c Type should be compared with other expression's types for
10550     /// layout-compatibility.
10551     unsigned LayoutCompatible : 1;
10552     unsigned MustBeNull : 1;
10553   };
10554 
10555   /// A pair of ArgumentKind identifier and magic value.  This uniquely
10556   /// identifies the magic value.
10557   typedef std::pair<const IdentifierInfo *, uint64_t> TypeTagMagicValue;
10558 
10559 private:
10560   /// A map from magic value to type information.
10561   std::unique_ptr<llvm::DenseMap<TypeTagMagicValue, TypeTagData>>
10562       TypeTagForDatatypeMagicValues;
10563 
10564   /// Peform checks on a call of a function with argument_with_type_tag
10565   /// or pointer_with_type_tag attributes.
10566   void CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
10567                                 const ArrayRef<const Expr *> ExprArgs,
10568                                 SourceLocation CallSiteLoc);
10569 
10570   /// Check if we are taking the address of a packed field
10571   /// as this may be a problem if the pointer value is dereferenced.
10572   void CheckAddressOfPackedMember(Expr *rhs);
10573 
10574   /// The parser's current scope.
10575   ///
10576   /// The parser maintains this state here.
10577   Scope *CurScope;
10578 
10579   mutable IdentifierInfo *Ident_super;
10580   mutable IdentifierInfo *Ident___float128;
10581 
10582   /// Nullability type specifiers.
10583   IdentifierInfo *Ident__Nonnull = nullptr;
10584   IdentifierInfo *Ident__Nullable = nullptr;
10585   IdentifierInfo *Ident__Null_unspecified = nullptr;
10586 
10587   IdentifierInfo *Ident_NSError = nullptr;
10588 
10589   /// The handler for the FileChanged preprocessor events.
10590   ///
10591   /// Used for diagnostics that implement custom semantic analysis for #include
10592   /// directives, like -Wpragma-pack.
10593   sema::SemaPPCallbacks *SemaPPCallbackHandler;
10594 
10595 protected:
10596   friend class Parser;
10597   friend class InitializationSequence;
10598   friend class ASTReader;
10599   friend class ASTDeclReader;
10600   friend class ASTWriter;
10601 
10602 public:
10603   /// Retrieve the keyword associated
10604   IdentifierInfo *getNullabilityKeyword(NullabilityKind nullability);
10605 
10606   /// The struct behind the CFErrorRef pointer.
10607   RecordDecl *CFError = nullptr;
10608 
10609   /// Retrieve the identifier "NSError".
10610   IdentifierInfo *getNSErrorIdent();
10611 
10612   /// Retrieve the parser's current scope.
10613   ///
10614   /// This routine must only be used when it is certain that semantic analysis
10615   /// and the parser are in precisely the same context, which is not the case
10616   /// when, e.g., we are performing any kind of template instantiation.
10617   /// Therefore, the only safe places to use this scope are in the parser
10618   /// itself and in routines directly invoked from the parser and *never* from
10619   /// template substitution or instantiation.
getCurScope()10620   Scope *getCurScope() const { return CurScope; }
10621 
incrementMSManglingNumber()10622   void incrementMSManglingNumber() const {
10623     return CurScope->incrementMSManglingNumber();
10624   }
10625 
10626   IdentifierInfo *getSuperIdentifier() const;
10627   IdentifierInfo *getFloat128Identifier() const;
10628 
10629   Decl *getObjCDeclContext() const;
10630 
getCurLexicalContext()10631   DeclContext *getCurLexicalContext() const {
10632     return OriginalLexicalContext ? OriginalLexicalContext : CurContext;
10633   }
10634 
getCurObjCLexicalContext()10635   const DeclContext *getCurObjCLexicalContext() const {
10636     const DeclContext *DC = getCurLexicalContext();
10637     // A category implicitly has the attribute of the interface.
10638     if (const ObjCCategoryDecl *CatD = dyn_cast<ObjCCategoryDecl>(DC))
10639       DC = CatD->getClassInterface();
10640     return DC;
10641   }
10642 
10643   /// To be used for checking whether the arguments being passed to
10644   /// function exceeds the number of parameters expected for it.
10645   static bool TooManyArguments(size_t NumParams, size_t NumArgs,
10646                                bool PartialOverloading = false) {
10647     // We check whether we're just after a comma in code-completion.
10648     if (NumArgs > 0 && PartialOverloading)
10649       return NumArgs + 1 > NumParams; // If so, we view as an extra argument.
10650     return NumArgs > NumParams;
10651   }
10652 
10653   // Emitting members of dllexported classes is delayed until the class
10654   // (including field initializers) is fully parsed.
10655   SmallVector<CXXRecordDecl*, 4> DelayedDllExportClasses;
10656 
10657 private:
10658   class SavePendingParsedClassStateRAII {
10659   public:
SavePendingParsedClassStateRAII(Sema & S)10660     SavePendingParsedClassStateRAII(Sema &S) : S(S) { swapSavedState(); }
10661 
~SavePendingParsedClassStateRAII()10662     ~SavePendingParsedClassStateRAII() {
10663       assert(S.DelayedExceptionSpecChecks.empty() &&
10664              "there shouldn't be any pending delayed exception spec checks");
10665       assert(S.DelayedDefaultedMemberExceptionSpecs.empty() &&
10666              "there shouldn't be any pending delayed defaulted member "
10667              "exception specs");
10668       assert(S.DelayedDllExportClasses.empty() &&
10669              "there shouldn't be any pending delayed DLL export classes");
10670       swapSavedState();
10671     }
10672 
10673   private:
10674     Sema &S;
10675     decltype(DelayedExceptionSpecChecks) SavedExceptionSpecChecks;
10676     decltype(DelayedDefaultedMemberExceptionSpecs)
10677         SavedDefaultedMemberExceptionSpecs;
10678     decltype(DelayedDllExportClasses) SavedDllExportClasses;
10679 
swapSavedState()10680     void swapSavedState() {
10681       SavedExceptionSpecChecks.swap(S.DelayedExceptionSpecChecks);
10682       SavedDefaultedMemberExceptionSpecs.swap(
10683           S.DelayedDefaultedMemberExceptionSpecs);
10684       SavedDllExportClasses.swap(S.DelayedDllExportClasses);
10685     }
10686   };
10687 
10688   /// Helper class that collects misaligned member designations and
10689   /// their location info for delayed diagnostics.
10690   struct MisalignedMember {
10691     Expr *E;
10692     RecordDecl *RD;
10693     ValueDecl *MD;
10694     CharUnits Alignment;
10695 
MisalignedMemberMisalignedMember10696     MisalignedMember() : E(), RD(), MD(), Alignment() {}
MisalignedMemberMisalignedMember10697     MisalignedMember(Expr *E, RecordDecl *RD, ValueDecl *MD,
10698                      CharUnits Alignment)
10699         : E(E), RD(RD), MD(MD), Alignment(Alignment) {}
MisalignedMemberMisalignedMember10700     explicit MisalignedMember(Expr *E)
10701         : MisalignedMember(E, nullptr, nullptr, CharUnits()) {}
10702 
10703     bool operator==(const MisalignedMember &m) { return this->E == m.E; }
10704   };
10705   /// Small set of gathered accesses to potentially misaligned members
10706   /// due to the packed attribute.
10707   SmallVector<MisalignedMember, 4> MisalignedMembers;
10708 
10709   /// Adds an expression to the set of gathered misaligned members.
10710   void AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD,
10711                                      CharUnits Alignment);
10712 
10713 public:
10714   /// Diagnoses the current set of gathered accesses. This typically
10715   /// happens at full expression level. The set is cleared after emitting the
10716   /// diagnostics.
10717   void DiagnoseMisalignedMembers();
10718 
10719   /// This function checks if the expression is in the sef of potentially
10720   /// misaligned members and it is converted to some pointer type T with lower
10721   /// or equal alignment requirements. If so it removes it. This is used when
10722   /// we do not want to diagnose such misaligned access (e.g. in conversions to
10723   /// void*).
10724   void DiscardMisalignedMemberAddress(const Type *T, Expr *E);
10725 
10726   /// This function calls Action when it determines that E designates a
10727   /// misaligned member due to the packed attribute. This is used to emit
10728   /// local diagnostics like in reference binding.
10729   void RefersToMemberWithReducedAlignment(
10730       Expr *E,
10731       llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)>
10732           Action);
10733 };
10734 
10735 /// RAII object that enters a new expression evaluation context.
10736 class EnterExpressionEvaluationContext {
10737   Sema &Actions;
10738   bool Entered = true;
10739 
10740 public:
10741   EnterExpressionEvaluationContext(
10742       Sema &Actions, Sema::ExpressionEvaluationContext NewContext,
10743       Decl *LambdaContextDecl = nullptr,
10744       Sema::ExpressionEvaluationContextRecord::ExpressionKind ExprContext =
10745           Sema::ExpressionEvaluationContextRecord::EK_Other,
10746       bool ShouldEnter = true)
Actions(Actions)10747       : Actions(Actions), Entered(ShouldEnter) {
10748     if (Entered)
10749       Actions.PushExpressionEvaluationContext(NewContext, LambdaContextDecl,
10750                                               ExprContext);
10751   }
10752   EnterExpressionEvaluationContext(
10753       Sema &Actions, Sema::ExpressionEvaluationContext NewContext,
10754       Sema::ReuseLambdaContextDecl_t,
10755       Sema::ExpressionEvaluationContextRecord::ExpressionKind ExprContext =
10756           Sema::ExpressionEvaluationContextRecord::EK_Other)
Actions(Actions)10757       : Actions(Actions) {
10758     Actions.PushExpressionEvaluationContext(
10759         NewContext, Sema::ReuseLambdaContextDecl, ExprContext);
10760   }
10761 
10762   enum InitListTag { InitList };
10763   EnterExpressionEvaluationContext(Sema &Actions, InitListTag,
10764                                    bool ShouldEnter = true)
Actions(Actions)10765       : Actions(Actions), Entered(false) {
10766     // In C++11 onwards, narrowing checks are performed on the contents of
10767     // braced-init-lists, even when they occur within unevaluated operands.
10768     // Therefore we still need to instantiate constexpr functions used in such
10769     // a context.
10770     if (ShouldEnter && Actions.isUnevaluatedContext() &&
10771         Actions.getLangOpts().CPlusPlus11) {
10772       Actions.PushExpressionEvaluationContext(
10773           Sema::ExpressionEvaluationContext::UnevaluatedList);
10774       Entered = true;
10775     }
10776   }
10777 
~EnterExpressionEvaluationContext()10778   ~EnterExpressionEvaluationContext() {
10779     if (Entered)
10780       Actions.PopExpressionEvaluationContext();
10781   }
10782 };
10783 
10784 DeductionFailureInfo
10785 MakeDeductionFailureInfo(ASTContext &Context, Sema::TemplateDeductionResult TDK,
10786                          sema::TemplateDeductionInfo &Info);
10787 
10788 /// Contains a late templated function.
10789 /// Will be parsed at the end of the translation unit, used by Sema & Parser.
10790 struct LateParsedTemplate {
10791   CachedTokens Toks;
10792   /// The template function declaration to be late parsed.
10793   Decl *D;
10794 };
10795 
10796 } // end namespace clang
10797 
10798 namespace llvm {
10799 // Hash a FunctionDeclAndLoc by looking at both its FunctionDecl and its
10800 // SourceLocation.
10801 template <> struct DenseMapInfo<clang::Sema::FunctionDeclAndLoc> {
10802   using FunctionDeclAndLoc = clang::Sema::FunctionDeclAndLoc;
10803   using FDBaseInfo = DenseMapInfo<clang::CanonicalDeclPtr<clang::FunctionDecl>>;
10804 
10805   static FunctionDeclAndLoc getEmptyKey() {
10806     return {FDBaseInfo::getEmptyKey(), clang::SourceLocation()};
10807   }
10808 
10809   static FunctionDeclAndLoc getTombstoneKey() {
10810     return {FDBaseInfo::getTombstoneKey(), clang::SourceLocation()};
10811   }
10812 
10813   static unsigned getHashValue(const FunctionDeclAndLoc &FDL) {
10814     return hash_combine(FDBaseInfo::getHashValue(FDL.FD),
10815                         FDL.Loc.getRawEncoding());
10816   }
10817 
10818   static bool isEqual(const FunctionDeclAndLoc &LHS,
10819                       const FunctionDeclAndLoc &RHS) {
10820     return LHS.FD == RHS.FD && LHS.Loc == RHS.Loc;
10821   }
10822 };
10823 } // namespace llvm
10824 
10825 #endif
10826