1 //===--- Sema.h - Semantic Analysis & AST Building --------------*- C++ -*-===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file defines the Sema class, which performs semantic analysis and
10 // builds ASTs.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #ifndef LLVM_CLANG_SEMA_SEMA_H
15 #define LLVM_CLANG_SEMA_SEMA_H
16 
17 #include "clang/AST/ASTConcept.h"
18 #include "clang/AST/ASTFwd.h"
19 #include "clang/AST/Attr.h"
20 #include "clang/AST/Availability.h"
21 #include "clang/AST/ComparisonCategories.h"
22 #include "clang/AST/DeclTemplate.h"
23 #include "clang/AST/DeclarationName.h"
24 #include "clang/AST/Expr.h"
25 #include "clang/AST/ExprCXX.h"
26 #include "clang/AST/ExprConcepts.h"
27 #include "clang/AST/ExprObjC.h"
28 #include "clang/AST/ExprOpenMP.h"
29 #include "clang/AST/ExternalASTSource.h"
30 #include "clang/AST/LocInfoType.h"
31 #include "clang/AST/MangleNumberingContext.h"
32 #include "clang/AST/NSAPI.h"
33 #include "clang/AST/PrettyPrinter.h"
34 #include "clang/AST/StmtCXX.h"
35 #include "clang/AST/StmtOpenMP.h"
36 #include "clang/AST/TypeLoc.h"
37 #include "clang/AST/TypeOrdering.h"
38 #include "clang/Basic/BitmaskEnum.h"
39 #include "clang/Basic/Builtins.h"
40 #include "clang/Basic/DarwinSDKInfo.h"
41 #include "clang/Basic/ExpressionTraits.h"
42 #include "clang/Basic/Module.h"
43 #include "clang/Basic/OpenCLOptions.h"
44 #include "clang/Basic/OpenMPKinds.h"
45 #include "clang/Basic/PragmaKinds.h"
46 #include "clang/Basic/Specifiers.h"
47 #include "clang/Basic/TemplateKinds.h"
48 #include "clang/Basic/TypeTraits.h"
49 #include "clang/Sema/AnalysisBasedWarnings.h"
50 #include "clang/Sema/CleanupInfo.h"
51 #include "clang/Sema/DeclSpec.h"
52 #include "clang/Sema/ExternalSemaSource.h"
53 #include "clang/Sema/IdentifierResolver.h"
54 #include "clang/Sema/ObjCMethodList.h"
55 #include "clang/Sema/Ownership.h"
56 #include "clang/Sema/Scope.h"
57 #include "clang/Sema/SemaConcept.h"
58 #include "clang/Sema/TypoCorrection.h"
59 #include "clang/Sema/Weak.h"
60 #include "llvm/ADT/ArrayRef.h"
61 #include "llvm/ADT/SetVector.h"
62 #include "llvm/ADT/SmallBitVector.h"
63 #include "llvm/ADT/SmallPtrSet.h"
64 #include "llvm/ADT/SmallSet.h"
65 #include "llvm/ADT/SmallVector.h"
66 #include "llvm/ADT/TinyPtrVector.h"
67 #include "llvm/Frontend/OpenMP/OMPConstants.h"
68 #include <deque>
69 #include <memory>
70 #include <optional>
71 #include <string>
72 #include <tuple>
73 #include <vector>
74 
75 namespace llvm {
76   class APSInt;
77   template <typename ValueT, typename ValueInfoT> class DenseSet;
78   class SmallBitVector;
79   struct InlineAsmIdentifierInfo;
80 }
81 
82 namespace clang {
83   class ADLResult;
84   class ASTConsumer;
85   class ASTContext;
86   class ASTMutationListener;
87   class ASTReader;
88   class ASTWriter;
89   class ArrayType;
90   class ParsedAttr;
91   class BindingDecl;
92   class BlockDecl;
93   class CapturedDecl;
94   class CXXBasePath;
95   class CXXBasePaths;
96   class CXXBindTemporaryExpr;
97   typedef SmallVector<CXXBaseSpecifier*, 4> CXXCastPath;
98   class CXXConstructorDecl;
99   class CXXConversionDecl;
100   class CXXDeleteExpr;
101   class CXXDestructorDecl;
102   class CXXFieldCollector;
103   class CXXMemberCallExpr;
104   class CXXMethodDecl;
105   class CXXScopeSpec;
106   class CXXTemporary;
107   class CXXTryStmt;
108   class CallExpr;
109   class ClassTemplateDecl;
110   class ClassTemplatePartialSpecializationDecl;
111   class ClassTemplateSpecializationDecl;
112   class VarTemplatePartialSpecializationDecl;
113   class CodeCompleteConsumer;
114   class CodeCompletionAllocator;
115   class CodeCompletionTUInfo;
116   class CodeCompletionResult;
117   class CoroutineBodyStmt;
118   class Decl;
119   class DeclAccessPair;
120   class DeclContext;
121   class DeclRefExpr;
122   class DeclaratorDecl;
123   class DeducedTemplateArgument;
124   class DependentDiagnostic;
125   class DesignatedInitExpr;
126   class Designation;
127   class EnableIfAttr;
128   class EnumConstantDecl;
129   class Expr;
130   class ExtVectorType;
131   class FormatAttr;
132   class FriendDecl;
133   class FunctionDecl;
134   class FunctionProtoType;
135   class FunctionTemplateDecl;
136   class ImplicitConversionSequence;
137   typedef MutableArrayRef<ImplicitConversionSequence> ConversionSequenceList;
138   class InitListExpr;
139   class InitializationKind;
140   class InitializationSequence;
141   class InitializedEntity;
142   class IntegerLiteral;
143   class LabelStmt;
144   class LambdaExpr;
145   class LangOptions;
146   class LocalInstantiationScope;
147   class LookupResult;
148   class MacroInfo;
149   typedef ArrayRef<std::pair<IdentifierInfo *, SourceLocation>> ModuleIdPath;
150   class ModuleLoader;
151   class MultiLevelTemplateArgumentList;
152   class NamedDecl;
153   class ObjCCategoryDecl;
154   class ObjCCategoryImplDecl;
155   class ObjCCompatibleAliasDecl;
156   class ObjCContainerDecl;
157   class ObjCImplDecl;
158   class ObjCImplementationDecl;
159   class ObjCInterfaceDecl;
160   class ObjCIvarDecl;
161   template <class T> class ObjCList;
162   class ObjCMessageExpr;
163   class ObjCMethodDecl;
164   class ObjCPropertyDecl;
165   class ObjCProtocolDecl;
166   class OMPThreadPrivateDecl;
167   class OMPRequiresDecl;
168   class OMPDeclareReductionDecl;
169   class OMPDeclareSimdDecl;
170   class OMPClause;
171   struct OMPVarListLocTy;
172   struct OverloadCandidate;
173   enum class OverloadCandidateParamOrder : char;
174   enum OverloadCandidateRewriteKind : unsigned;
175   class OverloadCandidateSet;
176   class OverloadExpr;
177   class ParenListExpr;
178   class ParmVarDecl;
179   class Preprocessor;
180   class PseudoDestructorTypeStorage;
181   class PseudoObjectExpr;
182   class QualType;
183   class StandardConversionSequence;
184   class Stmt;
185   class StringLiteral;
186   class SwitchStmt;
187   class TemplateArgument;
188   class TemplateArgumentList;
189   class TemplateArgumentLoc;
190   class TemplateDecl;
191   class TemplateInstantiationCallback;
192   class TemplateParameterList;
193   class TemplatePartialOrderingContext;
194   class TemplateTemplateParmDecl;
195   class Token;
196   class TypeAliasDecl;
197   class TypedefDecl;
198   class TypedefNameDecl;
199   class TypeLoc;
200   class TypoCorrectionConsumer;
201   class UnqualifiedId;
202   class UnresolvedLookupExpr;
203   class UnresolvedMemberExpr;
204   class UnresolvedSetImpl;
205   class UnresolvedSetIterator;
206   class UsingDecl;
207   class UsingShadowDecl;
208   class ValueDecl;
209   class VarDecl;
210   class VarTemplateSpecializationDecl;
211   class VisibilityAttr;
212   class VisibleDeclConsumer;
213   class IndirectFieldDecl;
214   struct DeductionFailureInfo;
215   class TemplateSpecCandidateSet;
216 
217 namespace sema {
218   class AccessedEntity;
219   class BlockScopeInfo;
220   class Capture;
221   class CapturedRegionScopeInfo;
222   class CapturingScopeInfo;
223   class CompoundScopeInfo;
224   class DelayedDiagnostic;
225   class DelayedDiagnosticPool;
226   class FunctionScopeInfo;
227   class LambdaScopeInfo;
228   class PossiblyUnreachableDiag;
229   class RISCVIntrinsicManager;
230   class SemaPPCallbacks;
231   class TemplateDeductionInfo;
232 }
233 
234 namespace threadSafety {
235   class BeforeSet;
236   void threadSafetyCleanup(BeforeSet* Cache);
237 }
238 
239 // FIXME: No way to easily map from TemplateTypeParmTypes to
240 // TemplateTypeParmDecls, so we have this horrible PointerUnion.
241 typedef std::pair<llvm::PointerUnion<const TemplateTypeParmType *, NamedDecl *>,
242                   SourceLocation>
243     UnexpandedParameterPack;
244 
245 /// Describes whether we've seen any nullability information for the given
246 /// file.
247 struct FileNullability {
248   /// The first pointer declarator (of any pointer kind) in the file that does
249   /// not have a corresponding nullability annotation.
250   SourceLocation PointerLoc;
251 
252   /// The end location for the first pointer declarator in the file. Used for
253   /// placing fix-its.
254   SourceLocation PointerEndLoc;
255 
256   /// Which kind of pointer declarator we saw.
257   uint8_t PointerKind;
258 
259   /// Whether we saw any type nullability annotations in the given file.
260   bool SawTypeNullability = false;
261 };
262 
263 /// A mapping from file IDs to a record of whether we've seen nullability
264 /// information in that file.
265 class FileNullabilityMap {
266   /// A mapping from file IDs to the nullability information for each file ID.
267   llvm::DenseMap<FileID, FileNullability> Map;
268 
269   /// A single-element cache based on the file ID.
270   struct {
271     FileID File;
272     FileNullability Nullability;
273   } Cache;
274 
275 public:
276   FileNullability &operator[](FileID file) {
277     // Check the single-element cache.
278     if (file == Cache.File)
279       return Cache.Nullability;
280 
281     // It's not in the single-element cache; flush the cache if we have one.
282     if (!Cache.File.isInvalid()) {
283       Map[Cache.File] = Cache.Nullability;
284     }
285 
286     // Pull this entry into the cache.
287     Cache.File = file;
288     Cache.Nullability = Map[file];
289     return Cache.Nullability;
290   }
291 };
292 
293 /// Tracks expected type during expression parsing, for use in code completion.
294 /// The type is tied to a particular token, all functions that update or consume
295 /// the type take a start location of the token they are looking at as a
296 /// parameter. This avoids updating the type on hot paths in the parser.
297 class PreferredTypeBuilder {
298 public:
299   PreferredTypeBuilder(bool Enabled) : Enabled(Enabled) {}
300 
301   void enterCondition(Sema &S, SourceLocation Tok);
302   void enterReturn(Sema &S, SourceLocation Tok);
303   void enterVariableInit(SourceLocation Tok, Decl *D);
304   /// Handles e.g. BaseType{ .D = Tok...
305   void enterDesignatedInitializer(SourceLocation Tok, QualType BaseType,
306                                   const Designation &D);
307   /// Computing a type for the function argument may require running
308   /// overloading, so we postpone its computation until it is actually needed.
309   ///
310   /// Clients should be very careful when using this function, as it stores a
311   /// function_ref, clients should make sure all calls to get() with the same
312   /// location happen while function_ref is alive.
313   ///
314   /// The callback should also emit signature help as a side-effect, but only
315   /// if the completion point has been reached.
316   void enterFunctionArgument(SourceLocation Tok,
317                              llvm::function_ref<QualType()> ComputeType);
318 
319   void enterParenExpr(SourceLocation Tok, SourceLocation LParLoc);
320   void enterUnary(Sema &S, SourceLocation Tok, tok::TokenKind OpKind,
321                   SourceLocation OpLoc);
322   void enterBinary(Sema &S, SourceLocation Tok, Expr *LHS, tok::TokenKind Op);
323   void enterMemAccess(Sema &S, SourceLocation Tok, Expr *Base);
324   void enterSubscript(Sema &S, SourceLocation Tok, Expr *LHS);
325   /// Handles all type casts, including C-style cast, C++ casts, etc.
326   void enterTypeCast(SourceLocation Tok, QualType CastType);
327 
328   /// Get the expected type associated with this location, if any.
329   ///
330   /// If the location is a function argument, determining the expected type
331   /// involves considering all function overloads and the arguments so far.
332   /// In this case, signature help for these function overloads will be reported
333   /// as a side-effect (only if the completion point has been reached).
334   QualType get(SourceLocation Tok) const {
335     if (!Enabled || Tok != ExpectedLoc)
336       return QualType();
337     if (!Type.isNull())
338       return Type;
339     if (ComputeType)
340       return ComputeType();
341     return QualType();
342   }
343 
344 private:
345   bool Enabled;
346   /// Start position of a token for which we store expected type.
347   SourceLocation ExpectedLoc;
348   /// Expected type for a token starting at ExpectedLoc.
349   QualType Type;
350   /// A function to compute expected type at ExpectedLoc. It is only considered
351   /// if Type is null.
352   llvm::function_ref<QualType()> ComputeType;
353 };
354 
355 /// Sema - This implements semantic analysis and AST building for C.
356 class Sema final {
357   Sema(const Sema &) = delete;
358   void operator=(const Sema &) = delete;
359 
360   ///Source of additional semantic information.
361   IntrusiveRefCntPtr<ExternalSemaSource> ExternalSource;
362 
363   static bool mightHaveNonExternalLinkage(const DeclaratorDecl *FD);
364 
365   /// Determine whether two declarations should be linked together, given that
366   /// the old declaration might not be visible and the new declaration might
367   /// not have external linkage.
368   bool shouldLinkPossiblyHiddenDecl(const NamedDecl *Old,
369                                     const NamedDecl *New) {
370     if (isVisible(Old))
371      return true;
372     // See comment in below overload for why it's safe to compute the linkage
373     // of the new declaration here.
374     if (New->isExternallyDeclarable()) {
375       assert(Old->isExternallyDeclarable() &&
376              "should not have found a non-externally-declarable previous decl");
377       return true;
378     }
379     return false;
380   }
381   bool shouldLinkPossiblyHiddenDecl(LookupResult &Old, const NamedDecl *New);
382 
383   void setupImplicitSpecialMemberType(CXXMethodDecl *SpecialMem,
384                                       QualType ResultTy,
385                                       ArrayRef<QualType> Args);
386 
387 public:
388   /// The maximum alignment, same as in llvm::Value. We duplicate them here
389   /// because that allows us not to duplicate the constants in clang code,
390   /// which we must to since we can't directly use the llvm constants.
391   /// The value is verified against llvm here: lib/CodeGen/CGDecl.cpp
392   ///
393   /// This is the greatest alignment value supported by load, store, and alloca
394   /// instructions, and global values.
395   static const unsigned MaxAlignmentExponent = 32;
396   static const uint64_t MaximumAlignment = 1ull << MaxAlignmentExponent;
397 
398   typedef OpaquePtr<DeclGroupRef> DeclGroupPtrTy;
399   typedef OpaquePtr<TemplateName> TemplateTy;
400   typedef OpaquePtr<QualType> TypeTy;
401 
402   OpenCLOptions OpenCLFeatures;
403   FPOptions CurFPFeatures;
404 
405   const LangOptions &LangOpts;
406   Preprocessor &PP;
407   ASTContext &Context;
408   ASTConsumer &Consumer;
409   DiagnosticsEngine &Diags;
410   SourceManager &SourceMgr;
411 
412   /// Flag indicating whether or not to collect detailed statistics.
413   bool CollectStats;
414 
415   /// Code-completion consumer.
416   CodeCompleteConsumer *CodeCompleter;
417 
418   /// CurContext - This is the current declaration context of parsing.
419   DeclContext *CurContext;
420 
421   /// Generally null except when we temporarily switch decl contexts,
422   /// like in \see ActOnObjCTemporaryExitContainerContext.
423   DeclContext *OriginalLexicalContext;
424 
425   /// VAListTagName - The declaration name corresponding to __va_list_tag.
426   /// This is used as part of a hack to omit that class from ADL results.
427   DeclarationName VAListTagName;
428 
429   bool MSStructPragmaOn; // True when \#pragma ms_struct on
430 
431   /// Controls member pointer representation format under the MS ABI.
432   LangOptions::PragmaMSPointersToMembersKind
433       MSPointerToMemberRepresentationMethod;
434 
435   /// Stack of active SEH __finally scopes.  Can be empty.
436   SmallVector<Scope*, 2> CurrentSEHFinally;
437 
438   /// Source location for newly created implicit MSInheritanceAttrs
439   SourceLocation ImplicitMSInheritanceAttrLoc;
440 
441   /// Holds TypoExprs that are created from `createDelayedTypo`. This is used by
442   /// `TransformTypos` in order to keep track of any TypoExprs that are created
443   /// recursively during typo correction and wipe them away if the correction
444   /// fails.
445   llvm::SmallVector<TypoExpr *, 2> TypoExprs;
446 
447   /// pragma clang section kind
448   enum PragmaClangSectionKind {
449     PCSK_Invalid      = 0,
450     PCSK_BSS          = 1,
451     PCSK_Data         = 2,
452     PCSK_Rodata       = 3,
453     PCSK_Text         = 4,
454     PCSK_Relro        = 5
455    };
456 
457   enum PragmaClangSectionAction {
458     PCSA_Set     = 0,
459     PCSA_Clear   = 1
460   };
461 
462   struct PragmaClangSection {
463     std::string SectionName;
464     bool Valid = false;
465     SourceLocation PragmaLocation;
466   };
467 
468    PragmaClangSection PragmaClangBSSSection;
469    PragmaClangSection PragmaClangDataSection;
470    PragmaClangSection PragmaClangRodataSection;
471    PragmaClangSection PragmaClangRelroSection;
472    PragmaClangSection PragmaClangTextSection;
473 
474   enum PragmaMsStackAction {
475     PSK_Reset     = 0x0,                // #pragma ()
476     PSK_Set       = 0x1,                // #pragma (value)
477     PSK_Push      = 0x2,                // #pragma (push[, id])
478     PSK_Pop       = 0x4,                // #pragma (pop[, id])
479     PSK_Show      = 0x8,                // #pragma (show) -- only for "pack"!
480     PSK_Push_Set  = PSK_Push | PSK_Set, // #pragma (push[, id], value)
481     PSK_Pop_Set   = PSK_Pop | PSK_Set,  // #pragma (pop[, id], value)
482   };
483 
484   struct PragmaPackInfo {
485     PragmaMsStackAction Action;
486     StringRef SlotLabel;
487     Token Alignment;
488   };
489 
490   // #pragma pack and align.
491   class AlignPackInfo {
492   public:
493     // `Native` represents default align mode, which may vary based on the
494     // platform.
495     enum Mode : unsigned char { Native, Natural, Packed, Mac68k };
496 
497     // #pragma pack info constructor
498     AlignPackInfo(AlignPackInfo::Mode M, unsigned Num, bool IsXL)
499         : PackAttr(true), AlignMode(M), PackNumber(Num), XLStack(IsXL) {
500       assert(Num == PackNumber && "The pack number has been truncated.");
501     }
502 
503     // #pragma align info constructor
504     AlignPackInfo(AlignPackInfo::Mode M, bool IsXL)
505         : PackAttr(false), AlignMode(M),
506           PackNumber(M == Packed ? 1 : UninitPackVal), XLStack(IsXL) {}
507 
508     explicit AlignPackInfo(bool IsXL) : AlignPackInfo(Native, IsXL) {}
509 
510     AlignPackInfo() : AlignPackInfo(Native, false) {}
511 
512     // When a AlignPackInfo itself cannot be used, this returns an 32-bit
513     // integer encoding for it. This should only be passed to
514     // AlignPackInfo::getFromRawEncoding, it should not be inspected directly.
515     static uint32_t getRawEncoding(const AlignPackInfo &Info) {
516       std::uint32_t Encoding{};
517       if (Info.IsXLStack())
518         Encoding |= IsXLMask;
519 
520       Encoding |= static_cast<uint32_t>(Info.getAlignMode()) << 1;
521 
522       if (Info.IsPackAttr())
523         Encoding |= PackAttrMask;
524 
525       Encoding |= static_cast<uint32_t>(Info.getPackNumber()) << 4;
526 
527       return Encoding;
528     }
529 
530     static AlignPackInfo getFromRawEncoding(unsigned Encoding) {
531       bool IsXL = static_cast<bool>(Encoding & IsXLMask);
532       AlignPackInfo::Mode M =
533           static_cast<AlignPackInfo::Mode>((Encoding & AlignModeMask) >> 1);
534       int PackNumber = (Encoding & PackNumMask) >> 4;
535 
536       if (Encoding & PackAttrMask)
537         return AlignPackInfo(M, PackNumber, IsXL);
538 
539       return AlignPackInfo(M, IsXL);
540     }
541 
542     bool IsPackAttr() const { return PackAttr; }
543 
544     bool IsAlignAttr() const { return !PackAttr; }
545 
546     Mode getAlignMode() const { return AlignMode; }
547 
548     unsigned getPackNumber() const { return PackNumber; }
549 
550     bool IsPackSet() const {
551       // #pragma align, #pragma pack(), and #pragma pack(0) do not set the pack
552       // attriute on a decl.
553       return PackNumber != UninitPackVal && PackNumber != 0;
554     }
555 
556     bool IsXLStack() const { return XLStack; }
557 
558     bool operator==(const AlignPackInfo &Info) const {
559       return std::tie(AlignMode, PackNumber, PackAttr, XLStack) ==
560              std::tie(Info.AlignMode, Info.PackNumber, Info.PackAttr,
561                       Info.XLStack);
562     }
563 
564     bool operator!=(const AlignPackInfo &Info) const {
565       return !(*this == Info);
566     }
567 
568   private:
569     /// \brief True if this is a pragma pack attribute,
570     ///         not a pragma align attribute.
571     bool PackAttr;
572 
573     /// \brief The alignment mode that is in effect.
574     Mode AlignMode;
575 
576     /// \brief The pack number of the stack.
577     unsigned char PackNumber;
578 
579     /// \brief True if it is a XL #pragma align/pack stack.
580     bool XLStack;
581 
582     /// \brief Uninitialized pack value.
583     static constexpr unsigned char UninitPackVal = -1;
584 
585     // Masks to encode and decode an AlignPackInfo.
586     static constexpr uint32_t IsXLMask{0x0000'0001};
587     static constexpr uint32_t AlignModeMask{0x0000'0006};
588     static constexpr uint32_t PackAttrMask{0x00000'0008};
589     static constexpr uint32_t PackNumMask{0x0000'01F0};
590   };
591 
592   template<typename ValueType>
593   struct PragmaStack {
594     struct Slot {
595       llvm::StringRef StackSlotLabel;
596       ValueType Value;
597       SourceLocation PragmaLocation;
598       SourceLocation PragmaPushLocation;
599       Slot(llvm::StringRef StackSlotLabel, ValueType Value,
600            SourceLocation PragmaLocation, SourceLocation PragmaPushLocation)
601           : StackSlotLabel(StackSlotLabel), Value(Value),
602             PragmaLocation(PragmaLocation),
603             PragmaPushLocation(PragmaPushLocation) {}
604     };
605 
606     void Act(SourceLocation PragmaLocation, PragmaMsStackAction Action,
607              llvm::StringRef StackSlotLabel, ValueType Value) {
608       if (Action == PSK_Reset) {
609         CurrentValue = DefaultValue;
610         CurrentPragmaLocation = PragmaLocation;
611         return;
612       }
613       if (Action & PSK_Push)
614         Stack.emplace_back(StackSlotLabel, CurrentValue, CurrentPragmaLocation,
615                            PragmaLocation);
616       else if (Action & PSK_Pop) {
617         if (!StackSlotLabel.empty()) {
618           // If we've got a label, try to find it and jump there.
619           auto I = llvm::find_if(llvm::reverse(Stack), [&](const Slot &x) {
620             return x.StackSlotLabel == StackSlotLabel;
621           });
622           // If we found the label so pop from there.
623           if (I != Stack.rend()) {
624             CurrentValue = I->Value;
625             CurrentPragmaLocation = I->PragmaLocation;
626             Stack.erase(std::prev(I.base()), Stack.end());
627           }
628         } else if (!Stack.empty()) {
629           // We do not have a label, just pop the last entry.
630           CurrentValue = Stack.back().Value;
631           CurrentPragmaLocation = Stack.back().PragmaLocation;
632           Stack.pop_back();
633         }
634       }
635       if (Action & PSK_Set) {
636         CurrentValue = Value;
637         CurrentPragmaLocation = PragmaLocation;
638       }
639     }
640 
641     // MSVC seems to add artificial slots to #pragma stacks on entering a C++
642     // method body to restore the stacks on exit, so it works like this:
643     //
644     //   struct S {
645     //     #pragma <name>(push, InternalPragmaSlot, <current_pragma_value>)
646     //     void Method {}
647     //     #pragma <name>(pop, InternalPragmaSlot)
648     //   };
649     //
650     // It works even with #pragma vtordisp, although MSVC doesn't support
651     //   #pragma vtordisp(push [, id], n)
652     // syntax.
653     //
654     // Push / pop a named sentinel slot.
655     void SentinelAction(PragmaMsStackAction Action, StringRef Label) {
656       assert((Action == PSK_Push || Action == PSK_Pop) &&
657              "Can only push / pop #pragma stack sentinels!");
658       Act(CurrentPragmaLocation, Action, Label, CurrentValue);
659     }
660 
661     // Constructors.
662     explicit PragmaStack(const ValueType &Default)
663         : DefaultValue(Default), CurrentValue(Default) {}
664 
665     bool hasValue() const { return CurrentValue != DefaultValue; }
666 
667     SmallVector<Slot, 2> Stack;
668     ValueType DefaultValue; // Value used for PSK_Reset action.
669     ValueType CurrentValue;
670     SourceLocation CurrentPragmaLocation;
671   };
672   // FIXME: We should serialize / deserialize these if they occur in a PCH (but
673   // we shouldn't do so if they're in a module).
674 
675   /// Whether to insert vtordisps prior to virtual bases in the Microsoft
676   /// C++ ABI.  Possible values are 0, 1, and 2, which mean:
677   ///
678   /// 0: Suppress all vtordisps
679   /// 1: Insert vtordisps in the presence of vbase overrides and non-trivial
680   ///    structors
681   /// 2: Always insert vtordisps to support RTTI on partially constructed
682   ///    objects
683   PragmaStack<MSVtorDispMode> VtorDispStack;
684   PragmaStack<AlignPackInfo> AlignPackStack;
685   // The current #pragma align/pack values and locations at each #include.
686   struct AlignPackIncludeState {
687     AlignPackInfo CurrentValue;
688     SourceLocation CurrentPragmaLocation;
689     bool HasNonDefaultValue, ShouldWarnOnInclude;
690   };
691   SmallVector<AlignPackIncludeState, 8> AlignPackIncludeStack;
692   // Segment #pragmas.
693   PragmaStack<StringLiteral *> DataSegStack;
694   PragmaStack<StringLiteral *> BSSSegStack;
695   PragmaStack<StringLiteral *> ConstSegStack;
696   PragmaStack<StringLiteral *> CodeSegStack;
697 
698   // #pragma strict_gs_check.
699   PragmaStack<bool> StrictGuardStackCheckStack;
700 
701   // This stack tracks the current state of Sema.CurFPFeatures.
702   PragmaStack<FPOptionsOverride> FpPragmaStack;
703   FPOptionsOverride CurFPFeatureOverrides() {
704     FPOptionsOverride result;
705     if (!FpPragmaStack.hasValue()) {
706       result = FPOptionsOverride();
707     } else {
708       result = FpPragmaStack.CurrentValue;
709     }
710     return result;
711   }
712 
713   // Saves the current floating-point pragma stack and clear it in this Sema.
714   class FpPragmaStackSaveRAII {
715   public:
716     FpPragmaStackSaveRAII(Sema &S)
717         : S(S), SavedStack(std::move(S.FpPragmaStack)) {
718       S.FpPragmaStack.Stack.clear();
719     }
720     ~FpPragmaStackSaveRAII() { S.FpPragmaStack = std::move(SavedStack); }
721 
722   private:
723     Sema &S;
724     PragmaStack<FPOptionsOverride> SavedStack;
725   };
726 
727   void resetFPOptions(FPOptions FPO) {
728     CurFPFeatures = FPO;
729     FpPragmaStack.CurrentValue = FPO.getChangesFrom(FPOptions(LangOpts));
730   }
731 
732   // RAII object to push / pop sentinel slots for all MS #pragma stacks.
733   // Actions should be performed only if we enter / exit a C++ method body.
734   class PragmaStackSentinelRAII {
735   public:
736     PragmaStackSentinelRAII(Sema &S, StringRef SlotLabel, bool ShouldAct);
737     ~PragmaStackSentinelRAII();
738 
739   private:
740     Sema &S;
741     StringRef SlotLabel;
742     bool ShouldAct;
743   };
744 
745   /// A mapping that describes the nullability we've seen in each header file.
746   FileNullabilityMap NullabilityMap;
747 
748   /// Last section used with #pragma init_seg.
749   StringLiteral *CurInitSeg;
750   SourceLocation CurInitSegLoc;
751 
752   /// Sections used with #pragma alloc_text.
753   llvm::StringMap<std::tuple<StringRef, SourceLocation>> FunctionToSectionMap;
754 
755   /// VisContext - Manages the stack for \#pragma GCC visibility.
756   void *VisContext; // Really a "PragmaVisStack*"
757 
758   /// This an attribute introduced by \#pragma clang attribute.
759   struct PragmaAttributeEntry {
760     SourceLocation Loc;
761     ParsedAttr *Attribute;
762     SmallVector<attr::SubjectMatchRule, 4> MatchRules;
763     bool IsUsed;
764   };
765 
766   /// A push'd group of PragmaAttributeEntries.
767   struct PragmaAttributeGroup {
768     /// The location of the push attribute.
769     SourceLocation Loc;
770     /// The namespace of this push group.
771     const IdentifierInfo *Namespace;
772     SmallVector<PragmaAttributeEntry, 2> Entries;
773   };
774 
775   SmallVector<PragmaAttributeGroup, 2> PragmaAttributeStack;
776 
777   /// The declaration that is currently receiving an attribute from the
778   /// #pragma attribute stack.
779   const Decl *PragmaAttributeCurrentTargetDecl;
780 
781   /// This represents the last location of a "#pragma clang optimize off"
782   /// directive if such a directive has not been closed by an "on" yet. If
783   /// optimizations are currently "on", this is set to an invalid location.
784   SourceLocation OptimizeOffPragmaLocation;
785 
786   /// The "on" or "off" argument passed by \#pragma optimize, that denotes
787   /// whether the optimizations in the list passed to the pragma should be
788   /// turned off or on. This boolean is true by default because command line
789   /// options are honored when `#pragma optimize("", on)`.
790   /// (i.e. `ModifyFnAttributeMSPragmaOptimze()` does nothing)
791   bool MSPragmaOptimizeIsOn = true;
792 
793   /// Set of no-builtin functions listed by \#pragma function.
794   llvm::SmallSetVector<StringRef, 4> MSFunctionNoBuiltins;
795 
796   /// Flag indicating if Sema is building a recovery call expression.
797   ///
798   /// This flag is used to avoid building recovery call expressions
799   /// if Sema is already doing so, which would cause infinite recursions.
800   bool IsBuildingRecoveryCallExpr;
801 
802   /// Used to control the generation of ExprWithCleanups.
803   CleanupInfo Cleanup;
804 
805   /// ExprCleanupObjects - This is the stack of objects requiring
806   /// cleanup that are created by the current full expression.
807   SmallVector<ExprWithCleanups::CleanupObject, 8> ExprCleanupObjects;
808 
809   /// Store a set of either DeclRefExprs or MemberExprs that contain a reference
810   /// to a variable (constant) that may or may not be odr-used in this Expr, and
811   /// we won't know until all lvalue-to-rvalue and discarded value conversions
812   /// have been applied to all subexpressions of the enclosing full expression.
813   /// This is cleared at the end of each full expression.
814   using MaybeODRUseExprSet = llvm::SmallSetVector<Expr *, 4>;
815   MaybeODRUseExprSet MaybeODRUseExprs;
816 
817   std::unique_ptr<sema::FunctionScopeInfo> CachedFunctionScope;
818 
819   /// Stack containing information about each of the nested
820   /// function, block, and method scopes that are currently active.
821   SmallVector<sema::FunctionScopeInfo *, 4> FunctionScopes;
822 
823   /// The index of the first FunctionScope that corresponds to the current
824   /// context.
825   unsigned FunctionScopesStart = 0;
826 
827   /// Track the number of currently active capturing scopes.
828   unsigned CapturingFunctionScopes = 0;
829 
830   ArrayRef<sema::FunctionScopeInfo*> getFunctionScopes() const {
831     return llvm::ArrayRef(FunctionScopes.begin() + FunctionScopesStart,
832                           FunctionScopes.end());
833   }
834 
835   /// Stack containing information needed when in C++2a an 'auto' is encountered
836   /// in a function declaration parameter type specifier in order to invent a
837   /// corresponding template parameter in the enclosing abbreviated function
838   /// template. This information is also present in LambdaScopeInfo, stored in
839   /// the FunctionScopes stack.
840   SmallVector<InventedTemplateParameterInfo, 4> InventedParameterInfos;
841 
842   /// The index of the first InventedParameterInfo that refers to the current
843   /// context.
844   unsigned InventedParameterInfosStart = 0;
845 
846   ArrayRef<InventedTemplateParameterInfo> getInventedParameterInfos() const {
847     return llvm::ArrayRef(InventedParameterInfos.begin() +
848                               InventedParameterInfosStart,
849                           InventedParameterInfos.end());
850   }
851 
852   typedef LazyVector<TypedefNameDecl *, ExternalSemaSource,
853                      &ExternalSemaSource::ReadExtVectorDecls, 2, 2>
854     ExtVectorDeclsType;
855 
856   /// ExtVectorDecls - This is a list all the extended vector types. This allows
857   /// us to associate a raw vector type with one of the ext_vector type names.
858   /// This is only necessary for issuing pretty diagnostics.
859   ExtVectorDeclsType ExtVectorDecls;
860 
861   /// FieldCollector - Collects CXXFieldDecls during parsing of C++ classes.
862   std::unique_ptr<CXXFieldCollector> FieldCollector;
863 
864   typedef llvm::SmallSetVector<const NamedDecl *, 16> NamedDeclSetType;
865 
866   /// Set containing all declared private fields that are not used.
867   NamedDeclSetType UnusedPrivateFields;
868 
869   /// Set containing all typedefs that are likely unused.
870   llvm::SmallSetVector<const TypedefNameDecl *, 4>
871       UnusedLocalTypedefNameCandidates;
872 
873   /// Delete-expressions to be analyzed at the end of translation unit
874   ///
875   /// This list contains class members, and locations of delete-expressions
876   /// that could not be proven as to whether they mismatch with new-expression
877   /// used in initializer of the field.
878   typedef std::pair<SourceLocation, bool> DeleteExprLoc;
879   typedef llvm::SmallVector<DeleteExprLoc, 4> DeleteLocs;
880   llvm::MapVector<FieldDecl *, DeleteLocs> DeleteExprs;
881 
882   typedef llvm::SmallPtrSet<const CXXRecordDecl*, 8> RecordDeclSetTy;
883 
884   /// PureVirtualClassDiagSet - a set of class declarations which we have
885   /// emitted a list of pure virtual functions. Used to prevent emitting the
886   /// same list more than once.
887   std::unique_ptr<RecordDeclSetTy> PureVirtualClassDiagSet;
888 
889   /// ParsingInitForAutoVars - a set of declarations with auto types for which
890   /// we are currently parsing the initializer.
891   llvm::SmallPtrSet<const Decl*, 4> ParsingInitForAutoVars;
892 
893   /// Look for a locally scoped extern "C" declaration by the given name.
894   NamedDecl *findLocallyScopedExternCDecl(DeclarationName Name);
895 
896   typedef LazyVector<VarDecl *, ExternalSemaSource,
897                      &ExternalSemaSource::ReadTentativeDefinitions, 2, 2>
898     TentativeDefinitionsType;
899 
900   /// All the tentative definitions encountered in the TU.
901   TentativeDefinitionsType TentativeDefinitions;
902 
903   /// All the external declarations encoutered and used in the TU.
904   SmallVector<VarDecl *, 4> ExternalDeclarations;
905 
906   typedef LazyVector<const DeclaratorDecl *, ExternalSemaSource,
907                      &ExternalSemaSource::ReadUnusedFileScopedDecls, 2, 2>
908     UnusedFileScopedDeclsType;
909 
910   /// The set of file scoped decls seen so far that have not been used
911   /// and must warn if not used. Only contains the first declaration.
912   UnusedFileScopedDeclsType UnusedFileScopedDecls;
913 
914   typedef LazyVector<CXXConstructorDecl *, ExternalSemaSource,
915                      &ExternalSemaSource::ReadDelegatingConstructors, 2, 2>
916     DelegatingCtorDeclsType;
917 
918   /// All the delegating constructors seen so far in the file, used for
919   /// cycle detection at the end of the TU.
920   DelegatingCtorDeclsType DelegatingCtorDecls;
921 
922   /// All the overriding functions seen during a class definition
923   /// that had their exception spec checks delayed, plus the overridden
924   /// function.
925   SmallVector<std::pair<const CXXMethodDecl*, const CXXMethodDecl*>, 2>
926     DelayedOverridingExceptionSpecChecks;
927 
928   /// All the function redeclarations seen during a class definition that had
929   /// their exception spec checks delayed, plus the prior declaration they
930   /// should be checked against. Except during error recovery, the new decl
931   /// should always be a friend declaration, as that's the only valid way to
932   /// redeclare a special member before its class is complete.
933   SmallVector<std::pair<FunctionDecl*, FunctionDecl*>, 2>
934     DelayedEquivalentExceptionSpecChecks;
935 
936   typedef llvm::MapVector<const FunctionDecl *,
937                           std::unique_ptr<LateParsedTemplate>>
938       LateParsedTemplateMapT;
939   LateParsedTemplateMapT LateParsedTemplateMap;
940 
941   /// Callback to the parser to parse templated functions when needed.
942   typedef void LateTemplateParserCB(void *P, LateParsedTemplate &LPT);
943   typedef void LateTemplateParserCleanupCB(void *P);
944   LateTemplateParserCB *LateTemplateParser;
945   LateTemplateParserCleanupCB *LateTemplateParserCleanup;
946   void *OpaqueParser;
947 
948   void SetLateTemplateParser(LateTemplateParserCB *LTP,
949                              LateTemplateParserCleanupCB *LTPCleanup,
950                              void *P) {
951     LateTemplateParser = LTP;
952     LateTemplateParserCleanup = LTPCleanup;
953     OpaqueParser = P;
954   }
955 
956   class DelayedDiagnostics;
957 
958   class DelayedDiagnosticsState {
959     sema::DelayedDiagnosticPool *SavedPool = nullptr;
960     friend class Sema::DelayedDiagnostics;
961   };
962   typedef DelayedDiagnosticsState ParsingDeclState;
963   typedef DelayedDiagnosticsState ProcessingContextState;
964 
965   /// A class which encapsulates the logic for delaying diagnostics
966   /// during parsing and other processing.
967   class DelayedDiagnostics {
968     /// The current pool of diagnostics into which delayed
969     /// diagnostics should go.
970     sema::DelayedDiagnosticPool *CurPool = nullptr;
971 
972   public:
973     DelayedDiagnostics() = default;
974 
975     /// Adds a delayed diagnostic.
976     void add(const sema::DelayedDiagnostic &diag); // in DelayedDiagnostic.h
977 
978     /// Determines whether diagnostics should be delayed.
979     bool shouldDelayDiagnostics() { return CurPool != nullptr; }
980 
981     /// Returns the current delayed-diagnostics pool.
982     sema::DelayedDiagnosticPool *getCurrentPool() const {
983       return CurPool;
984     }
985 
986     /// Enter a new scope.  Access and deprecation diagnostics will be
987     /// collected in this pool.
988     DelayedDiagnosticsState push(sema::DelayedDiagnosticPool &pool) {
989       DelayedDiagnosticsState state;
990       state.SavedPool = CurPool;
991       CurPool = &pool;
992       return state;
993     }
994 
995     /// Leave a delayed-diagnostic state that was previously pushed.
996     /// Do not emit any of the diagnostics.  This is performed as part
997     /// of the bookkeeping of popping a pool "properly".
998     void popWithoutEmitting(DelayedDiagnosticsState state) {
999       CurPool = state.SavedPool;
1000     }
1001 
1002     /// Enter a new scope where access and deprecation diagnostics are
1003     /// not delayed.
1004     DelayedDiagnosticsState pushUndelayed() {
1005       DelayedDiagnosticsState state;
1006       state.SavedPool = CurPool;
1007       CurPool = nullptr;
1008       return state;
1009     }
1010 
1011     /// Undo a previous pushUndelayed().
1012     void popUndelayed(DelayedDiagnosticsState state) {
1013       assert(CurPool == nullptr);
1014       CurPool = state.SavedPool;
1015     }
1016   } DelayedDiagnostics;
1017 
1018   /// A RAII object to temporarily push a declaration context.
1019   class ContextRAII {
1020   private:
1021     Sema &S;
1022     DeclContext *SavedContext;
1023     ProcessingContextState SavedContextState;
1024     QualType SavedCXXThisTypeOverride;
1025     unsigned SavedFunctionScopesStart;
1026     unsigned SavedInventedParameterInfosStart;
1027 
1028   public:
1029     ContextRAII(Sema &S, DeclContext *ContextToPush, bool NewThisContext = true)
1030       : S(S), SavedContext(S.CurContext),
1031         SavedContextState(S.DelayedDiagnostics.pushUndelayed()),
1032         SavedCXXThisTypeOverride(S.CXXThisTypeOverride),
1033         SavedFunctionScopesStart(S.FunctionScopesStart),
1034         SavedInventedParameterInfosStart(S.InventedParameterInfosStart)
1035     {
1036       assert(ContextToPush && "pushing null context");
1037       S.CurContext = ContextToPush;
1038       if (NewThisContext)
1039         S.CXXThisTypeOverride = QualType();
1040       // Any saved FunctionScopes do not refer to this context.
1041       S.FunctionScopesStart = S.FunctionScopes.size();
1042       S.InventedParameterInfosStart = S.InventedParameterInfos.size();
1043     }
1044 
1045     void pop() {
1046       if (!SavedContext) return;
1047       S.CurContext = SavedContext;
1048       S.DelayedDiagnostics.popUndelayed(SavedContextState);
1049       S.CXXThisTypeOverride = SavedCXXThisTypeOverride;
1050       S.FunctionScopesStart = SavedFunctionScopesStart;
1051       S.InventedParameterInfosStart = SavedInventedParameterInfosStart;
1052       SavedContext = nullptr;
1053     }
1054 
1055     ~ContextRAII() {
1056       pop();
1057     }
1058   };
1059 
1060   /// Whether the AST is currently being rebuilt to correct immediate
1061   /// invocations. Immediate invocation candidates and references to consteval
1062   /// functions aren't tracked when this is set.
1063   bool RebuildingImmediateInvocation = false;
1064 
1065   /// Used to change context to isConstantEvaluated without pushing a heavy
1066   /// ExpressionEvaluationContextRecord object.
1067   bool isConstantEvaluatedOverride;
1068 
1069   bool isConstantEvaluated() const {
1070     return ExprEvalContexts.back().isConstantEvaluated() ||
1071            isConstantEvaluatedOverride;
1072   }
1073 
1074   /// RAII object to handle the state changes required to synthesize
1075   /// a function body.
1076   class SynthesizedFunctionScope {
1077     Sema &S;
1078     Sema::ContextRAII SavedContext;
1079     bool PushedCodeSynthesisContext = false;
1080 
1081   public:
1082     SynthesizedFunctionScope(Sema &S, DeclContext *DC)
1083         : S(S), SavedContext(S, DC) {
1084       auto *FD = dyn_cast<FunctionDecl>(DC);
1085       S.PushFunctionScope();
1086       S.PushExpressionEvaluationContext(
1087           (FD && FD->isConsteval())
1088               ? ExpressionEvaluationContext::ImmediateFunctionContext
1089               : ExpressionEvaluationContext::PotentiallyEvaluated);
1090       if (FD) {
1091         FD->setWillHaveBody(true);
1092         S.ExprEvalContexts.back().InImmediateFunctionContext =
1093             FD->isImmediateFunction();
1094         S.ExprEvalContexts.back().InImmediateEscalatingFunctionContext =
1095             S.getLangOpts().CPlusPlus20 && FD->isImmediateEscalating();
1096       } else
1097         assert(isa<ObjCMethodDecl>(DC));
1098     }
1099 
1100     void addContextNote(SourceLocation UseLoc) {
1101       assert(!PushedCodeSynthesisContext);
1102 
1103       Sema::CodeSynthesisContext Ctx;
1104       Ctx.Kind = Sema::CodeSynthesisContext::DefiningSynthesizedFunction;
1105       Ctx.PointOfInstantiation = UseLoc;
1106       Ctx.Entity = cast<Decl>(S.CurContext);
1107       S.pushCodeSynthesisContext(Ctx);
1108 
1109       PushedCodeSynthesisContext = true;
1110     }
1111 
1112     ~SynthesizedFunctionScope() {
1113       if (PushedCodeSynthesisContext)
1114         S.popCodeSynthesisContext();
1115       if (auto *FD = dyn_cast<FunctionDecl>(S.CurContext)) {
1116         FD->setWillHaveBody(false);
1117         S.CheckImmediateEscalatingFunctionDefinition(FD, S.getCurFunction());
1118       }
1119       S.PopExpressionEvaluationContext();
1120       S.PopFunctionScopeInfo();
1121     }
1122   };
1123 
1124   /// WeakUndeclaredIdentifiers - Identifiers contained in \#pragma weak before
1125   /// declared. Rare. May alias another identifier, declared or undeclared.
1126   ///
1127   /// For aliases, the target identifier is used as a key for eventual
1128   /// processing when the target is declared. For the single-identifier form,
1129   /// the sole identifier is used as the key. Each entry is a `SetVector`
1130   /// (ordered by parse order) of aliases (identified by the alias name) in case
1131   /// of multiple aliases to the same undeclared identifier.
1132   llvm::MapVector<
1133       IdentifierInfo *,
1134       llvm::SetVector<
1135           WeakInfo, llvm::SmallVector<WeakInfo, 1u>,
1136           llvm::SmallDenseSet<WeakInfo, 2u, WeakInfo::DenseMapInfoByAliasOnly>>>
1137       WeakUndeclaredIdentifiers;
1138 
1139   /// ExtnameUndeclaredIdentifiers - Identifiers contained in
1140   /// \#pragma redefine_extname before declared.  Used in Solaris system headers
1141   /// to define functions that occur in multiple standards to call the version
1142   /// in the currently selected standard.
1143   llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*> ExtnameUndeclaredIdentifiers;
1144 
1145 
1146   /// Load weak undeclared identifiers from the external source.
1147   void LoadExternalWeakUndeclaredIdentifiers();
1148 
1149   /// WeakTopLevelDecl - Translation-unit scoped declarations generated by
1150   /// \#pragma weak during processing of other Decls.
1151   /// I couldn't figure out a clean way to generate these in-line, so
1152   /// we store them here and handle separately -- which is a hack.
1153   /// It would be best to refactor this.
1154   SmallVector<Decl*,2> WeakTopLevelDecl;
1155 
1156   IdentifierResolver IdResolver;
1157 
1158   /// Translation Unit Scope - useful to Objective-C actions that need
1159   /// to lookup file scope declarations in the "ordinary" C decl namespace.
1160   /// For example, user-defined classes, built-in "id" type, etc.
1161   Scope *TUScope;
1162 
1163   /// The C++ "std" namespace, where the standard library resides.
1164   LazyDeclPtr StdNamespace;
1165 
1166   /// The C++ "std::bad_alloc" class, which is defined by the C++
1167   /// standard library.
1168   LazyDeclPtr StdBadAlloc;
1169 
1170   /// The C++ "std::align_val_t" enum class, which is defined by the C++
1171   /// standard library.
1172   LazyDeclPtr StdAlignValT;
1173 
1174   /// The C++ "std::initializer_list" template, which is defined in
1175   /// \<initializer_list>.
1176   ClassTemplateDecl *StdInitializerList;
1177 
1178   /// The C++ "std::coroutine_traits" template, which is defined in
1179   /// \<coroutine_traits>
1180   ClassTemplateDecl *StdCoroutineTraitsCache;
1181 
1182   /// The C++ "type_info" declaration, which is defined in \<typeinfo>.
1183   RecordDecl *CXXTypeInfoDecl;
1184 
1185   /// The C++ "std::source_location::__impl" struct, defined in
1186   /// \<source_location>.
1187   RecordDecl *StdSourceLocationImplDecl;
1188 
1189   /// Caches identifiers/selectors for NSFoundation APIs.
1190   std::unique_ptr<NSAPI> NSAPIObj;
1191 
1192   /// The declaration of the Objective-C NSNumber class.
1193   ObjCInterfaceDecl *NSNumberDecl;
1194 
1195   /// The declaration of the Objective-C NSValue class.
1196   ObjCInterfaceDecl *NSValueDecl;
1197 
1198   /// Pointer to NSNumber type (NSNumber *).
1199   QualType NSNumberPointer;
1200 
1201   /// Pointer to NSValue type (NSValue *).
1202   QualType NSValuePointer;
1203 
1204   /// The Objective-C NSNumber methods used to create NSNumber literals.
1205   ObjCMethodDecl *NSNumberLiteralMethods[NSAPI::NumNSNumberLiteralMethods];
1206 
1207   /// The declaration of the Objective-C NSString class.
1208   ObjCInterfaceDecl *NSStringDecl;
1209 
1210   /// Pointer to NSString type (NSString *).
1211   QualType NSStringPointer;
1212 
1213   /// The declaration of the stringWithUTF8String: method.
1214   ObjCMethodDecl *StringWithUTF8StringMethod;
1215 
1216   /// The declaration of the valueWithBytes:objCType: method.
1217   ObjCMethodDecl *ValueWithBytesObjCTypeMethod;
1218 
1219   /// The declaration of the Objective-C NSArray class.
1220   ObjCInterfaceDecl *NSArrayDecl;
1221 
1222   /// The declaration of the arrayWithObjects:count: method.
1223   ObjCMethodDecl *ArrayWithObjectsMethod;
1224 
1225   /// The declaration of the Objective-C NSDictionary class.
1226   ObjCInterfaceDecl *NSDictionaryDecl;
1227 
1228   /// The declaration of the dictionaryWithObjects:forKeys:count: method.
1229   ObjCMethodDecl *DictionaryWithObjectsMethod;
1230 
1231   /// id<NSCopying> type.
1232   QualType QIDNSCopying;
1233 
1234   /// will hold 'respondsToSelector:'
1235   Selector RespondsToSelectorSel;
1236 
1237   /// A flag to remember whether the implicit forms of operator new and delete
1238   /// have been declared.
1239   bool GlobalNewDeleteDeclared;
1240 
1241   /// Describes how the expressions currently being parsed are
1242   /// evaluated at run-time, if at all.
1243   enum class ExpressionEvaluationContext {
1244     /// The current expression and its subexpressions occur within an
1245     /// unevaluated operand (C++11 [expr]p7), such as the subexpression of
1246     /// \c sizeof, where the type of the expression may be significant but
1247     /// no code will be generated to evaluate the value of the expression at
1248     /// run time.
1249     Unevaluated,
1250 
1251     /// The current expression occurs within a braced-init-list within
1252     /// an unevaluated operand. This is mostly like a regular unevaluated
1253     /// context, except that we still instantiate constexpr functions that are
1254     /// referenced here so that we can perform narrowing checks correctly.
1255     UnevaluatedList,
1256 
1257     /// The current expression occurs within a discarded statement.
1258     /// This behaves largely similarly to an unevaluated operand in preventing
1259     /// definitions from being required, but not in other ways.
1260     DiscardedStatement,
1261 
1262     /// The current expression occurs within an unevaluated
1263     /// operand that unconditionally permits abstract references to
1264     /// fields, such as a SIZE operator in MS-style inline assembly.
1265     UnevaluatedAbstract,
1266 
1267     /// The current context is "potentially evaluated" in C++11 terms,
1268     /// but the expression is evaluated at compile-time (like the values of
1269     /// cases in a switch statement).
1270     ConstantEvaluated,
1271 
1272     /// In addition of being constant evaluated, the current expression
1273     /// occurs in an immediate function context - either a consteval function
1274     /// or a consteval if statement.
1275     ImmediateFunctionContext,
1276 
1277     /// The current expression is potentially evaluated at run time,
1278     /// which means that code may be generated to evaluate the value of the
1279     /// expression at run time.
1280     PotentiallyEvaluated,
1281 
1282     /// The current expression is potentially evaluated, but any
1283     /// declarations referenced inside that expression are only used if
1284     /// in fact the current expression is used.
1285     ///
1286     /// This value is used when parsing default function arguments, for which
1287     /// we would like to provide diagnostics (e.g., passing non-POD arguments
1288     /// through varargs) but do not want to mark declarations as "referenced"
1289     /// until the default argument is used.
1290     PotentiallyEvaluatedIfUsed
1291   };
1292 
1293   using ImmediateInvocationCandidate = llvm::PointerIntPair<ConstantExpr *, 1>;
1294 
1295   /// Data structure used to record current or nested
1296   /// expression evaluation contexts.
1297   struct ExpressionEvaluationContextRecord {
1298     /// The expression evaluation context.
1299     ExpressionEvaluationContext Context;
1300 
1301     /// Whether the enclosing context needed a cleanup.
1302     CleanupInfo ParentCleanup;
1303 
1304     /// The number of active cleanup objects when we entered
1305     /// this expression evaluation context.
1306     unsigned NumCleanupObjects;
1307 
1308     /// The number of typos encountered during this expression evaluation
1309     /// context (i.e. the number of TypoExprs created).
1310     unsigned NumTypos;
1311 
1312     MaybeODRUseExprSet SavedMaybeODRUseExprs;
1313 
1314     /// The lambdas that are present within this context, if it
1315     /// is indeed an unevaluated context.
1316     SmallVector<LambdaExpr *, 2> Lambdas;
1317 
1318     /// The declaration that provides context for lambda expressions
1319     /// and block literals if the normal declaration context does not
1320     /// suffice, e.g., in a default function argument.
1321     Decl *ManglingContextDecl;
1322 
1323     /// If we are processing a decltype type, a set of call expressions
1324     /// for which we have deferred checking the completeness of the return type.
1325     SmallVector<CallExpr *, 8> DelayedDecltypeCalls;
1326 
1327     /// If we are processing a decltype type, a set of temporary binding
1328     /// expressions for which we have deferred checking the destructor.
1329     SmallVector<CXXBindTemporaryExpr *, 8> DelayedDecltypeBinds;
1330 
1331     llvm::SmallPtrSet<const Expr *, 8> PossibleDerefs;
1332 
1333     /// Expressions appearing as the LHS of a volatile assignment in this
1334     /// context. We produce a warning for these when popping the context if
1335     /// they are not discarded-value expressions nor unevaluated operands.
1336     SmallVector<Expr*, 2> VolatileAssignmentLHSs;
1337 
1338     /// Set of candidates for starting an immediate invocation.
1339     llvm::SmallVector<ImmediateInvocationCandidate, 4> ImmediateInvocationCandidates;
1340 
1341     /// Set of DeclRefExprs referencing a consteval function when used in a
1342     /// context not already known to be immediately invoked.
1343     llvm::SmallPtrSet<DeclRefExpr *, 4> ReferenceToConsteval;
1344 
1345     /// \brief Describes whether we are in an expression constext which we have
1346     /// to handle differently.
1347     enum ExpressionKind {
1348       EK_Decltype, EK_TemplateArgument, EK_Other
1349     } ExprContext;
1350 
1351     // A context can be nested in both a discarded statement context and
1352     // an immediate function context, so they need to be tracked independently.
1353     bool InDiscardedStatement;
1354     bool InImmediateFunctionContext;
1355     bool InImmediateEscalatingFunctionContext;
1356 
1357     bool IsCurrentlyCheckingDefaultArgumentOrInitializer = false;
1358 
1359     // When evaluating immediate functions in the initializer of a default
1360     // argument or default member initializer, this is the declaration whose
1361     // default initializer is being evaluated and the location of the call
1362     // or constructor definition.
1363     struct InitializationContext {
1364       InitializationContext(SourceLocation Loc, ValueDecl *Decl,
1365                             DeclContext *Context)
1366           : Loc(Loc), Decl(Decl), Context(Context) {
1367         assert(Decl && Context && "invalid initialization context");
1368       }
1369 
1370       SourceLocation Loc;
1371       ValueDecl *Decl = nullptr;
1372       DeclContext *Context = nullptr;
1373     };
1374     std::optional<InitializationContext> DelayedDefaultInitializationContext;
1375 
1376     ExpressionEvaluationContextRecord(ExpressionEvaluationContext Context,
1377                                       unsigned NumCleanupObjects,
1378                                       CleanupInfo ParentCleanup,
1379                                       Decl *ManglingContextDecl,
1380                                       ExpressionKind ExprContext)
1381         : Context(Context), ParentCleanup(ParentCleanup),
1382           NumCleanupObjects(NumCleanupObjects), NumTypos(0),
1383           ManglingContextDecl(ManglingContextDecl), ExprContext(ExprContext),
1384           InDiscardedStatement(false), InImmediateFunctionContext(false),
1385           InImmediateEscalatingFunctionContext(false) {}
1386 
1387     bool isUnevaluated() const {
1388       return Context == ExpressionEvaluationContext::Unevaluated ||
1389              Context == ExpressionEvaluationContext::UnevaluatedAbstract ||
1390              Context == ExpressionEvaluationContext::UnevaluatedList;
1391     }
1392 
1393     bool isConstantEvaluated() const {
1394       return Context == ExpressionEvaluationContext::ConstantEvaluated ||
1395              Context == ExpressionEvaluationContext::ImmediateFunctionContext;
1396     }
1397 
1398     bool isImmediateFunctionContext() const {
1399       return Context == ExpressionEvaluationContext::ImmediateFunctionContext ||
1400              (Context == ExpressionEvaluationContext::DiscardedStatement &&
1401               InImmediateFunctionContext) ||
1402              // C++23 [expr.const]p14:
1403              // An expression or conversion is in an immediate function
1404              // context if it is potentially evaluated and either:
1405              //   * its innermost enclosing non-block scope is a function
1406              //     parameter scope of an immediate function, or
1407              //   * its enclosing statement is enclosed by the compound-
1408              //     statement of a consteval if statement.
1409              (Context == ExpressionEvaluationContext::PotentiallyEvaluated &&
1410               InImmediateFunctionContext);
1411     }
1412 
1413     bool isDiscardedStatementContext() const {
1414       return Context == ExpressionEvaluationContext::DiscardedStatement ||
1415              (Context ==
1416                   ExpressionEvaluationContext::ImmediateFunctionContext &&
1417               InDiscardedStatement);
1418     }
1419   };
1420 
1421   /// A stack of expression evaluation contexts.
1422   SmallVector<ExpressionEvaluationContextRecord, 8> ExprEvalContexts;
1423 
1424   // Set of failed immediate invocations to avoid double diagnosing.
1425   llvm::SmallPtrSet<ConstantExpr *, 4> FailedImmediateInvocations;
1426 
1427   /// Emit a warning for all pending noderef expressions that we recorded.
1428   void WarnOnPendingNoDerefs(ExpressionEvaluationContextRecord &Rec);
1429 
1430   /// Compute the mangling number context for a lambda expression or
1431   /// block literal. Also return the extra mangling decl if any.
1432   ///
1433   /// \param DC - The DeclContext containing the lambda expression or
1434   /// block literal.
1435   std::tuple<MangleNumberingContext *, Decl *>
1436   getCurrentMangleNumberContext(const DeclContext *DC);
1437 
1438 
1439   /// SpecialMemberOverloadResult - The overloading result for a special member
1440   /// function.
1441   ///
1442   /// This is basically a wrapper around PointerIntPair. The lowest bits of the
1443   /// integer are used to determine whether overload resolution succeeded.
1444   class SpecialMemberOverloadResult {
1445   public:
1446     enum Kind {
1447       NoMemberOrDeleted,
1448       Ambiguous,
1449       Success
1450     };
1451 
1452   private:
1453     llvm::PointerIntPair<CXXMethodDecl *, 2> Pair;
1454 
1455   public:
1456     SpecialMemberOverloadResult() {}
1457     SpecialMemberOverloadResult(CXXMethodDecl *MD)
1458         : Pair(MD, MD->isDeleted() ? NoMemberOrDeleted : Success) {}
1459 
1460     CXXMethodDecl *getMethod() const { return Pair.getPointer(); }
1461     void setMethod(CXXMethodDecl *MD) { Pair.setPointer(MD); }
1462 
1463     Kind getKind() const { return static_cast<Kind>(Pair.getInt()); }
1464     void setKind(Kind K) { Pair.setInt(K); }
1465   };
1466 
1467   class SpecialMemberOverloadResultEntry
1468       : public llvm::FastFoldingSetNode,
1469         public SpecialMemberOverloadResult {
1470   public:
1471     SpecialMemberOverloadResultEntry(const llvm::FoldingSetNodeID &ID)
1472       : FastFoldingSetNode(ID)
1473     {}
1474   };
1475 
1476   /// A cache of special member function overload resolution results
1477   /// for C++ records.
1478   llvm::FoldingSet<SpecialMemberOverloadResultEntry> SpecialMemberCache;
1479 
1480   /// A cache of the flags available in enumerations with the flag_bits
1481   /// attribute.
1482   mutable llvm::DenseMap<const EnumDecl*, llvm::APInt> FlagBitsCache;
1483 
1484   /// The kind of translation unit we are processing.
1485   ///
1486   /// When we're processing a complete translation unit, Sema will perform
1487   /// end-of-translation-unit semantic tasks (such as creating
1488   /// initializers for tentative definitions in C) once parsing has
1489   /// completed. Modules and precompiled headers perform different kinds of
1490   /// checks.
1491   const TranslationUnitKind TUKind;
1492 
1493   llvm::BumpPtrAllocator BumpAlloc;
1494 
1495   /// The number of SFINAE diagnostics that have been trapped.
1496   unsigned NumSFINAEErrors;
1497 
1498   typedef llvm::DenseMap<ParmVarDecl *, llvm::TinyPtrVector<ParmVarDecl *>>
1499     UnparsedDefaultArgInstantiationsMap;
1500 
1501   /// A mapping from parameters with unparsed default arguments to the
1502   /// set of instantiations of each parameter.
1503   ///
1504   /// This mapping is a temporary data structure used when parsing
1505   /// nested class templates or nested classes of class templates,
1506   /// where we might end up instantiating an inner class before the
1507   /// default arguments of its methods have been parsed.
1508   UnparsedDefaultArgInstantiationsMap UnparsedDefaultArgInstantiations;
1509 
1510   // Contains the locations of the beginning of unparsed default
1511   // argument locations.
1512   llvm::DenseMap<ParmVarDecl *, SourceLocation> UnparsedDefaultArgLocs;
1513 
1514   /// UndefinedInternals - all the used, undefined objects which require a
1515   /// definition in this translation unit.
1516   llvm::MapVector<NamedDecl *, SourceLocation> UndefinedButUsed;
1517 
1518   /// Determine if VD, which must be a variable or function, is an external
1519   /// symbol that nonetheless can't be referenced from outside this translation
1520   /// unit because its type has no linkage and it's not extern "C".
1521   bool isExternalWithNoLinkageType(const ValueDecl *VD) const;
1522 
1523   /// Obtain a sorted list of functions that are undefined but ODR-used.
1524   void getUndefinedButUsed(
1525       SmallVectorImpl<std::pair<NamedDecl *, SourceLocation> > &Undefined);
1526 
1527   /// Retrieves list of suspicious delete-expressions that will be checked at
1528   /// the end of translation unit.
1529   const llvm::MapVector<FieldDecl *, DeleteLocs> &
1530   getMismatchingDeleteExpressions() const;
1531 
1532   class GlobalMethodPool {
1533   public:
1534     using Lists = std::pair<ObjCMethodList, ObjCMethodList>;
1535     using iterator = llvm::DenseMap<Selector, Lists>::iterator;
1536     iterator begin() { return Methods.begin(); }
1537     iterator end() { return Methods.end(); }
1538     iterator find(Selector Sel) { return Methods.find(Sel); }
1539     std::pair<iterator, bool> insert(std::pair<Selector, Lists> &&Val) {
1540       return Methods.insert(Val);
1541     }
1542     int count(Selector Sel) const { return Methods.count(Sel); }
1543     bool empty() const { return Methods.empty(); }
1544 
1545   private:
1546     llvm::DenseMap<Selector, Lists> Methods;
1547   };
1548 
1549   /// Method Pool - allows efficient lookup when typechecking messages to "id".
1550   /// We need to maintain a list, since selectors can have differing signatures
1551   /// across classes. In Cocoa, this happens to be extremely uncommon (only 1%
1552   /// of selectors are "overloaded").
1553   /// At the head of the list it is recorded whether there were 0, 1, or >= 2
1554   /// methods inside categories with a particular selector.
1555   GlobalMethodPool MethodPool;
1556 
1557   /// Method selectors used in a \@selector expression. Used for implementation
1558   /// of -Wselector.
1559   llvm::MapVector<Selector, SourceLocation> ReferencedSelectors;
1560 
1561   /// List of SourceLocations where 'self' is implicitly retained inside a
1562   /// block.
1563   llvm::SmallVector<std::pair<SourceLocation, const BlockDecl *>, 1>
1564       ImplicitlyRetainedSelfLocs;
1565 
1566   /// Kinds of C++ special members.
1567   enum CXXSpecialMember {
1568     CXXDefaultConstructor,
1569     CXXCopyConstructor,
1570     CXXMoveConstructor,
1571     CXXCopyAssignment,
1572     CXXMoveAssignment,
1573     CXXDestructor,
1574     CXXInvalid
1575   };
1576 
1577   typedef llvm::PointerIntPair<CXXRecordDecl *, 3, CXXSpecialMember>
1578       SpecialMemberDecl;
1579 
1580   /// The C++ special members which we are currently in the process of
1581   /// declaring. If this process recursively triggers the declaration of the
1582   /// same special member, we should act as if it is not yet declared.
1583   llvm::SmallPtrSet<SpecialMemberDecl, 4> SpecialMembersBeingDeclared;
1584 
1585   /// Kinds of defaulted comparison operator functions.
1586   enum class DefaultedComparisonKind : unsigned char {
1587     /// This is not a defaultable comparison operator.
1588     None,
1589     /// This is an operator== that should be implemented as a series of
1590     /// subobject comparisons.
1591     Equal,
1592     /// This is an operator<=> that should be implemented as a series of
1593     /// subobject comparisons.
1594     ThreeWay,
1595     /// This is an operator!= that should be implemented as a rewrite in terms
1596     /// of a == comparison.
1597     NotEqual,
1598     /// This is an <, <=, >, or >= that should be implemented as a rewrite in
1599     /// terms of a <=> comparison.
1600     Relational,
1601   };
1602 
1603   /// The function definitions which were renamed as part of typo-correction
1604   /// to match their respective declarations. We want to keep track of them
1605   /// to ensure that we don't emit a "redefinition" error if we encounter a
1606   /// correctly named definition after the renamed definition.
1607   llvm::SmallPtrSet<const NamedDecl *, 4> TypoCorrectedFunctionDefinitions;
1608 
1609   /// Stack of types that correspond to the parameter entities that are
1610   /// currently being copy-initialized. Can be empty.
1611   llvm::SmallVector<QualType, 4> CurrentParameterCopyTypes;
1612 
1613   void ReadMethodPool(Selector Sel);
1614   void updateOutOfDateSelector(Selector Sel);
1615 
1616   /// Private Helper predicate to check for 'self'.
1617   bool isSelfExpr(Expr *RExpr);
1618   bool isSelfExpr(Expr *RExpr, const ObjCMethodDecl *Method);
1619 
1620   /// Cause the active diagnostic on the DiagosticsEngine to be
1621   /// emitted. This is closely coupled to the SemaDiagnosticBuilder class and
1622   /// should not be used elsewhere.
1623   void EmitCurrentDiagnostic(unsigned DiagID);
1624 
1625   /// Records and restores the CurFPFeatures state on entry/exit of compound
1626   /// statements.
1627   class FPFeaturesStateRAII {
1628   public:
1629     FPFeaturesStateRAII(Sema &S);
1630     ~FPFeaturesStateRAII();
1631     FPOptionsOverride getOverrides() { return OldOverrides; }
1632 
1633   private:
1634     Sema& S;
1635     FPOptions OldFPFeaturesState;
1636     FPOptionsOverride OldOverrides;
1637     LangOptions::FPEvalMethodKind OldEvalMethod;
1638     SourceLocation OldFPPragmaLocation;
1639   };
1640 
1641   void addImplicitTypedef(StringRef Name, QualType T);
1642 
1643   bool WarnedStackExhausted = false;
1644 
1645   /// Increment when we find a reference; decrement when we find an ignored
1646   /// assignment.  Ultimately the value is 0 if every reference is an ignored
1647   /// assignment.
1648   llvm::DenseMap<const VarDecl *, int> RefsMinusAssignments;
1649 
1650   /// Indicate RISC-V vector builtin functions enabled or not.
1651   bool DeclareRISCVVBuiltins = false;
1652 
1653   /// Indicate RISC-V SiFive vector builtin functions enabled or not.
1654   bool DeclareRISCVSiFiveVectorBuiltins = false;
1655 
1656 private:
1657   std::unique_ptr<sema::RISCVIntrinsicManager> RVIntrinsicManager;
1658 
1659   std::optional<std::unique_ptr<DarwinSDKInfo>> CachedDarwinSDKInfo;
1660 
1661   bool WarnedDarwinSDKInfoMissing = false;
1662 
1663 public:
1664   Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer,
1665        TranslationUnitKind TUKind = TU_Complete,
1666        CodeCompleteConsumer *CompletionConsumer = nullptr);
1667   ~Sema();
1668 
1669   /// Perform initialization that occurs after the parser has been
1670   /// initialized but before it parses anything.
1671   void Initialize();
1672 
1673   /// This virtual key function only exists to limit the emission of debug info
1674   /// describing the Sema class. GCC and Clang only emit debug info for a class
1675   /// with a vtable when the vtable is emitted. Sema is final and not
1676   /// polymorphic, but the debug info size savings are so significant that it is
1677   /// worth adding a vtable just to take advantage of this optimization.
1678   virtual void anchor();
1679 
1680   const LangOptions &getLangOpts() const { return LangOpts; }
1681   OpenCLOptions &getOpenCLOptions() { return OpenCLFeatures; }
1682   FPOptions     &getCurFPFeatures() { return CurFPFeatures; }
1683 
1684   DiagnosticsEngine &getDiagnostics() const { return Diags; }
1685   SourceManager &getSourceManager() const { return SourceMgr; }
1686   Preprocessor &getPreprocessor() const { return PP; }
1687   ASTContext &getASTContext() const { return Context; }
1688   ASTConsumer &getASTConsumer() const { return Consumer; }
1689   ASTMutationListener *getASTMutationListener() const;
1690   ExternalSemaSource *getExternalSource() const { return ExternalSource.get(); }
1691 
1692   DarwinSDKInfo *getDarwinSDKInfoForAvailabilityChecking(SourceLocation Loc,
1693                                                          StringRef Platform);
1694   DarwinSDKInfo *getDarwinSDKInfoForAvailabilityChecking();
1695 
1696   ///Registers an external source. If an external source already exists,
1697   /// creates a multiplex external source and appends to it.
1698   ///
1699   ///\param[in] E - A non-null external sema source.
1700   ///
1701   void addExternalSource(ExternalSemaSource *E);
1702 
1703   void PrintStats() const;
1704 
1705   /// Warn that the stack is nearly exhausted.
1706   void warnStackExhausted(SourceLocation Loc);
1707 
1708   /// Run some code with "sufficient" stack space. (Currently, at least 256K is
1709   /// guaranteed). Produces a warning if we're low on stack space and allocates
1710   /// more in that case. Use this in code that may recurse deeply (for example,
1711   /// in template instantiation) to avoid stack overflow.
1712   void runWithSufficientStackSpace(SourceLocation Loc,
1713                                    llvm::function_ref<void()> Fn);
1714 
1715   /// Helper class that creates diagnostics with optional
1716   /// template instantiation stacks.
1717   ///
1718   /// This class provides a wrapper around the basic DiagnosticBuilder
1719   /// class that emits diagnostics. ImmediateDiagBuilder is
1720   /// responsible for emitting the diagnostic (as DiagnosticBuilder
1721   /// does) and, if the diagnostic comes from inside a template
1722   /// instantiation, printing the template instantiation stack as
1723   /// well.
1724   class ImmediateDiagBuilder : public DiagnosticBuilder {
1725     Sema &SemaRef;
1726     unsigned DiagID;
1727 
1728   public:
1729     ImmediateDiagBuilder(DiagnosticBuilder &DB, Sema &SemaRef, unsigned DiagID)
1730         : DiagnosticBuilder(DB), SemaRef(SemaRef), DiagID(DiagID) {}
1731     ImmediateDiagBuilder(DiagnosticBuilder &&DB, Sema &SemaRef, unsigned DiagID)
1732         : DiagnosticBuilder(DB), SemaRef(SemaRef), DiagID(DiagID) {}
1733 
1734     // This is a cunning lie. DiagnosticBuilder actually performs move
1735     // construction in its copy constructor (but due to varied uses, it's not
1736     // possible to conveniently express this as actual move construction). So
1737     // the default copy ctor here is fine, because the base class disables the
1738     // source anyway, so the user-defined ~ImmediateDiagBuilder is a safe no-op
1739     // in that case anwyay.
1740     ImmediateDiagBuilder(const ImmediateDiagBuilder &) = default;
1741 
1742     ~ImmediateDiagBuilder() {
1743       // If we aren't active, there is nothing to do.
1744       if (!isActive()) return;
1745 
1746       // Otherwise, we need to emit the diagnostic. First clear the diagnostic
1747       // builder itself so it won't emit the diagnostic in its own destructor.
1748       //
1749       // This seems wasteful, in that as written the DiagnosticBuilder dtor will
1750       // do its own needless checks to see if the diagnostic needs to be
1751       // emitted. However, because we take care to ensure that the builder
1752       // objects never escape, a sufficiently smart compiler will be able to
1753       // eliminate that code.
1754       Clear();
1755 
1756       // Dispatch to Sema to emit the diagnostic.
1757       SemaRef.EmitCurrentDiagnostic(DiagID);
1758     }
1759 
1760     /// Teach operator<< to produce an object of the correct type.
1761     template <typename T>
1762     friend const ImmediateDiagBuilder &
1763     operator<<(const ImmediateDiagBuilder &Diag, const T &Value) {
1764       const DiagnosticBuilder &BaseDiag = Diag;
1765       BaseDiag << Value;
1766       return Diag;
1767     }
1768 
1769     // It is necessary to limit this to rvalue reference to avoid calling this
1770     // function with a bitfield lvalue argument since non-const reference to
1771     // bitfield is not allowed.
1772     template <typename T,
1773               typename = std::enable_if_t<!std::is_lvalue_reference<T>::value>>
1774     const ImmediateDiagBuilder &operator<<(T &&V) const {
1775       const DiagnosticBuilder &BaseDiag = *this;
1776       BaseDiag << std::move(V);
1777       return *this;
1778     }
1779   };
1780 
1781   /// A generic diagnostic builder for errors which may or may not be deferred.
1782   ///
1783   /// In CUDA, there exist constructs (e.g. variable-length arrays, try/catch)
1784   /// which are not allowed to appear inside __device__ functions and are
1785   /// allowed to appear in __host__ __device__ functions only if the host+device
1786   /// function is never codegen'ed.
1787   ///
1788   /// To handle this, we use the notion of "deferred diagnostics", where we
1789   /// attach a diagnostic to a FunctionDecl that's emitted iff it's codegen'ed.
1790   ///
1791   /// This class lets you emit either a regular diagnostic, a deferred
1792   /// diagnostic, or no diagnostic at all, according to an argument you pass to
1793   /// its constructor, thus simplifying the process of creating these "maybe
1794   /// deferred" diagnostics.
1795   class SemaDiagnosticBuilder {
1796   public:
1797     enum Kind {
1798       /// Emit no diagnostics.
1799       K_Nop,
1800       /// Emit the diagnostic immediately (i.e., behave like Sema::Diag()).
1801       K_Immediate,
1802       /// Emit the diagnostic immediately, and, if it's a warning or error, also
1803       /// emit a call stack showing how this function can be reached by an a
1804       /// priori known-emitted function.
1805       K_ImmediateWithCallStack,
1806       /// Create a deferred diagnostic, which is emitted only if the function
1807       /// it's attached to is codegen'ed.  Also emit a call stack as with
1808       /// K_ImmediateWithCallStack.
1809       K_Deferred
1810     };
1811 
1812     SemaDiagnosticBuilder(Kind K, SourceLocation Loc, unsigned DiagID,
1813                           const FunctionDecl *Fn, Sema &S);
1814     SemaDiagnosticBuilder(SemaDiagnosticBuilder &&D);
1815     SemaDiagnosticBuilder(const SemaDiagnosticBuilder &) = default;
1816 
1817     // The copy and move assignment operator is defined as deleted pending
1818     // further motivation.
1819     SemaDiagnosticBuilder &operator=(const SemaDiagnosticBuilder &) = delete;
1820     SemaDiagnosticBuilder &operator=(SemaDiagnosticBuilder &&) = delete;
1821 
1822     ~SemaDiagnosticBuilder();
1823 
1824     bool isImmediate() const { return ImmediateDiag.has_value(); }
1825 
1826     /// Convertible to bool: True if we immediately emitted an error, false if
1827     /// we didn't emit an error or we created a deferred error.
1828     ///
1829     /// Example usage:
1830     ///
1831     ///   if (SemaDiagnosticBuilder(...) << foo << bar)
1832     ///     return ExprError();
1833     ///
1834     /// But see CUDADiagIfDeviceCode() and CUDADiagIfHostCode() -- you probably
1835     /// want to use these instead of creating a SemaDiagnosticBuilder yourself.
1836     operator bool() const { return isImmediate(); }
1837 
1838     template <typename T>
1839     friend const SemaDiagnosticBuilder &
1840     operator<<(const SemaDiagnosticBuilder &Diag, const T &Value) {
1841       if (Diag.ImmediateDiag)
1842         *Diag.ImmediateDiag << Value;
1843       else if (Diag.PartialDiagId)
1844         Diag.S.DeviceDeferredDiags[Diag.Fn][*Diag.PartialDiagId].second
1845             << Value;
1846       return Diag;
1847     }
1848 
1849     // It is necessary to limit this to rvalue reference to avoid calling this
1850     // function with a bitfield lvalue argument since non-const reference to
1851     // bitfield is not allowed.
1852     template <typename T,
1853               typename = std::enable_if_t<!std::is_lvalue_reference<T>::value>>
1854     const SemaDiagnosticBuilder &operator<<(T &&V) const {
1855       if (ImmediateDiag)
1856         *ImmediateDiag << std::move(V);
1857       else if (PartialDiagId)
1858         S.DeviceDeferredDiags[Fn][*PartialDiagId].second << std::move(V);
1859       return *this;
1860     }
1861 
1862     friend const SemaDiagnosticBuilder &
1863     operator<<(const SemaDiagnosticBuilder &Diag, const PartialDiagnostic &PD) {
1864       if (Diag.ImmediateDiag)
1865         PD.Emit(*Diag.ImmediateDiag);
1866       else if (Diag.PartialDiagId)
1867         Diag.S.DeviceDeferredDiags[Diag.Fn][*Diag.PartialDiagId].second = PD;
1868       return Diag;
1869     }
1870 
1871     void AddFixItHint(const FixItHint &Hint) const {
1872       if (ImmediateDiag)
1873         ImmediateDiag->AddFixItHint(Hint);
1874       else if (PartialDiagId)
1875         S.DeviceDeferredDiags[Fn][*PartialDiagId].second.AddFixItHint(Hint);
1876     }
1877 
1878     friend ExprResult ExprError(const SemaDiagnosticBuilder &) {
1879       return ExprError();
1880     }
1881     friend StmtResult StmtError(const SemaDiagnosticBuilder &) {
1882       return StmtError();
1883     }
1884     operator ExprResult() const { return ExprError(); }
1885     operator StmtResult() const { return StmtError(); }
1886     operator TypeResult() const { return TypeError(); }
1887     operator DeclResult() const { return DeclResult(true); }
1888     operator MemInitResult() const { return MemInitResult(true); }
1889 
1890   private:
1891     Sema &S;
1892     SourceLocation Loc;
1893     unsigned DiagID;
1894     const FunctionDecl *Fn;
1895     bool ShowCallStack;
1896 
1897     // Invariant: At most one of these Optionals has a value.
1898     // FIXME: Switch these to a Variant once that exists.
1899     std::optional<ImmediateDiagBuilder> ImmediateDiag;
1900     std::optional<unsigned> PartialDiagId;
1901   };
1902 
1903   /// Is the last error level diagnostic immediate. This is used to determined
1904   /// whether the next info diagnostic should be immediate.
1905   bool IsLastErrorImmediate = true;
1906 
1907   /// Emit a diagnostic.
1908   SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID,
1909                              bool DeferHint = false);
1910 
1911   /// Emit a partial diagnostic.
1912   SemaDiagnosticBuilder Diag(SourceLocation Loc, const PartialDiagnostic &PD,
1913                              bool DeferHint = false);
1914 
1915   /// Build a partial diagnostic.
1916   PartialDiagnostic PDiag(unsigned DiagID = 0); // in SemaInternal.h
1917 
1918   /// Whether deferrable diagnostics should be deferred.
1919   bool DeferDiags = false;
1920 
1921   /// RAII class to control scope of DeferDiags.
1922   class DeferDiagsRAII {
1923     Sema &S;
1924     bool SavedDeferDiags = false;
1925 
1926   public:
1927     DeferDiagsRAII(Sema &S, bool DeferDiags)
1928         : S(S), SavedDeferDiags(S.DeferDiags) {
1929       S.DeferDiags = DeferDiags;
1930     }
1931     ~DeferDiagsRAII() { S.DeferDiags = SavedDeferDiags; }
1932   };
1933 
1934   /// Whether uncompilable error has occurred. This includes error happens
1935   /// in deferred diagnostics.
1936   bool hasUncompilableErrorOccurred() const;
1937 
1938   bool findMacroSpelling(SourceLocation &loc, StringRef name);
1939 
1940   /// Get a string to suggest for zero-initialization of a type.
1941   std::string
1942   getFixItZeroInitializerForType(QualType T, SourceLocation Loc) const;
1943   std::string getFixItZeroLiteralForType(QualType T, SourceLocation Loc) const;
1944 
1945   /// Calls \c Lexer::getLocForEndOfToken()
1946   SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset = 0);
1947 
1948   /// Retrieve the module loader associated with the preprocessor.
1949   ModuleLoader &getModuleLoader() const;
1950 
1951   /// Invent a new identifier for parameters of abbreviated templates.
1952   IdentifierInfo *
1953   InventAbbreviatedTemplateParameterTypeName(IdentifierInfo *ParamName,
1954                                              unsigned Index);
1955 
1956   void emitAndClearUnusedLocalTypedefWarnings();
1957 
1958   private:
1959     /// Function or variable declarations to be checked for whether the deferred
1960     /// diagnostics should be emitted.
1961     llvm::SmallSetVector<Decl *, 4> DeclsToCheckForDeferredDiags;
1962 
1963   public:
1964   // Emit all deferred diagnostics.
1965   void emitDeferredDiags();
1966 
1967   enum TUFragmentKind {
1968     /// The global module fragment, between 'module;' and a module-declaration.
1969     Global,
1970     /// A normal translation unit fragment. For a non-module unit, this is the
1971     /// entire translation unit. Otherwise, it runs from the module-declaration
1972     /// to the private-module-fragment (if any) or the end of the TU (if not).
1973     Normal,
1974     /// The private module fragment, between 'module :private;' and the end of
1975     /// the translation unit.
1976     Private
1977   };
1978 
1979   void ActOnStartOfTranslationUnit();
1980   void ActOnEndOfTranslationUnit();
1981   void ActOnEndOfTranslationUnitFragment(TUFragmentKind Kind);
1982 
1983   void CheckDelegatingCtorCycles();
1984 
1985   Scope *getScopeForContext(DeclContext *Ctx);
1986 
1987   void PushFunctionScope();
1988   void PushBlockScope(Scope *BlockScope, BlockDecl *Block);
1989   sema::LambdaScopeInfo *PushLambdaScope();
1990 
1991   /// This is used to inform Sema what the current TemplateParameterDepth
1992   /// is during Parsing.  Currently it is used to pass on the depth
1993   /// when parsing generic lambda 'auto' parameters.
1994   void RecordParsingTemplateParameterDepth(unsigned Depth);
1995 
1996   void PushCapturedRegionScope(Scope *RegionScope, CapturedDecl *CD,
1997                                RecordDecl *RD, CapturedRegionKind K,
1998                                unsigned OpenMPCaptureLevel = 0);
1999 
2000   /// Custom deleter to allow FunctionScopeInfos to be kept alive for a short
2001   /// time after they've been popped.
2002   class PoppedFunctionScopeDeleter {
2003     Sema *Self;
2004 
2005   public:
2006     explicit PoppedFunctionScopeDeleter(Sema *Self) : Self(Self) {}
2007     void operator()(sema::FunctionScopeInfo *Scope) const;
2008   };
2009 
2010   using PoppedFunctionScopePtr =
2011       std::unique_ptr<sema::FunctionScopeInfo, PoppedFunctionScopeDeleter>;
2012 
2013   PoppedFunctionScopePtr
2014   PopFunctionScopeInfo(const sema::AnalysisBasedWarnings::Policy *WP = nullptr,
2015                        const Decl *D = nullptr,
2016                        QualType BlockType = QualType());
2017 
2018   sema::FunctionScopeInfo *getCurFunction() const {
2019     return FunctionScopes.empty() ? nullptr : FunctionScopes.back();
2020   }
2021 
2022   sema::FunctionScopeInfo *getEnclosingFunction() const;
2023 
2024   void setFunctionHasBranchIntoScope();
2025   void setFunctionHasBranchProtectedScope();
2026   void setFunctionHasIndirectGoto();
2027   void setFunctionHasMustTail();
2028 
2029   void PushCompoundScope(bool IsStmtExpr);
2030   void PopCompoundScope();
2031 
2032   sema::CompoundScopeInfo &getCurCompoundScope() const;
2033 
2034   bool hasAnyUnrecoverableErrorsInThisFunction() const;
2035 
2036   /// Retrieve the current block, if any.
2037   sema::BlockScopeInfo *getCurBlock();
2038 
2039   /// Get the innermost lambda enclosing the current location, if any. This
2040   /// looks through intervening non-lambda scopes such as local functions and
2041   /// blocks.
2042   sema::LambdaScopeInfo *getEnclosingLambda() const;
2043 
2044   /// Retrieve the current lambda scope info, if any.
2045   /// \param IgnoreNonLambdaCapturingScope true if should find the top-most
2046   /// lambda scope info ignoring all inner capturing scopes that are not
2047   /// lambda scopes.
2048   sema::LambdaScopeInfo *
2049   getCurLambda(bool IgnoreNonLambdaCapturingScope = false);
2050 
2051   /// Retrieve the current generic lambda info, if any.
2052   sema::LambdaScopeInfo *getCurGenericLambda();
2053 
2054   /// Retrieve the current captured region, if any.
2055   sema::CapturedRegionScopeInfo *getCurCapturedRegion();
2056 
2057   /// Retrieve the current function, if any, that should be analyzed for
2058   /// potential availability violations.
2059   sema::FunctionScopeInfo *getCurFunctionAvailabilityContext();
2060 
2061   /// WeakTopLevelDeclDecls - access to \#pragma weak-generated Decls
2062   SmallVectorImpl<Decl *> &WeakTopLevelDecls() { return WeakTopLevelDecl; }
2063 
2064   /// Called before parsing a function declarator belonging to a function
2065   /// declaration.
2066   void ActOnStartFunctionDeclarationDeclarator(Declarator &D,
2067                                                unsigned TemplateParameterDepth);
2068 
2069   /// Called after parsing a function declarator belonging to a function
2070   /// declaration.
2071   void ActOnFinishFunctionDeclarationDeclarator(Declarator &D);
2072 
2073   void ActOnComment(SourceRange Comment);
2074 
2075   //===--------------------------------------------------------------------===//
2076   // Type Analysis / Processing: SemaType.cpp.
2077   //
2078 
2079   QualType BuildQualifiedType(QualType T, SourceLocation Loc, Qualifiers Qs,
2080                               const DeclSpec *DS = nullptr);
2081   QualType BuildQualifiedType(QualType T, SourceLocation Loc, unsigned CVRA,
2082                               const DeclSpec *DS = nullptr);
2083   QualType BuildPointerType(QualType T,
2084                             SourceLocation Loc, DeclarationName Entity);
2085   QualType BuildReferenceType(QualType T, bool LValueRef,
2086                               SourceLocation Loc, DeclarationName Entity);
2087   QualType BuildArrayType(QualType T, ArrayType::ArraySizeModifier ASM,
2088                           Expr *ArraySize, unsigned Quals,
2089                           SourceRange Brackets, DeclarationName Entity);
2090   QualType BuildVectorType(QualType T, Expr *VecSize, SourceLocation AttrLoc);
2091   QualType BuildExtVectorType(QualType T, Expr *ArraySize,
2092                               SourceLocation AttrLoc);
2093   QualType BuildMatrixType(QualType T, Expr *NumRows, Expr *NumColumns,
2094                            SourceLocation AttrLoc);
2095 
2096   QualType BuildAddressSpaceAttr(QualType &T, LangAS ASIdx, Expr *AddrSpace,
2097                                  SourceLocation AttrLoc);
2098 
2099   /// Same as above, but constructs the AddressSpace index if not provided.
2100   QualType BuildAddressSpaceAttr(QualType &T, Expr *AddrSpace,
2101                                  SourceLocation AttrLoc);
2102 
2103   bool CheckQualifiedFunctionForTypeId(QualType T, SourceLocation Loc);
2104 
2105   bool CheckFunctionReturnType(QualType T, SourceLocation Loc);
2106 
2107   /// Build a function type.
2108   ///
2109   /// This routine checks the function type according to C++ rules and
2110   /// under the assumption that the result type and parameter types have
2111   /// just been instantiated from a template. It therefore duplicates
2112   /// some of the behavior of GetTypeForDeclarator, but in a much
2113   /// simpler form that is only suitable for this narrow use case.
2114   ///
2115   /// \param T The return type of the function.
2116   ///
2117   /// \param ParamTypes The parameter types of the function. This array
2118   /// will be modified to account for adjustments to the types of the
2119   /// function parameters.
2120   ///
2121   /// \param Loc The location of the entity whose type involves this
2122   /// function type or, if there is no such entity, the location of the
2123   /// type that will have function type.
2124   ///
2125   /// \param Entity The name of the entity that involves the function
2126   /// type, if known.
2127   ///
2128   /// \param EPI Extra information about the function type. Usually this will
2129   /// be taken from an existing function with the same prototype.
2130   ///
2131   /// \returns A suitable function type, if there are no errors. The
2132   /// unqualified type will always be a FunctionProtoType.
2133   /// Otherwise, returns a NULL type.
2134   QualType BuildFunctionType(QualType T,
2135                              MutableArrayRef<QualType> ParamTypes,
2136                              SourceLocation Loc, DeclarationName Entity,
2137                              const FunctionProtoType::ExtProtoInfo &EPI);
2138 
2139   QualType BuildMemberPointerType(QualType T, QualType Class,
2140                                   SourceLocation Loc,
2141                                   DeclarationName Entity);
2142   QualType BuildBlockPointerType(QualType T,
2143                                  SourceLocation Loc, DeclarationName Entity);
2144   QualType BuildParenType(QualType T);
2145   QualType BuildAtomicType(QualType T, SourceLocation Loc);
2146   QualType BuildReadPipeType(QualType T,
2147                          SourceLocation Loc);
2148   QualType BuildWritePipeType(QualType T,
2149                          SourceLocation Loc);
2150   QualType BuildBitIntType(bool IsUnsigned, Expr *BitWidth, SourceLocation Loc);
2151 
2152   TypeSourceInfo *GetTypeForDeclarator(Declarator &D, Scope *S);
2153   TypeSourceInfo *GetTypeForDeclaratorCast(Declarator &D, QualType FromTy);
2154 
2155   /// Package the given type and TSI into a ParsedType.
2156   ParsedType CreateParsedType(QualType T, TypeSourceInfo *TInfo);
2157   DeclarationNameInfo GetNameForDeclarator(Declarator &D);
2158   DeclarationNameInfo GetNameFromUnqualifiedId(const UnqualifiedId &Name);
2159   static QualType GetTypeFromParser(ParsedType Ty,
2160                                     TypeSourceInfo **TInfo = nullptr);
2161   CanThrowResult canThrow(const Stmt *E);
2162   /// Determine whether the callee of a particular function call can throw.
2163   /// E, D and Loc are all optional.
2164   static CanThrowResult canCalleeThrow(Sema &S, const Expr *E, const Decl *D,
2165                                        SourceLocation Loc = SourceLocation());
2166   const FunctionProtoType *ResolveExceptionSpec(SourceLocation Loc,
2167                                                 const FunctionProtoType *FPT);
2168   void UpdateExceptionSpec(FunctionDecl *FD,
2169                            const FunctionProtoType::ExceptionSpecInfo &ESI);
2170   bool CheckSpecifiedExceptionType(QualType &T, SourceRange Range);
2171   bool CheckDistantExceptionSpec(QualType T);
2172   bool CheckEquivalentExceptionSpec(FunctionDecl *Old, FunctionDecl *New);
2173   bool CheckEquivalentExceptionSpec(
2174       const FunctionProtoType *Old, SourceLocation OldLoc,
2175       const FunctionProtoType *New, SourceLocation NewLoc);
2176   bool CheckEquivalentExceptionSpec(
2177       const PartialDiagnostic &DiagID, const PartialDiagnostic & NoteID,
2178       const FunctionProtoType *Old, SourceLocation OldLoc,
2179       const FunctionProtoType *New, SourceLocation NewLoc);
2180   bool handlerCanCatch(QualType HandlerType, QualType ExceptionType);
2181   bool CheckExceptionSpecSubset(const PartialDiagnostic &DiagID,
2182                                 const PartialDiagnostic &NestedDiagID,
2183                                 const PartialDiagnostic &NoteID,
2184                                 const PartialDiagnostic &NoThrowDiagID,
2185                                 const FunctionProtoType *Superset,
2186                                 SourceLocation SuperLoc,
2187                                 const FunctionProtoType *Subset,
2188                                 SourceLocation SubLoc);
2189   bool CheckParamExceptionSpec(const PartialDiagnostic &NestedDiagID,
2190                                const PartialDiagnostic &NoteID,
2191                                const FunctionProtoType *Target,
2192                                SourceLocation TargetLoc,
2193                                const FunctionProtoType *Source,
2194                                SourceLocation SourceLoc);
2195 
2196   TypeResult ActOnTypeName(Scope *S, Declarator &D);
2197 
2198   /// The parser has parsed the context-sensitive type 'instancetype'
2199   /// in an Objective-C message declaration. Return the appropriate type.
2200   ParsedType ActOnObjCInstanceType(SourceLocation Loc);
2201 
2202   /// Abstract class used to diagnose incomplete types.
2203   struct TypeDiagnoser {
2204     TypeDiagnoser() {}
2205 
2206     virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) = 0;
2207     virtual ~TypeDiagnoser() {}
2208   };
2209 
2210   static int getPrintable(int I) { return I; }
2211   static unsigned getPrintable(unsigned I) { return I; }
2212   static bool getPrintable(bool B) { return B; }
2213   static const char * getPrintable(const char *S) { return S; }
2214   static StringRef getPrintable(StringRef S) { return S; }
2215   static const std::string &getPrintable(const std::string &S) { return S; }
2216   static const IdentifierInfo *getPrintable(const IdentifierInfo *II) {
2217     return II;
2218   }
2219   static DeclarationName getPrintable(DeclarationName N) { return N; }
2220   static QualType getPrintable(QualType T) { return T; }
2221   static SourceRange getPrintable(SourceRange R) { return R; }
2222   static SourceRange getPrintable(SourceLocation L) { return L; }
2223   static SourceRange getPrintable(const Expr *E) { return E->getSourceRange(); }
2224   static SourceRange getPrintable(TypeLoc TL) { return TL.getSourceRange();}
2225 
2226   template <typename... Ts> class BoundTypeDiagnoser : public TypeDiagnoser {
2227   protected:
2228     unsigned DiagID;
2229     std::tuple<const Ts &...> Args;
2230 
2231     template <std::size_t... Is>
2232     void emit(const SemaDiagnosticBuilder &DB,
2233               std::index_sequence<Is...>) const {
2234       // Apply all tuple elements to the builder in order.
2235       bool Dummy[] = {false, (DB << getPrintable(std::get<Is>(Args)))...};
2236       (void)Dummy;
2237     }
2238 
2239   public:
2240     BoundTypeDiagnoser(unsigned DiagID, const Ts &...Args)
2241         : TypeDiagnoser(), DiagID(DiagID), Args(Args...) {
2242       assert(DiagID != 0 && "no diagnostic for type diagnoser");
2243     }
2244 
2245     void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
2246       const SemaDiagnosticBuilder &DB = S.Diag(Loc, DiagID);
2247       emit(DB, std::index_sequence_for<Ts...>());
2248       DB << T;
2249     }
2250   };
2251 
2252   /// Do a check to make sure \p Name looks like a legal argument for the
2253   /// swift_name attribute applied to decl \p D.  Raise a diagnostic if the name
2254   /// is invalid for the given declaration.
2255   ///
2256   /// \p AL is used to provide caret diagnostics in case of a malformed name.
2257   ///
2258   /// \returns true if the name is a valid swift name for \p D, false otherwise.
2259   bool DiagnoseSwiftName(Decl *D, StringRef Name, SourceLocation Loc,
2260                          const ParsedAttr &AL, bool IsAsync);
2261 
2262   /// A derivative of BoundTypeDiagnoser for which the diagnostic's type
2263   /// parameter is preceded by a 0/1 enum that is 1 if the type is sizeless.
2264   /// For example, a diagnostic with no other parameters would generally have
2265   /// the form "...%select{incomplete|sizeless}0 type %1...".
2266   template <typename... Ts>
2267   class SizelessTypeDiagnoser : public BoundTypeDiagnoser<Ts...> {
2268   public:
2269     SizelessTypeDiagnoser(unsigned DiagID, const Ts &... Args)
2270         : BoundTypeDiagnoser<Ts...>(DiagID, Args...) {}
2271 
2272     void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
2273       const SemaDiagnosticBuilder &DB = S.Diag(Loc, this->DiagID);
2274       this->emit(DB, std::index_sequence_for<Ts...>());
2275       DB << T->isSizelessType() << T;
2276     }
2277   };
2278 
2279   enum class CompleteTypeKind {
2280     /// Apply the normal rules for complete types.  In particular,
2281     /// treat all sizeless types as incomplete.
2282     Normal,
2283 
2284     /// Relax the normal rules for complete types so that they include
2285     /// sizeless built-in types.
2286     AcceptSizeless,
2287 
2288     // FIXME: Eventually we should flip the default to Normal and opt in
2289     // to AcceptSizeless rather than opt out of it.
2290     Default = AcceptSizeless
2291   };
2292 
2293   enum class AcceptableKind { Visible, Reachable };
2294 
2295 private:
2296   /// Methods for marking which expressions involve dereferencing a pointer
2297   /// marked with the 'noderef' attribute. Expressions are checked bottom up as
2298   /// they are parsed, meaning that a noderef pointer may not be accessed. For
2299   /// example, in `&*p` where `p` is a noderef pointer, we will first parse the
2300   /// `*p`, but need to check that `address of` is called on it. This requires
2301   /// keeping a container of all pending expressions and checking if the address
2302   /// of them are eventually taken.
2303   void CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E);
2304   void CheckAddressOfNoDeref(const Expr *E);
2305   void CheckMemberAccessOfNoDeref(const MemberExpr *E);
2306 
2307   bool RequireCompleteTypeImpl(SourceLocation Loc, QualType T,
2308                                CompleteTypeKind Kind, TypeDiagnoser *Diagnoser);
2309 
2310   struct ModuleScope {
2311     SourceLocation BeginLoc;
2312     clang::Module *Module = nullptr;
2313     bool ModuleInterface = false;
2314     VisibleModuleSet OuterVisibleModules;
2315   };
2316   /// The modules we're currently parsing.
2317   llvm::SmallVector<ModuleScope, 16> ModuleScopes;
2318 
2319   /// For an interface unit, this is the implicitly imported interface unit.
2320   clang::Module *ThePrimaryInterface = nullptr;
2321 
2322   /// The explicit global module fragment of the current translation unit.
2323   /// The explicit Global Module Fragment, as specified in C++
2324   /// [module.global.frag].
2325   clang::Module *TheGlobalModuleFragment = nullptr;
2326 
2327   /// The implicit global module fragments of the current translation unit.
2328   /// We would only create at most two implicit global module fragments to
2329   /// avoid performance penalties when there are many language linkage
2330   /// exports.
2331   ///
2332   /// The contents in the implicit global module fragment can't be discarded
2333   /// no matter if it is exported or not.
2334   clang::Module *TheImplicitGlobalModuleFragment = nullptr;
2335   clang::Module *TheExportedImplicitGlobalModuleFragment = nullptr;
2336 
2337   /// Namespace definitions that we will export when they finish.
2338   llvm::SmallPtrSet<const NamespaceDecl*, 8> DeferredExportedNamespaces;
2339 
2340   /// In a C++ standard module, inline declarations require a definition to be
2341   /// present at the end of a definition domain.  This set holds the decls to
2342   /// be checked at the end of the TU.
2343   llvm::SmallPtrSet<const FunctionDecl *, 8> PendingInlineFuncDecls;
2344 
2345   /// Helper function to judge if we are in module purview.
2346   /// Return false if we are not in a module.
2347   bool isCurrentModulePurview() const {
2348     return getCurrentModule() ? getCurrentModule()->isModulePurview() : false;
2349   }
2350 
2351   /// Enter the scope of the explicit global module fragment.
2352   Module *PushGlobalModuleFragment(SourceLocation BeginLoc);
2353   /// Leave the scope of the explicit global module fragment.
2354   void PopGlobalModuleFragment();
2355 
2356   /// Enter the scope of an implicit global module fragment.
2357   Module *PushImplicitGlobalModuleFragment(SourceLocation BeginLoc,
2358                                            bool IsExported);
2359   /// Leave the scope of an implicit global module fragment.
2360   void PopImplicitGlobalModuleFragment();
2361 
2362   VisibleModuleSet VisibleModules;
2363 
2364   /// Cache for module units which is usable for current module.
2365   llvm::DenseSet<const Module *> UsableModuleUnitsCache;
2366 
2367   bool isUsableModule(const Module *M);
2368 
2369   bool isAcceptableSlow(const NamedDecl *D, AcceptableKind Kind);
2370 
2371 public:
2372   /// Get the module unit whose scope we are currently within.
2373   Module *getCurrentModule() const {
2374     return ModuleScopes.empty() ? nullptr : ModuleScopes.back().Module;
2375   }
2376 
2377   /// Is the module scope we are an interface?
2378   bool currentModuleIsInterface() const {
2379     return ModuleScopes.empty() ? false : ModuleScopes.back().ModuleInterface;
2380   }
2381 
2382   /// Is the module scope we are in a C++ Header Unit?
2383   bool currentModuleIsHeaderUnit() const {
2384     return ModuleScopes.empty() ? false
2385                                 : ModuleScopes.back().Module->isHeaderUnit();
2386   }
2387 
2388   /// Get the module owning an entity.
2389   Module *getOwningModule(const Decl *Entity) {
2390     return Entity->getOwningModule();
2391   }
2392 
2393   /// Make a merged definition of an existing hidden definition \p ND
2394   /// visible at the specified location.
2395   void makeMergedDefinitionVisible(NamedDecl *ND);
2396 
2397   bool isModuleVisible(const Module *M, bool ModulePrivate = false);
2398 
2399   // When loading a non-modular PCH files, this is used to restore module
2400   // visibility.
2401   void makeModuleVisible(Module *Mod, SourceLocation ImportLoc) {
2402     VisibleModules.setVisible(Mod, ImportLoc);
2403   }
2404 
2405   /// Determine whether a declaration is visible to name lookup.
2406   bool isVisible(const NamedDecl *D) {
2407     return D->isUnconditionallyVisible() ||
2408            isAcceptableSlow(D, AcceptableKind::Visible);
2409   }
2410 
2411   /// Determine whether a declaration is reachable.
2412   bool isReachable(const NamedDecl *D) {
2413     // All visible declarations are reachable.
2414     return D->isUnconditionallyVisible() ||
2415            isAcceptableSlow(D, AcceptableKind::Reachable);
2416   }
2417 
2418   /// Determine whether a declaration is acceptable (visible/reachable).
2419   bool isAcceptable(const NamedDecl *D, AcceptableKind Kind) {
2420     return Kind == AcceptableKind::Visible ? isVisible(D) : isReachable(D);
2421   }
2422 
2423   /// Determine whether any declaration of an entity is visible.
2424   bool
2425   hasVisibleDeclaration(const NamedDecl *D,
2426                         llvm::SmallVectorImpl<Module *> *Modules = nullptr) {
2427     return isVisible(D) || hasVisibleDeclarationSlow(D, Modules);
2428   }
2429 
2430   bool hasVisibleDeclarationSlow(const NamedDecl *D,
2431                                  llvm::SmallVectorImpl<Module *> *Modules);
2432   /// Determine whether any declaration of an entity is reachable.
2433   bool
2434   hasReachableDeclaration(const NamedDecl *D,
2435                           llvm::SmallVectorImpl<Module *> *Modules = nullptr) {
2436     return isReachable(D) || hasReachableDeclarationSlow(D, Modules);
2437   }
2438   bool hasReachableDeclarationSlow(
2439       const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr);
2440 
2441   bool hasVisibleMergedDefinition(const NamedDecl *Def);
2442   bool hasMergedDefinitionInCurrentModule(const NamedDecl *Def);
2443 
2444   /// Determine if \p D and \p Suggested have a structurally compatible
2445   /// layout as described in C11 6.2.7/1.
2446   bool hasStructuralCompatLayout(Decl *D, Decl *Suggested);
2447 
2448   /// Determine if \p D has a visible definition. If not, suggest a declaration
2449   /// that should be made visible to expose the definition.
2450   bool hasVisibleDefinition(NamedDecl *D, NamedDecl **Suggested,
2451                             bool OnlyNeedComplete = false);
2452   bool hasVisibleDefinition(const NamedDecl *D) {
2453     NamedDecl *Hidden;
2454     return hasVisibleDefinition(const_cast<NamedDecl*>(D), &Hidden);
2455   }
2456 
2457   /// Determine if \p D has a reachable definition. If not, suggest a
2458   /// declaration that should be made reachable to expose the definition.
2459   bool hasReachableDefinition(NamedDecl *D, NamedDecl **Suggested,
2460                               bool OnlyNeedComplete = false);
2461   bool hasReachableDefinition(NamedDecl *D) {
2462     NamedDecl *Hidden;
2463     return hasReachableDefinition(D, &Hidden);
2464   }
2465 
2466   bool hasAcceptableDefinition(NamedDecl *D, NamedDecl **Suggested,
2467                                AcceptableKind Kind,
2468                                bool OnlyNeedComplete = false);
2469   bool hasAcceptableDefinition(NamedDecl *D, AcceptableKind Kind) {
2470     NamedDecl *Hidden;
2471     return hasAcceptableDefinition(D, &Hidden, Kind);
2472   }
2473 
2474   /// Determine if the template parameter \p D has a visible default argument.
2475   bool
2476   hasVisibleDefaultArgument(const NamedDecl *D,
2477                             llvm::SmallVectorImpl<Module *> *Modules = nullptr);
2478   /// Determine if the template parameter \p D has a reachable default argument.
2479   bool hasReachableDefaultArgument(
2480       const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr);
2481   /// Determine if the template parameter \p D has a reachable default argument.
2482   bool hasAcceptableDefaultArgument(const NamedDecl *D,
2483                                     llvm::SmallVectorImpl<Module *> *Modules,
2484                                     Sema::AcceptableKind Kind);
2485 
2486   /// Determine if there is a visible declaration of \p D that is an explicit
2487   /// specialization declaration for a specialization of a template. (For a
2488   /// member specialization, use hasVisibleMemberSpecialization.)
2489   bool hasVisibleExplicitSpecialization(
2490       const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr);
2491   /// Determine if there is a reachable declaration of \p D that is an explicit
2492   /// specialization declaration for a specialization of a template. (For a
2493   /// member specialization, use hasReachableMemberSpecialization.)
2494   bool hasReachableExplicitSpecialization(
2495       const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr);
2496 
2497   /// Determine if there is a visible declaration of \p D that is a member
2498   /// specialization declaration (as opposed to an instantiated declaration).
2499   bool hasVisibleMemberSpecialization(
2500       const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr);
2501   /// Determine if there is a reachable declaration of \p D that is a member
2502   /// specialization declaration (as opposed to an instantiated declaration).
2503   bool hasReachableMemberSpecialization(
2504       const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr);
2505 
2506   /// Determine if \p A and \p B are equivalent internal linkage declarations
2507   /// from different modules, and thus an ambiguity error can be downgraded to
2508   /// an extension warning.
2509   bool isEquivalentInternalLinkageDeclaration(const NamedDecl *A,
2510                                               const NamedDecl *B);
2511   void diagnoseEquivalentInternalLinkageDeclarations(
2512       SourceLocation Loc, const NamedDecl *D,
2513       ArrayRef<const NamedDecl *> Equiv);
2514 
2515   bool isUsualDeallocationFunction(const CXXMethodDecl *FD);
2516 
2517   // Check whether the size of array element of type \p EltTy is a multiple of
2518   // its alignment and return false if it isn't.
2519   bool checkArrayElementAlignment(QualType EltTy, SourceLocation Loc);
2520 
2521   bool isCompleteType(SourceLocation Loc, QualType T,
2522                       CompleteTypeKind Kind = CompleteTypeKind::Default) {
2523     return !RequireCompleteTypeImpl(Loc, T, Kind, nullptr);
2524   }
2525   bool RequireCompleteType(SourceLocation Loc, QualType T,
2526                            CompleteTypeKind Kind, TypeDiagnoser &Diagnoser);
2527   bool RequireCompleteType(SourceLocation Loc, QualType T,
2528                            CompleteTypeKind Kind, unsigned DiagID);
2529 
2530   bool RequireCompleteType(SourceLocation Loc, QualType T,
2531                            TypeDiagnoser &Diagnoser) {
2532     return RequireCompleteType(Loc, T, CompleteTypeKind::Default, Diagnoser);
2533   }
2534   bool RequireCompleteType(SourceLocation Loc, QualType T, unsigned DiagID) {
2535     return RequireCompleteType(Loc, T, CompleteTypeKind::Default, DiagID);
2536   }
2537 
2538   template <typename... Ts>
2539   bool RequireCompleteType(SourceLocation Loc, QualType T, unsigned DiagID,
2540                            const Ts &...Args) {
2541     BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
2542     return RequireCompleteType(Loc, T, Diagnoser);
2543   }
2544 
2545   template <typename... Ts>
2546   bool RequireCompleteSizedType(SourceLocation Loc, QualType T, unsigned DiagID,
2547                                 const Ts &... Args) {
2548     SizelessTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
2549     return RequireCompleteType(Loc, T, CompleteTypeKind::Normal, Diagnoser);
2550   }
2551 
2552   /// Get the type of expression E, triggering instantiation to complete the
2553   /// type if necessary -- that is, if the expression refers to a templated
2554   /// static data member of incomplete array type.
2555   ///
2556   /// May still return an incomplete type if instantiation was not possible or
2557   /// if the type is incomplete for a different reason. Use
2558   /// RequireCompleteExprType instead if a diagnostic is expected for an
2559   /// incomplete expression type.
2560   QualType getCompletedType(Expr *E);
2561 
2562   void completeExprArrayBound(Expr *E);
2563   bool RequireCompleteExprType(Expr *E, CompleteTypeKind Kind,
2564                                TypeDiagnoser &Diagnoser);
2565   bool RequireCompleteExprType(Expr *E, unsigned DiagID);
2566 
2567   template <typename... Ts>
2568   bool RequireCompleteExprType(Expr *E, unsigned DiagID, const Ts &...Args) {
2569     BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
2570     return RequireCompleteExprType(E, CompleteTypeKind::Default, Diagnoser);
2571   }
2572 
2573   template <typename... Ts>
2574   bool RequireCompleteSizedExprType(Expr *E, unsigned DiagID,
2575                                     const Ts &... Args) {
2576     SizelessTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
2577     return RequireCompleteExprType(E, CompleteTypeKind::Normal, Diagnoser);
2578   }
2579 
2580   bool RequireLiteralType(SourceLocation Loc, QualType T,
2581                           TypeDiagnoser &Diagnoser);
2582   bool RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID);
2583 
2584   template <typename... Ts>
2585   bool RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID,
2586                           const Ts &...Args) {
2587     BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
2588     return RequireLiteralType(Loc, T, Diagnoser);
2589   }
2590 
2591   QualType getElaboratedType(ElaboratedTypeKeyword Keyword,
2592                              const CXXScopeSpec &SS, QualType T,
2593                              TagDecl *OwnedTagDecl = nullptr);
2594 
2595   // Returns the underlying type of a decltype with the given expression.
2596   QualType getDecltypeForExpr(Expr *E);
2597 
2598   QualType BuildTypeofExprType(Expr *E, TypeOfKind Kind);
2599   /// If AsUnevaluated is false, E is treated as though it were an evaluated
2600   /// context, such as when building a type for decltype(auto).
2601   QualType BuildDecltypeType(Expr *E, bool AsUnevaluated = true);
2602 
2603   using UTTKind = UnaryTransformType::UTTKind;
2604   QualType BuildUnaryTransformType(QualType BaseType, UTTKind UKind,
2605                                    SourceLocation Loc);
2606   QualType BuiltinEnumUnderlyingType(QualType BaseType, SourceLocation Loc);
2607   QualType BuiltinAddPointer(QualType BaseType, SourceLocation Loc);
2608   QualType BuiltinRemovePointer(QualType BaseType, SourceLocation Loc);
2609   QualType BuiltinDecay(QualType BaseType, SourceLocation Loc);
2610   QualType BuiltinAddReference(QualType BaseType, UTTKind UKind,
2611                                SourceLocation Loc);
2612   QualType BuiltinRemoveExtent(QualType BaseType, UTTKind UKind,
2613                                SourceLocation Loc);
2614   QualType BuiltinRemoveReference(QualType BaseType, UTTKind UKind,
2615                                   SourceLocation Loc);
2616   QualType BuiltinChangeCVRQualifiers(QualType BaseType, UTTKind UKind,
2617                                       SourceLocation Loc);
2618   QualType BuiltinChangeSignedness(QualType BaseType, UTTKind UKind,
2619                                    SourceLocation Loc);
2620 
2621   //===--------------------------------------------------------------------===//
2622   // Symbol table / Decl tracking callbacks: SemaDecl.cpp.
2623   //
2624 
2625   struct SkipBodyInfo {
2626     SkipBodyInfo() = default;
2627     bool ShouldSkip = false;
2628     bool CheckSameAsPrevious = false;
2629     NamedDecl *Previous = nullptr;
2630     NamedDecl *New = nullptr;
2631   };
2632 
2633   DeclGroupPtrTy ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType = nullptr);
2634 
2635   void DiagnoseUseOfUnimplementedSelectors();
2636 
2637   bool isSimpleTypeSpecifier(tok::TokenKind Kind) const;
2638 
2639   ParsedType getTypeName(const IdentifierInfo &II, SourceLocation NameLoc,
2640                          Scope *S, CXXScopeSpec *SS = nullptr,
2641                          bool isClassName = false, bool HasTrailingDot = false,
2642                          ParsedType ObjectType = nullptr,
2643                          bool IsCtorOrDtorName = false,
2644                          bool WantNontrivialTypeSourceInfo = false,
2645                          bool IsClassTemplateDeductionContext = true,
2646                          ImplicitTypenameContext AllowImplicitTypename =
2647                              ImplicitTypenameContext::No,
2648                          IdentifierInfo **CorrectedII = nullptr);
2649   TypeSpecifierType isTagName(IdentifierInfo &II, Scope *S);
2650   bool isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S);
2651   void DiagnoseUnknownTypeName(IdentifierInfo *&II,
2652                                SourceLocation IILoc,
2653                                Scope *S,
2654                                CXXScopeSpec *SS,
2655                                ParsedType &SuggestedType,
2656                                bool IsTemplateName = false);
2657 
2658   /// Attempt to behave like MSVC in situations where lookup of an unqualified
2659   /// type name has failed in a dependent context. In these situations, we
2660   /// automatically form a DependentTypeName that will retry lookup in a related
2661   /// scope during instantiation.
2662   ParsedType ActOnMSVCUnknownTypeName(const IdentifierInfo &II,
2663                                       SourceLocation NameLoc,
2664                                       bool IsTemplateTypeArg);
2665 
2666   /// Describes the result of the name lookup and resolution performed
2667   /// by \c ClassifyName().
2668   enum NameClassificationKind {
2669     /// This name is not a type or template in this context, but might be
2670     /// something else.
2671     NC_Unknown,
2672     /// Classification failed; an error has been produced.
2673     NC_Error,
2674     /// The name has been typo-corrected to a keyword.
2675     NC_Keyword,
2676     /// The name was classified as a type.
2677     NC_Type,
2678     /// The name was classified as a specific non-type, non-template
2679     /// declaration. ActOnNameClassifiedAsNonType should be called to
2680     /// convert the declaration to an expression.
2681     NC_NonType,
2682     /// The name was classified as an ADL-only function name.
2683     /// ActOnNameClassifiedAsUndeclaredNonType should be called to convert the
2684     /// result to an expression.
2685     NC_UndeclaredNonType,
2686     /// The name denotes a member of a dependent type that could not be
2687     /// resolved. ActOnNameClassifiedAsDependentNonType should be called to
2688     /// convert the result to an expression.
2689     NC_DependentNonType,
2690     /// The name was classified as an overload set, and an expression
2691     /// representing that overload set has been formed.
2692     /// ActOnNameClassifiedAsOverloadSet should be called to form a suitable
2693     /// expression referencing the overload set.
2694     NC_OverloadSet,
2695     /// The name was classified as a template whose specializations are types.
2696     NC_TypeTemplate,
2697     /// The name was classified as a variable template name.
2698     NC_VarTemplate,
2699     /// The name was classified as a function template name.
2700     NC_FunctionTemplate,
2701     /// The name was classified as an ADL-only function template name.
2702     NC_UndeclaredTemplate,
2703     /// The name was classified as a concept name.
2704     NC_Concept,
2705   };
2706 
2707   class NameClassification {
2708     NameClassificationKind Kind;
2709     union {
2710       ExprResult Expr;
2711       NamedDecl *NonTypeDecl;
2712       TemplateName Template;
2713       ParsedType Type;
2714     };
2715 
2716     explicit NameClassification(NameClassificationKind Kind) : Kind(Kind) {}
2717 
2718   public:
2719     NameClassification(ParsedType Type) : Kind(NC_Type), Type(Type) {}
2720 
2721     NameClassification(const IdentifierInfo *Keyword) : Kind(NC_Keyword) {}
2722 
2723     static NameClassification Error() {
2724       return NameClassification(NC_Error);
2725     }
2726 
2727     static NameClassification Unknown() {
2728       return NameClassification(NC_Unknown);
2729     }
2730 
2731     static NameClassification OverloadSet(ExprResult E) {
2732       NameClassification Result(NC_OverloadSet);
2733       Result.Expr = E;
2734       return Result;
2735     }
2736 
2737     static NameClassification NonType(NamedDecl *D) {
2738       NameClassification Result(NC_NonType);
2739       Result.NonTypeDecl = D;
2740       return Result;
2741     }
2742 
2743     static NameClassification UndeclaredNonType() {
2744       return NameClassification(NC_UndeclaredNonType);
2745     }
2746 
2747     static NameClassification DependentNonType() {
2748       return NameClassification(NC_DependentNonType);
2749     }
2750 
2751     static NameClassification TypeTemplate(TemplateName Name) {
2752       NameClassification Result(NC_TypeTemplate);
2753       Result.Template = Name;
2754       return Result;
2755     }
2756 
2757     static NameClassification VarTemplate(TemplateName Name) {
2758       NameClassification Result(NC_VarTemplate);
2759       Result.Template = Name;
2760       return Result;
2761     }
2762 
2763     static NameClassification FunctionTemplate(TemplateName Name) {
2764       NameClassification Result(NC_FunctionTemplate);
2765       Result.Template = Name;
2766       return Result;
2767     }
2768 
2769     static NameClassification Concept(TemplateName Name) {
2770       NameClassification Result(NC_Concept);
2771       Result.Template = Name;
2772       return Result;
2773     }
2774 
2775     static NameClassification UndeclaredTemplate(TemplateName Name) {
2776       NameClassification Result(NC_UndeclaredTemplate);
2777       Result.Template = Name;
2778       return Result;
2779     }
2780 
2781     NameClassificationKind getKind() const { return Kind; }
2782 
2783     ExprResult getExpression() const {
2784       assert(Kind == NC_OverloadSet);
2785       return Expr;
2786     }
2787 
2788     ParsedType getType() const {
2789       assert(Kind == NC_Type);
2790       return Type;
2791     }
2792 
2793     NamedDecl *getNonTypeDecl() const {
2794       assert(Kind == NC_NonType);
2795       return NonTypeDecl;
2796     }
2797 
2798     TemplateName getTemplateName() const {
2799       assert(Kind == NC_TypeTemplate || Kind == NC_FunctionTemplate ||
2800              Kind == NC_VarTemplate || Kind == NC_Concept ||
2801              Kind == NC_UndeclaredTemplate);
2802       return Template;
2803     }
2804 
2805     TemplateNameKind getTemplateNameKind() const {
2806       switch (Kind) {
2807       case NC_TypeTemplate:
2808         return TNK_Type_template;
2809       case NC_FunctionTemplate:
2810         return TNK_Function_template;
2811       case NC_VarTemplate:
2812         return TNK_Var_template;
2813       case NC_Concept:
2814         return TNK_Concept_template;
2815       case NC_UndeclaredTemplate:
2816         return TNK_Undeclared_template;
2817       default:
2818         llvm_unreachable("unsupported name classification.");
2819       }
2820     }
2821   };
2822 
2823   /// Perform name lookup on the given name, classifying it based on
2824   /// the results of name lookup and the following token.
2825   ///
2826   /// This routine is used by the parser to resolve identifiers and help direct
2827   /// parsing. When the identifier cannot be found, this routine will attempt
2828   /// to correct the typo and classify based on the resulting name.
2829   ///
2830   /// \param S The scope in which we're performing name lookup.
2831   ///
2832   /// \param SS The nested-name-specifier that precedes the name.
2833   ///
2834   /// \param Name The identifier. If typo correction finds an alternative name,
2835   /// this pointer parameter will be updated accordingly.
2836   ///
2837   /// \param NameLoc The location of the identifier.
2838   ///
2839   /// \param NextToken The token following the identifier. Used to help
2840   /// disambiguate the name.
2841   ///
2842   /// \param CCC The correction callback, if typo correction is desired.
2843   NameClassification ClassifyName(Scope *S, CXXScopeSpec &SS,
2844                                   IdentifierInfo *&Name, SourceLocation NameLoc,
2845                                   const Token &NextToken,
2846                                   CorrectionCandidateCallback *CCC = nullptr);
2847 
2848   /// Act on the result of classifying a name as an undeclared (ADL-only)
2849   /// non-type declaration.
2850   ExprResult ActOnNameClassifiedAsUndeclaredNonType(IdentifierInfo *Name,
2851                                                     SourceLocation NameLoc);
2852   /// Act on the result of classifying a name as an undeclared member of a
2853   /// dependent base class.
2854   ExprResult ActOnNameClassifiedAsDependentNonType(const CXXScopeSpec &SS,
2855                                                    IdentifierInfo *Name,
2856                                                    SourceLocation NameLoc,
2857                                                    bool IsAddressOfOperand);
2858   /// Act on the result of classifying a name as a specific non-type
2859   /// declaration.
2860   ExprResult ActOnNameClassifiedAsNonType(Scope *S, const CXXScopeSpec &SS,
2861                                           NamedDecl *Found,
2862                                           SourceLocation NameLoc,
2863                                           const Token &NextToken);
2864   /// Act on the result of classifying a name as an overload set.
2865   ExprResult ActOnNameClassifiedAsOverloadSet(Scope *S, Expr *OverloadSet);
2866 
2867   /// Describes the detailed kind of a template name. Used in diagnostics.
2868   enum class TemplateNameKindForDiagnostics {
2869     ClassTemplate,
2870     FunctionTemplate,
2871     VarTemplate,
2872     AliasTemplate,
2873     TemplateTemplateParam,
2874     Concept,
2875     DependentTemplate
2876   };
2877   TemplateNameKindForDiagnostics
2878   getTemplateNameKindForDiagnostics(TemplateName Name);
2879 
2880   /// Determine whether it's plausible that E was intended to be a
2881   /// template-name.
2882   bool mightBeIntendedToBeTemplateName(ExprResult E, bool &Dependent) {
2883     if (!getLangOpts().CPlusPlus || E.isInvalid())
2884       return false;
2885     Dependent = false;
2886     if (auto *DRE = dyn_cast<DeclRefExpr>(E.get()))
2887       return !DRE->hasExplicitTemplateArgs();
2888     if (auto *ME = dyn_cast<MemberExpr>(E.get()))
2889       return !ME->hasExplicitTemplateArgs();
2890     Dependent = true;
2891     if (auto *DSDRE = dyn_cast<DependentScopeDeclRefExpr>(E.get()))
2892       return !DSDRE->hasExplicitTemplateArgs();
2893     if (auto *DSME = dyn_cast<CXXDependentScopeMemberExpr>(E.get()))
2894       return !DSME->hasExplicitTemplateArgs();
2895     // Any additional cases recognized here should also be handled by
2896     // diagnoseExprIntendedAsTemplateName.
2897     return false;
2898   }
2899   void diagnoseExprIntendedAsTemplateName(Scope *S, ExprResult TemplateName,
2900                                           SourceLocation Less,
2901                                           SourceLocation Greater);
2902 
2903   void warnOnReservedIdentifier(const NamedDecl *D);
2904 
2905   Decl *ActOnDeclarator(Scope *S, Declarator &D);
2906 
2907   NamedDecl *HandleDeclarator(Scope *S, Declarator &D,
2908                               MultiTemplateParamsArg TemplateParameterLists);
2909   bool tryToFixVariablyModifiedVarType(TypeSourceInfo *&TInfo,
2910                                        QualType &T, SourceLocation Loc,
2911                                        unsigned FailedFoldDiagID);
2912   void RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S);
2913   bool DiagnoseClassNameShadow(DeclContext *DC, DeclarationNameInfo Info);
2914   bool diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
2915                                     DeclarationName Name, SourceLocation Loc,
2916                                     bool IsTemplateId);
2917   void
2918   diagnoseIgnoredQualifiers(unsigned DiagID, unsigned Quals,
2919                             SourceLocation FallbackLoc,
2920                             SourceLocation ConstQualLoc = SourceLocation(),
2921                             SourceLocation VolatileQualLoc = SourceLocation(),
2922                             SourceLocation RestrictQualLoc = SourceLocation(),
2923                             SourceLocation AtomicQualLoc = SourceLocation(),
2924                             SourceLocation UnalignedQualLoc = SourceLocation());
2925 
2926   static bool adjustContextForLocalExternDecl(DeclContext *&DC);
2927   void DiagnoseFunctionSpecifiers(const DeclSpec &DS);
2928   NamedDecl *getShadowedDeclaration(const TypedefNameDecl *D,
2929                                     const LookupResult &R);
2930   NamedDecl *getShadowedDeclaration(const VarDecl *D, const LookupResult &R);
2931   NamedDecl *getShadowedDeclaration(const BindingDecl *D,
2932                                     const LookupResult &R);
2933   void CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl,
2934                    const LookupResult &R);
2935   void CheckShadow(Scope *S, VarDecl *D);
2936 
2937   /// Warn if 'E', which is an expression that is about to be modified, refers
2938   /// to a shadowing declaration.
2939   void CheckShadowingDeclModification(Expr *E, SourceLocation Loc);
2940 
2941   void DiagnoseShadowingLambdaDecls(const sema::LambdaScopeInfo *LSI);
2942 
2943 private:
2944   /// Map of current shadowing declarations to shadowed declarations. Warn if
2945   /// it looks like the user is trying to modify the shadowing declaration.
2946   llvm::DenseMap<const NamedDecl *, const NamedDecl *> ShadowingDecls;
2947 
2948 public:
2949   void CheckCastAlign(Expr *Op, QualType T, SourceRange TRange);
2950   void handleTagNumbering(const TagDecl *Tag, Scope *TagScope);
2951   void setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
2952                                     TypedefNameDecl *NewTD);
2953   void CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *D);
2954   NamedDecl* ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
2955                                     TypeSourceInfo *TInfo,
2956                                     LookupResult &Previous);
2957   NamedDecl* ActOnTypedefNameDecl(Scope* S, DeclContext* DC, TypedefNameDecl *D,
2958                                   LookupResult &Previous, bool &Redeclaration);
2959   NamedDecl *ActOnVariableDeclarator(
2960       Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo,
2961       LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists,
2962       bool &AddToScope, ArrayRef<BindingDecl *> Bindings = std::nullopt);
2963   NamedDecl *
2964   ActOnDecompositionDeclarator(Scope *S, Declarator &D,
2965                                MultiTemplateParamsArg TemplateParamLists);
2966   // Returns true if the variable declaration is a redeclaration
2967   bool CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous);
2968   void CheckVariableDeclarationType(VarDecl *NewVD);
2969   bool DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit,
2970                                      Expr *Init);
2971   void CheckCompleteVariableDeclaration(VarDecl *VD);
2972   void CheckCompleteDecompositionDeclaration(DecompositionDecl *DD);
2973   void MaybeSuggestAddingStaticToDecl(const FunctionDecl *D);
2974 
2975   NamedDecl* ActOnFunctionDeclarator(Scope* S, Declarator& D, DeclContext* DC,
2976                                      TypeSourceInfo *TInfo,
2977                                      LookupResult &Previous,
2978                                      MultiTemplateParamsArg TemplateParamLists,
2979                                      bool &AddToScope);
2980   bool AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD);
2981 
2982   enum class CheckConstexprKind {
2983     /// Diagnose issues that are non-constant or that are extensions.
2984     Diagnose,
2985     /// Identify whether this function satisfies the formal rules for constexpr
2986     /// functions in the current lanugage mode (with no extensions).
2987     CheckValid
2988   };
2989 
2990   bool CheckConstexprFunctionDefinition(const FunctionDecl *FD,
2991                                         CheckConstexprKind Kind);
2992 
2993   void DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD);
2994   void FindHiddenVirtualMethods(CXXMethodDecl *MD,
2995                           SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods);
2996   void NoteHiddenVirtualMethods(CXXMethodDecl *MD,
2997                           SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods);
2998   // Returns true if the function declaration is a redeclaration
2999   bool CheckFunctionDeclaration(Scope *S,
3000                                 FunctionDecl *NewFD, LookupResult &Previous,
3001                                 bool IsMemberSpecialization, bool DeclIsDefn);
3002   bool shouldLinkDependentDeclWithPrevious(Decl *D, Decl *OldDecl);
3003   bool canFullyTypeCheckRedeclaration(ValueDecl *NewD, ValueDecl *OldD,
3004                                       QualType NewT, QualType OldT);
3005   void CheckMain(FunctionDecl *FD, const DeclSpec &D);
3006   void CheckMSVCRTEntryPoint(FunctionDecl *FD);
3007   void CheckHLSLEntryPoint(FunctionDecl *FD);
3008   Attr *getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD,
3009                                                    bool IsDefinition);
3010   void CheckFunctionOrTemplateParamDeclarator(Scope *S, Declarator &D);
3011   Decl *ActOnParamDeclarator(Scope *S, Declarator &D);
3012   ParmVarDecl *BuildParmVarDeclForTypedef(DeclContext *DC,
3013                                           SourceLocation Loc,
3014                                           QualType T);
3015   ParmVarDecl *CheckParameter(DeclContext *DC, SourceLocation StartLoc,
3016                               SourceLocation NameLoc, IdentifierInfo *Name,
3017                               QualType T, TypeSourceInfo *TSInfo,
3018                               StorageClass SC);
3019   void ActOnParamDefaultArgument(Decl *param,
3020                                  SourceLocation EqualLoc,
3021                                  Expr *defarg);
3022   void ActOnParamUnparsedDefaultArgument(Decl *param, SourceLocation EqualLoc,
3023                                          SourceLocation ArgLoc);
3024   void ActOnParamDefaultArgumentError(Decl *param, SourceLocation EqualLoc);
3025   ExprResult ConvertParamDefaultArgument(ParmVarDecl *Param, Expr *DefaultArg,
3026                                          SourceLocation EqualLoc);
3027   void SetParamDefaultArgument(ParmVarDecl *Param, Expr *DefaultArg,
3028                                SourceLocation EqualLoc);
3029 
3030   // Contexts where using non-trivial C union types can be disallowed. This is
3031   // passed to err_non_trivial_c_union_in_invalid_context.
3032   enum NonTrivialCUnionContext {
3033     // Function parameter.
3034     NTCUC_FunctionParam,
3035     // Function return.
3036     NTCUC_FunctionReturn,
3037     // Default-initialized object.
3038     NTCUC_DefaultInitializedObject,
3039     // Variable with automatic storage duration.
3040     NTCUC_AutoVar,
3041     // Initializer expression that might copy from another object.
3042     NTCUC_CopyInit,
3043     // Assignment.
3044     NTCUC_Assignment,
3045     // Compound literal.
3046     NTCUC_CompoundLiteral,
3047     // Block capture.
3048     NTCUC_BlockCapture,
3049     // lvalue-to-rvalue conversion of volatile type.
3050     NTCUC_LValueToRValueVolatile,
3051   };
3052 
3053   /// Emit diagnostics if the initializer or any of its explicit or
3054   /// implicitly-generated subexpressions require copying or
3055   /// default-initializing a type that is or contains a C union type that is
3056   /// non-trivial to copy or default-initialize.
3057   void checkNonTrivialCUnionInInitializer(const Expr *Init, SourceLocation Loc);
3058 
3059   // These flags are passed to checkNonTrivialCUnion.
3060   enum NonTrivialCUnionKind {
3061     NTCUK_Init = 0x1,
3062     NTCUK_Destruct = 0x2,
3063     NTCUK_Copy = 0x4,
3064   };
3065 
3066   /// Emit diagnostics if a non-trivial C union type or a struct that contains
3067   /// a non-trivial C union is used in an invalid context.
3068   void checkNonTrivialCUnion(QualType QT, SourceLocation Loc,
3069                              NonTrivialCUnionContext UseContext,
3070                              unsigned NonTrivialKind);
3071 
3072   void AddInitializerToDecl(Decl *dcl, Expr *init, bool DirectInit);
3073   void ActOnUninitializedDecl(Decl *dcl);
3074   void ActOnInitializerError(Decl *Dcl);
3075 
3076   void ActOnPureSpecifier(Decl *D, SourceLocation PureSpecLoc);
3077   void ActOnCXXForRangeDecl(Decl *D);
3078   StmtResult ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc,
3079                                         IdentifierInfo *Ident,
3080                                         ParsedAttributes &Attrs);
3081   void SetDeclDeleted(Decl *dcl, SourceLocation DelLoc);
3082   void SetDeclDefaulted(Decl *dcl, SourceLocation DefaultLoc);
3083   void CheckStaticLocalForDllExport(VarDecl *VD);
3084   void CheckThreadLocalForLargeAlignment(VarDecl *VD);
3085   void FinalizeDeclaration(Decl *D);
3086   DeclGroupPtrTy FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
3087                                          ArrayRef<Decl *> Group);
3088   DeclGroupPtrTy BuildDeclaratorGroup(MutableArrayRef<Decl *> Group);
3089 
3090   /// Should be called on all declarations that might have attached
3091   /// documentation comments.
3092   void ActOnDocumentableDecl(Decl *D);
3093   void ActOnDocumentableDecls(ArrayRef<Decl *> Group);
3094 
3095   enum class FnBodyKind {
3096     /// C++ [dcl.fct.def.general]p1
3097     /// function-body:
3098     ///   ctor-initializer[opt] compound-statement
3099     ///   function-try-block
3100     Other,
3101     ///   = default ;
3102     Default,
3103     ///   = delete ;
3104     Delete
3105   };
3106 
3107   void ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
3108                                        SourceLocation LocAfterDecls);
3109   void CheckForFunctionRedefinition(
3110       FunctionDecl *FD, const FunctionDecl *EffectiveDefinition = nullptr,
3111       SkipBodyInfo *SkipBody = nullptr);
3112   Decl *ActOnStartOfFunctionDef(Scope *S, Declarator &D,
3113                                 MultiTemplateParamsArg TemplateParamLists,
3114                                 SkipBodyInfo *SkipBody = nullptr,
3115                                 FnBodyKind BodyKind = FnBodyKind::Other);
3116   Decl *ActOnStartOfFunctionDef(Scope *S, Decl *D,
3117                                 SkipBodyInfo *SkipBody = nullptr,
3118                                 FnBodyKind BodyKind = FnBodyKind::Other);
3119   void SetFunctionBodyKind(Decl *D, SourceLocation Loc, FnBodyKind BodyKind);
3120   void ActOnStartTrailingRequiresClause(Scope *S, Declarator &D);
3121   ExprResult ActOnFinishTrailingRequiresClause(ExprResult ConstraintExpr);
3122   ExprResult ActOnRequiresClause(ExprResult ConstraintExpr);
3123   void ActOnStartOfObjCMethodDef(Scope *S, Decl *D);
3124   bool isObjCMethodDecl(Decl *D) {
3125     return D && isa<ObjCMethodDecl>(D);
3126   }
3127 
3128   /// Determine whether we can delay parsing the body of a function or
3129   /// function template until it is used, assuming we don't care about emitting
3130   /// code for that function.
3131   ///
3132   /// This will be \c false if we may need the body of the function in the
3133   /// middle of parsing an expression (where it's impractical to switch to
3134   /// parsing a different function), for instance, if it's constexpr in C++11
3135   /// or has an 'auto' return type in C++14. These cases are essentially bugs.
3136   bool canDelayFunctionBody(const Declarator &D);
3137 
3138   /// Determine whether we can skip parsing the body of a function
3139   /// definition, assuming we don't care about analyzing its body or emitting
3140   /// code for that function.
3141   ///
3142   /// This will be \c false only if we may need the body of the function in
3143   /// order to parse the rest of the program (for instance, if it is
3144   /// \c constexpr in C++11 or has an 'auto' return type in C++14).
3145   bool canSkipFunctionBody(Decl *D);
3146 
3147   /// Determine whether \param D is function like (function or function
3148   /// template) for parsing.
3149   bool isDeclaratorFunctionLike(Declarator &D);
3150 
3151   void computeNRVO(Stmt *Body, sema::FunctionScopeInfo *Scope);
3152   Decl *ActOnFinishFunctionBody(Decl *Decl, Stmt *Body);
3153   Decl *ActOnFinishFunctionBody(Decl *Decl, Stmt *Body, bool IsInstantiation);
3154   Decl *ActOnSkippedFunctionBody(Decl *Decl);
3155   void ActOnFinishInlineFunctionDef(FunctionDecl *D);
3156 
3157   /// ActOnFinishDelayedAttribute - Invoked when we have finished parsing an
3158   /// attribute for which parsing is delayed.
3159   void ActOnFinishDelayedAttribute(Scope *S, Decl *D, ParsedAttributes &Attrs);
3160 
3161   /// Diagnose any unused parameters in the given sequence of
3162   /// ParmVarDecl pointers.
3163   void DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters);
3164 
3165   /// Diagnose whether the size of parameters or return value of a
3166   /// function or obj-c method definition is pass-by-value and larger than a
3167   /// specified threshold.
3168   void
3169   DiagnoseSizeOfParametersAndReturnValue(ArrayRef<ParmVarDecl *> Parameters,
3170                                          QualType ReturnTy, NamedDecl *D);
3171 
3172   void DiagnoseInvalidJumps(Stmt *Body);
3173   Decl *ActOnFileScopeAsmDecl(Expr *expr,
3174                               SourceLocation AsmLoc,
3175                               SourceLocation RParenLoc);
3176 
3177   Decl *ActOnTopLevelStmtDecl(Stmt *Statement);
3178 
3179   /// Handle a C++11 empty-declaration and attribute-declaration.
3180   Decl *ActOnEmptyDeclaration(Scope *S, const ParsedAttributesView &AttrList,
3181                               SourceLocation SemiLoc);
3182 
3183   enum class ModuleDeclKind {
3184     Interface,               ///< 'export module X;'
3185     Implementation,          ///< 'module X;'
3186     PartitionInterface,      ///< 'export module X:Y;'
3187     PartitionImplementation, ///< 'module X:Y;'
3188   };
3189 
3190   /// An enumeration to represent the transition of states in parsing module
3191   /// fragments and imports.  If we are not parsing a C++20 TU, or we find
3192   /// an error in state transition, the state is set to NotACXX20Module.
3193   enum class ModuleImportState {
3194     FirstDecl,      ///< Parsing the first decl in a TU.
3195     GlobalFragment, ///< after 'module;' but before 'module X;'
3196     ImportAllowed,  ///< after 'module X;' but before any non-import decl.
3197     ImportFinished, ///< after any non-import decl.
3198     PrivateFragmentImportAllowed,  ///< after 'module :private;' but before any
3199                                    ///< non-import decl.
3200     PrivateFragmentImportFinished, ///< after 'module :private;' but a
3201                                    ///< non-import decl has already been seen.
3202     NotACXX20Module ///< Not a C++20 TU, or an invalid state was found.
3203   };
3204 
3205 private:
3206   /// The parser has begun a translation unit to be compiled as a C++20
3207   /// Header Unit, helper for ActOnStartOfTranslationUnit() only.
3208   void HandleStartOfHeaderUnit();
3209 
3210 public:
3211   /// The parser has processed a module-declaration that begins the definition
3212   /// of a module interface or implementation.
3213   DeclGroupPtrTy ActOnModuleDecl(SourceLocation StartLoc,
3214                                  SourceLocation ModuleLoc, ModuleDeclKind MDK,
3215                                  ModuleIdPath Path, ModuleIdPath Partition,
3216                                  ModuleImportState &ImportState);
3217 
3218   /// The parser has processed a global-module-fragment declaration that begins
3219   /// the definition of the global module fragment of the current module unit.
3220   /// \param ModuleLoc The location of the 'module' keyword.
3221   DeclGroupPtrTy ActOnGlobalModuleFragmentDecl(SourceLocation ModuleLoc);
3222 
3223   /// The parser has processed a private-module-fragment declaration that begins
3224   /// the definition of the private module fragment of the current module unit.
3225   /// \param ModuleLoc The location of the 'module' keyword.
3226   /// \param PrivateLoc The location of the 'private' keyword.
3227   DeclGroupPtrTy ActOnPrivateModuleFragmentDecl(SourceLocation ModuleLoc,
3228                                                 SourceLocation PrivateLoc);
3229 
3230   /// The parser has processed a module import declaration.
3231   ///
3232   /// \param StartLoc The location of the first token in the declaration. This
3233   ///        could be the location of an '@', 'export', or 'import'.
3234   /// \param ExportLoc The location of the 'export' keyword, if any.
3235   /// \param ImportLoc The location of the 'import' keyword.
3236   /// \param Path The module toplevel name as an access path.
3237   /// \param IsPartition If the name is for a partition.
3238   DeclResult ActOnModuleImport(SourceLocation StartLoc,
3239                                SourceLocation ExportLoc,
3240                                SourceLocation ImportLoc, ModuleIdPath Path,
3241                                bool IsPartition = false);
3242   DeclResult ActOnModuleImport(SourceLocation StartLoc,
3243                                SourceLocation ExportLoc,
3244                                SourceLocation ImportLoc, Module *M,
3245                                ModuleIdPath Path = {});
3246 
3247   /// The parser has processed a module import translated from a
3248   /// #include or similar preprocessing directive.
3249   void ActOnModuleInclude(SourceLocation DirectiveLoc, Module *Mod);
3250   void BuildModuleInclude(SourceLocation DirectiveLoc, Module *Mod);
3251 
3252   /// The parsed has entered a submodule.
3253   void ActOnModuleBegin(SourceLocation DirectiveLoc, Module *Mod);
3254   /// The parser has left a submodule.
3255   void ActOnModuleEnd(SourceLocation DirectiveLoc, Module *Mod);
3256 
3257   /// Create an implicit import of the given module at the given
3258   /// source location, for error recovery, if possible.
3259   ///
3260   /// This routine is typically used when an entity found by name lookup
3261   /// is actually hidden within a module that we know about but the user
3262   /// has forgotten to import.
3263   void createImplicitModuleImportForErrorRecovery(SourceLocation Loc,
3264                                                   Module *Mod);
3265 
3266   /// Kinds of missing import. Note, the values of these enumerators correspond
3267   /// to %select values in diagnostics.
3268   enum class MissingImportKind {
3269     Declaration,
3270     Definition,
3271     DefaultArgument,
3272     ExplicitSpecialization,
3273     PartialSpecialization
3274   };
3275 
3276   /// Diagnose that the specified declaration needs to be visible but
3277   /// isn't, and suggest a module import that would resolve the problem.
3278   void diagnoseMissingImport(SourceLocation Loc, const NamedDecl *Decl,
3279                              MissingImportKind MIK, bool Recover = true);
3280   void diagnoseMissingImport(SourceLocation Loc, const NamedDecl *Decl,
3281                              SourceLocation DeclLoc, ArrayRef<Module *> Modules,
3282                              MissingImportKind MIK, bool Recover);
3283 
3284   Decl *ActOnStartExportDecl(Scope *S, SourceLocation ExportLoc,
3285                              SourceLocation LBraceLoc);
3286   Decl *ActOnFinishExportDecl(Scope *S, Decl *ExportDecl,
3287                               SourceLocation RBraceLoc);
3288 
3289   /// We've found a use of a templated declaration that would trigger an
3290   /// implicit instantiation. Check that any relevant explicit specializations
3291   /// and partial specializations are visible/reachable, and diagnose if not.
3292   void checkSpecializationVisibility(SourceLocation Loc, NamedDecl *Spec);
3293   void checkSpecializationReachability(SourceLocation Loc, NamedDecl *Spec);
3294 
3295   /// Retrieve a suitable printing policy for diagnostics.
3296   PrintingPolicy getPrintingPolicy() const {
3297     return getPrintingPolicy(Context, PP);
3298   }
3299 
3300   /// Retrieve a suitable printing policy for diagnostics.
3301   static PrintingPolicy getPrintingPolicy(const ASTContext &Ctx,
3302                                           const Preprocessor &PP);
3303 
3304   /// Scope actions.
3305   void ActOnPopScope(SourceLocation Loc, Scope *S);
3306   void ActOnTranslationUnitScope(Scope *S);
3307 
3308   Decl *ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
3309                                    const ParsedAttributesView &DeclAttrs,
3310                                    RecordDecl *&AnonRecord);
3311   Decl *ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
3312                                    const ParsedAttributesView &DeclAttrs,
3313                                    MultiTemplateParamsArg TemplateParams,
3314                                    bool IsExplicitInstantiation,
3315                                    RecordDecl *&AnonRecord);
3316 
3317   Decl *BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
3318                                     AccessSpecifier AS,
3319                                     RecordDecl *Record,
3320                                     const PrintingPolicy &Policy);
3321 
3322   Decl *BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
3323                                        RecordDecl *Record);
3324 
3325   /// Common ways to introduce type names without a tag for use in diagnostics.
3326   /// Keep in sync with err_tag_reference_non_tag.
3327   enum NonTagKind {
3328     NTK_NonStruct,
3329     NTK_NonClass,
3330     NTK_NonUnion,
3331     NTK_NonEnum,
3332     NTK_Typedef,
3333     NTK_TypeAlias,
3334     NTK_Template,
3335     NTK_TypeAliasTemplate,
3336     NTK_TemplateTemplateArgument,
3337   };
3338 
3339   /// Given a non-tag type declaration, returns an enum useful for indicating
3340   /// what kind of non-tag type this is.
3341   NonTagKind getNonTagTypeDeclKind(const Decl *D, TagTypeKind TTK);
3342 
3343   bool isAcceptableTagRedeclaration(const TagDecl *Previous,
3344                                     TagTypeKind NewTag, bool isDefinition,
3345                                     SourceLocation NewTagLoc,
3346                                     const IdentifierInfo *Name);
3347 
3348   enum TagUseKind {
3349     TUK_Reference,   // Reference to a tag:  'struct foo *X;'
3350     TUK_Declaration, // Fwd decl of a tag:   'struct foo;'
3351     TUK_Definition,  // Definition of a tag: 'struct foo { int X; } Y;'
3352     TUK_Friend       // Friend declaration:  'friend struct foo;'
3353   };
3354 
3355   enum OffsetOfKind {
3356     // Not parsing a type within __builtin_offsetof.
3357     OOK_Outside,
3358     // Parsing a type within __builtin_offsetof.
3359     OOK_Builtin,
3360     // Parsing a type within macro "offsetof", defined in __buitin_offsetof
3361     // To improve our diagnostic message.
3362     OOK_Macro,
3363   };
3364 
3365   DeclResult ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
3366                       SourceLocation KWLoc, CXXScopeSpec &SS,
3367                       IdentifierInfo *Name, SourceLocation NameLoc,
3368                       const ParsedAttributesView &Attr, AccessSpecifier AS,
3369                       SourceLocation ModulePrivateLoc,
3370                       MultiTemplateParamsArg TemplateParameterLists,
3371                       bool &OwnedDecl, bool &IsDependent,
3372                       SourceLocation ScopedEnumKWLoc,
3373                       bool ScopedEnumUsesClassTag, TypeResult UnderlyingType,
3374                       bool IsTypeSpecifier, bool IsTemplateParamOrArg,
3375                       OffsetOfKind OOK, SkipBodyInfo *SkipBody = nullptr);
3376 
3377   DeclResult ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
3378                                      unsigned TagSpec, SourceLocation TagLoc,
3379                                      CXXScopeSpec &SS, IdentifierInfo *Name,
3380                                      SourceLocation NameLoc,
3381                                      const ParsedAttributesView &Attr,
3382                                      MultiTemplateParamsArg TempParamLists);
3383 
3384   TypeResult ActOnDependentTag(Scope *S,
3385                                unsigned TagSpec,
3386                                TagUseKind TUK,
3387                                const CXXScopeSpec &SS,
3388                                IdentifierInfo *Name,
3389                                SourceLocation TagLoc,
3390                                SourceLocation NameLoc);
3391 
3392   void ActOnDefs(Scope *S, Decl *TagD, SourceLocation DeclStart,
3393                  IdentifierInfo *ClassName,
3394                  SmallVectorImpl<Decl *> &Decls);
3395   Decl *ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
3396                    Declarator &D, Expr *BitfieldWidth);
3397 
3398   FieldDecl *HandleField(Scope *S, RecordDecl *TagD, SourceLocation DeclStart,
3399                          Declarator &D, Expr *BitfieldWidth,
3400                          InClassInitStyle InitStyle,
3401                          AccessSpecifier AS);
3402   MSPropertyDecl *HandleMSProperty(Scope *S, RecordDecl *TagD,
3403                                    SourceLocation DeclStart, Declarator &D,
3404                                    Expr *BitfieldWidth,
3405                                    InClassInitStyle InitStyle,
3406                                    AccessSpecifier AS,
3407                                    const ParsedAttr &MSPropertyAttr);
3408 
3409   FieldDecl *CheckFieldDecl(DeclarationName Name, QualType T,
3410                             TypeSourceInfo *TInfo,
3411                             RecordDecl *Record, SourceLocation Loc,
3412                             bool Mutable, Expr *BitfieldWidth,
3413                             InClassInitStyle InitStyle,
3414                             SourceLocation TSSL,
3415                             AccessSpecifier AS, NamedDecl *PrevDecl,
3416                             Declarator *D = nullptr);
3417 
3418   bool CheckNontrivialField(FieldDecl *FD);
3419   void DiagnoseNontrivial(const CXXRecordDecl *Record, CXXSpecialMember CSM);
3420 
3421   enum TrivialABIHandling {
3422     /// The triviality of a method unaffected by "trivial_abi".
3423     TAH_IgnoreTrivialABI,
3424 
3425     /// The triviality of a method affected by "trivial_abi".
3426     TAH_ConsiderTrivialABI
3427   };
3428 
3429   bool SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
3430                               TrivialABIHandling TAH = TAH_IgnoreTrivialABI,
3431                               bool Diagnose = false);
3432 
3433   /// For a defaulted function, the kind of defaulted function that it is.
3434   class DefaultedFunctionKind {
3435     CXXSpecialMember SpecialMember : 8;
3436     DefaultedComparisonKind Comparison : 8;
3437 
3438   public:
3439     DefaultedFunctionKind()
3440         : SpecialMember(CXXInvalid), Comparison(DefaultedComparisonKind::None) {
3441     }
3442     DefaultedFunctionKind(CXXSpecialMember CSM)
3443         : SpecialMember(CSM), Comparison(DefaultedComparisonKind::None) {}
3444     DefaultedFunctionKind(DefaultedComparisonKind Comp)
3445         : SpecialMember(CXXInvalid), Comparison(Comp) {}
3446 
3447     bool isSpecialMember() const { return SpecialMember != CXXInvalid; }
3448     bool isComparison() const {
3449       return Comparison != DefaultedComparisonKind::None;
3450     }
3451 
3452     explicit operator bool() const {
3453       return isSpecialMember() || isComparison();
3454     }
3455 
3456     CXXSpecialMember asSpecialMember() const { return SpecialMember; }
3457     DefaultedComparisonKind asComparison() const { return Comparison; }
3458 
3459     /// Get the index of this function kind for use in diagnostics.
3460     unsigned getDiagnosticIndex() const {
3461       static_assert(CXXInvalid > CXXDestructor,
3462                     "invalid should have highest index");
3463       static_assert((unsigned)DefaultedComparisonKind::None == 0,
3464                     "none should be equal to zero");
3465       return SpecialMember + (unsigned)Comparison;
3466     }
3467   };
3468 
3469   DefaultedFunctionKind getDefaultedFunctionKind(const FunctionDecl *FD);
3470 
3471   CXXSpecialMember getSpecialMember(const CXXMethodDecl *MD) {
3472     return getDefaultedFunctionKind(MD).asSpecialMember();
3473   }
3474   DefaultedComparisonKind getDefaultedComparisonKind(const FunctionDecl *FD) {
3475     return getDefaultedFunctionKind(FD).asComparison();
3476   }
3477 
3478   void ActOnLastBitfield(SourceLocation DeclStart,
3479                          SmallVectorImpl<Decl *> &AllIvarDecls);
3480   Decl *ActOnIvar(Scope *S, SourceLocation DeclStart,
3481                   Declarator &D, Expr *BitfieldWidth,
3482                   tok::ObjCKeywordKind visibility);
3483 
3484   // This is used for both record definitions and ObjC interface declarations.
3485   void ActOnFields(Scope *S, SourceLocation RecLoc, Decl *TagDecl,
3486                    ArrayRef<Decl *> Fields, SourceLocation LBrac,
3487                    SourceLocation RBrac, const ParsedAttributesView &AttrList);
3488 
3489   /// ActOnTagStartDefinition - Invoked when we have entered the
3490   /// scope of a tag's definition (e.g., for an enumeration, class,
3491   /// struct, or union).
3492   void ActOnTagStartDefinition(Scope *S, Decl *TagDecl);
3493 
3494   /// Perform ODR-like check for C/ObjC when merging tag types from modules.
3495   /// Differently from C++, actually parse the body and reject / error out
3496   /// in case of a structural mismatch.
3497   bool ActOnDuplicateDefinition(Decl *Prev, SkipBodyInfo &SkipBody);
3498 
3499   /// Check ODR hashes for C/ObjC when merging types from modules.
3500   /// Differently from C++, actually parse the body and reject in case
3501   /// of a mismatch.
3502   template <typename T,
3503             typename = std::enable_if_t<std::is_base_of<NamedDecl, T>::value>>
3504   bool ActOnDuplicateODRHashDefinition(T *Duplicate, T *Previous) {
3505     if (Duplicate->getODRHash() != Previous->getODRHash())
3506       return false;
3507 
3508     // Make the previous decl visible.
3509     makeMergedDefinitionVisible(Previous);
3510     return true;
3511   }
3512 
3513   typedef void *SkippedDefinitionContext;
3514 
3515   /// Invoked when we enter a tag definition that we're skipping.
3516   SkippedDefinitionContext ActOnTagStartSkippedDefinition(Scope *S, Decl *TD);
3517 
3518   void ActOnObjCContainerStartDefinition(ObjCContainerDecl *IDecl);
3519 
3520   /// ActOnStartCXXMemberDeclarations - Invoked when we have parsed a
3521   /// C++ record definition's base-specifiers clause and are starting its
3522   /// member declarations.
3523   void ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagDecl,
3524                                        SourceLocation FinalLoc,
3525                                        bool IsFinalSpelledSealed,
3526                                        bool IsAbstract,
3527                                        SourceLocation LBraceLoc);
3528 
3529   /// ActOnTagFinishDefinition - Invoked once we have finished parsing
3530   /// the definition of a tag (enumeration, class, struct, or union).
3531   void ActOnTagFinishDefinition(Scope *S, Decl *TagDecl,
3532                                 SourceRange BraceRange);
3533 
3534   void ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context);
3535 
3536   void ActOnObjCContainerFinishDefinition();
3537 
3538   /// Invoked when we must temporarily exit the objective-c container
3539   /// scope for parsing/looking-up C constructs.
3540   ///
3541   /// Must be followed by a call to \see ActOnObjCReenterContainerContext
3542   void ActOnObjCTemporaryExitContainerContext(ObjCContainerDecl *ObjCCtx);
3543   void ActOnObjCReenterContainerContext(ObjCContainerDecl *ObjCCtx);
3544 
3545   /// ActOnTagDefinitionError - Invoked when there was an unrecoverable
3546   /// error parsing the definition of a tag.
3547   void ActOnTagDefinitionError(Scope *S, Decl *TagDecl);
3548 
3549   EnumConstantDecl *CheckEnumConstant(EnumDecl *Enum,
3550                                       EnumConstantDecl *LastEnumConst,
3551                                       SourceLocation IdLoc,
3552                                       IdentifierInfo *Id,
3553                                       Expr *val);
3554   bool CheckEnumUnderlyingType(TypeSourceInfo *TI);
3555   bool CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
3556                               QualType EnumUnderlyingTy, bool IsFixed,
3557                               const EnumDecl *Prev);
3558 
3559   /// Determine whether the body of an anonymous enumeration should be skipped.
3560   /// \param II The name of the first enumerator.
3561   SkipBodyInfo shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II,
3562                                       SourceLocation IILoc);
3563 
3564   Decl *ActOnEnumConstant(Scope *S, Decl *EnumDecl, Decl *LastEnumConstant,
3565                           SourceLocation IdLoc, IdentifierInfo *Id,
3566                           const ParsedAttributesView &Attrs,
3567                           SourceLocation EqualLoc, Expr *Val);
3568   void ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange,
3569                      Decl *EnumDecl, ArrayRef<Decl *> Elements, Scope *S,
3570                      const ParsedAttributesView &Attr);
3571 
3572   /// Set the current declaration context until it gets popped.
3573   void PushDeclContext(Scope *S, DeclContext *DC);
3574   void PopDeclContext();
3575 
3576   /// EnterDeclaratorContext - Used when we must lookup names in the context
3577   /// of a declarator's nested name specifier.
3578   void EnterDeclaratorContext(Scope *S, DeclContext *DC);
3579   void ExitDeclaratorContext(Scope *S);
3580 
3581   /// Enter a template parameter scope, after it's been associated with a particular
3582   /// DeclContext. Causes lookup within the scope to chain through enclosing contexts
3583   /// in the correct order.
3584   void EnterTemplatedContext(Scope *S, DeclContext *DC);
3585 
3586   /// Push the parameters of D, which must be a function, into scope.
3587   void ActOnReenterFunctionContext(Scope* S, Decl* D);
3588   void ActOnExitFunctionContext();
3589 
3590   /// If \p AllowLambda is true, treat lambda as function.
3591   DeclContext *getFunctionLevelDeclContext(bool AllowLambda = false) const;
3592 
3593   /// Returns a pointer to the innermost enclosing function, or nullptr if the
3594   /// current context is not inside a function. If \p AllowLambda is true,
3595   /// this can return the call operator of an enclosing lambda, otherwise
3596   /// lambdas are skipped when looking for an enclosing function.
3597   FunctionDecl *getCurFunctionDecl(bool AllowLambda = false) const;
3598 
3599   /// getCurMethodDecl - If inside of a method body, this returns a pointer to
3600   /// the method decl for the method being parsed.  If we're currently
3601   /// in a 'block', this returns the containing context.
3602   ObjCMethodDecl *getCurMethodDecl();
3603 
3604   /// getCurFunctionOrMethodDecl - Return the Decl for the current ObjC method
3605   /// or C function we're in, otherwise return null.  If we're currently
3606   /// in a 'block', this returns the containing context.
3607   NamedDecl *getCurFunctionOrMethodDecl() const;
3608 
3609   /// Add this decl to the scope shadowed decl chains.
3610   void PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext = true);
3611 
3612   /// isDeclInScope - If 'Ctx' is a function/method, isDeclInScope returns true
3613   /// if 'D' is in Scope 'S', otherwise 'S' is ignored and isDeclInScope returns
3614   /// true if 'D' belongs to the given declaration context.
3615   ///
3616   /// \param AllowInlineNamespace If \c true, allow the declaration to be in the
3617   ///        enclosing namespace set of the context, rather than contained
3618   ///        directly within it.
3619   bool isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S = nullptr,
3620                      bool AllowInlineNamespace = false) const;
3621 
3622   /// Finds the scope corresponding to the given decl context, if it
3623   /// happens to be an enclosing scope.  Otherwise return NULL.
3624   static Scope *getScopeForDeclContext(Scope *S, DeclContext *DC);
3625 
3626   /// Subroutines of ActOnDeclarator().
3627   TypedefDecl *ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
3628                                 TypeSourceInfo *TInfo);
3629   bool isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New);
3630 
3631   /// Describes the kind of merge to perform for availability
3632   /// attributes (including "deprecated", "unavailable", and "availability").
3633   enum AvailabilityMergeKind {
3634     /// Don't merge availability attributes at all.
3635     AMK_None,
3636     /// Merge availability attributes for a redeclaration, which requires
3637     /// an exact match.
3638     AMK_Redeclaration,
3639     /// Merge availability attributes for an override, which requires
3640     /// an exact match or a weakening of constraints.
3641     AMK_Override,
3642     /// Merge availability attributes for an implementation of
3643     /// a protocol requirement.
3644     AMK_ProtocolImplementation,
3645     /// Merge availability attributes for an implementation of
3646     /// an optional protocol requirement.
3647     AMK_OptionalProtocolImplementation
3648   };
3649 
3650   /// Describes the kind of priority given to an availability attribute.
3651   ///
3652   /// The sum of priorities deteremines the final priority of the attribute.
3653   /// The final priority determines how the attribute will be merged.
3654   /// An attribute with a lower priority will always remove higher priority
3655   /// attributes for the specified platform when it is being applied. An
3656   /// attribute with a higher priority will not be applied if the declaration
3657   /// already has an availability attribute with a lower priority for the
3658   /// specified platform. The final prirority values are not expected to match
3659   /// the values in this enumeration, but instead should be treated as a plain
3660   /// integer value. This enumeration just names the priority weights that are
3661   /// used to calculate that final vaue.
3662   enum AvailabilityPriority : int {
3663     /// The availability attribute was specified explicitly next to the
3664     /// declaration.
3665     AP_Explicit = 0,
3666 
3667     /// The availability attribute was applied using '#pragma clang attribute'.
3668     AP_PragmaClangAttribute = 1,
3669 
3670     /// The availability attribute for a specific platform was inferred from
3671     /// an availability attribute for another platform.
3672     AP_InferredFromOtherPlatform = 2
3673   };
3674 
3675   /// Attribute merging methods. Return true if a new attribute was added.
3676   AvailabilityAttr *
3677   mergeAvailabilityAttr(NamedDecl *D, const AttributeCommonInfo &CI,
3678                         IdentifierInfo *Platform, bool Implicit,
3679                         VersionTuple Introduced, VersionTuple Deprecated,
3680                         VersionTuple Obsoleted, bool IsUnavailable,
3681                         StringRef Message, bool IsStrict, StringRef Replacement,
3682                         AvailabilityMergeKind AMK, int Priority);
3683   TypeVisibilityAttr *
3684   mergeTypeVisibilityAttr(Decl *D, const AttributeCommonInfo &CI,
3685                           TypeVisibilityAttr::VisibilityType Vis);
3686   VisibilityAttr *mergeVisibilityAttr(Decl *D, const AttributeCommonInfo &CI,
3687                                       VisibilityAttr::VisibilityType Vis);
3688   UuidAttr *mergeUuidAttr(Decl *D, const AttributeCommonInfo &CI,
3689                           StringRef UuidAsWritten, MSGuidDecl *GuidDecl);
3690   DLLImportAttr *mergeDLLImportAttr(Decl *D, const AttributeCommonInfo &CI);
3691   DLLExportAttr *mergeDLLExportAttr(Decl *D, const AttributeCommonInfo &CI);
3692   MSInheritanceAttr *mergeMSInheritanceAttr(Decl *D,
3693                                             const AttributeCommonInfo &CI,
3694                                             bool BestCase,
3695                                             MSInheritanceModel Model);
3696   ErrorAttr *mergeErrorAttr(Decl *D, const AttributeCommonInfo &CI,
3697                             StringRef NewUserDiagnostic);
3698   FormatAttr *mergeFormatAttr(Decl *D, const AttributeCommonInfo &CI,
3699                               IdentifierInfo *Format, int FormatIdx,
3700                               int FirstArg);
3701   SectionAttr *mergeSectionAttr(Decl *D, const AttributeCommonInfo &CI,
3702                                 StringRef Name);
3703   CodeSegAttr *mergeCodeSegAttr(Decl *D, const AttributeCommonInfo &CI,
3704                                 StringRef Name);
3705   AlwaysInlineAttr *mergeAlwaysInlineAttr(Decl *D,
3706                                           const AttributeCommonInfo &CI,
3707                                           const IdentifierInfo *Ident);
3708   MinSizeAttr *mergeMinSizeAttr(Decl *D, const AttributeCommonInfo &CI);
3709   SwiftNameAttr *mergeSwiftNameAttr(Decl *D, const SwiftNameAttr &SNA,
3710                                     StringRef Name);
3711   OptimizeNoneAttr *mergeOptimizeNoneAttr(Decl *D,
3712                                           const AttributeCommonInfo &CI);
3713   InternalLinkageAttr *mergeInternalLinkageAttr(Decl *D, const ParsedAttr &AL);
3714   InternalLinkageAttr *mergeInternalLinkageAttr(Decl *D,
3715                                                 const InternalLinkageAttr &AL);
3716   WebAssemblyImportNameAttr *mergeImportNameAttr(
3717       Decl *D, const WebAssemblyImportNameAttr &AL);
3718   WebAssemblyImportModuleAttr *mergeImportModuleAttr(
3719       Decl *D, const WebAssemblyImportModuleAttr &AL);
3720   EnforceTCBAttr *mergeEnforceTCBAttr(Decl *D, const EnforceTCBAttr &AL);
3721   EnforceTCBLeafAttr *mergeEnforceTCBLeafAttr(Decl *D,
3722                                               const EnforceTCBLeafAttr &AL);
3723   BTFDeclTagAttr *mergeBTFDeclTagAttr(Decl *D, const BTFDeclTagAttr &AL);
3724   HLSLNumThreadsAttr *mergeHLSLNumThreadsAttr(Decl *D,
3725                                               const AttributeCommonInfo &AL,
3726                                               int X, int Y, int Z);
3727   HLSLShaderAttr *mergeHLSLShaderAttr(Decl *D, const AttributeCommonInfo &AL,
3728                                       HLSLShaderAttr::ShaderType ShaderType);
3729 
3730   void mergeDeclAttributes(NamedDecl *New, Decl *Old,
3731                            AvailabilityMergeKind AMK = AMK_Redeclaration);
3732   void MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New,
3733                             LookupResult &OldDecls);
3734   bool MergeFunctionDecl(FunctionDecl *New, NamedDecl *&Old, Scope *S,
3735                          bool MergeTypeWithOld, bool NewDeclIsDefn);
3736   bool MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
3737                                     Scope *S, bool MergeTypeWithOld);
3738   void mergeObjCMethodDecls(ObjCMethodDecl *New, ObjCMethodDecl *Old);
3739   void MergeVarDecl(VarDecl *New, LookupResult &Previous);
3740   void MergeVarDeclTypes(VarDecl *New, VarDecl *Old, bool MergeTypeWithOld);
3741   void MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old);
3742   bool checkVarDeclRedefinition(VarDecl *OldDefn, VarDecl *NewDefn);
3743   void notePreviousDefinition(const NamedDecl *Old, SourceLocation New);
3744   bool MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old, Scope *S);
3745 
3746   // AssignmentAction - This is used by all the assignment diagnostic functions
3747   // to represent what is actually causing the operation
3748   enum AssignmentAction {
3749     AA_Assigning,
3750     AA_Passing,
3751     AA_Returning,
3752     AA_Converting,
3753     AA_Initializing,
3754     AA_Sending,
3755     AA_Casting,
3756     AA_Passing_CFAudited
3757   };
3758 
3759   /// C++ Overloading.
3760   enum OverloadKind {
3761     /// This is a legitimate overload: the existing declarations are
3762     /// functions or function templates with different signatures.
3763     Ovl_Overload,
3764 
3765     /// This is not an overload because the signature exactly matches
3766     /// an existing declaration.
3767     Ovl_Match,
3768 
3769     /// This is not an overload because the lookup results contain a
3770     /// non-function.
3771     Ovl_NonFunction
3772   };
3773   OverloadKind CheckOverload(Scope *S,
3774                              FunctionDecl *New,
3775                              const LookupResult &OldDecls,
3776                              NamedDecl *&OldDecl,
3777                              bool UseMemberUsingDeclRules);
3778   bool IsOverload(FunctionDecl *New, FunctionDecl *Old,
3779                   bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs = true,
3780                   bool ConsiderRequiresClauses = true);
3781 
3782   // Calculates whether the expression Constraint depends on an enclosing
3783   // template, for the purposes of [temp.friend] p9.
3784   // TemplateDepth is the 'depth' of the friend function, which is used to
3785   // compare whether a declaration reference is referring to a containing
3786   // template, or just the current friend function. A 'lower' TemplateDepth in
3787   // the AST refers to a 'containing' template. As the constraint is
3788   // uninstantiated, this is relative to the 'top' of the TU.
3789   bool
3790   ConstraintExpressionDependsOnEnclosingTemplate(const FunctionDecl *Friend,
3791                                                  unsigned TemplateDepth,
3792                                                  const Expr *Constraint);
3793 
3794   // Calculates whether the friend function depends on an enclosing template for
3795   // the purposes of [temp.friend] p9.
3796   bool FriendConstraintsDependOnEnclosingTemplate(const FunctionDecl *FD);
3797 
3798   // Calculates whether two constraint expressions are equal irrespective of a
3799   // difference in 'depth'. This takes a pair of optional 'NamedDecl's 'Old' and
3800   // 'New', which are the "source" of the constraint, since this is necessary
3801   // for figuring out the relative 'depth' of the constraint. The depth of the
3802   // 'primary template' and the 'instantiated from' templates aren't necessarily
3803   // the same, such as a case when one is a 'friend' defined in a class.
3804   bool AreConstraintExpressionsEqual(const NamedDecl *Old,
3805                                      const Expr *OldConstr,
3806                                      const NamedDecl *New,
3807                                      const Expr *NewConstr);
3808 
3809   enum class AllowedExplicit {
3810     /// Allow no explicit functions to be used.
3811     None,
3812     /// Allow explicit conversion functions but not explicit constructors.
3813     Conversions,
3814     /// Allow both explicit conversion functions and explicit constructors.
3815     All
3816   };
3817 
3818   ImplicitConversionSequence
3819   TryImplicitConversion(Expr *From, QualType ToType,
3820                         bool SuppressUserConversions,
3821                         AllowedExplicit AllowExplicit,
3822                         bool InOverloadResolution,
3823                         bool CStyle,
3824                         bool AllowObjCWritebackConversion);
3825 
3826   bool IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType);
3827   bool IsFloatingPointPromotion(QualType FromType, QualType ToType);
3828   bool IsComplexPromotion(QualType FromType, QualType ToType);
3829   bool IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
3830                            bool InOverloadResolution,
3831                            QualType& ConvertedType, bool &IncompatibleObjC);
3832   bool isObjCPointerConversion(QualType FromType, QualType ToType,
3833                                QualType& ConvertedType, bool &IncompatibleObjC);
3834   bool isObjCWritebackConversion(QualType FromType, QualType ToType,
3835                                  QualType &ConvertedType);
3836   bool IsBlockPointerConversion(QualType FromType, QualType ToType,
3837                                 QualType& ConvertedType);
3838   bool FunctionParamTypesAreEqual(const FunctionProtoType *OldType,
3839                                   const FunctionProtoType *NewType,
3840                                   unsigned *ArgPos = nullptr,
3841                                   bool Reversed = false);
3842   void HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
3843                                   QualType FromType, QualType ToType);
3844 
3845   void maybeExtendBlockObject(ExprResult &E);
3846   CastKind PrepareCastToObjCObjectPointer(ExprResult &E);
3847   bool CheckPointerConversion(Expr *From, QualType ToType,
3848                               CastKind &Kind,
3849                               CXXCastPath& BasePath,
3850                               bool IgnoreBaseAccess,
3851                               bool Diagnose = true);
3852   bool IsMemberPointerConversion(Expr *From, QualType FromType, QualType ToType,
3853                                  bool InOverloadResolution,
3854                                  QualType &ConvertedType);
3855   bool CheckMemberPointerConversion(Expr *From, QualType ToType,
3856                                     CastKind &Kind,
3857                                     CXXCastPath &BasePath,
3858                                     bool IgnoreBaseAccess);
3859   bool IsQualificationConversion(QualType FromType, QualType ToType,
3860                                  bool CStyle, bool &ObjCLifetimeConversion);
3861   bool IsFunctionConversion(QualType FromType, QualType ToType,
3862                             QualType &ResultTy);
3863   bool DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType);
3864   bool isSameOrCompatibleFunctionType(QualType Param, QualType Arg);
3865 
3866   bool CanPerformAggregateInitializationForOverloadResolution(
3867       const InitializedEntity &Entity, InitListExpr *From);
3868 
3869   bool IsStringInit(Expr *Init, const ArrayType *AT);
3870 
3871   bool CanPerformCopyInitialization(const InitializedEntity &Entity,
3872                                     ExprResult Init);
3873   ExprResult PerformCopyInitialization(const InitializedEntity &Entity,
3874                                        SourceLocation EqualLoc,
3875                                        ExprResult Init,
3876                                        bool TopLevelOfInitList = false,
3877                                        bool AllowExplicit = false);
3878   ExprResult PerformObjectArgumentInitialization(Expr *From,
3879                                                  NestedNameSpecifier *Qualifier,
3880                                                  NamedDecl *FoundDecl,
3881                                                  CXXMethodDecl *Method);
3882 
3883   /// Check that the lifetime of the initializer (and its subobjects) is
3884   /// sufficient for initializing the entity, and perform lifetime extension
3885   /// (when permitted) if not.
3886   void checkInitializerLifetime(const InitializedEntity &Entity, Expr *Init);
3887 
3888   ExprResult PerformContextuallyConvertToBool(Expr *From);
3889   ExprResult PerformContextuallyConvertToObjCPointer(Expr *From);
3890 
3891   /// Contexts in which a converted constant expression is required.
3892   enum CCEKind {
3893     CCEK_CaseValue,    ///< Expression in a case label.
3894     CCEK_Enumerator,   ///< Enumerator value with fixed underlying type.
3895     CCEK_TemplateArg,  ///< Value of a non-type template parameter.
3896     CCEK_ArrayBound,   ///< Array bound in array declarator or new-expression.
3897     CCEK_ExplicitBool, ///< Condition in an explicit(bool) specifier.
3898     CCEK_Noexcept,     ///< Condition in a noexcept(bool) specifier.
3899     CCEK_StaticAssertMessageSize, ///< Call to size() in a static assert
3900                                   ///< message.
3901     CCEK_StaticAssertMessageData, ///< Call to data() in a static assert
3902                                   ///< message.
3903   };
3904 
3905   ExprResult BuildConvertedConstantExpression(Expr *From, QualType T,
3906                                               CCEKind CCE,
3907                                               NamedDecl *Dest = nullptr);
3908 
3909   ExprResult CheckConvertedConstantExpression(Expr *From, QualType T,
3910                                               llvm::APSInt &Value, CCEKind CCE);
3911   ExprResult CheckConvertedConstantExpression(Expr *From, QualType T,
3912                                               APValue &Value, CCEKind CCE,
3913                                               NamedDecl *Dest = nullptr);
3914 
3915   /// Abstract base class used to perform a contextual implicit
3916   /// conversion from an expression to any type passing a filter.
3917   class ContextualImplicitConverter {
3918   public:
3919     bool Suppress;
3920     bool SuppressConversion;
3921 
3922     ContextualImplicitConverter(bool Suppress = false,
3923                                 bool SuppressConversion = false)
3924         : Suppress(Suppress), SuppressConversion(SuppressConversion) {}
3925 
3926     /// Determine whether the specified type is a valid destination type
3927     /// for this conversion.
3928     virtual bool match(QualType T) = 0;
3929 
3930     /// Emits a diagnostic complaining that the expression does not have
3931     /// integral or enumeration type.
3932     virtual SemaDiagnosticBuilder
3933     diagnoseNoMatch(Sema &S, SourceLocation Loc, QualType T) = 0;
3934 
3935     /// Emits a diagnostic when the expression has incomplete class type.
3936     virtual SemaDiagnosticBuilder
3937     diagnoseIncomplete(Sema &S, SourceLocation Loc, QualType T) = 0;
3938 
3939     /// Emits a diagnostic when the only matching conversion function
3940     /// is explicit.
3941     virtual SemaDiagnosticBuilder diagnoseExplicitConv(
3942         Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) = 0;
3943 
3944     /// Emits a note for the explicit conversion function.
3945     virtual SemaDiagnosticBuilder
3946     noteExplicitConv(Sema &S, CXXConversionDecl *Conv, QualType ConvTy) = 0;
3947 
3948     /// Emits a diagnostic when there are multiple possible conversion
3949     /// functions.
3950     virtual SemaDiagnosticBuilder
3951     diagnoseAmbiguous(Sema &S, SourceLocation Loc, QualType T) = 0;
3952 
3953     /// Emits a note for one of the candidate conversions.
3954     virtual SemaDiagnosticBuilder
3955     noteAmbiguous(Sema &S, CXXConversionDecl *Conv, QualType ConvTy) = 0;
3956 
3957     /// Emits a diagnostic when we picked a conversion function
3958     /// (for cases when we are not allowed to pick a conversion function).
3959     virtual SemaDiagnosticBuilder diagnoseConversion(
3960         Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) = 0;
3961 
3962     virtual ~ContextualImplicitConverter() {}
3963   };
3964 
3965   class ICEConvertDiagnoser : public ContextualImplicitConverter {
3966     bool AllowScopedEnumerations;
3967 
3968   public:
3969     ICEConvertDiagnoser(bool AllowScopedEnumerations,
3970                         bool Suppress, bool SuppressConversion)
3971         : ContextualImplicitConverter(Suppress, SuppressConversion),
3972           AllowScopedEnumerations(AllowScopedEnumerations) {}
3973 
3974     /// Match an integral or (possibly scoped) enumeration type.
3975     bool match(QualType T) override;
3976 
3977     SemaDiagnosticBuilder
3978     diagnoseNoMatch(Sema &S, SourceLocation Loc, QualType T) override {
3979       return diagnoseNotInt(S, Loc, T);
3980     }
3981 
3982     /// Emits a diagnostic complaining that the expression does not have
3983     /// integral or enumeration type.
3984     virtual SemaDiagnosticBuilder
3985     diagnoseNotInt(Sema &S, SourceLocation Loc, QualType T) = 0;
3986   };
3987 
3988   /// Perform a contextual implicit conversion.
3989   ExprResult PerformContextualImplicitConversion(
3990       SourceLocation Loc, Expr *FromE, ContextualImplicitConverter &Converter);
3991 
3992 
3993   enum ObjCSubscriptKind {
3994     OS_Array,
3995     OS_Dictionary,
3996     OS_Error
3997   };
3998   ObjCSubscriptKind CheckSubscriptingKind(Expr *FromE);
3999 
4000   // Note that LK_String is intentionally after the other literals, as
4001   // this is used for diagnostics logic.
4002   enum ObjCLiteralKind {
4003     LK_Array,
4004     LK_Dictionary,
4005     LK_Numeric,
4006     LK_Boxed,
4007     LK_String,
4008     LK_Block,
4009     LK_None
4010   };
4011   ObjCLiteralKind CheckLiteralKind(Expr *FromE);
4012 
4013   ExprResult PerformObjectMemberConversion(Expr *From,
4014                                            NestedNameSpecifier *Qualifier,
4015                                            NamedDecl *FoundDecl,
4016                                            NamedDecl *Member);
4017 
4018   // Members have to be NamespaceDecl* or TranslationUnitDecl*.
4019   // TODO: make this is a typesafe union.
4020   typedef llvm::SmallSetVector<DeclContext   *, 16> AssociatedNamespaceSet;
4021   typedef llvm::SmallSetVector<CXXRecordDecl *, 16> AssociatedClassSet;
4022 
4023   using ADLCallKind = CallExpr::ADLCallKind;
4024 
4025   void AddOverloadCandidate(
4026       FunctionDecl *Function, DeclAccessPair FoundDecl, ArrayRef<Expr *> Args,
4027       OverloadCandidateSet &CandidateSet, bool SuppressUserConversions = false,
4028       bool PartialOverloading = false, bool AllowExplicit = true,
4029       bool AllowExplicitConversion = false,
4030       ADLCallKind IsADLCandidate = ADLCallKind::NotADL,
4031       ConversionSequenceList EarlyConversions = std::nullopt,
4032       OverloadCandidateParamOrder PO = {},
4033       bool AggregateCandidateDeduction = false);
4034   void AddFunctionCandidates(const UnresolvedSetImpl &Functions,
4035                       ArrayRef<Expr *> Args,
4036                       OverloadCandidateSet &CandidateSet,
4037                       TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr,
4038                       bool SuppressUserConversions = false,
4039                       bool PartialOverloading = false,
4040                       bool FirstArgumentIsBase = false);
4041   void AddMethodCandidate(DeclAccessPair FoundDecl,
4042                           QualType ObjectType,
4043                           Expr::Classification ObjectClassification,
4044                           ArrayRef<Expr *> Args,
4045                           OverloadCandidateSet& CandidateSet,
4046                           bool SuppressUserConversion = false,
4047                           OverloadCandidateParamOrder PO = {});
4048   void
4049   AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
4050                      CXXRecordDecl *ActingContext, QualType ObjectType,
4051                      Expr::Classification ObjectClassification,
4052                      ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet,
4053                      bool SuppressUserConversions = false,
4054                      bool PartialOverloading = false,
4055                      ConversionSequenceList EarlyConversions = std::nullopt,
4056                      OverloadCandidateParamOrder PO = {});
4057   void AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
4058                                   DeclAccessPair FoundDecl,
4059                                   CXXRecordDecl *ActingContext,
4060                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
4061                                   QualType ObjectType,
4062                                   Expr::Classification ObjectClassification,
4063                                   ArrayRef<Expr *> Args,
4064                                   OverloadCandidateSet& CandidateSet,
4065                                   bool SuppressUserConversions = false,
4066                                   bool PartialOverloading = false,
4067                                   OverloadCandidateParamOrder PO = {});
4068   void AddTemplateOverloadCandidate(
4069       FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
4070       TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
4071       OverloadCandidateSet &CandidateSet, bool SuppressUserConversions = false,
4072       bool PartialOverloading = false, bool AllowExplicit = true,
4073       ADLCallKind IsADLCandidate = ADLCallKind::NotADL,
4074       OverloadCandidateParamOrder PO = {},
4075       bool AggregateCandidateDeduction = false);
4076   bool CheckNonDependentConversions(
4077       FunctionTemplateDecl *FunctionTemplate, ArrayRef<QualType> ParamTypes,
4078       ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet,
4079       ConversionSequenceList &Conversions, bool SuppressUserConversions,
4080       CXXRecordDecl *ActingContext = nullptr, QualType ObjectType = QualType(),
4081       Expr::Classification ObjectClassification = {},
4082       OverloadCandidateParamOrder PO = {});
4083   void AddConversionCandidate(
4084       CXXConversionDecl *Conversion, DeclAccessPair FoundDecl,
4085       CXXRecordDecl *ActingContext, Expr *From, QualType ToType,
4086       OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
4087       bool AllowExplicit, bool AllowResultConversion = true);
4088   void AddTemplateConversionCandidate(
4089       FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
4090       CXXRecordDecl *ActingContext, Expr *From, QualType ToType,
4091       OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
4092       bool AllowExplicit, bool AllowResultConversion = true);
4093   void AddSurrogateCandidate(CXXConversionDecl *Conversion,
4094                              DeclAccessPair FoundDecl,
4095                              CXXRecordDecl *ActingContext,
4096                              const FunctionProtoType *Proto,
4097                              Expr *Object, ArrayRef<Expr *> Args,
4098                              OverloadCandidateSet& CandidateSet);
4099   void AddNonMemberOperatorCandidates(
4100       const UnresolvedSetImpl &Functions, ArrayRef<Expr *> Args,
4101       OverloadCandidateSet &CandidateSet,
4102       TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr);
4103   void AddMemberOperatorCandidates(OverloadedOperatorKind Op,
4104                                    SourceLocation OpLoc, ArrayRef<Expr *> Args,
4105                                    OverloadCandidateSet &CandidateSet,
4106                                    OverloadCandidateParamOrder PO = {});
4107   void AddBuiltinCandidate(QualType *ParamTys, ArrayRef<Expr *> Args,
4108                            OverloadCandidateSet& CandidateSet,
4109                            bool IsAssignmentOperator = false,
4110                            unsigned NumContextualBoolArguments = 0);
4111   void AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
4112                                     SourceLocation OpLoc, ArrayRef<Expr *> Args,
4113                                     OverloadCandidateSet& CandidateSet);
4114   void AddArgumentDependentLookupCandidates(DeclarationName Name,
4115                                             SourceLocation Loc,
4116                                             ArrayRef<Expr *> Args,
4117                                 TemplateArgumentListInfo *ExplicitTemplateArgs,
4118                                             OverloadCandidateSet& CandidateSet,
4119                                             bool PartialOverloading = false);
4120 
4121   // Emit as a 'note' the specific overload candidate
4122   void NoteOverloadCandidate(
4123       const NamedDecl *Found, const FunctionDecl *Fn,
4124       OverloadCandidateRewriteKind RewriteKind = OverloadCandidateRewriteKind(),
4125       QualType DestType = QualType(), bool TakingAddress = false);
4126 
4127   // Emit as a series of 'note's all template and non-templates identified by
4128   // the expression Expr
4129   void NoteAllOverloadCandidates(Expr *E, QualType DestType = QualType(),
4130                                  bool TakingAddress = false);
4131 
4132   /// Check the enable_if expressions on the given function. Returns the first
4133   /// failing attribute, or NULL if they were all successful.
4134   EnableIfAttr *CheckEnableIf(FunctionDecl *Function, SourceLocation CallLoc,
4135                               ArrayRef<Expr *> Args,
4136                               bool MissingImplicitThis = false);
4137 
4138   /// Find the failed Boolean condition within a given Boolean
4139   /// constant expression, and describe it with a string.
4140   std::pair<Expr *, std::string> findFailedBooleanCondition(Expr *Cond);
4141 
4142   /// Emit diagnostics for the diagnose_if attributes on Function, ignoring any
4143   /// non-ArgDependent DiagnoseIfAttrs.
4144   ///
4145   /// Argument-dependent diagnose_if attributes should be checked each time a
4146   /// function is used as a direct callee of a function call.
4147   ///
4148   /// Returns true if any errors were emitted.
4149   bool diagnoseArgDependentDiagnoseIfAttrs(const FunctionDecl *Function,
4150                                            const Expr *ThisArg,
4151                                            ArrayRef<const Expr *> Args,
4152                                            SourceLocation Loc);
4153 
4154   /// Emit diagnostics for the diagnose_if attributes on Function, ignoring any
4155   /// ArgDependent DiagnoseIfAttrs.
4156   ///
4157   /// Argument-independent diagnose_if attributes should be checked on every use
4158   /// of a function.
4159   ///
4160   /// Returns true if any errors were emitted.
4161   bool diagnoseArgIndependentDiagnoseIfAttrs(const NamedDecl *ND,
4162                                              SourceLocation Loc);
4163 
4164   /// Returns whether the given function's address can be taken or not,
4165   /// optionally emitting a diagnostic if the address can't be taken.
4166   ///
4167   /// Returns false if taking the address of the function is illegal.
4168   bool checkAddressOfFunctionIsAvailable(const FunctionDecl *Function,
4169                                          bool Complain = false,
4170                                          SourceLocation Loc = SourceLocation());
4171 
4172   // [PossiblyAFunctionType]  -->   [Return]
4173   // NonFunctionType --> NonFunctionType
4174   // R (A) --> R(A)
4175   // R (*)(A) --> R (A)
4176   // R (&)(A) --> R (A)
4177   // R (S::*)(A) --> R (A)
4178   QualType ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType);
4179 
4180   FunctionDecl *
4181   ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
4182                                      QualType TargetType,
4183                                      bool Complain,
4184                                      DeclAccessPair &Found,
4185                                      bool *pHadMultipleCandidates = nullptr);
4186 
4187   FunctionDecl *
4188   resolveAddressOfSingleOverloadCandidate(Expr *E, DeclAccessPair &FoundResult);
4189 
4190   bool resolveAndFixAddressOfSingleOverloadCandidate(
4191       ExprResult &SrcExpr, bool DoFunctionPointerConversion = false);
4192 
4193   FunctionDecl *ResolveSingleFunctionTemplateSpecialization(
4194       OverloadExpr *ovl, bool Complain = false, DeclAccessPair *Found = nullptr,
4195       TemplateSpecCandidateSet *FailedTSC = nullptr);
4196 
4197   bool ResolveAndFixSingleFunctionTemplateSpecialization(
4198       ExprResult &SrcExpr, bool DoFunctionPointerConversion = false,
4199       bool Complain = false, SourceRange OpRangeForComplaining = SourceRange(),
4200       QualType DestTypeForComplaining = QualType(),
4201       unsigned DiagIDForComplaining = 0);
4202 
4203   Expr *FixOverloadedFunctionReference(Expr *E,
4204                                        DeclAccessPair FoundDecl,
4205                                        FunctionDecl *Fn);
4206   ExprResult FixOverloadedFunctionReference(ExprResult,
4207                                             DeclAccessPair FoundDecl,
4208                                             FunctionDecl *Fn);
4209 
4210   void AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
4211                                    ArrayRef<Expr *> Args,
4212                                    OverloadCandidateSet &CandidateSet,
4213                                    bool PartialOverloading = false);
4214   void AddOverloadedCallCandidates(
4215       LookupResult &R, TemplateArgumentListInfo *ExplicitTemplateArgs,
4216       ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet);
4217 
4218   // An enum used to represent the different possible results of building a
4219   // range-based for loop.
4220   enum ForRangeStatus {
4221     FRS_Success,
4222     FRS_NoViableFunction,
4223     FRS_DiagnosticIssued
4224   };
4225 
4226   ForRangeStatus BuildForRangeBeginEndCall(SourceLocation Loc,
4227                                            SourceLocation RangeLoc,
4228                                            const DeclarationNameInfo &NameInfo,
4229                                            LookupResult &MemberLookup,
4230                                            OverloadCandidateSet *CandidateSet,
4231                                            Expr *Range, ExprResult *CallExpr);
4232 
4233   ExprResult BuildOverloadedCallExpr(Scope *S, Expr *Fn,
4234                                      UnresolvedLookupExpr *ULE,
4235                                      SourceLocation LParenLoc,
4236                                      MultiExprArg Args,
4237                                      SourceLocation RParenLoc,
4238                                      Expr *ExecConfig,
4239                                      bool AllowTypoCorrection=true,
4240                                      bool CalleesAddressIsTaken=false);
4241 
4242   bool buildOverloadedCallSet(Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE,
4243                               MultiExprArg Args, SourceLocation RParenLoc,
4244                               OverloadCandidateSet *CandidateSet,
4245                               ExprResult *Result);
4246 
4247   ExprResult CreateUnresolvedLookupExpr(CXXRecordDecl *NamingClass,
4248                                         NestedNameSpecifierLoc NNSLoc,
4249                                         DeclarationNameInfo DNI,
4250                                         const UnresolvedSetImpl &Fns,
4251                                         bool PerformADL = true);
4252 
4253   ExprResult CreateOverloadedUnaryOp(SourceLocation OpLoc,
4254                                      UnaryOperatorKind Opc,
4255                                      const UnresolvedSetImpl &Fns,
4256                                      Expr *input, bool RequiresADL = true);
4257 
4258   void LookupOverloadedBinOp(OverloadCandidateSet &CandidateSet,
4259                              OverloadedOperatorKind Op,
4260                              const UnresolvedSetImpl &Fns,
4261                              ArrayRef<Expr *> Args, bool RequiresADL = true);
4262   ExprResult CreateOverloadedBinOp(SourceLocation OpLoc,
4263                                    BinaryOperatorKind Opc,
4264                                    const UnresolvedSetImpl &Fns,
4265                                    Expr *LHS, Expr *RHS,
4266                                    bool RequiresADL = true,
4267                                    bool AllowRewrittenCandidates = true,
4268                                    FunctionDecl *DefaultedFn = nullptr);
4269   ExprResult BuildSynthesizedThreeWayComparison(SourceLocation OpLoc,
4270                                                 const UnresolvedSetImpl &Fns,
4271                                                 Expr *LHS, Expr *RHS,
4272                                                 FunctionDecl *DefaultedFn);
4273 
4274   ExprResult CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
4275                                                 SourceLocation RLoc, Expr *Base,
4276                                                 MultiExprArg Args);
4277 
4278   ExprResult BuildCallToMemberFunction(Scope *S, Expr *MemExpr,
4279                                        SourceLocation LParenLoc,
4280                                        MultiExprArg Args,
4281                                        SourceLocation RParenLoc,
4282                                        Expr *ExecConfig = nullptr,
4283                                        bool IsExecConfig = false,
4284                                        bool AllowRecovery = false);
4285   ExprResult
4286   BuildCallToObjectOfClassType(Scope *S, Expr *Object, SourceLocation LParenLoc,
4287                                MultiExprArg Args,
4288                                SourceLocation RParenLoc);
4289 
4290   ExprResult BuildOverloadedArrowExpr(Scope *S, Expr *Base,
4291                                       SourceLocation OpLoc,
4292                                       bool *NoArrowOperatorFound = nullptr);
4293 
4294   /// CheckCallReturnType - Checks that a call expression's return type is
4295   /// complete. Returns true on failure. The location passed in is the location
4296   /// that best represents the call.
4297   bool CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
4298                            CallExpr *CE, FunctionDecl *FD);
4299 
4300   /// Helpers for dealing with blocks and functions.
4301   bool CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters,
4302                                 bool CheckParameterNames);
4303   void CheckCXXDefaultArguments(FunctionDecl *FD);
4304   void CheckExtraCXXDefaultArguments(Declarator &D);
4305   Scope *getNonFieldDeclScope(Scope *S);
4306 
4307   /// \name Name lookup
4308   ///
4309   /// These routines provide name lookup that is used during semantic
4310   /// analysis to resolve the various kinds of names (identifiers,
4311   /// overloaded operator names, constructor names, etc.) into zero or
4312   /// more declarations within a particular scope. The major entry
4313   /// points are LookupName, which performs unqualified name lookup,
4314   /// and LookupQualifiedName, which performs qualified name lookup.
4315   ///
4316   /// All name lookup is performed based on some specific criteria,
4317   /// which specify what names will be visible to name lookup and how
4318   /// far name lookup should work. These criteria are important both
4319   /// for capturing language semantics (certain lookups will ignore
4320   /// certain names, for example) and for performance, since name
4321   /// lookup is often a bottleneck in the compilation of C++. Name
4322   /// lookup criteria is specified via the LookupCriteria enumeration.
4323   ///
4324   /// The results of name lookup can vary based on the kind of name
4325   /// lookup performed, the current language, and the translation
4326   /// unit. In C, for example, name lookup will either return nothing
4327   /// (no entity found) or a single declaration. In C++, name lookup
4328   /// can additionally refer to a set of overloaded functions or
4329   /// result in an ambiguity. All of the possible results of name
4330   /// lookup are captured by the LookupResult class, which provides
4331   /// the ability to distinguish among them.
4332   //@{
4333 
4334   /// Describes the kind of name lookup to perform.
4335   enum LookupNameKind {
4336     /// Ordinary name lookup, which finds ordinary names (functions,
4337     /// variables, typedefs, etc.) in C and most kinds of names
4338     /// (functions, variables, members, types, etc.) in C++.
4339     LookupOrdinaryName = 0,
4340     /// Tag name lookup, which finds the names of enums, classes,
4341     /// structs, and unions.
4342     LookupTagName,
4343     /// Label name lookup.
4344     LookupLabel,
4345     /// Member name lookup, which finds the names of
4346     /// class/struct/union members.
4347     LookupMemberName,
4348     /// Look up of an operator name (e.g., operator+) for use with
4349     /// operator overloading. This lookup is similar to ordinary name
4350     /// lookup, but will ignore any declarations that are class members.
4351     LookupOperatorName,
4352     /// Look up a name following ~ in a destructor name. This is an ordinary
4353     /// lookup, but prefers tags to typedefs.
4354     LookupDestructorName,
4355     /// Look up of a name that precedes the '::' scope resolution
4356     /// operator in C++. This lookup completely ignores operator, object,
4357     /// function, and enumerator names (C++ [basic.lookup.qual]p1).
4358     LookupNestedNameSpecifierName,
4359     /// Look up a namespace name within a C++ using directive or
4360     /// namespace alias definition, ignoring non-namespace names (C++
4361     /// [basic.lookup.udir]p1).
4362     LookupNamespaceName,
4363     /// Look up all declarations in a scope with the given name,
4364     /// including resolved using declarations.  This is appropriate
4365     /// for checking redeclarations for a using declaration.
4366     LookupUsingDeclName,
4367     /// Look up an ordinary name that is going to be redeclared as a
4368     /// name with linkage. This lookup ignores any declarations that
4369     /// are outside of the current scope unless they have linkage. See
4370     /// C99 6.2.2p4-5 and C++ [basic.link]p6.
4371     LookupRedeclarationWithLinkage,
4372     /// Look up a friend of a local class. This lookup does not look
4373     /// outside the innermost non-class scope. See C++11 [class.friend]p11.
4374     LookupLocalFriendName,
4375     /// Look up the name of an Objective-C protocol.
4376     LookupObjCProtocolName,
4377     /// Look up implicit 'self' parameter of an objective-c method.
4378     LookupObjCImplicitSelfParam,
4379     /// Look up the name of an OpenMP user-defined reduction operation.
4380     LookupOMPReductionName,
4381     /// Look up the name of an OpenMP user-defined mapper.
4382     LookupOMPMapperName,
4383     /// Look up any declaration with any name.
4384     LookupAnyName
4385   };
4386 
4387   /// Specifies whether (or how) name lookup is being performed for a
4388   /// redeclaration (vs. a reference).
4389   enum RedeclarationKind {
4390     /// The lookup is a reference to this name that is not for the
4391     /// purpose of redeclaring the name.
4392     NotForRedeclaration = 0,
4393     /// The lookup results will be used for redeclaration of a name,
4394     /// if an entity by that name already exists and is visible.
4395     ForVisibleRedeclaration,
4396     /// The lookup results will be used for redeclaration of a name
4397     /// with external linkage; non-visible lookup results with external linkage
4398     /// may also be found.
4399     ForExternalRedeclaration
4400   };
4401 
4402   RedeclarationKind forRedeclarationInCurContext() const {
4403     // A declaration with an owning module for linkage can never link against
4404     // anything that is not visible. We don't need to check linkage here; if
4405     // the context has internal linkage, redeclaration lookup won't find things
4406     // from other TUs, and we can't safely compute linkage yet in general.
4407     if (cast<Decl>(CurContext)
4408             ->getOwningModuleForLinkage(/*IgnoreLinkage*/true))
4409       return ForVisibleRedeclaration;
4410     return ForExternalRedeclaration;
4411   }
4412 
4413   /// The possible outcomes of name lookup for a literal operator.
4414   enum LiteralOperatorLookupResult {
4415     /// The lookup resulted in an error.
4416     LOLR_Error,
4417     /// The lookup found no match but no diagnostic was issued.
4418     LOLR_ErrorNoDiagnostic,
4419     /// The lookup found a single 'cooked' literal operator, which
4420     /// expects a normal literal to be built and passed to it.
4421     LOLR_Cooked,
4422     /// The lookup found a single 'raw' literal operator, which expects
4423     /// a string literal containing the spelling of the literal token.
4424     LOLR_Raw,
4425     /// The lookup found an overload set of literal operator templates,
4426     /// which expect the characters of the spelling of the literal token to be
4427     /// passed as a non-type template argument pack.
4428     LOLR_Template,
4429     /// The lookup found an overload set of literal operator templates,
4430     /// which expect the character type and characters of the spelling of the
4431     /// string literal token to be passed as template arguments.
4432     LOLR_StringTemplatePack,
4433   };
4434 
4435   SpecialMemberOverloadResult LookupSpecialMember(CXXRecordDecl *D,
4436                                                   CXXSpecialMember SM,
4437                                                   bool ConstArg,
4438                                                   bool VolatileArg,
4439                                                   bool RValueThis,
4440                                                   bool ConstThis,
4441                                                   bool VolatileThis);
4442 
4443   typedef std::function<void(const TypoCorrection &)> TypoDiagnosticGenerator;
4444   typedef std::function<ExprResult(Sema &, TypoExpr *, TypoCorrection)>
4445       TypoRecoveryCallback;
4446 
4447 private:
4448   bool CppLookupName(LookupResult &R, Scope *S);
4449 
4450   struct TypoExprState {
4451     std::unique_ptr<TypoCorrectionConsumer> Consumer;
4452     TypoDiagnosticGenerator DiagHandler;
4453     TypoRecoveryCallback RecoveryHandler;
4454     TypoExprState();
4455     TypoExprState(TypoExprState &&other) noexcept;
4456     TypoExprState &operator=(TypoExprState &&other) noexcept;
4457   };
4458 
4459   /// The set of unhandled TypoExprs and their associated state.
4460   llvm::MapVector<TypoExpr *, TypoExprState> DelayedTypos;
4461 
4462   /// Creates a new TypoExpr AST node.
4463   TypoExpr *createDelayedTypo(std::unique_ptr<TypoCorrectionConsumer> TCC,
4464                               TypoDiagnosticGenerator TDG,
4465                               TypoRecoveryCallback TRC, SourceLocation TypoLoc);
4466 
4467   // The set of known/encountered (unique, canonicalized) NamespaceDecls.
4468   //
4469   // The boolean value will be true to indicate that the namespace was loaded
4470   // from an AST/PCH file, or false otherwise.
4471   llvm::MapVector<NamespaceDecl*, bool> KnownNamespaces;
4472 
4473   /// Whether we have already loaded known namespaces from an extenal
4474   /// source.
4475   bool LoadedExternalKnownNamespaces;
4476 
4477   /// Helper for CorrectTypo and CorrectTypoDelayed used to create and
4478   /// populate a new TypoCorrectionConsumer. Returns nullptr if typo correction
4479   /// should be skipped entirely.
4480   std::unique_ptr<TypoCorrectionConsumer>
4481   makeTypoCorrectionConsumer(const DeclarationNameInfo &Typo,
4482                              Sema::LookupNameKind LookupKind, Scope *S,
4483                              CXXScopeSpec *SS,
4484                              CorrectionCandidateCallback &CCC,
4485                              DeclContext *MemberContext, bool EnteringContext,
4486                              const ObjCObjectPointerType *OPT,
4487                              bool ErrorRecovery);
4488 
4489 public:
4490   const TypoExprState &getTypoExprState(TypoExpr *TE) const;
4491 
4492   /// Clears the state of the given TypoExpr.
4493   void clearDelayedTypo(TypoExpr *TE);
4494 
4495   /// Look up a name, looking for a single declaration.  Return
4496   /// null if the results were absent, ambiguous, or overloaded.
4497   ///
4498   /// It is preferable to use the elaborated form and explicitly handle
4499   /// ambiguity and overloaded.
4500   NamedDecl *LookupSingleName(Scope *S, DeclarationName Name,
4501                               SourceLocation Loc,
4502                               LookupNameKind NameKind,
4503                               RedeclarationKind Redecl
4504                                 = NotForRedeclaration);
4505   bool LookupBuiltin(LookupResult &R);
4506   void LookupNecessaryTypesForBuiltin(Scope *S, unsigned ID);
4507   bool LookupName(LookupResult &R, Scope *S, bool AllowBuiltinCreation = false,
4508                   bool ForceNoCPlusPlus = false);
4509   bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
4510                            bool InUnqualifiedLookup = false);
4511   bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
4512                            CXXScopeSpec &SS);
4513   bool LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS,
4514                         bool AllowBuiltinCreation = false,
4515                         bool EnteringContext = false);
4516   ObjCProtocolDecl *LookupProtocol(IdentifierInfo *II, SourceLocation IdLoc,
4517                                    RedeclarationKind Redecl
4518                                      = NotForRedeclaration);
4519   bool LookupInSuper(LookupResult &R, CXXRecordDecl *Class);
4520 
4521   void LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S,
4522                                     UnresolvedSetImpl &Functions);
4523 
4524   LabelDecl *LookupOrCreateLabel(IdentifierInfo *II, SourceLocation IdentLoc,
4525                                  SourceLocation GnuLabelLoc = SourceLocation());
4526 
4527   DeclContextLookupResult LookupConstructors(CXXRecordDecl *Class);
4528   CXXConstructorDecl *LookupDefaultConstructor(CXXRecordDecl *Class);
4529   CXXConstructorDecl *LookupCopyingConstructor(CXXRecordDecl *Class,
4530                                                unsigned Quals);
4531   CXXMethodDecl *LookupCopyingAssignment(CXXRecordDecl *Class, unsigned Quals,
4532                                          bool RValueThis, unsigned ThisQuals);
4533   CXXConstructorDecl *LookupMovingConstructor(CXXRecordDecl *Class,
4534                                               unsigned Quals);
4535   CXXMethodDecl *LookupMovingAssignment(CXXRecordDecl *Class, unsigned Quals,
4536                                         bool RValueThis, unsigned ThisQuals);
4537   CXXDestructorDecl *LookupDestructor(CXXRecordDecl *Class);
4538 
4539   bool checkLiteralOperatorId(const CXXScopeSpec &SS, const UnqualifiedId &Id,
4540                               bool IsUDSuffix);
4541   LiteralOperatorLookupResult
4542   LookupLiteralOperator(Scope *S, LookupResult &R, ArrayRef<QualType> ArgTys,
4543                         bool AllowRaw, bool AllowTemplate,
4544                         bool AllowStringTemplate, bool DiagnoseMissing,
4545                         StringLiteral *StringLit = nullptr);
4546   bool isKnownName(StringRef name);
4547 
4548   /// Status of the function emission on the CUDA/HIP/OpenMP host/device attrs.
4549   enum class FunctionEmissionStatus {
4550     Emitted,
4551     CUDADiscarded,     // Discarded due to CUDA/HIP hostness
4552     OMPDiscarded,      // Discarded due to OpenMP hostness
4553     TemplateDiscarded, // Discarded due to uninstantiated templates
4554     Unknown,
4555   };
4556   FunctionEmissionStatus getEmissionStatus(const FunctionDecl *Decl,
4557                                            bool Final = false);
4558 
4559   // Whether the callee should be ignored in CUDA/HIP/OpenMP host/device check.
4560   bool shouldIgnoreInHostDeviceCheck(FunctionDecl *Callee);
4561 
4562   void ArgumentDependentLookup(DeclarationName Name, SourceLocation Loc,
4563                                ArrayRef<Expr *> Args, ADLResult &Functions);
4564 
4565   void LookupVisibleDecls(Scope *S, LookupNameKind Kind,
4566                           VisibleDeclConsumer &Consumer,
4567                           bool IncludeGlobalScope = true,
4568                           bool LoadExternal = true);
4569   void LookupVisibleDecls(DeclContext *Ctx, LookupNameKind Kind,
4570                           VisibleDeclConsumer &Consumer,
4571                           bool IncludeGlobalScope = true,
4572                           bool IncludeDependentBases = false,
4573                           bool LoadExternal = true);
4574 
4575   enum CorrectTypoKind {
4576     CTK_NonError,     // CorrectTypo used in a non error recovery situation.
4577     CTK_ErrorRecovery // CorrectTypo used in normal error recovery.
4578   };
4579 
4580   TypoCorrection CorrectTypo(const DeclarationNameInfo &Typo,
4581                              Sema::LookupNameKind LookupKind,
4582                              Scope *S, CXXScopeSpec *SS,
4583                              CorrectionCandidateCallback &CCC,
4584                              CorrectTypoKind Mode,
4585                              DeclContext *MemberContext = nullptr,
4586                              bool EnteringContext = false,
4587                              const ObjCObjectPointerType *OPT = nullptr,
4588                              bool RecordFailure = true);
4589 
4590   TypoExpr *CorrectTypoDelayed(const DeclarationNameInfo &Typo,
4591                                Sema::LookupNameKind LookupKind, Scope *S,
4592                                CXXScopeSpec *SS,
4593                                CorrectionCandidateCallback &CCC,
4594                                TypoDiagnosticGenerator TDG,
4595                                TypoRecoveryCallback TRC, CorrectTypoKind Mode,
4596                                DeclContext *MemberContext = nullptr,
4597                                bool EnteringContext = false,
4598                                const ObjCObjectPointerType *OPT = nullptr);
4599 
4600   /// Process any TypoExprs in the given Expr and its children,
4601   /// generating diagnostics as appropriate and returning a new Expr if there
4602   /// were typos that were all successfully corrected and ExprError if one or
4603   /// more typos could not be corrected.
4604   ///
4605   /// \param E The Expr to check for TypoExprs.
4606   ///
4607   /// \param InitDecl A VarDecl to avoid because the Expr being corrected is its
4608   /// initializer.
4609   ///
4610   /// \param RecoverUncorrectedTypos If true, when typo correction fails, it
4611   /// will rebuild the given Expr with all TypoExprs degraded to RecoveryExprs.
4612   ///
4613   /// \param Filter A function applied to a newly rebuilt Expr to determine if
4614   /// it is an acceptable/usable result from a single combination of typo
4615   /// corrections. As long as the filter returns ExprError, different
4616   /// combinations of corrections will be tried until all are exhausted.
4617   ExprResult CorrectDelayedTyposInExpr(
4618       Expr *E, VarDecl *InitDecl = nullptr,
4619       bool RecoverUncorrectedTypos = false,
4620       llvm::function_ref<ExprResult(Expr *)> Filter =
4621           [](Expr *E) -> ExprResult { return E; });
4622 
4623   ExprResult CorrectDelayedTyposInExpr(
4624       ExprResult ER, VarDecl *InitDecl = nullptr,
4625       bool RecoverUncorrectedTypos = false,
4626       llvm::function_ref<ExprResult(Expr *)> Filter =
4627           [](Expr *E) -> ExprResult { return E; }) {
4628     return ER.isInvalid()
4629                ? ER
4630                : CorrectDelayedTyposInExpr(ER.get(), InitDecl,
4631                                            RecoverUncorrectedTypos, Filter);
4632   }
4633 
4634   void diagnoseTypo(const TypoCorrection &Correction,
4635                     const PartialDiagnostic &TypoDiag,
4636                     bool ErrorRecovery = true);
4637 
4638   void diagnoseTypo(const TypoCorrection &Correction,
4639                     const PartialDiagnostic &TypoDiag,
4640                     const PartialDiagnostic &PrevNote,
4641                     bool ErrorRecovery = true);
4642 
4643   void MarkTypoCorrectedFunctionDefinition(const NamedDecl *F);
4644 
4645   void FindAssociatedClassesAndNamespaces(SourceLocation InstantiationLoc,
4646                                           ArrayRef<Expr *> Args,
4647                                    AssociatedNamespaceSet &AssociatedNamespaces,
4648                                    AssociatedClassSet &AssociatedClasses);
4649 
4650   void FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S,
4651                             bool ConsiderLinkage, bool AllowInlineNamespace);
4652 
4653   bool CheckRedeclarationModuleOwnership(NamedDecl *New, NamedDecl *Old);
4654   bool CheckRedeclarationExported(NamedDecl *New, NamedDecl *Old);
4655   bool CheckRedeclarationInModule(NamedDecl *New, NamedDecl *Old);
4656   bool IsRedefinitionInModule(const NamedDecl *New,
4657                                  const NamedDecl *Old) const;
4658 
4659   void DiagnoseAmbiguousLookup(LookupResult &Result);
4660   //@}
4661 
4662   /// Attempts to produce a RecoveryExpr after some AST node cannot be created.
4663   ExprResult CreateRecoveryExpr(SourceLocation Begin, SourceLocation End,
4664                                 ArrayRef<Expr *> SubExprs,
4665                                 QualType T = QualType());
4666 
4667   ObjCInterfaceDecl *getObjCInterfaceDecl(IdentifierInfo *&Id,
4668                                           SourceLocation IdLoc,
4669                                           bool TypoCorrection = false);
4670   FunctionDecl *CreateBuiltin(IdentifierInfo *II, QualType Type, unsigned ID,
4671                               SourceLocation Loc);
4672   NamedDecl *LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID,
4673                                  Scope *S, bool ForRedeclaration,
4674                                  SourceLocation Loc);
4675   NamedDecl *ImplicitlyDefineFunction(SourceLocation Loc, IdentifierInfo &II,
4676                                       Scope *S);
4677   void AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(
4678       FunctionDecl *FD);
4679   void AddKnownFunctionAttributes(FunctionDecl *FD);
4680 
4681   // More parsing and symbol table subroutines.
4682 
4683   void ProcessPragmaWeak(Scope *S, Decl *D);
4684   // Decl attributes - this routine is the top level dispatcher.
4685   void ProcessDeclAttributes(Scope *S, Decl *D, const Declarator &PD);
4686   // Helper for delayed processing of attributes.
4687   void ProcessDeclAttributeDelayed(Decl *D,
4688                                    const ParsedAttributesView &AttrList);
4689 
4690   // Options for ProcessDeclAttributeList().
4691   struct ProcessDeclAttributeOptions {
4692     ProcessDeclAttributeOptions()
4693         : IncludeCXX11Attributes(true), IgnoreTypeAttributes(false) {}
4694 
4695     ProcessDeclAttributeOptions WithIncludeCXX11Attributes(bool Val) {
4696       ProcessDeclAttributeOptions Result = *this;
4697       Result.IncludeCXX11Attributes = Val;
4698       return Result;
4699     }
4700 
4701     ProcessDeclAttributeOptions WithIgnoreTypeAttributes(bool Val) {
4702       ProcessDeclAttributeOptions Result = *this;
4703       Result.IgnoreTypeAttributes = Val;
4704       return Result;
4705     }
4706 
4707     // Should C++11 attributes be processed?
4708     bool IncludeCXX11Attributes;
4709 
4710     // Should any type attributes encountered be ignored?
4711     // If this option is false, a diagnostic will be emitted for any type
4712     // attributes of a kind that does not "slide" from the declaration to
4713     // the decl-specifier-seq.
4714     bool IgnoreTypeAttributes;
4715   };
4716 
4717   void ProcessDeclAttributeList(Scope *S, Decl *D,
4718                                 const ParsedAttributesView &AttrList,
4719                                 const ProcessDeclAttributeOptions &Options =
4720                                     ProcessDeclAttributeOptions());
4721   bool ProcessAccessDeclAttributeList(AccessSpecDecl *ASDecl,
4722                                    const ParsedAttributesView &AttrList);
4723 
4724   void checkUnusedDeclAttributes(Declarator &D);
4725 
4726   /// Handles semantic checking for features that are common to all attributes,
4727   /// such as checking whether a parameter was properly specified, or the
4728   /// correct number of arguments were passed, etc. Returns true if the
4729   /// attribute has been diagnosed.
4730   bool checkCommonAttributeFeatures(const Decl *D, const ParsedAttr &A,
4731                                     bool SkipArgCountCheck = false);
4732   bool checkCommonAttributeFeatures(const Stmt *S, const ParsedAttr &A,
4733                                     bool SkipArgCountCheck = false);
4734 
4735   /// Determine if type T is a valid subject for a nonnull and similar
4736   /// attributes. By default, we look through references (the behavior used by
4737   /// nonnull), but if the second parameter is true, then we treat a reference
4738   /// type as valid.
4739   bool isValidPointerAttrType(QualType T, bool RefOkay = false);
4740 
4741   bool CheckRegparmAttr(const ParsedAttr &attr, unsigned &value);
4742   bool CheckCallingConvAttr(const ParsedAttr &attr, CallingConv &CC,
4743                             const FunctionDecl *FD = nullptr);
4744   bool CheckAttrTarget(const ParsedAttr &CurrAttr);
4745   bool CheckAttrNoArgs(const ParsedAttr &CurrAttr);
4746   bool checkStringLiteralArgumentAttr(const AttributeCommonInfo &CI,
4747                                       const Expr *E, StringRef &Str,
4748                                       SourceLocation *ArgLocation = nullptr);
4749   bool checkStringLiteralArgumentAttr(const ParsedAttr &Attr, unsigned ArgNum,
4750                                       StringRef &Str,
4751                                       SourceLocation *ArgLocation = nullptr);
4752   llvm::Error isValidSectionSpecifier(StringRef Str);
4753   bool checkSectionName(SourceLocation LiteralLoc, StringRef Str);
4754   bool checkTargetAttr(SourceLocation LiteralLoc, StringRef Str);
4755   bool checkTargetVersionAttr(SourceLocation LiteralLoc, StringRef &Str,
4756                               bool &isDefault);
4757   bool
4758   checkTargetClonesAttrString(SourceLocation LiteralLoc, StringRef Str,
4759                               const StringLiteral *Literal, bool &HasDefault,
4760                               bool &HasCommas, bool &HasNotDefault,
4761                               SmallVectorImpl<SmallString<64>> &StringsBuffer);
4762   bool checkMSInheritanceAttrOnDefinition(
4763       CXXRecordDecl *RD, SourceRange Range, bool BestCase,
4764       MSInheritanceModel SemanticSpelling);
4765 
4766   void CheckAlignasUnderalignment(Decl *D);
4767 
4768   bool CheckNoInlineAttr(const Stmt *OrigSt, const Stmt *CurSt,
4769                          const AttributeCommonInfo &A);
4770   bool CheckAlwaysInlineAttr(const Stmt *OrigSt, const Stmt *CurSt,
4771                              const AttributeCommonInfo &A);
4772 
4773   /// Adjust the calling convention of a method to be the ABI default if it
4774   /// wasn't specified explicitly.  This handles method types formed from
4775   /// function type typedefs and typename template arguments.
4776   void adjustMemberFunctionCC(QualType &T, bool IsStatic, bool IsCtorOrDtor,
4777                               SourceLocation Loc);
4778 
4779   // Check if there is an explicit attribute, but only look through parens.
4780   // The intent is to look for an attribute on the current declarator, but not
4781   // one that came from a typedef.
4782   bool hasExplicitCallingConv(QualType T);
4783 
4784   /// Get the outermost AttributedType node that sets a calling convention.
4785   /// Valid types should not have multiple attributes with different CCs.
4786   const AttributedType *getCallingConvAttributedType(QualType T) const;
4787 
4788   /// Process the attributes before creating an attributed statement. Returns
4789   /// the semantic attributes that have been processed.
4790   void ProcessStmtAttributes(Stmt *Stmt, const ParsedAttributes &InAttrs,
4791                              SmallVectorImpl<const Attr *> &OutAttrs);
4792 
4793   void WarnConflictingTypedMethods(ObjCMethodDecl *Method,
4794                                    ObjCMethodDecl *MethodDecl,
4795                                    bool IsProtocolMethodDecl);
4796 
4797   void CheckConflictingOverridingMethod(ObjCMethodDecl *Method,
4798                                    ObjCMethodDecl *Overridden,
4799                                    bool IsProtocolMethodDecl);
4800 
4801   /// WarnExactTypedMethods - This routine issues a warning if method
4802   /// implementation declaration matches exactly that of its declaration.
4803   void WarnExactTypedMethods(ObjCMethodDecl *Method,
4804                              ObjCMethodDecl *MethodDecl,
4805                              bool IsProtocolMethodDecl);
4806 
4807   typedef llvm::SmallPtrSet<Selector, 8> SelectorSet;
4808 
4809   /// CheckImplementationIvars - This routine checks if the instance variables
4810   /// listed in the implelementation match those listed in the interface.
4811   void CheckImplementationIvars(ObjCImplementationDecl *ImpDecl,
4812                                 ObjCIvarDecl **Fields, unsigned nIvars,
4813                                 SourceLocation Loc);
4814 
4815   /// ImplMethodsVsClassMethods - This is main routine to warn if any method
4816   /// remains unimplemented in the class or category \@implementation.
4817   void ImplMethodsVsClassMethods(Scope *S, ObjCImplDecl* IMPDecl,
4818                                  ObjCContainerDecl* IDecl,
4819                                  bool IncompleteImpl = false);
4820 
4821   /// DiagnoseUnimplementedProperties - This routine warns on those properties
4822   /// which must be implemented by this implementation.
4823   void DiagnoseUnimplementedProperties(Scope *S, ObjCImplDecl* IMPDecl,
4824                                        ObjCContainerDecl *CDecl,
4825                                        bool SynthesizeProperties);
4826 
4827   /// Diagnose any null-resettable synthesized setters.
4828   void diagnoseNullResettableSynthesizedSetters(const ObjCImplDecl *impDecl);
4829 
4830   /// DefaultSynthesizeProperties - This routine default synthesizes all
4831   /// properties which must be synthesized in the class's \@implementation.
4832   void DefaultSynthesizeProperties(Scope *S, ObjCImplDecl *IMPDecl,
4833                                    ObjCInterfaceDecl *IDecl,
4834                                    SourceLocation AtEnd);
4835   void DefaultSynthesizeProperties(Scope *S, Decl *D, SourceLocation AtEnd);
4836 
4837   /// IvarBacksCurrentMethodAccessor - This routine returns 'true' if 'IV' is
4838   /// an ivar synthesized for 'Method' and 'Method' is a property accessor
4839   /// declared in class 'IFace'.
4840   bool IvarBacksCurrentMethodAccessor(ObjCInterfaceDecl *IFace,
4841                                       ObjCMethodDecl *Method, ObjCIvarDecl *IV);
4842 
4843   /// DiagnoseUnusedBackingIvarInAccessor - Issue an 'unused' warning if ivar which
4844   /// backs the property is not used in the property's accessor.
4845   void DiagnoseUnusedBackingIvarInAccessor(Scope *S,
4846                                            const ObjCImplementationDecl *ImplD);
4847 
4848   /// GetIvarBackingPropertyAccessor - If method is a property setter/getter and
4849   /// it property has a backing ivar, returns this ivar; otherwise, returns NULL.
4850   /// It also returns ivar's property on success.
4851   ObjCIvarDecl *GetIvarBackingPropertyAccessor(const ObjCMethodDecl *Method,
4852                                                const ObjCPropertyDecl *&PDecl) const;
4853 
4854   /// Called by ActOnProperty to handle \@property declarations in
4855   /// class extensions.
4856   ObjCPropertyDecl *HandlePropertyInClassExtension(Scope *S,
4857                       SourceLocation AtLoc,
4858                       SourceLocation LParenLoc,
4859                       FieldDeclarator &FD,
4860                       Selector GetterSel,
4861                       SourceLocation GetterNameLoc,
4862                       Selector SetterSel,
4863                       SourceLocation SetterNameLoc,
4864                       const bool isReadWrite,
4865                       unsigned &Attributes,
4866                       const unsigned AttributesAsWritten,
4867                       QualType T,
4868                       TypeSourceInfo *TSI,
4869                       tok::ObjCKeywordKind MethodImplKind);
4870 
4871   /// Called by ActOnProperty and HandlePropertyInClassExtension to
4872   /// handle creating the ObjcPropertyDecl for a category or \@interface.
4873   ObjCPropertyDecl *CreatePropertyDecl(Scope *S,
4874                                        ObjCContainerDecl *CDecl,
4875                                        SourceLocation AtLoc,
4876                                        SourceLocation LParenLoc,
4877                                        FieldDeclarator &FD,
4878                                        Selector GetterSel,
4879                                        SourceLocation GetterNameLoc,
4880                                        Selector SetterSel,
4881                                        SourceLocation SetterNameLoc,
4882                                        const bool isReadWrite,
4883                                        const unsigned Attributes,
4884                                        const unsigned AttributesAsWritten,
4885                                        QualType T,
4886                                        TypeSourceInfo *TSI,
4887                                        tok::ObjCKeywordKind MethodImplKind,
4888                                        DeclContext *lexicalDC = nullptr);
4889 
4890   /// AtomicPropertySetterGetterRules - This routine enforces the rule (via
4891   /// warning) when atomic property has one but not the other user-declared
4892   /// setter or getter.
4893   void AtomicPropertySetterGetterRules(ObjCImplDecl* IMPDecl,
4894                                        ObjCInterfaceDecl* IDecl);
4895 
4896   void DiagnoseOwningPropertyGetterSynthesis(const ObjCImplementationDecl *D);
4897 
4898   void DiagnoseMissingDesignatedInitOverrides(
4899                                           const ObjCImplementationDecl *ImplD,
4900                                           const ObjCInterfaceDecl *IFD);
4901 
4902   void DiagnoseDuplicateIvars(ObjCInterfaceDecl *ID, ObjCInterfaceDecl *SID);
4903 
4904   enum MethodMatchStrategy {
4905     MMS_loose,
4906     MMS_strict
4907   };
4908 
4909   /// MatchTwoMethodDeclarations - Checks if two methods' type match and returns
4910   /// true, or false, accordingly.
4911   bool MatchTwoMethodDeclarations(const ObjCMethodDecl *Method,
4912                                   const ObjCMethodDecl *PrevMethod,
4913                                   MethodMatchStrategy strategy = MMS_strict);
4914 
4915   /// MatchAllMethodDeclarations - Check methods declaraed in interface or
4916   /// or protocol against those declared in their implementations.
4917   void MatchAllMethodDeclarations(const SelectorSet &InsMap,
4918                                   const SelectorSet &ClsMap,
4919                                   SelectorSet &InsMapSeen,
4920                                   SelectorSet &ClsMapSeen,
4921                                   ObjCImplDecl* IMPDecl,
4922                                   ObjCContainerDecl* IDecl,
4923                                   bool &IncompleteImpl,
4924                                   bool ImmediateClass,
4925                                   bool WarnCategoryMethodImpl=false);
4926 
4927   /// CheckCategoryVsClassMethodMatches - Checks that methods implemented in
4928   /// category matches with those implemented in its primary class and
4929   /// warns each time an exact match is found.
4930   void CheckCategoryVsClassMethodMatches(ObjCCategoryImplDecl *CatIMP);
4931 
4932   /// Add the given method to the list of globally-known methods.
4933   void addMethodToGlobalList(ObjCMethodList *List, ObjCMethodDecl *Method);
4934 
4935   /// Returns default addr space for method qualifiers.
4936   LangAS getDefaultCXXMethodAddrSpace() const;
4937 
4938 private:
4939   /// AddMethodToGlobalPool - Add an instance or factory method to the global
4940   /// pool. See descriptoin of AddInstanceMethodToGlobalPool.
4941   void AddMethodToGlobalPool(ObjCMethodDecl *Method, bool impl, bool instance);
4942 
4943   /// LookupMethodInGlobalPool - Returns the instance or factory method and
4944   /// optionally warns if there are multiple signatures.
4945   ObjCMethodDecl *LookupMethodInGlobalPool(Selector Sel, SourceRange R,
4946                                            bool receiverIdOrClass,
4947                                            bool instance);
4948 
4949 public:
4950   /// - Returns instance or factory methods in global method pool for
4951   /// given selector. It checks the desired kind first, if none is found, and
4952   /// parameter checkTheOther is set, it then checks the other kind. If no such
4953   /// method or only one method is found, function returns false; otherwise, it
4954   /// returns true.
4955   bool
4956   CollectMultipleMethodsInGlobalPool(Selector Sel,
4957                                      SmallVectorImpl<ObjCMethodDecl*>& Methods,
4958                                      bool InstanceFirst, bool CheckTheOther,
4959                                      const ObjCObjectType *TypeBound = nullptr);
4960 
4961   bool
4962   AreMultipleMethodsInGlobalPool(Selector Sel, ObjCMethodDecl *BestMethod,
4963                                  SourceRange R, bool receiverIdOrClass,
4964                                  SmallVectorImpl<ObjCMethodDecl*>& Methods);
4965 
4966   void
4967   DiagnoseMultipleMethodInGlobalPool(SmallVectorImpl<ObjCMethodDecl*> &Methods,
4968                                      Selector Sel, SourceRange R,
4969                                      bool receiverIdOrClass);
4970 
4971 private:
4972   /// - Returns a selector which best matches given argument list or
4973   /// nullptr if none could be found
4974   ObjCMethodDecl *SelectBestMethod(Selector Sel, MultiExprArg Args,
4975                                    bool IsInstance,
4976                                    SmallVectorImpl<ObjCMethodDecl*>& Methods);
4977 
4978 
4979   /// Record the typo correction failure and return an empty correction.
4980   TypoCorrection FailedCorrection(IdentifierInfo *Typo, SourceLocation TypoLoc,
4981                                   bool RecordFailure = true) {
4982     if (RecordFailure)
4983       TypoCorrectionFailures[Typo].insert(TypoLoc);
4984     return TypoCorrection();
4985   }
4986 
4987 public:
4988   /// AddInstanceMethodToGlobalPool - All instance methods in a translation
4989   /// unit are added to a global pool. This allows us to efficiently associate
4990   /// a selector with a method declaraation for purposes of typechecking
4991   /// messages sent to "id" (where the class of the object is unknown).
4992   void AddInstanceMethodToGlobalPool(ObjCMethodDecl *Method, bool impl=false) {
4993     AddMethodToGlobalPool(Method, impl, /*instance*/true);
4994   }
4995 
4996   /// AddFactoryMethodToGlobalPool - Same as above, but for factory methods.
4997   void AddFactoryMethodToGlobalPool(ObjCMethodDecl *Method, bool impl=false) {
4998     AddMethodToGlobalPool(Method, impl, /*instance*/false);
4999   }
5000 
5001   /// AddAnyMethodToGlobalPool - Add any method, instance or factory to global
5002   /// pool.
5003   void AddAnyMethodToGlobalPool(Decl *D);
5004 
5005   /// LookupInstanceMethodInGlobalPool - Returns the method and warns if
5006   /// there are multiple signatures.
5007   ObjCMethodDecl *LookupInstanceMethodInGlobalPool(Selector Sel, SourceRange R,
5008                                                    bool receiverIdOrClass=false) {
5009     return LookupMethodInGlobalPool(Sel, R, receiverIdOrClass,
5010                                     /*instance*/true);
5011   }
5012 
5013   /// LookupFactoryMethodInGlobalPool - Returns the method and warns if
5014   /// there are multiple signatures.
5015   ObjCMethodDecl *LookupFactoryMethodInGlobalPool(Selector Sel, SourceRange R,
5016                                                   bool receiverIdOrClass=false) {
5017     return LookupMethodInGlobalPool(Sel, R, receiverIdOrClass,
5018                                     /*instance*/false);
5019   }
5020 
5021   const ObjCMethodDecl *SelectorsForTypoCorrection(Selector Sel,
5022                               QualType ObjectType=QualType());
5023   /// LookupImplementedMethodInGlobalPool - Returns the method which has an
5024   /// implementation.
5025   ObjCMethodDecl *LookupImplementedMethodInGlobalPool(Selector Sel);
5026 
5027   /// CollectIvarsToConstructOrDestruct - Collect those ivars which require
5028   /// initialization.
5029   void CollectIvarsToConstructOrDestruct(ObjCInterfaceDecl *OI,
5030                                   SmallVectorImpl<ObjCIvarDecl*> &Ivars);
5031 
5032   //===--------------------------------------------------------------------===//
5033   // Statement Parsing Callbacks: SemaStmt.cpp.
5034 public:
5035   class FullExprArg {
5036   public:
5037     FullExprArg() : E(nullptr) { }
5038     FullExprArg(Sema &actions) : E(nullptr) { }
5039 
5040     ExprResult release() {
5041       return E;
5042     }
5043 
5044     Expr *get() const { return E; }
5045 
5046     Expr *operator->() {
5047       return E;
5048     }
5049 
5050   private:
5051     // FIXME: No need to make the entire Sema class a friend when it's just
5052     // Sema::MakeFullExpr that needs access to the constructor below.
5053     friend class Sema;
5054 
5055     explicit FullExprArg(Expr *expr) : E(expr) {}
5056 
5057     Expr *E;
5058   };
5059 
5060   FullExprArg MakeFullExpr(Expr *Arg) {
5061     return MakeFullExpr(Arg, Arg ? Arg->getExprLoc() : SourceLocation());
5062   }
5063   FullExprArg MakeFullExpr(Expr *Arg, SourceLocation CC) {
5064     return FullExprArg(
5065         ActOnFinishFullExpr(Arg, CC, /*DiscardedValue*/ false).get());
5066   }
5067   FullExprArg MakeFullDiscardedValueExpr(Expr *Arg) {
5068     ExprResult FE =
5069         ActOnFinishFullExpr(Arg, Arg ? Arg->getExprLoc() : SourceLocation(),
5070                             /*DiscardedValue*/ true);
5071     return FullExprArg(FE.get());
5072   }
5073 
5074   StmtResult ActOnExprStmt(ExprResult Arg, bool DiscardedValue = true);
5075   StmtResult ActOnExprStmtError();
5076 
5077   StmtResult ActOnNullStmt(SourceLocation SemiLoc,
5078                            bool HasLeadingEmptyMacro = false);
5079 
5080   void ActOnStartOfCompoundStmt(bool IsStmtExpr);
5081   void ActOnAfterCompoundStatementLeadingPragmas();
5082   void ActOnFinishOfCompoundStmt();
5083   StmtResult ActOnCompoundStmt(SourceLocation L, SourceLocation R,
5084                                ArrayRef<Stmt *> Elts, bool isStmtExpr);
5085 
5086   /// A RAII object to enter scope of a compound statement.
5087   class CompoundScopeRAII {
5088   public:
5089     CompoundScopeRAII(Sema &S, bool IsStmtExpr = false) : S(S) {
5090       S.ActOnStartOfCompoundStmt(IsStmtExpr);
5091     }
5092 
5093     ~CompoundScopeRAII() {
5094       S.ActOnFinishOfCompoundStmt();
5095     }
5096 
5097   private:
5098     Sema &S;
5099   };
5100 
5101   /// An RAII helper that pops function a function scope on exit.
5102   struct FunctionScopeRAII {
5103     Sema &S;
5104     bool Active;
5105     FunctionScopeRAII(Sema &S) : S(S), Active(true) {}
5106     ~FunctionScopeRAII() {
5107       if (Active)
5108         S.PopFunctionScopeInfo();
5109     }
5110     void disable() { Active = false; }
5111   };
5112 
5113   StmtResult ActOnDeclStmt(DeclGroupPtrTy Decl,
5114                                    SourceLocation StartLoc,
5115                                    SourceLocation EndLoc);
5116   void ActOnForEachDeclStmt(DeclGroupPtrTy Decl);
5117   StmtResult ActOnForEachLValueExpr(Expr *E);
5118   ExprResult ActOnCaseExpr(SourceLocation CaseLoc, ExprResult Val);
5119   StmtResult ActOnCaseStmt(SourceLocation CaseLoc, ExprResult LHS,
5120                            SourceLocation DotDotDotLoc, ExprResult RHS,
5121                            SourceLocation ColonLoc);
5122   void ActOnCaseStmtBody(Stmt *CaseStmt, Stmt *SubStmt);
5123 
5124   StmtResult ActOnDefaultStmt(SourceLocation DefaultLoc,
5125                                       SourceLocation ColonLoc,
5126                                       Stmt *SubStmt, Scope *CurScope);
5127   StmtResult ActOnLabelStmt(SourceLocation IdentLoc, LabelDecl *TheDecl,
5128                             SourceLocation ColonLoc, Stmt *SubStmt);
5129 
5130   StmtResult BuildAttributedStmt(SourceLocation AttrsLoc,
5131                                  ArrayRef<const Attr *> Attrs, Stmt *SubStmt);
5132   StmtResult ActOnAttributedStmt(const ParsedAttributes &AttrList,
5133                                  Stmt *SubStmt);
5134 
5135   class ConditionResult;
5136 
5137   StmtResult ActOnIfStmt(SourceLocation IfLoc, IfStatementKind StatementKind,
5138                          SourceLocation LParenLoc, Stmt *InitStmt,
5139                          ConditionResult Cond, SourceLocation RParenLoc,
5140                          Stmt *ThenVal, SourceLocation ElseLoc, Stmt *ElseVal);
5141   StmtResult BuildIfStmt(SourceLocation IfLoc, IfStatementKind StatementKind,
5142                          SourceLocation LParenLoc, Stmt *InitStmt,
5143                          ConditionResult Cond, SourceLocation RParenLoc,
5144                          Stmt *ThenVal, SourceLocation ElseLoc, Stmt *ElseVal);
5145   StmtResult ActOnStartOfSwitchStmt(SourceLocation SwitchLoc,
5146                                     SourceLocation LParenLoc, Stmt *InitStmt,
5147                                     ConditionResult Cond,
5148                                     SourceLocation RParenLoc);
5149   StmtResult ActOnFinishSwitchStmt(SourceLocation SwitchLoc,
5150                                            Stmt *Switch, Stmt *Body);
5151   StmtResult ActOnWhileStmt(SourceLocation WhileLoc, SourceLocation LParenLoc,
5152                             ConditionResult Cond, SourceLocation RParenLoc,
5153                             Stmt *Body);
5154   StmtResult ActOnDoStmt(SourceLocation DoLoc, Stmt *Body,
5155                          SourceLocation WhileLoc, SourceLocation CondLParen,
5156                          Expr *Cond, SourceLocation CondRParen);
5157 
5158   StmtResult ActOnForStmt(SourceLocation ForLoc,
5159                           SourceLocation LParenLoc,
5160                           Stmt *First,
5161                           ConditionResult Second,
5162                           FullExprArg Third,
5163                           SourceLocation RParenLoc,
5164                           Stmt *Body);
5165   ExprResult CheckObjCForCollectionOperand(SourceLocation forLoc,
5166                                            Expr *collection);
5167   StmtResult ActOnObjCForCollectionStmt(SourceLocation ForColLoc,
5168                                         Stmt *First, Expr *collection,
5169                                         SourceLocation RParenLoc);
5170   StmtResult FinishObjCForCollectionStmt(Stmt *ForCollection, Stmt *Body);
5171 
5172   enum BuildForRangeKind {
5173     /// Initial building of a for-range statement.
5174     BFRK_Build,
5175     /// Instantiation or recovery rebuild of a for-range statement. Don't
5176     /// attempt any typo-correction.
5177     BFRK_Rebuild,
5178     /// Determining whether a for-range statement could be built. Avoid any
5179     /// unnecessary or irreversible actions.
5180     BFRK_Check
5181   };
5182 
5183   StmtResult ActOnCXXForRangeStmt(Scope *S, SourceLocation ForLoc,
5184                                   SourceLocation CoawaitLoc,
5185                                   Stmt *InitStmt,
5186                                   Stmt *LoopVar,
5187                                   SourceLocation ColonLoc, Expr *Collection,
5188                                   SourceLocation RParenLoc,
5189                                   BuildForRangeKind Kind);
5190   StmtResult BuildCXXForRangeStmt(SourceLocation ForLoc,
5191                                   SourceLocation CoawaitLoc,
5192                                   Stmt *InitStmt,
5193                                   SourceLocation ColonLoc,
5194                                   Stmt *RangeDecl, Stmt *Begin, Stmt *End,
5195                                   Expr *Cond, Expr *Inc,
5196                                   Stmt *LoopVarDecl,
5197                                   SourceLocation RParenLoc,
5198                                   BuildForRangeKind Kind);
5199   StmtResult FinishCXXForRangeStmt(Stmt *ForRange, Stmt *Body);
5200 
5201   StmtResult ActOnGotoStmt(SourceLocation GotoLoc,
5202                            SourceLocation LabelLoc,
5203                            LabelDecl *TheDecl);
5204   StmtResult ActOnIndirectGotoStmt(SourceLocation GotoLoc,
5205                                    SourceLocation StarLoc,
5206                                    Expr *DestExp);
5207   StmtResult ActOnContinueStmt(SourceLocation ContinueLoc, Scope *CurScope);
5208   StmtResult ActOnBreakStmt(SourceLocation BreakLoc, Scope *CurScope);
5209 
5210   void ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope,
5211                                 CapturedRegionKind Kind, unsigned NumParams);
5212   typedef std::pair<StringRef, QualType> CapturedParamNameType;
5213   void ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope,
5214                                 CapturedRegionKind Kind,
5215                                 ArrayRef<CapturedParamNameType> Params,
5216                                 unsigned OpenMPCaptureLevel = 0);
5217   StmtResult ActOnCapturedRegionEnd(Stmt *S);
5218   void ActOnCapturedRegionError();
5219   RecordDecl *CreateCapturedStmtRecordDecl(CapturedDecl *&CD,
5220                                            SourceLocation Loc,
5221                                            unsigned NumParams);
5222 
5223   struct NamedReturnInfo {
5224     const VarDecl *Candidate;
5225 
5226     enum Status : uint8_t { None, MoveEligible, MoveEligibleAndCopyElidable };
5227     Status S;
5228 
5229     bool isMoveEligible() const { return S != None; };
5230     bool isCopyElidable() const { return S == MoveEligibleAndCopyElidable; }
5231   };
5232   enum class SimplerImplicitMoveMode { ForceOff, Normal, ForceOn };
5233   NamedReturnInfo getNamedReturnInfo(
5234       Expr *&E, SimplerImplicitMoveMode Mode = SimplerImplicitMoveMode::Normal);
5235   NamedReturnInfo getNamedReturnInfo(const VarDecl *VD);
5236   const VarDecl *getCopyElisionCandidate(NamedReturnInfo &Info,
5237                                          QualType ReturnType);
5238 
5239   ExprResult
5240   PerformMoveOrCopyInitialization(const InitializedEntity &Entity,
5241                                   const NamedReturnInfo &NRInfo, Expr *Value,
5242                                   bool SupressSimplerImplicitMoves = false);
5243 
5244   StmtResult ActOnReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp,
5245                              Scope *CurScope);
5246   StmtResult BuildReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp,
5247                              bool AllowRecovery = false);
5248   StmtResult ActOnCapScopeReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp,
5249                                      NamedReturnInfo &NRInfo,
5250                                      bool SupressSimplerImplicitMoves);
5251 
5252   StmtResult ActOnGCCAsmStmt(SourceLocation AsmLoc, bool IsSimple,
5253                              bool IsVolatile, unsigned NumOutputs,
5254                              unsigned NumInputs, IdentifierInfo **Names,
5255                              MultiExprArg Constraints, MultiExprArg Exprs,
5256                              Expr *AsmString, MultiExprArg Clobbers,
5257                              unsigned NumLabels,
5258                              SourceLocation RParenLoc);
5259 
5260   void FillInlineAsmIdentifierInfo(Expr *Res,
5261                                    llvm::InlineAsmIdentifierInfo &Info);
5262   ExprResult LookupInlineAsmIdentifier(CXXScopeSpec &SS,
5263                                        SourceLocation TemplateKWLoc,
5264                                        UnqualifiedId &Id,
5265                                        bool IsUnevaluatedContext);
5266   bool LookupInlineAsmField(StringRef Base, StringRef Member,
5267                             unsigned &Offset, SourceLocation AsmLoc);
5268   ExprResult LookupInlineAsmVarDeclField(Expr *RefExpr, StringRef Member,
5269                                          SourceLocation AsmLoc);
5270   StmtResult ActOnMSAsmStmt(SourceLocation AsmLoc, SourceLocation LBraceLoc,
5271                             ArrayRef<Token> AsmToks,
5272                             StringRef AsmString,
5273                             unsigned NumOutputs, unsigned NumInputs,
5274                             ArrayRef<StringRef> Constraints,
5275                             ArrayRef<StringRef> Clobbers,
5276                             ArrayRef<Expr*> Exprs,
5277                             SourceLocation EndLoc);
5278   LabelDecl *GetOrCreateMSAsmLabel(StringRef ExternalLabelName,
5279                                    SourceLocation Location,
5280                                    bool AlwaysCreate);
5281 
5282   VarDecl *BuildObjCExceptionDecl(TypeSourceInfo *TInfo, QualType ExceptionType,
5283                                   SourceLocation StartLoc,
5284                                   SourceLocation IdLoc, IdentifierInfo *Id,
5285                                   bool Invalid = false);
5286 
5287   Decl *ActOnObjCExceptionDecl(Scope *S, Declarator &D);
5288 
5289   StmtResult ActOnObjCAtCatchStmt(SourceLocation AtLoc, SourceLocation RParen,
5290                                   Decl *Parm, Stmt *Body);
5291 
5292   StmtResult ActOnObjCAtFinallyStmt(SourceLocation AtLoc, Stmt *Body);
5293 
5294   StmtResult ActOnObjCAtTryStmt(SourceLocation AtLoc, Stmt *Try,
5295                                 MultiStmtArg Catch, Stmt *Finally);
5296 
5297   StmtResult BuildObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw);
5298   StmtResult ActOnObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw,
5299                                   Scope *CurScope);
5300   ExprResult ActOnObjCAtSynchronizedOperand(SourceLocation atLoc,
5301                                             Expr *operand);
5302   StmtResult ActOnObjCAtSynchronizedStmt(SourceLocation AtLoc,
5303                                          Expr *SynchExpr,
5304                                          Stmt *SynchBody);
5305 
5306   StmtResult ActOnObjCAutoreleasePoolStmt(SourceLocation AtLoc, Stmt *Body);
5307 
5308   VarDecl *BuildExceptionDeclaration(Scope *S, TypeSourceInfo *TInfo,
5309                                      SourceLocation StartLoc,
5310                                      SourceLocation IdLoc,
5311                                      IdentifierInfo *Id);
5312 
5313   Decl *ActOnExceptionDeclarator(Scope *S, Declarator &D);
5314 
5315   StmtResult ActOnCXXCatchBlock(SourceLocation CatchLoc,
5316                                 Decl *ExDecl, Stmt *HandlerBlock);
5317   StmtResult ActOnCXXTryBlock(SourceLocation TryLoc, Stmt *TryBlock,
5318                               ArrayRef<Stmt *> Handlers);
5319 
5320   StmtResult ActOnSEHTryBlock(bool IsCXXTry, // try (true) or __try (false) ?
5321                               SourceLocation TryLoc, Stmt *TryBlock,
5322                               Stmt *Handler);
5323   StmtResult ActOnSEHExceptBlock(SourceLocation Loc,
5324                                  Expr *FilterExpr,
5325                                  Stmt *Block);
5326   void ActOnStartSEHFinallyBlock();
5327   void ActOnAbortSEHFinallyBlock();
5328   StmtResult ActOnFinishSEHFinallyBlock(SourceLocation Loc, Stmt *Block);
5329   StmtResult ActOnSEHLeaveStmt(SourceLocation Loc, Scope *CurScope);
5330 
5331   void DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock);
5332 
5333   bool ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const;
5334 
5335   /// If it's a file scoped decl that must warn if not used, keep track
5336   /// of it.
5337   void MarkUnusedFileScopedDecl(const DeclaratorDecl *D);
5338 
5339   typedef llvm::function_ref<void(SourceLocation Loc, PartialDiagnostic PD)>
5340       DiagReceiverTy;
5341 
5342   /// DiagnoseUnusedExprResult - If the statement passed in is an expression
5343   /// whose result is unused, warn.
5344   void DiagnoseUnusedExprResult(const Stmt *S, unsigned DiagID);
5345   void DiagnoseUnusedNestedTypedefs(const RecordDecl *D);
5346   void DiagnoseUnusedNestedTypedefs(const RecordDecl *D,
5347                                     DiagReceiverTy DiagReceiver);
5348   void DiagnoseUnusedDecl(const NamedDecl *ND);
5349   void DiagnoseUnusedDecl(const NamedDecl *ND, DiagReceiverTy DiagReceiver);
5350 
5351   /// If VD is set but not otherwise used, diagnose, for a parameter or a
5352   /// variable.
5353   void DiagnoseUnusedButSetDecl(const VarDecl *VD, DiagReceiverTy DiagReceiver);
5354 
5355   /// Emit \p DiagID if statement located on \p StmtLoc has a suspicious null
5356   /// statement as a \p Body, and it is located on the same line.
5357   ///
5358   /// This helps prevent bugs due to typos, such as:
5359   ///     if (condition);
5360   ///       do_stuff();
5361   void DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
5362                              const Stmt *Body,
5363                              unsigned DiagID);
5364 
5365   /// Warn if a for/while loop statement \p S, which is followed by
5366   /// \p PossibleBody, has a suspicious null statement as a body.
5367   void DiagnoseEmptyLoopBody(const Stmt *S,
5368                              const Stmt *PossibleBody);
5369 
5370   /// Warn if a value is moved to itself.
5371   void DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
5372                         SourceLocation OpLoc);
5373 
5374   /// Returns a field in a CXXRecordDecl that has the same name as the decl \p
5375   /// SelfAssigned when inside a CXXMethodDecl.
5376   const FieldDecl *
5377   getSelfAssignmentClassMemberCandidate(const ValueDecl *SelfAssigned);
5378 
5379   /// Warn if we're implicitly casting from a _Nullable pointer type to a
5380   /// _Nonnull one.
5381   void diagnoseNullableToNonnullConversion(QualType DstType, QualType SrcType,
5382                                            SourceLocation Loc);
5383 
5384   /// Warn when implicitly casting 0 to nullptr.
5385   void diagnoseZeroToNullptrConversion(CastKind Kind, const Expr *E);
5386 
5387   ParsingDeclState PushParsingDeclaration(sema::DelayedDiagnosticPool &pool) {
5388     return DelayedDiagnostics.push(pool);
5389   }
5390   void PopParsingDeclaration(ParsingDeclState state, Decl *decl);
5391 
5392   typedef ProcessingContextState ParsingClassState;
5393   ParsingClassState PushParsingClass() {
5394     ParsingClassDepth++;
5395     return DelayedDiagnostics.pushUndelayed();
5396   }
5397   void PopParsingClass(ParsingClassState state) {
5398     ParsingClassDepth--;
5399     DelayedDiagnostics.popUndelayed(state);
5400   }
5401 
5402   void redelayDiagnostics(sema::DelayedDiagnosticPool &pool);
5403 
5404   void DiagnoseAvailabilityOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs,
5405                                   const ObjCInterfaceDecl *UnknownObjCClass,
5406                                   bool ObjCPropertyAccess,
5407                                   bool AvoidPartialAvailabilityChecks = false,
5408                                   ObjCInterfaceDecl *ClassReceiver = nullptr);
5409 
5410   bool makeUnavailableInSystemHeader(SourceLocation loc,
5411                                      UnavailableAttr::ImplicitReason reason);
5412 
5413   /// Issue any -Wunguarded-availability warnings in \c FD
5414   void DiagnoseUnguardedAvailabilityViolations(Decl *FD);
5415 
5416   void handleDelayedAvailabilityCheck(sema::DelayedDiagnostic &DD, Decl *Ctx);
5417 
5418   //===--------------------------------------------------------------------===//
5419   // Expression Parsing Callbacks: SemaExpr.cpp.
5420 
5421   bool CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid);
5422   // A version of DiagnoseUseOfDecl that should be used if overload resolution
5423   // has been used to find this declaration, which means we don't have to bother
5424   // checking the trailing requires clause.
5425   bool DiagnoseUseOfOverloadedDecl(NamedDecl *D, SourceLocation Loc) {
5426     return DiagnoseUseOfDecl(
5427         D, Loc, /*UnknownObjCClass=*/nullptr, /*ObjCPropertyAccess=*/false,
5428         /*AvoidPartialAvailabilityChecks=*/false, /*ClassReceiver=*/nullptr,
5429         /*SkipTrailingRequiresClause=*/true);
5430   }
5431 
5432   bool DiagnoseUseOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs,
5433                          const ObjCInterfaceDecl *UnknownObjCClass = nullptr,
5434                          bool ObjCPropertyAccess = false,
5435                          bool AvoidPartialAvailabilityChecks = false,
5436                          ObjCInterfaceDecl *ClassReciever = nullptr,
5437                          bool SkipTrailingRequiresClause = false);
5438   void NoteDeletedFunction(FunctionDecl *FD);
5439   void NoteDeletedInheritingConstructor(CXXConstructorDecl *CD);
5440   bool DiagnosePropertyAccessorMismatch(ObjCPropertyDecl *PD,
5441                                         ObjCMethodDecl *Getter,
5442                                         SourceLocation Loc);
5443   void DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
5444                              ArrayRef<Expr *> Args);
5445 
5446   void PushExpressionEvaluationContext(
5447       ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl = nullptr,
5448       ExpressionEvaluationContextRecord::ExpressionKind Type =
5449           ExpressionEvaluationContextRecord::EK_Other);
5450   enum ReuseLambdaContextDecl_t { ReuseLambdaContextDecl };
5451   void PushExpressionEvaluationContext(
5452       ExpressionEvaluationContext NewContext, ReuseLambdaContextDecl_t,
5453       ExpressionEvaluationContextRecord::ExpressionKind Type =
5454           ExpressionEvaluationContextRecord::EK_Other);
5455   void PopExpressionEvaluationContext();
5456 
5457   void DiscardCleanupsInEvaluationContext();
5458 
5459   ExprResult TransformToPotentiallyEvaluated(Expr *E);
5460   TypeSourceInfo *TransformToPotentiallyEvaluated(TypeSourceInfo *TInfo);
5461   ExprResult HandleExprEvaluationContextForTypeof(Expr *E);
5462 
5463   ExprResult CheckUnevaluatedOperand(Expr *E);
5464   void CheckUnusedVolatileAssignment(Expr *E);
5465 
5466   ExprResult ActOnConstantExpression(ExprResult Res);
5467 
5468   // Functions for marking a declaration referenced.  These functions also
5469   // contain the relevant logic for marking if a reference to a function or
5470   // variable is an odr-use (in the C++11 sense).  There are separate variants
5471   // for expressions referring to a decl; these exist because odr-use marking
5472   // needs to be delayed for some constant variables when we build one of the
5473   // named expressions.
5474   //
5475   // MightBeOdrUse indicates whether the use could possibly be an odr-use, and
5476   // should usually be true. This only needs to be set to false if the lack of
5477   // odr-use cannot be determined from the current context (for instance,
5478   // because the name denotes a virtual function and was written without an
5479   // explicit nested-name-specifier).
5480   void MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, bool MightBeOdrUse);
5481   void MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func,
5482                               bool MightBeOdrUse = true);
5483   void MarkVariableReferenced(SourceLocation Loc, VarDecl *Var);
5484   void MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base = nullptr);
5485   void MarkMemberReferenced(MemberExpr *E);
5486   void MarkFunctionParmPackReferenced(FunctionParmPackExpr *E);
5487   void MarkCaptureUsedInEnclosingContext(ValueDecl *Capture, SourceLocation Loc,
5488                                          unsigned CapturingScopeIndex);
5489 
5490   ExprResult CheckLValueToRValueConversionOperand(Expr *E);
5491   void CleanupVarDeclMarking();
5492 
5493   enum TryCaptureKind {
5494     TryCapture_Implicit, TryCapture_ExplicitByVal, TryCapture_ExplicitByRef
5495   };
5496 
5497   /// Try to capture the given variable.
5498   ///
5499   /// \param Var The variable to capture.
5500   ///
5501   /// \param Loc The location at which the capture occurs.
5502   ///
5503   /// \param Kind The kind of capture, which may be implicit (for either a
5504   /// block or a lambda), or explicit by-value or by-reference (for a lambda).
5505   ///
5506   /// \param EllipsisLoc The location of the ellipsis, if one is provided in
5507   /// an explicit lambda capture.
5508   ///
5509   /// \param BuildAndDiagnose Whether we are actually supposed to add the
5510   /// captures or diagnose errors. If false, this routine merely check whether
5511   /// the capture can occur without performing the capture itself or complaining
5512   /// if the variable cannot be captured.
5513   ///
5514   /// \param CaptureType Will be set to the type of the field used to capture
5515   /// this variable in the innermost block or lambda. Only valid when the
5516   /// variable can be captured.
5517   ///
5518   /// \param DeclRefType Will be set to the type of a reference to the capture
5519   /// from within the current scope. Only valid when the variable can be
5520   /// captured.
5521   ///
5522   /// \param FunctionScopeIndexToStopAt If non-null, it points to the index
5523   /// of the FunctionScopeInfo stack beyond which we do not attempt to capture.
5524   /// This is useful when enclosing lambdas must speculatively capture
5525   /// variables that may or may not be used in certain specializations of
5526   /// a nested generic lambda.
5527   ///
5528   /// \returns true if an error occurred (i.e., the variable cannot be
5529   /// captured) and false if the capture succeeded.
5530   bool tryCaptureVariable(ValueDecl *Var, SourceLocation Loc,
5531                           TryCaptureKind Kind, SourceLocation EllipsisLoc,
5532                           bool BuildAndDiagnose, QualType &CaptureType,
5533                           QualType &DeclRefType,
5534                           const unsigned *const FunctionScopeIndexToStopAt);
5535 
5536   /// Try to capture the given variable.
5537   bool tryCaptureVariable(ValueDecl *Var, SourceLocation Loc,
5538                           TryCaptureKind Kind = TryCapture_Implicit,
5539                           SourceLocation EllipsisLoc = SourceLocation());
5540 
5541   /// Checks if the variable must be captured.
5542   bool NeedToCaptureVariable(ValueDecl *Var, SourceLocation Loc);
5543 
5544   /// Given a variable, determine the type that a reference to that
5545   /// variable will have in the given scope.
5546   QualType getCapturedDeclRefType(ValueDecl *Var, SourceLocation Loc);
5547 
5548   /// Mark all of the declarations referenced within a particular AST node as
5549   /// referenced. Used when template instantiation instantiates a non-dependent
5550   /// type -- entities referenced by the type are now referenced.
5551   void MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T);
5552   void MarkDeclarationsReferencedInExpr(
5553       Expr *E, bool SkipLocalVariables = false,
5554       ArrayRef<const Expr *> StopAt = std::nullopt);
5555 
5556   /// Try to recover by turning the given expression into a
5557   /// call.  Returns true if recovery was attempted or an error was
5558   /// emitted; this may also leave the ExprResult invalid.
5559   bool tryToRecoverWithCall(ExprResult &E, const PartialDiagnostic &PD,
5560                             bool ForceComplain = false,
5561                             bool (*IsPlausibleResult)(QualType) = nullptr);
5562 
5563   /// Figure out if an expression could be turned into a call.
5564   bool tryExprAsCall(Expr &E, QualType &ZeroArgCallReturnTy,
5565                      UnresolvedSetImpl &NonTemplateOverloads);
5566 
5567   /// Try to convert an expression \p E to type \p Ty. Returns the result of the
5568   /// conversion.
5569   ExprResult tryConvertExprToType(Expr *E, QualType Ty);
5570 
5571   /// Conditionally issue a diagnostic based on the statements's reachability
5572   /// analysis.
5573   ///
5574   /// \param Stmts If Stmts is non-empty, delay reporting the diagnostic until
5575   /// the function body is parsed, and then do a basic reachability analysis to
5576   /// determine if the statement is reachable. If it is unreachable, the
5577   /// diagnostic will not be emitted.
5578   bool DiagIfReachable(SourceLocation Loc, ArrayRef<const Stmt *> Stmts,
5579                        const PartialDiagnostic &PD);
5580 
5581   /// Conditionally issue a diagnostic based on the current
5582   /// evaluation context.
5583   ///
5584   /// \param Statement If Statement is non-null, delay reporting the
5585   /// diagnostic until the function body is parsed, and then do a basic
5586   /// reachability analysis to determine if the statement is reachable.
5587   /// If it is unreachable, the diagnostic will not be emitted.
5588   bool DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
5589                            const PartialDiagnostic &PD);
5590   /// Similar, but diagnostic is only produced if all the specified statements
5591   /// are reachable.
5592   bool DiagRuntimeBehavior(SourceLocation Loc, ArrayRef<const Stmt*> Stmts,
5593                            const PartialDiagnostic &PD);
5594 
5595   // Primary Expressions.
5596   SourceRange getExprRange(Expr *E) const;
5597 
5598   ExprResult ActOnIdExpression(
5599       Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
5600       UnqualifiedId &Id, bool HasTrailingLParen, bool IsAddressOfOperand,
5601       CorrectionCandidateCallback *CCC = nullptr,
5602       bool IsInlineAsmIdentifier = false, Token *KeywordReplacement = nullptr);
5603 
5604   void DecomposeUnqualifiedId(const UnqualifiedId &Id,
5605                               TemplateArgumentListInfo &Buffer,
5606                               DeclarationNameInfo &NameInfo,
5607                               const TemplateArgumentListInfo *&TemplateArgs);
5608 
5609   bool DiagnoseDependentMemberLookup(const LookupResult &R);
5610 
5611   bool
5612   DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
5613                       CorrectionCandidateCallback &CCC,
5614                       TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr,
5615                       ArrayRef<Expr *> Args = std::nullopt,
5616                       TypoExpr **Out = nullptr);
5617 
5618   DeclResult LookupIvarInObjCMethod(LookupResult &Lookup, Scope *S,
5619                                     IdentifierInfo *II);
5620   ExprResult BuildIvarRefExpr(Scope *S, SourceLocation Loc, ObjCIvarDecl *IV);
5621 
5622   ExprResult LookupInObjCMethod(LookupResult &LookUp, Scope *S,
5623                                 IdentifierInfo *II,
5624                                 bool AllowBuiltinCreation=false);
5625 
5626   ExprResult ActOnDependentIdExpression(const CXXScopeSpec &SS,
5627                                         SourceLocation TemplateKWLoc,
5628                                         const DeclarationNameInfo &NameInfo,
5629                                         bool isAddressOfOperand,
5630                                 const TemplateArgumentListInfo *TemplateArgs);
5631 
5632   /// If \p D cannot be odr-used in the current expression evaluation context,
5633   /// return a reason explaining why. Otherwise, return NOUR_None.
5634   NonOdrUseReason getNonOdrUseReasonInCurrentContext(ValueDecl *D);
5635 
5636   DeclRefExpr *BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
5637                                 SourceLocation Loc,
5638                                 const CXXScopeSpec *SS = nullptr);
5639   DeclRefExpr *
5640   BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
5641                    const DeclarationNameInfo &NameInfo,
5642                    const CXXScopeSpec *SS = nullptr,
5643                    NamedDecl *FoundD = nullptr,
5644                    SourceLocation TemplateKWLoc = SourceLocation(),
5645                    const TemplateArgumentListInfo *TemplateArgs = nullptr);
5646   DeclRefExpr *
5647   BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
5648                    const DeclarationNameInfo &NameInfo,
5649                    NestedNameSpecifierLoc NNS,
5650                    NamedDecl *FoundD = nullptr,
5651                    SourceLocation TemplateKWLoc = SourceLocation(),
5652                    const TemplateArgumentListInfo *TemplateArgs = nullptr);
5653 
5654   ExprResult
5655   BuildAnonymousStructUnionMemberReference(
5656       const CXXScopeSpec &SS,
5657       SourceLocation nameLoc,
5658       IndirectFieldDecl *indirectField,
5659       DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_none),
5660       Expr *baseObjectExpr = nullptr,
5661       SourceLocation opLoc = SourceLocation());
5662 
5663   ExprResult BuildPossibleImplicitMemberExpr(
5664       const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, LookupResult &R,
5665       const TemplateArgumentListInfo *TemplateArgs, const Scope *S,
5666       UnresolvedLookupExpr *AsULE = nullptr);
5667   ExprResult BuildImplicitMemberExpr(const CXXScopeSpec &SS,
5668                                      SourceLocation TemplateKWLoc,
5669                                      LookupResult &R,
5670                                 const TemplateArgumentListInfo *TemplateArgs,
5671                                      bool IsDefiniteInstance,
5672                                      const Scope *S);
5673   bool UseArgumentDependentLookup(const CXXScopeSpec &SS,
5674                                   const LookupResult &R,
5675                                   bool HasTrailingLParen);
5676 
5677   ExprResult
5678   BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS,
5679                                     const DeclarationNameInfo &NameInfo,
5680                                     bool IsAddressOfOperand, const Scope *S,
5681                                     TypeSourceInfo **RecoveryTSI = nullptr);
5682 
5683   ExprResult BuildDependentDeclRefExpr(const CXXScopeSpec &SS,
5684                                        SourceLocation TemplateKWLoc,
5685                                 const DeclarationNameInfo &NameInfo,
5686                                 const TemplateArgumentListInfo *TemplateArgs);
5687 
5688   ExprResult BuildDeclarationNameExpr(const CXXScopeSpec &SS,
5689                                       LookupResult &R,
5690                                       bool NeedsADL,
5691                                       bool AcceptInvalidDecl = false);
5692   ExprResult BuildDeclarationNameExpr(
5693       const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
5694       NamedDecl *FoundD = nullptr,
5695       const TemplateArgumentListInfo *TemplateArgs = nullptr,
5696       bool AcceptInvalidDecl = false);
5697 
5698   ExprResult BuildLiteralOperatorCall(LookupResult &R,
5699                       DeclarationNameInfo &SuffixInfo,
5700                       ArrayRef<Expr *> Args,
5701                       SourceLocation LitEndLoc,
5702                       TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr);
5703 
5704   ExprResult BuildPredefinedExpr(SourceLocation Loc,
5705                                  PredefinedExpr::IdentKind IK);
5706   ExprResult ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind);
5707   ExprResult ActOnIntegerConstant(SourceLocation Loc, uint64_t Val);
5708 
5709   ExprResult BuildSYCLUniqueStableNameExpr(SourceLocation OpLoc,
5710                                            SourceLocation LParen,
5711                                            SourceLocation RParen,
5712                                            TypeSourceInfo *TSI);
5713   ExprResult ActOnSYCLUniqueStableNameExpr(SourceLocation OpLoc,
5714                                            SourceLocation LParen,
5715                                            SourceLocation RParen,
5716                                            ParsedType ParsedTy);
5717 
5718   bool CheckLoopHintExpr(Expr *E, SourceLocation Loc);
5719 
5720   ExprResult ActOnNumericConstant(const Token &Tok, Scope *UDLScope = nullptr);
5721   ExprResult ActOnCharacterConstant(const Token &Tok,
5722                                     Scope *UDLScope = nullptr);
5723   ExprResult ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E);
5724   ExprResult ActOnParenListExpr(SourceLocation L,
5725                                 SourceLocation R,
5726                                 MultiExprArg Val);
5727 
5728   /// ActOnStringLiteral - The specified tokens were lexed as pasted string
5729   /// fragments (e.g. "foo" "bar" L"baz").
5730   ExprResult ActOnStringLiteral(ArrayRef<Token> StringToks,
5731                                 Scope *UDLScope = nullptr);
5732 
5733   ExprResult ActOnUnevaluatedStringLiteral(ArrayRef<Token> StringToks);
5734 
5735   /// ControllingExprOrType is either an opaque pointer coming out of a
5736   /// ParsedType or an Expr *. FIXME: it'd be better to split this interface
5737   /// into two so we don't take a void *, but that's awkward because one of
5738   /// the operands is either a ParsedType or an Expr *, which doesn't lend
5739   /// itself to generic code very well.
5740   ExprResult ActOnGenericSelectionExpr(SourceLocation KeyLoc,
5741                                        SourceLocation DefaultLoc,
5742                                        SourceLocation RParenLoc,
5743                                        bool PredicateIsExpr,
5744                                        void *ControllingExprOrType,
5745                                        ArrayRef<ParsedType> ArgTypes,
5746                                        ArrayRef<Expr *> ArgExprs);
5747   /// ControllingExprOrType is either a TypeSourceInfo * or an Expr *. FIXME:
5748   /// it'd be better to split this interface into two so we don't take a
5749   /// void *, but see the FIXME on ActOnGenericSelectionExpr as to why that
5750   /// isn't a trivial change.
5751   ExprResult CreateGenericSelectionExpr(SourceLocation KeyLoc,
5752                                         SourceLocation DefaultLoc,
5753                                         SourceLocation RParenLoc,
5754                                         bool PredicateIsExpr,
5755                                         void *ControllingExprOrType,
5756                                         ArrayRef<TypeSourceInfo *> Types,
5757                                         ArrayRef<Expr *> Exprs);
5758 
5759   // Binary/Unary Operators.  'Tok' is the token for the operator.
5760   ExprResult CreateBuiltinUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc,
5761                                   Expr *InputExpr, bool IsAfterAmp = false);
5762   ExprResult BuildUnaryOp(Scope *S, SourceLocation OpLoc, UnaryOperatorKind Opc,
5763                           Expr *Input, bool IsAfterAmp = false);
5764   ExprResult ActOnUnaryOp(Scope *S, SourceLocation OpLoc, tok::TokenKind Op,
5765                           Expr *Input, bool IsAfterAmp = false);
5766 
5767   bool isQualifiedMemberAccess(Expr *E);
5768   QualType CheckAddressOfOperand(ExprResult &Operand, SourceLocation OpLoc);
5769 
5770   bool CheckTypeTraitArity(unsigned Arity, SourceLocation Loc, size_t N);
5771 
5772   bool ActOnAlignasTypeArgument(StringRef KWName, ParsedType Ty,
5773                                 SourceLocation OpLoc, SourceRange R);
5774   bool CheckAlignasTypeArgument(StringRef KWName, TypeSourceInfo *TInfo,
5775                                 SourceLocation OpLoc, SourceRange R);
5776 
5777   ExprResult CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
5778                                             SourceLocation OpLoc,
5779                                             UnaryExprOrTypeTrait ExprKind,
5780                                             SourceRange R);
5781   ExprResult CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
5782                                             UnaryExprOrTypeTrait ExprKind);
5783   ExprResult
5784     ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
5785                                   UnaryExprOrTypeTrait ExprKind,
5786                                   bool IsType, void *TyOrEx,
5787                                   SourceRange ArgRange);
5788 
5789   ExprResult CheckPlaceholderExpr(Expr *E);
5790   bool CheckVecStepExpr(Expr *E);
5791 
5792   bool CheckUnaryExprOrTypeTraitOperand(Expr *E, UnaryExprOrTypeTrait ExprKind);
5793   bool CheckUnaryExprOrTypeTraitOperand(QualType ExprType, SourceLocation OpLoc,
5794                                         SourceRange ExprRange,
5795                                         UnaryExprOrTypeTrait ExprKind,
5796                                         StringRef KWName);
5797   ExprResult ActOnSizeofParameterPackExpr(Scope *S,
5798                                           SourceLocation OpLoc,
5799                                           IdentifierInfo &Name,
5800                                           SourceLocation NameLoc,
5801                                           SourceLocation RParenLoc);
5802   ExprResult ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
5803                                  tok::TokenKind Kind, Expr *Input);
5804 
5805   ExprResult ActOnArraySubscriptExpr(Scope *S, Expr *Base, SourceLocation LLoc,
5806                                      MultiExprArg ArgExprs,
5807                                      SourceLocation RLoc);
5808   ExprResult CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
5809                                              Expr *Idx, SourceLocation RLoc);
5810 
5811   ExprResult CreateBuiltinMatrixSubscriptExpr(Expr *Base, Expr *RowIdx,
5812                                               Expr *ColumnIdx,
5813                                               SourceLocation RBLoc);
5814 
5815   ExprResult ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc,
5816                                       Expr *LowerBound,
5817                                       SourceLocation ColonLocFirst,
5818                                       SourceLocation ColonLocSecond,
5819                                       Expr *Length, Expr *Stride,
5820                                       SourceLocation RBLoc);
5821   ExprResult ActOnOMPArrayShapingExpr(Expr *Base, SourceLocation LParenLoc,
5822                                       SourceLocation RParenLoc,
5823                                       ArrayRef<Expr *> Dims,
5824                                       ArrayRef<SourceRange> Brackets);
5825 
5826   /// Data structure for iterator expression.
5827   struct OMPIteratorData {
5828     IdentifierInfo *DeclIdent = nullptr;
5829     SourceLocation DeclIdentLoc;
5830     ParsedType Type;
5831     OMPIteratorExpr::IteratorRange Range;
5832     SourceLocation AssignLoc;
5833     SourceLocation ColonLoc;
5834     SourceLocation SecColonLoc;
5835   };
5836 
5837   ExprResult ActOnOMPIteratorExpr(Scope *S, SourceLocation IteratorKwLoc,
5838                                   SourceLocation LLoc, SourceLocation RLoc,
5839                                   ArrayRef<OMPIteratorData> Data);
5840 
5841   // This struct is for use by ActOnMemberAccess to allow
5842   // BuildMemberReferenceExpr to be able to reinvoke ActOnMemberAccess after
5843   // changing the access operator from a '.' to a '->' (to see if that is the
5844   // change needed to fix an error about an unknown member, e.g. when the class
5845   // defines a custom operator->).
5846   struct ActOnMemberAccessExtraArgs {
5847     Scope *S;
5848     UnqualifiedId &Id;
5849     Decl *ObjCImpDecl;
5850   };
5851 
5852   ExprResult BuildMemberReferenceExpr(
5853       Expr *Base, QualType BaseType, SourceLocation OpLoc, bool IsArrow,
5854       CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
5855       NamedDecl *FirstQualifierInScope, const DeclarationNameInfo &NameInfo,
5856       const TemplateArgumentListInfo *TemplateArgs,
5857       const Scope *S,
5858       ActOnMemberAccessExtraArgs *ExtraArgs = nullptr);
5859 
5860   ExprResult
5861   BuildMemberReferenceExpr(Expr *Base, QualType BaseType, SourceLocation OpLoc,
5862                            bool IsArrow, const CXXScopeSpec &SS,
5863                            SourceLocation TemplateKWLoc,
5864                            NamedDecl *FirstQualifierInScope, LookupResult &R,
5865                            const TemplateArgumentListInfo *TemplateArgs,
5866                            const Scope *S,
5867                            bool SuppressQualifierCheck = false,
5868                            ActOnMemberAccessExtraArgs *ExtraArgs = nullptr);
5869 
5870   ExprResult BuildFieldReferenceExpr(Expr *BaseExpr, bool IsArrow,
5871                                      SourceLocation OpLoc,
5872                                      const CXXScopeSpec &SS, FieldDecl *Field,
5873                                      DeclAccessPair FoundDecl,
5874                                      const DeclarationNameInfo &MemberNameInfo);
5875 
5876   ExprResult PerformMemberExprBaseConversion(Expr *Base, bool IsArrow);
5877 
5878   bool CheckQualifiedMemberReference(Expr *BaseExpr, QualType BaseType,
5879                                      const CXXScopeSpec &SS,
5880                                      const LookupResult &R);
5881 
5882   ExprResult ActOnDependentMemberExpr(Expr *Base, QualType BaseType,
5883                                       bool IsArrow, SourceLocation OpLoc,
5884                                       const CXXScopeSpec &SS,
5885                                       SourceLocation TemplateKWLoc,
5886                                       NamedDecl *FirstQualifierInScope,
5887                                const DeclarationNameInfo &NameInfo,
5888                                const TemplateArgumentListInfo *TemplateArgs);
5889 
5890   ExprResult ActOnMemberAccessExpr(Scope *S, Expr *Base,
5891                                    SourceLocation OpLoc,
5892                                    tok::TokenKind OpKind,
5893                                    CXXScopeSpec &SS,
5894                                    SourceLocation TemplateKWLoc,
5895                                    UnqualifiedId &Member,
5896                                    Decl *ObjCImpDecl);
5897 
5898   MemberExpr *
5899   BuildMemberExpr(Expr *Base, bool IsArrow, SourceLocation OpLoc,
5900                   const CXXScopeSpec *SS, SourceLocation TemplateKWLoc,
5901                   ValueDecl *Member, DeclAccessPair FoundDecl,
5902                   bool HadMultipleCandidates,
5903                   const DeclarationNameInfo &MemberNameInfo, QualType Ty,
5904                   ExprValueKind VK, ExprObjectKind OK,
5905                   const TemplateArgumentListInfo *TemplateArgs = nullptr);
5906   MemberExpr *
5907   BuildMemberExpr(Expr *Base, bool IsArrow, SourceLocation OpLoc,
5908                   NestedNameSpecifierLoc NNS, SourceLocation TemplateKWLoc,
5909                   ValueDecl *Member, DeclAccessPair FoundDecl,
5910                   bool HadMultipleCandidates,
5911                   const DeclarationNameInfo &MemberNameInfo, QualType Ty,
5912                   ExprValueKind VK, ExprObjectKind OK,
5913                   const TemplateArgumentListInfo *TemplateArgs = nullptr);
5914 
5915   void ActOnDefaultCtorInitializers(Decl *CDtorDecl);
5916   bool ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
5917                                FunctionDecl *FDecl,
5918                                const FunctionProtoType *Proto,
5919                                ArrayRef<Expr *> Args,
5920                                SourceLocation RParenLoc,
5921                                bool ExecConfig = false);
5922   void CheckStaticArrayArgument(SourceLocation CallLoc,
5923                                 ParmVarDecl *Param,
5924                                 const Expr *ArgExpr);
5925 
5926   /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
5927   /// This provides the location of the left/right parens and a list of comma
5928   /// locations.
5929   ExprResult ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
5930                            MultiExprArg ArgExprs, SourceLocation RParenLoc,
5931                            Expr *ExecConfig = nullptr);
5932   ExprResult BuildCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
5933                            MultiExprArg ArgExprs, SourceLocation RParenLoc,
5934                            Expr *ExecConfig = nullptr,
5935                            bool IsExecConfig = false,
5936                            bool AllowRecovery = false);
5937   Expr *BuildBuiltinCallExpr(SourceLocation Loc, Builtin::ID Id,
5938                              MultiExprArg CallArgs);
5939   enum class AtomicArgumentOrder { API, AST };
5940   ExprResult
5941   BuildAtomicExpr(SourceRange CallRange, SourceRange ExprRange,
5942                   SourceLocation RParenLoc, MultiExprArg Args,
5943                   AtomicExpr::AtomicOp Op,
5944                   AtomicArgumentOrder ArgOrder = AtomicArgumentOrder::API);
5945   ExprResult
5946   BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl, SourceLocation LParenLoc,
5947                         ArrayRef<Expr *> Arg, SourceLocation RParenLoc,
5948                         Expr *Config = nullptr, bool IsExecConfig = false,
5949                         ADLCallKind UsesADL = ADLCallKind::NotADL);
5950 
5951   ExprResult ActOnCUDAExecConfigExpr(Scope *S, SourceLocation LLLLoc,
5952                                      MultiExprArg ExecConfig,
5953                                      SourceLocation GGGLoc);
5954 
5955   ExprResult ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
5956                            Declarator &D, ParsedType &Ty,
5957                            SourceLocation RParenLoc, Expr *CastExpr);
5958   ExprResult BuildCStyleCastExpr(SourceLocation LParenLoc,
5959                                  TypeSourceInfo *Ty,
5960                                  SourceLocation RParenLoc,
5961                                  Expr *Op);
5962   CastKind PrepareScalarCast(ExprResult &src, QualType destType);
5963 
5964   /// Build an altivec or OpenCL literal.
5965   ExprResult BuildVectorLiteral(SourceLocation LParenLoc,
5966                                 SourceLocation RParenLoc, Expr *E,
5967                                 TypeSourceInfo *TInfo);
5968 
5969   ExprResult MaybeConvertParenListExprToParenExpr(Scope *S, Expr *ME);
5970 
5971   ExprResult ActOnCompoundLiteral(SourceLocation LParenLoc,
5972                                   ParsedType Ty,
5973                                   SourceLocation RParenLoc,
5974                                   Expr *InitExpr);
5975 
5976   ExprResult BuildCompoundLiteralExpr(SourceLocation LParenLoc,
5977                                       TypeSourceInfo *TInfo,
5978                                       SourceLocation RParenLoc,
5979                                       Expr *LiteralExpr);
5980 
5981   ExprResult ActOnInitList(SourceLocation LBraceLoc,
5982                            MultiExprArg InitArgList,
5983                            SourceLocation RBraceLoc);
5984 
5985   ExprResult BuildInitList(SourceLocation LBraceLoc,
5986                            MultiExprArg InitArgList,
5987                            SourceLocation RBraceLoc);
5988 
5989   ExprResult ActOnDesignatedInitializer(Designation &Desig,
5990                                         SourceLocation EqualOrColonLoc,
5991                                         bool GNUSyntax,
5992                                         ExprResult Init);
5993 
5994 private:
5995   static BinaryOperatorKind ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind);
5996 
5997 public:
5998   ExprResult ActOnBinOp(Scope *S, SourceLocation TokLoc,
5999                         tok::TokenKind Kind, Expr *LHSExpr, Expr *RHSExpr);
6000   ExprResult BuildBinOp(Scope *S, SourceLocation OpLoc,
6001                         BinaryOperatorKind Opc, Expr *LHSExpr, Expr *RHSExpr);
6002   ExprResult CreateBuiltinBinOp(SourceLocation OpLoc, BinaryOperatorKind Opc,
6003                                 Expr *LHSExpr, Expr *RHSExpr);
6004   void LookupBinOp(Scope *S, SourceLocation OpLoc, BinaryOperatorKind Opc,
6005                    UnresolvedSetImpl &Functions);
6006 
6007   void DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc);
6008 
6009   /// ActOnConditionalOp - Parse a ?: operation.  Note that 'LHS' may be null
6010   /// in the case of a the GNU conditional expr extension.
6011   ExprResult ActOnConditionalOp(SourceLocation QuestionLoc,
6012                                 SourceLocation ColonLoc,
6013                                 Expr *CondExpr, Expr *LHSExpr, Expr *RHSExpr);
6014 
6015   /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
6016   ExprResult ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
6017                             LabelDecl *TheDecl);
6018 
6019   void ActOnStartStmtExpr();
6020   ExprResult ActOnStmtExpr(Scope *S, SourceLocation LPLoc, Stmt *SubStmt,
6021                            SourceLocation RPLoc);
6022   ExprResult BuildStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
6023                            SourceLocation RPLoc, unsigned TemplateDepth);
6024   // Handle the final expression in a statement expression.
6025   ExprResult ActOnStmtExprResult(ExprResult E);
6026   void ActOnStmtExprError();
6027 
6028   // __builtin_offsetof(type, identifier(.identifier|[expr])*)
6029   struct OffsetOfComponent {
6030     SourceLocation LocStart, LocEnd;
6031     bool isBrackets;  // true if [expr], false if .ident
6032     union {
6033       IdentifierInfo *IdentInfo;
6034       Expr *E;
6035     } U;
6036   };
6037 
6038   /// __builtin_offsetof(type, a.b[123][456].c)
6039   ExprResult BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
6040                                   TypeSourceInfo *TInfo,
6041                                   ArrayRef<OffsetOfComponent> Components,
6042                                   SourceLocation RParenLoc);
6043   ExprResult ActOnBuiltinOffsetOf(Scope *S,
6044                                   SourceLocation BuiltinLoc,
6045                                   SourceLocation TypeLoc,
6046                                   ParsedType ParsedArgTy,
6047                                   ArrayRef<OffsetOfComponent> Components,
6048                                   SourceLocation RParenLoc);
6049 
6050   // __builtin_choose_expr(constExpr, expr1, expr2)
6051   ExprResult ActOnChooseExpr(SourceLocation BuiltinLoc,
6052                              Expr *CondExpr, Expr *LHSExpr,
6053                              Expr *RHSExpr, SourceLocation RPLoc);
6054 
6055   // __builtin_va_arg(expr, type)
6056   ExprResult ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty,
6057                         SourceLocation RPLoc);
6058   ExprResult BuildVAArgExpr(SourceLocation BuiltinLoc, Expr *E,
6059                             TypeSourceInfo *TInfo, SourceLocation RPLoc);
6060 
6061   // __builtin_LINE(), __builtin_FUNCTION(), __builtin_FUNCSIG(),
6062   // __builtin_FILE(), __builtin_COLUMN(), __builtin_source_location()
6063   ExprResult ActOnSourceLocExpr(SourceLocExpr::IdentKind Kind,
6064                                 SourceLocation BuiltinLoc,
6065                                 SourceLocation RPLoc);
6066 
6067   // Build a potentially resolved SourceLocExpr.
6068   ExprResult BuildSourceLocExpr(SourceLocExpr::IdentKind Kind,
6069                                 QualType ResultTy, SourceLocation BuiltinLoc,
6070                                 SourceLocation RPLoc,
6071                                 DeclContext *ParentContext);
6072 
6073   // __null
6074   ExprResult ActOnGNUNullExpr(SourceLocation TokenLoc);
6075 
6076   bool CheckCaseExpression(Expr *E);
6077 
6078   /// Describes the result of an "if-exists" condition check.
6079   enum IfExistsResult {
6080     /// The symbol exists.
6081     IER_Exists,
6082 
6083     /// The symbol does not exist.
6084     IER_DoesNotExist,
6085 
6086     /// The name is a dependent name, so the results will differ
6087     /// from one instantiation to the next.
6088     IER_Dependent,
6089 
6090     /// An error occurred.
6091     IER_Error
6092   };
6093 
6094   IfExistsResult
6095   CheckMicrosoftIfExistsSymbol(Scope *S, CXXScopeSpec &SS,
6096                                const DeclarationNameInfo &TargetNameInfo);
6097 
6098   IfExistsResult
6099   CheckMicrosoftIfExistsSymbol(Scope *S, SourceLocation KeywordLoc,
6100                                bool IsIfExists, CXXScopeSpec &SS,
6101                                UnqualifiedId &Name);
6102 
6103   StmtResult BuildMSDependentExistsStmt(SourceLocation KeywordLoc,
6104                                         bool IsIfExists,
6105                                         NestedNameSpecifierLoc QualifierLoc,
6106                                         DeclarationNameInfo NameInfo,
6107                                         Stmt *Nested);
6108   StmtResult ActOnMSDependentExistsStmt(SourceLocation KeywordLoc,
6109                                         bool IsIfExists,
6110                                         CXXScopeSpec &SS, UnqualifiedId &Name,
6111                                         Stmt *Nested);
6112 
6113   //===------------------------- "Block" Extension ------------------------===//
6114 
6115   /// ActOnBlockStart - This callback is invoked when a block literal is
6116   /// started.
6117   void ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope);
6118 
6119   /// ActOnBlockArguments - This callback allows processing of block arguments.
6120   /// If there are no arguments, this is still invoked.
6121   void ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
6122                            Scope *CurScope);
6123 
6124   /// ActOnBlockError - If there is an error parsing a block, this callback
6125   /// is invoked to pop the information about the block from the action impl.
6126   void ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope);
6127 
6128   /// ActOnBlockStmtExpr - This is called when the body of a block statement
6129   /// literal was successfully completed.  ^(int x){...}
6130   ExprResult ActOnBlockStmtExpr(SourceLocation CaretLoc, Stmt *Body,
6131                                 Scope *CurScope);
6132 
6133   //===---------------------------- Clang Extensions ----------------------===//
6134 
6135   /// __builtin_convertvector(...)
6136   ExprResult ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy,
6137                                     SourceLocation BuiltinLoc,
6138                                     SourceLocation RParenLoc);
6139 
6140   //===---------------------------- OpenCL Features -----------------------===//
6141 
6142   /// __builtin_astype(...)
6143   ExprResult ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
6144                              SourceLocation BuiltinLoc,
6145                              SourceLocation RParenLoc);
6146   ExprResult BuildAsTypeExpr(Expr *E, QualType DestTy,
6147                              SourceLocation BuiltinLoc,
6148                              SourceLocation RParenLoc);
6149 
6150   //===---------------------------- HLSL Features -------------------------===//
6151   Decl *ActOnStartHLSLBuffer(Scope *BufferScope, bool CBuffer,
6152                              SourceLocation KwLoc, IdentifierInfo *Ident,
6153                              SourceLocation IdentLoc, SourceLocation LBrace);
6154   void ActOnFinishHLSLBuffer(Decl *Dcl, SourceLocation RBrace);
6155 
6156   //===---------------------------- C++ Features --------------------------===//
6157 
6158   // Act on C++ namespaces
6159   Decl *ActOnStartNamespaceDef(Scope *S, SourceLocation InlineLoc,
6160                                SourceLocation NamespaceLoc,
6161                                SourceLocation IdentLoc, IdentifierInfo *Ident,
6162                                SourceLocation LBrace,
6163                                const ParsedAttributesView &AttrList,
6164                                UsingDirectiveDecl *&UsingDecl, bool IsNested);
6165   void ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace);
6166 
6167   NamespaceDecl *getStdNamespace() const;
6168   NamespaceDecl *getOrCreateStdNamespace();
6169 
6170   CXXRecordDecl *getStdBadAlloc() const;
6171   EnumDecl *getStdAlignValT() const;
6172 
6173 private:
6174   // A cache representing if we've fully checked the various comparison category
6175   // types stored in ASTContext. The bit-index corresponds to the integer value
6176   // of a ComparisonCategoryType enumerator.
6177   llvm::SmallBitVector FullyCheckedComparisonCategories;
6178 
6179   ValueDecl *tryLookupCtorInitMemberDecl(CXXRecordDecl *ClassDecl,
6180                                          CXXScopeSpec &SS,
6181                                          ParsedType TemplateTypeTy,
6182                                          IdentifierInfo *MemberOrBase);
6183 
6184 public:
6185   enum class ComparisonCategoryUsage {
6186     /// The '<=>' operator was used in an expression and a builtin operator
6187     /// was selected.
6188     OperatorInExpression,
6189     /// A defaulted 'operator<=>' needed the comparison category. This
6190     /// typically only applies to 'std::strong_ordering', due to the implicit
6191     /// fallback return value.
6192     DefaultedOperator,
6193   };
6194 
6195   /// Lookup the specified comparison category types in the standard
6196   ///   library, an check the VarDecls possibly returned by the operator<=>
6197   ///   builtins for that type.
6198   ///
6199   /// \return The type of the comparison category type corresponding to the
6200   ///   specified Kind, or a null type if an error occurs
6201   QualType CheckComparisonCategoryType(ComparisonCategoryType Kind,
6202                                        SourceLocation Loc,
6203                                        ComparisonCategoryUsage Usage);
6204 
6205   /// Tests whether Ty is an instance of std::initializer_list and, if
6206   /// it is and Element is not NULL, assigns the element type to Element.
6207   bool isStdInitializerList(QualType Ty, QualType *Element);
6208 
6209   /// Looks for the std::initializer_list template and instantiates it
6210   /// with Element, or emits an error if it's not found.
6211   ///
6212   /// \returns The instantiated template, or null on error.
6213   QualType BuildStdInitializerList(QualType Element, SourceLocation Loc);
6214 
6215   /// Determine whether Ctor is an initializer-list constructor, as
6216   /// defined in [dcl.init.list]p2.
6217   bool isInitListConstructor(const FunctionDecl *Ctor);
6218 
6219   Decl *ActOnUsingDirective(Scope *CurScope, SourceLocation UsingLoc,
6220                             SourceLocation NamespcLoc, CXXScopeSpec &SS,
6221                             SourceLocation IdentLoc,
6222                             IdentifierInfo *NamespcName,
6223                             const ParsedAttributesView &AttrList);
6224 
6225   void PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir);
6226 
6227   Decl *ActOnNamespaceAliasDef(Scope *CurScope,
6228                                SourceLocation NamespaceLoc,
6229                                SourceLocation AliasLoc,
6230                                IdentifierInfo *Alias,
6231                                CXXScopeSpec &SS,
6232                                SourceLocation IdentLoc,
6233                                IdentifierInfo *Ident);
6234 
6235   void FilterUsingLookup(Scope *S, LookupResult &lookup);
6236   void HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow);
6237   bool CheckUsingShadowDecl(BaseUsingDecl *BUD, NamedDecl *Target,
6238                             const LookupResult &PreviousDecls,
6239                             UsingShadowDecl *&PrevShadow);
6240   UsingShadowDecl *BuildUsingShadowDecl(Scope *S, BaseUsingDecl *BUD,
6241                                         NamedDecl *Target,
6242                                         UsingShadowDecl *PrevDecl);
6243 
6244   bool CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
6245                                    bool HasTypenameKeyword,
6246                                    const CXXScopeSpec &SS,
6247                                    SourceLocation NameLoc,
6248                                    const LookupResult &Previous);
6249   bool CheckUsingDeclQualifier(SourceLocation UsingLoc, bool HasTypename,
6250                                const CXXScopeSpec &SS,
6251                                const DeclarationNameInfo &NameInfo,
6252                                SourceLocation NameLoc,
6253                                const LookupResult *R = nullptr,
6254                                const UsingDecl *UD = nullptr);
6255 
6256   NamedDecl *BuildUsingDeclaration(
6257       Scope *S, AccessSpecifier AS, SourceLocation UsingLoc,
6258       bool HasTypenameKeyword, SourceLocation TypenameLoc, CXXScopeSpec &SS,
6259       DeclarationNameInfo NameInfo, SourceLocation EllipsisLoc,
6260       const ParsedAttributesView &AttrList, bool IsInstantiation,
6261       bool IsUsingIfExists);
6262   NamedDecl *BuildUsingEnumDeclaration(Scope *S, AccessSpecifier AS,
6263                                        SourceLocation UsingLoc,
6264                                        SourceLocation EnumLoc,
6265                                        SourceLocation NameLoc,
6266                                        TypeSourceInfo *EnumType, EnumDecl *ED);
6267   NamedDecl *BuildUsingPackDecl(NamedDecl *InstantiatedFrom,
6268                                 ArrayRef<NamedDecl *> Expansions);
6269 
6270   bool CheckInheritingConstructorUsingDecl(UsingDecl *UD);
6271 
6272   /// Given a derived-class using shadow declaration for a constructor and the
6273   /// correspnding base class constructor, find or create the implicit
6274   /// synthesized derived class constructor to use for this initialization.
6275   CXXConstructorDecl *
6276   findInheritingConstructor(SourceLocation Loc, CXXConstructorDecl *BaseCtor,
6277                             ConstructorUsingShadowDecl *DerivedShadow);
6278 
6279   Decl *ActOnUsingDeclaration(Scope *CurScope, AccessSpecifier AS,
6280                               SourceLocation UsingLoc,
6281                               SourceLocation TypenameLoc, CXXScopeSpec &SS,
6282                               UnqualifiedId &Name, SourceLocation EllipsisLoc,
6283                               const ParsedAttributesView &AttrList);
6284   Decl *ActOnUsingEnumDeclaration(Scope *CurScope, AccessSpecifier AS,
6285                                   SourceLocation UsingLoc,
6286                                   SourceLocation EnumLoc,
6287                                   SourceLocation IdentLoc, IdentifierInfo &II,
6288                                   CXXScopeSpec *SS = nullptr);
6289   Decl *ActOnAliasDeclaration(Scope *CurScope, AccessSpecifier AS,
6290                               MultiTemplateParamsArg TemplateParams,
6291                               SourceLocation UsingLoc, UnqualifiedId &Name,
6292                               const ParsedAttributesView &AttrList,
6293                               TypeResult Type, Decl *DeclFromDeclSpec);
6294 
6295   /// BuildCXXConstructExpr - Creates a complete call to a constructor,
6296   /// including handling of its default argument expressions.
6297   ///
6298   /// \param ConstructKind - a CXXConstructExpr::ConstructionKind
6299   ExprResult
6300   BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
6301                         NamedDecl *FoundDecl,
6302                         CXXConstructorDecl *Constructor, MultiExprArg Exprs,
6303                         bool HadMultipleCandidates, bool IsListInitialization,
6304                         bool IsStdInitListInitialization,
6305                         bool RequiresZeroInit, unsigned ConstructKind,
6306                         SourceRange ParenRange);
6307 
6308   /// Build a CXXConstructExpr whose constructor has already been resolved if
6309   /// it denotes an inherited constructor.
6310   ExprResult
6311   BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
6312                         CXXConstructorDecl *Constructor, bool Elidable,
6313                         MultiExprArg Exprs,
6314                         bool HadMultipleCandidates, bool IsListInitialization,
6315                         bool IsStdInitListInitialization,
6316                         bool RequiresZeroInit, unsigned ConstructKind,
6317                         SourceRange ParenRange);
6318 
6319   // FIXME: Can we remove this and have the above BuildCXXConstructExpr check if
6320   // the constructor can be elidable?
6321   ExprResult
6322   BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
6323                         NamedDecl *FoundDecl,
6324                         CXXConstructorDecl *Constructor, bool Elidable,
6325                         MultiExprArg Exprs, bool HadMultipleCandidates,
6326                         bool IsListInitialization,
6327                         bool IsStdInitListInitialization, bool RequiresZeroInit,
6328                         unsigned ConstructKind, SourceRange ParenRange);
6329 
6330   ExprResult ConvertMemberDefaultInitExpression(FieldDecl *FD, Expr *InitExpr,
6331                                                 SourceLocation InitLoc);
6332 
6333   ExprResult BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field);
6334 
6335 
6336   /// Instantiate or parse a C++ default argument expression as necessary.
6337   /// Return true on error.
6338   bool CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD,
6339                               ParmVarDecl *Param, Expr *Init = nullptr,
6340                               bool SkipImmediateInvocations = true);
6341 
6342   /// BuildCXXDefaultArgExpr - Creates a CXXDefaultArgExpr, instantiating
6343   /// the default expr if needed.
6344   ExprResult BuildCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD,
6345                                     ParmVarDecl *Param, Expr *Init = nullptr);
6346 
6347   /// FinalizeVarWithDestructor - Prepare for calling destructor on the
6348   /// constructed variable.
6349   void FinalizeVarWithDestructor(VarDecl *VD, const RecordType *DeclInitType);
6350 
6351   /// Helper class that collects exception specifications for
6352   /// implicitly-declared special member functions.
6353   class ImplicitExceptionSpecification {
6354     // Pointer to allow copying
6355     Sema *Self;
6356     // We order exception specifications thus:
6357     // noexcept is the most restrictive, but is only used in C++11.
6358     // throw() comes next.
6359     // Then a throw(collected exceptions)
6360     // Finally no specification, which is expressed as noexcept(false).
6361     // throw(...) is used instead if any called function uses it.
6362     ExceptionSpecificationType ComputedEST;
6363     llvm::SmallPtrSet<CanQualType, 4> ExceptionsSeen;
6364     SmallVector<QualType, 4> Exceptions;
6365 
6366     void ClearExceptions() {
6367       ExceptionsSeen.clear();
6368       Exceptions.clear();
6369     }
6370 
6371   public:
6372     explicit ImplicitExceptionSpecification(Sema &Self)
6373       : Self(&Self), ComputedEST(EST_BasicNoexcept) {
6374       if (!Self.getLangOpts().CPlusPlus11)
6375         ComputedEST = EST_DynamicNone;
6376     }
6377 
6378     /// Get the computed exception specification type.
6379     ExceptionSpecificationType getExceptionSpecType() const {
6380       assert(!isComputedNoexcept(ComputedEST) &&
6381              "noexcept(expr) should not be a possible result");
6382       return ComputedEST;
6383     }
6384 
6385     /// The number of exceptions in the exception specification.
6386     unsigned size() const { return Exceptions.size(); }
6387 
6388     /// The set of exceptions in the exception specification.
6389     const QualType *data() const { return Exceptions.data(); }
6390 
6391     /// Integrate another called method into the collected data.
6392     void CalledDecl(SourceLocation CallLoc, const CXXMethodDecl *Method);
6393 
6394     /// Integrate an invoked expression into the collected data.
6395     void CalledExpr(Expr *E) { CalledStmt(E); }
6396 
6397     /// Integrate an invoked statement into the collected data.
6398     void CalledStmt(Stmt *S);
6399 
6400     /// Overwrite an EPI's exception specification with this
6401     /// computed exception specification.
6402     FunctionProtoType::ExceptionSpecInfo getExceptionSpec() const {
6403       FunctionProtoType::ExceptionSpecInfo ESI;
6404       ESI.Type = getExceptionSpecType();
6405       if (ESI.Type == EST_Dynamic) {
6406         ESI.Exceptions = Exceptions;
6407       } else if (ESI.Type == EST_None) {
6408         /// C++11 [except.spec]p14:
6409         ///   The exception-specification is noexcept(false) if the set of
6410         ///   potential exceptions of the special member function contains "any"
6411         ESI.Type = EST_NoexceptFalse;
6412         ESI.NoexceptExpr = Self->ActOnCXXBoolLiteral(SourceLocation(),
6413                                                      tok::kw_false).get();
6414       }
6415       return ESI;
6416     }
6417   };
6418 
6419   /// Evaluate the implicit exception specification for a defaulted
6420   /// special member function.
6421   void EvaluateImplicitExceptionSpec(SourceLocation Loc, FunctionDecl *FD);
6422 
6423   /// Check the given noexcept-specifier, convert its expression, and compute
6424   /// the appropriate ExceptionSpecificationType.
6425   ExprResult ActOnNoexceptSpec(Expr *NoexceptExpr,
6426                                ExceptionSpecificationType &EST);
6427 
6428   /// Check the given exception-specification and update the
6429   /// exception specification information with the results.
6430   void checkExceptionSpecification(bool IsTopLevel,
6431                                    ExceptionSpecificationType EST,
6432                                    ArrayRef<ParsedType> DynamicExceptions,
6433                                    ArrayRef<SourceRange> DynamicExceptionRanges,
6434                                    Expr *NoexceptExpr,
6435                                    SmallVectorImpl<QualType> &Exceptions,
6436                                    FunctionProtoType::ExceptionSpecInfo &ESI);
6437 
6438   /// Determine if we're in a case where we need to (incorrectly) eagerly
6439   /// parse an exception specification to work around a libstdc++ bug.
6440   bool isLibstdcxxEagerExceptionSpecHack(const Declarator &D);
6441 
6442   /// Add an exception-specification to the given member function
6443   /// (or member function template). The exception-specification was parsed
6444   /// after the method itself was declared.
6445   void actOnDelayedExceptionSpecification(Decl *Method,
6446          ExceptionSpecificationType EST,
6447          SourceRange SpecificationRange,
6448          ArrayRef<ParsedType> DynamicExceptions,
6449          ArrayRef<SourceRange> DynamicExceptionRanges,
6450          Expr *NoexceptExpr);
6451 
6452   class InheritedConstructorInfo;
6453 
6454   /// Determine if a special member function should have a deleted
6455   /// definition when it is defaulted.
6456   bool ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
6457                                  InheritedConstructorInfo *ICI = nullptr,
6458                                  bool Diagnose = false);
6459 
6460   /// Produce notes explaining why a defaulted function was defined as deleted.
6461   void DiagnoseDeletedDefaultedFunction(FunctionDecl *FD);
6462 
6463   /// Declare the implicit default constructor for the given class.
6464   ///
6465   /// \param ClassDecl The class declaration into which the implicit
6466   /// default constructor will be added.
6467   ///
6468   /// \returns The implicitly-declared default constructor.
6469   CXXConstructorDecl *DeclareImplicitDefaultConstructor(
6470                                                      CXXRecordDecl *ClassDecl);
6471 
6472   /// DefineImplicitDefaultConstructor - Checks for feasibility of
6473   /// defining this constructor as the default constructor.
6474   void DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
6475                                         CXXConstructorDecl *Constructor);
6476 
6477   /// Declare the implicit destructor for the given class.
6478   ///
6479   /// \param ClassDecl The class declaration into which the implicit
6480   /// destructor will be added.
6481   ///
6482   /// \returns The implicitly-declared destructor.
6483   CXXDestructorDecl *DeclareImplicitDestructor(CXXRecordDecl *ClassDecl);
6484 
6485   /// DefineImplicitDestructor - Checks for feasibility of
6486   /// defining this destructor as the default destructor.
6487   void DefineImplicitDestructor(SourceLocation CurrentLocation,
6488                                 CXXDestructorDecl *Destructor);
6489 
6490   /// Build an exception spec for destructors that don't have one.
6491   ///
6492   /// C++11 says that user-defined destructors with no exception spec get one
6493   /// that looks as if the destructor was implicitly declared.
6494   void AdjustDestructorExceptionSpec(CXXDestructorDecl *Destructor);
6495 
6496   /// Define the specified inheriting constructor.
6497   void DefineInheritingConstructor(SourceLocation UseLoc,
6498                                    CXXConstructorDecl *Constructor);
6499 
6500   /// Declare the implicit copy constructor for the given class.
6501   ///
6502   /// \param ClassDecl The class declaration into which the implicit
6503   /// copy constructor will be added.
6504   ///
6505   /// \returns The implicitly-declared copy constructor.
6506   CXXConstructorDecl *DeclareImplicitCopyConstructor(CXXRecordDecl *ClassDecl);
6507 
6508   /// DefineImplicitCopyConstructor - Checks for feasibility of
6509   /// defining this constructor as the copy constructor.
6510   void DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
6511                                      CXXConstructorDecl *Constructor);
6512 
6513   /// Declare the implicit move constructor for the given class.
6514   ///
6515   /// \param ClassDecl The Class declaration into which the implicit
6516   /// move constructor will be added.
6517   ///
6518   /// \returns The implicitly-declared move constructor, or NULL if it wasn't
6519   /// declared.
6520   CXXConstructorDecl *DeclareImplicitMoveConstructor(CXXRecordDecl *ClassDecl);
6521 
6522   /// DefineImplicitMoveConstructor - Checks for feasibility of
6523   /// defining this constructor as the move constructor.
6524   void DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
6525                                      CXXConstructorDecl *Constructor);
6526 
6527   /// Declare the implicit copy assignment operator for the given class.
6528   ///
6529   /// \param ClassDecl The class declaration into which the implicit
6530   /// copy assignment operator will be added.
6531   ///
6532   /// \returns The implicitly-declared copy assignment operator.
6533   CXXMethodDecl *DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl);
6534 
6535   /// Defines an implicitly-declared copy assignment operator.
6536   void DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
6537                                     CXXMethodDecl *MethodDecl);
6538 
6539   /// Declare the implicit move assignment operator for the given class.
6540   ///
6541   /// \param ClassDecl The Class declaration into which the implicit
6542   /// move assignment operator will be added.
6543   ///
6544   /// \returns The implicitly-declared move assignment operator, or NULL if it
6545   /// wasn't declared.
6546   CXXMethodDecl *DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl);
6547 
6548   /// Defines an implicitly-declared move assignment operator.
6549   void DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
6550                                     CXXMethodDecl *MethodDecl);
6551 
6552   /// Force the declaration of any implicitly-declared members of this
6553   /// class.
6554   void ForceDeclarationOfImplicitMembers(CXXRecordDecl *Class);
6555 
6556   /// Check a completed declaration of an implicit special member.
6557   void CheckImplicitSpecialMemberDeclaration(Scope *S, FunctionDecl *FD);
6558 
6559   /// Determine whether the given function is an implicitly-deleted
6560   /// special member function.
6561   bool isImplicitlyDeleted(FunctionDecl *FD);
6562 
6563   /// Check whether 'this' shows up in the type of a static member
6564   /// function after the (naturally empty) cv-qualifier-seq would be.
6565   ///
6566   /// \returns true if an error occurred.
6567   bool checkThisInStaticMemberFunctionType(CXXMethodDecl *Method);
6568 
6569   /// Whether this' shows up in the exception specification of a static
6570   /// member function.
6571   bool checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method);
6572 
6573   /// Check whether 'this' shows up in the attributes of the given
6574   /// static member function.
6575   ///
6576   /// \returns true if an error occurred.
6577   bool checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method);
6578 
6579   /// MaybeBindToTemporary - If the passed in expression has a record type with
6580   /// a non-trivial destructor, this will return CXXBindTemporaryExpr. Otherwise
6581   /// it simply returns the passed in expression.
6582   ExprResult MaybeBindToTemporary(Expr *E);
6583 
6584   /// Wrap the expression in a ConstantExpr if it is a potential immediate
6585   /// invocation.
6586   ExprResult CheckForImmediateInvocation(ExprResult E, FunctionDecl *Decl);
6587 
6588   bool CheckImmediateEscalatingFunctionDefinition(
6589       FunctionDecl *FD, const sema::FunctionScopeInfo *FSI);
6590 
6591   void MarkExpressionAsImmediateEscalating(Expr *E);
6592 
6593   void DiagnoseImmediateEscalatingReason(FunctionDecl *FD);
6594 
6595   bool CompleteConstructorCall(CXXConstructorDecl *Constructor,
6596                                QualType DeclInitType, MultiExprArg ArgsPtr,
6597                                SourceLocation Loc,
6598                                SmallVectorImpl<Expr *> &ConvertedArgs,
6599                                bool AllowExplicit = false,
6600                                bool IsListInitialization = false);
6601 
6602   ParsedType getInheritingConstructorName(CXXScopeSpec &SS,
6603                                           SourceLocation NameLoc,
6604                                           IdentifierInfo &Name);
6605 
6606   ParsedType getConstructorName(IdentifierInfo &II, SourceLocation NameLoc,
6607                                 Scope *S, CXXScopeSpec &SS,
6608                                 bool EnteringContext);
6609   ParsedType getDestructorName(SourceLocation TildeLoc,
6610                                IdentifierInfo &II, SourceLocation NameLoc,
6611                                Scope *S, CXXScopeSpec &SS,
6612                                ParsedType ObjectType,
6613                                bool EnteringContext);
6614 
6615   ParsedType getDestructorTypeForDecltype(const DeclSpec &DS,
6616                                           ParsedType ObjectType);
6617 
6618   // Checks that reinterpret casts don't have undefined behavior.
6619   void CheckCompatibleReinterpretCast(QualType SrcType, QualType DestType,
6620                                       bool IsDereference, SourceRange Range);
6621 
6622   // Checks that the vector type should be initialized from a scalar
6623   // by splatting the value rather than populating a single element.
6624   // This is the case for AltiVecVector types as well as with
6625   // AltiVecPixel and AltiVecBool when -faltivec-src-compat=xl is specified.
6626   bool ShouldSplatAltivecScalarInCast(const VectorType *VecTy);
6627 
6628   // Checks if the -faltivec-src-compat=gcc option is specified.
6629   // If so, AltiVecVector, AltiVecBool and AltiVecPixel types are
6630   // treated the same way as they are when trying to initialize
6631   // these vectors on gcc (an error is emitted).
6632   bool CheckAltivecInitFromScalar(SourceRange R, QualType VecTy,
6633                                   QualType SrcTy);
6634 
6635   /// ActOnCXXNamedCast - Parse
6636   /// {dynamic,static,reinterpret,const,addrspace}_cast's.
6637   ExprResult ActOnCXXNamedCast(SourceLocation OpLoc,
6638                                tok::TokenKind Kind,
6639                                SourceLocation LAngleBracketLoc,
6640                                Declarator &D,
6641                                SourceLocation RAngleBracketLoc,
6642                                SourceLocation LParenLoc,
6643                                Expr *E,
6644                                SourceLocation RParenLoc);
6645 
6646   ExprResult BuildCXXNamedCast(SourceLocation OpLoc,
6647                                tok::TokenKind Kind,
6648                                TypeSourceInfo *Ty,
6649                                Expr *E,
6650                                SourceRange AngleBrackets,
6651                                SourceRange Parens);
6652 
6653   ExprResult ActOnBuiltinBitCastExpr(SourceLocation KWLoc, Declarator &Dcl,
6654                                      ExprResult Operand,
6655                                      SourceLocation RParenLoc);
6656 
6657   ExprResult BuildBuiltinBitCastExpr(SourceLocation KWLoc, TypeSourceInfo *TSI,
6658                                      Expr *Operand, SourceLocation RParenLoc);
6659 
6660   ExprResult BuildCXXTypeId(QualType TypeInfoType,
6661                             SourceLocation TypeidLoc,
6662                             TypeSourceInfo *Operand,
6663                             SourceLocation RParenLoc);
6664   ExprResult BuildCXXTypeId(QualType TypeInfoType,
6665                             SourceLocation TypeidLoc,
6666                             Expr *Operand,
6667                             SourceLocation RParenLoc);
6668 
6669   /// ActOnCXXTypeid - Parse typeid( something ).
6670   ExprResult ActOnCXXTypeid(SourceLocation OpLoc,
6671                             SourceLocation LParenLoc, bool isType,
6672                             void *TyOrExpr,
6673                             SourceLocation RParenLoc);
6674 
6675   ExprResult BuildCXXUuidof(QualType TypeInfoType,
6676                             SourceLocation TypeidLoc,
6677                             TypeSourceInfo *Operand,
6678                             SourceLocation RParenLoc);
6679   ExprResult BuildCXXUuidof(QualType TypeInfoType,
6680                             SourceLocation TypeidLoc,
6681                             Expr *Operand,
6682                             SourceLocation RParenLoc);
6683 
6684   /// ActOnCXXUuidof - Parse __uuidof( something ).
6685   ExprResult ActOnCXXUuidof(SourceLocation OpLoc,
6686                             SourceLocation LParenLoc, bool isType,
6687                             void *TyOrExpr,
6688                             SourceLocation RParenLoc);
6689 
6690   /// Handle a C++1z fold-expression: ( expr op ... op expr ).
6691   ExprResult ActOnCXXFoldExpr(Scope *S, SourceLocation LParenLoc, Expr *LHS,
6692                               tok::TokenKind Operator,
6693                               SourceLocation EllipsisLoc, Expr *RHS,
6694                               SourceLocation RParenLoc);
6695   ExprResult BuildCXXFoldExpr(UnresolvedLookupExpr *Callee,
6696                               SourceLocation LParenLoc, Expr *LHS,
6697                               BinaryOperatorKind Operator,
6698                               SourceLocation EllipsisLoc, Expr *RHS,
6699                               SourceLocation RParenLoc,
6700                               std::optional<unsigned> NumExpansions);
6701   ExprResult BuildEmptyCXXFoldExpr(SourceLocation EllipsisLoc,
6702                                    BinaryOperatorKind Operator);
6703 
6704   //// ActOnCXXThis -  Parse 'this' pointer.
6705   ExprResult ActOnCXXThis(SourceLocation loc);
6706 
6707   /// Build a CXXThisExpr and mark it referenced in the current context.
6708   Expr *BuildCXXThisExpr(SourceLocation Loc, QualType Type, bool IsImplicit);
6709   void MarkThisReferenced(CXXThisExpr *This);
6710 
6711   /// Try to retrieve the type of the 'this' pointer.
6712   ///
6713   /// \returns The type of 'this', if possible. Otherwise, returns a NULL type.
6714   QualType getCurrentThisType();
6715 
6716   /// When non-NULL, the C++ 'this' expression is allowed despite the
6717   /// current context not being a non-static member function. In such cases,
6718   /// this provides the type used for 'this'.
6719   QualType CXXThisTypeOverride;
6720 
6721   /// RAII object used to temporarily allow the C++ 'this' expression
6722   /// to be used, with the given qualifiers on the current class type.
6723   class CXXThisScopeRAII {
6724     Sema &S;
6725     QualType OldCXXThisTypeOverride;
6726     bool Enabled;
6727 
6728   public:
6729     /// Introduce a new scope where 'this' may be allowed (when enabled),
6730     /// using the given declaration (which is either a class template or a
6731     /// class) along with the given qualifiers.
6732     /// along with the qualifiers placed on '*this'.
6733     CXXThisScopeRAII(Sema &S, Decl *ContextDecl, Qualifiers CXXThisTypeQuals,
6734                      bool Enabled = true);
6735 
6736     ~CXXThisScopeRAII();
6737   };
6738 
6739   /// Make sure the value of 'this' is actually available in the current
6740   /// context, if it is a potentially evaluated context.
6741   ///
6742   /// \param Loc The location at which the capture of 'this' occurs.
6743   ///
6744   /// \param Explicit Whether 'this' is explicitly captured in a lambda
6745   /// capture list.
6746   ///
6747   /// \param FunctionScopeIndexToStopAt If non-null, it points to the index
6748   /// of the FunctionScopeInfo stack beyond which we do not attempt to capture.
6749   /// This is useful when enclosing lambdas must speculatively capture
6750   /// 'this' that may or may not be used in certain specializations of
6751   /// a nested generic lambda (depending on whether the name resolves to
6752   /// a non-static member function or a static function).
6753   /// \return returns 'true' if failed, 'false' if success.
6754   bool CheckCXXThisCapture(SourceLocation Loc, bool Explicit = false,
6755       bool BuildAndDiagnose = true,
6756       const unsigned *const FunctionScopeIndexToStopAt = nullptr,
6757       bool ByCopy = false);
6758 
6759   /// Determine whether the given type is the type of *this that is used
6760   /// outside of the body of a member function for a type that is currently
6761   /// being defined.
6762   bool isThisOutsideMemberFunctionBody(QualType BaseType);
6763 
6764   /// ActOnCXXBoolLiteral - Parse {true,false} literals.
6765   ExprResult ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind);
6766 
6767 
6768   /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
6769   ExprResult ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind);
6770 
6771   ExprResult
6772   ActOnObjCAvailabilityCheckExpr(llvm::ArrayRef<AvailabilitySpec> AvailSpecs,
6773                                  SourceLocation AtLoc, SourceLocation RParen);
6774 
6775   /// ActOnCXXNullPtrLiteral - Parse 'nullptr'.
6776   ExprResult ActOnCXXNullPtrLiteral(SourceLocation Loc);
6777 
6778   //// ActOnCXXThrow -  Parse throw expressions.
6779   ExprResult ActOnCXXThrow(Scope *S, SourceLocation OpLoc, Expr *expr);
6780   ExprResult BuildCXXThrow(SourceLocation OpLoc, Expr *Ex,
6781                            bool IsThrownVarInScope);
6782   bool CheckCXXThrowOperand(SourceLocation ThrowLoc, QualType ThrowTy, Expr *E);
6783 
6784   /// ActOnCXXTypeConstructExpr - Parse construction of a specified type.
6785   /// Can be interpreted either as function-style casting ("int(x)")
6786   /// or class type construction ("ClassType(x,y,z)")
6787   /// or creation of a value-initialized type ("int()").
6788   ExprResult ActOnCXXTypeConstructExpr(ParsedType TypeRep,
6789                                        SourceLocation LParenOrBraceLoc,
6790                                        MultiExprArg Exprs,
6791                                        SourceLocation RParenOrBraceLoc,
6792                                        bool ListInitialization);
6793 
6794   ExprResult BuildCXXTypeConstructExpr(TypeSourceInfo *Type,
6795                                        SourceLocation LParenLoc,
6796                                        MultiExprArg Exprs,
6797                                        SourceLocation RParenLoc,
6798                                        bool ListInitialization);
6799 
6800   /// ActOnCXXNew - Parsed a C++ 'new' expression.
6801   ExprResult ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
6802                          SourceLocation PlacementLParen,
6803                          MultiExprArg PlacementArgs,
6804                          SourceLocation PlacementRParen,
6805                          SourceRange TypeIdParens, Declarator &D,
6806                          Expr *Initializer);
6807   ExprResult
6808   BuildCXXNew(SourceRange Range, bool UseGlobal, SourceLocation PlacementLParen,
6809               MultiExprArg PlacementArgs, SourceLocation PlacementRParen,
6810               SourceRange TypeIdParens, QualType AllocType,
6811               TypeSourceInfo *AllocTypeInfo, std::optional<Expr *> ArraySize,
6812               SourceRange DirectInitRange, Expr *Initializer);
6813 
6814   /// Determine whether \p FD is an aligned allocation or deallocation
6815   /// function that is unavailable.
6816   bool isUnavailableAlignedAllocationFunction(const FunctionDecl &FD) const;
6817 
6818   /// Produce diagnostics if \p FD is an aligned allocation or deallocation
6819   /// function that is unavailable.
6820   void diagnoseUnavailableAlignedAllocation(const FunctionDecl &FD,
6821                                             SourceLocation Loc);
6822 
6823   bool CheckAllocatedType(QualType AllocType, SourceLocation Loc,
6824                           SourceRange R);
6825 
6826   /// The scope in which to find allocation functions.
6827   enum AllocationFunctionScope {
6828     /// Only look for allocation functions in the global scope.
6829     AFS_Global,
6830     /// Only look for allocation functions in the scope of the
6831     /// allocated class.
6832     AFS_Class,
6833     /// Look for allocation functions in both the global scope
6834     /// and in the scope of the allocated class.
6835     AFS_Both
6836   };
6837 
6838   /// Finds the overloads of operator new and delete that are appropriate
6839   /// for the allocation.
6840   bool FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,
6841                                AllocationFunctionScope NewScope,
6842                                AllocationFunctionScope DeleteScope,
6843                                QualType AllocType, bool IsArray,
6844                                bool &PassAlignment, MultiExprArg PlaceArgs,
6845                                FunctionDecl *&OperatorNew,
6846                                FunctionDecl *&OperatorDelete,
6847                                bool Diagnose = true);
6848   void DeclareGlobalNewDelete();
6849   void DeclareGlobalAllocationFunction(DeclarationName Name, QualType Return,
6850                                        ArrayRef<QualType> Params);
6851 
6852   bool FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD,
6853                                 DeclarationName Name, FunctionDecl *&Operator,
6854                                 bool Diagnose = true, bool WantSize = false,
6855                                 bool WantAligned = false);
6856   FunctionDecl *FindUsualDeallocationFunction(SourceLocation StartLoc,
6857                                               bool CanProvideSize,
6858                                               bool Overaligned,
6859                                               DeclarationName Name);
6860   FunctionDecl *FindDeallocationFunctionForDestructor(SourceLocation StartLoc,
6861                                                       CXXRecordDecl *RD);
6862 
6863   /// ActOnCXXDelete - Parsed a C++ 'delete' expression
6864   ExprResult ActOnCXXDelete(SourceLocation StartLoc,
6865                             bool UseGlobal, bool ArrayForm,
6866                             Expr *Operand);
6867   void CheckVirtualDtorCall(CXXDestructorDecl *dtor, SourceLocation Loc,
6868                             bool IsDelete, bool CallCanBeVirtual,
6869                             bool WarnOnNonAbstractTypes,
6870                             SourceLocation DtorLoc);
6871 
6872   ExprResult ActOnNoexceptExpr(SourceLocation KeyLoc, SourceLocation LParen,
6873                                Expr *Operand, SourceLocation RParen);
6874   ExprResult BuildCXXNoexceptExpr(SourceLocation KeyLoc, Expr *Operand,
6875                                   SourceLocation RParen);
6876 
6877   /// Parsed one of the type trait support pseudo-functions.
6878   ExprResult ActOnTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
6879                             ArrayRef<ParsedType> Args,
6880                             SourceLocation RParenLoc);
6881   ExprResult BuildTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
6882                             ArrayRef<TypeSourceInfo *> Args,
6883                             SourceLocation RParenLoc);
6884 
6885   /// ActOnArrayTypeTrait - Parsed one of the binary type trait support
6886   /// pseudo-functions.
6887   ExprResult ActOnArrayTypeTrait(ArrayTypeTrait ATT,
6888                                  SourceLocation KWLoc,
6889                                  ParsedType LhsTy,
6890                                  Expr *DimExpr,
6891                                  SourceLocation RParen);
6892 
6893   ExprResult BuildArrayTypeTrait(ArrayTypeTrait ATT,
6894                                  SourceLocation KWLoc,
6895                                  TypeSourceInfo *TSInfo,
6896                                  Expr *DimExpr,
6897                                  SourceLocation RParen);
6898 
6899   /// ActOnExpressionTrait - Parsed one of the unary type trait support
6900   /// pseudo-functions.
6901   ExprResult ActOnExpressionTrait(ExpressionTrait OET,
6902                                   SourceLocation KWLoc,
6903                                   Expr *Queried,
6904                                   SourceLocation RParen);
6905 
6906   ExprResult BuildExpressionTrait(ExpressionTrait OET,
6907                                   SourceLocation KWLoc,
6908                                   Expr *Queried,
6909                                   SourceLocation RParen);
6910 
6911   ExprResult ActOnStartCXXMemberReference(Scope *S,
6912                                           Expr *Base,
6913                                           SourceLocation OpLoc,
6914                                           tok::TokenKind OpKind,
6915                                           ParsedType &ObjectType,
6916                                           bool &MayBePseudoDestructor);
6917 
6918   ExprResult BuildPseudoDestructorExpr(Expr *Base,
6919                                        SourceLocation OpLoc,
6920                                        tok::TokenKind OpKind,
6921                                        const CXXScopeSpec &SS,
6922                                        TypeSourceInfo *ScopeType,
6923                                        SourceLocation CCLoc,
6924                                        SourceLocation TildeLoc,
6925                                      PseudoDestructorTypeStorage DestroyedType);
6926 
6927   ExprResult ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
6928                                        SourceLocation OpLoc,
6929                                        tok::TokenKind OpKind,
6930                                        CXXScopeSpec &SS,
6931                                        UnqualifiedId &FirstTypeName,
6932                                        SourceLocation CCLoc,
6933                                        SourceLocation TildeLoc,
6934                                        UnqualifiedId &SecondTypeName);
6935 
6936   ExprResult ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
6937                                        SourceLocation OpLoc,
6938                                        tok::TokenKind OpKind,
6939                                        SourceLocation TildeLoc,
6940                                        const DeclSpec& DS);
6941 
6942   /// MaybeCreateExprWithCleanups - If the current full-expression
6943   /// requires any cleanups, surround it with a ExprWithCleanups node.
6944   /// Otherwise, just returns the passed-in expression.
6945   Expr *MaybeCreateExprWithCleanups(Expr *SubExpr);
6946   Stmt *MaybeCreateStmtWithCleanups(Stmt *SubStmt);
6947   ExprResult MaybeCreateExprWithCleanups(ExprResult SubExpr);
6948 
6949   MaterializeTemporaryExpr *
6950   CreateMaterializeTemporaryExpr(QualType T, Expr *Temporary,
6951                                  bool BoundToLvalueReference);
6952 
6953   ExprResult ActOnFinishFullExpr(Expr *Expr, bool DiscardedValue) {
6954     return ActOnFinishFullExpr(
6955         Expr, Expr ? Expr->getExprLoc() : SourceLocation(), DiscardedValue);
6956   }
6957   ExprResult ActOnFinishFullExpr(Expr *Expr, SourceLocation CC,
6958                                  bool DiscardedValue, bool IsConstexpr = false,
6959                                  bool IsTemplateArgument = false);
6960   StmtResult ActOnFinishFullStmt(Stmt *Stmt);
6961 
6962   // Marks SS invalid if it represents an incomplete type.
6963   bool RequireCompleteDeclContext(CXXScopeSpec &SS, DeclContext *DC);
6964   // Complete an enum decl, maybe without a scope spec.
6965   bool RequireCompleteEnumDecl(EnumDecl *D, SourceLocation L,
6966                                CXXScopeSpec *SS = nullptr);
6967 
6968   DeclContext *computeDeclContext(QualType T);
6969   DeclContext *computeDeclContext(const CXXScopeSpec &SS,
6970                                   bool EnteringContext = false);
6971   bool isDependentScopeSpecifier(const CXXScopeSpec &SS);
6972   CXXRecordDecl *getCurrentInstantiationOf(NestedNameSpecifier *NNS);
6973 
6974   /// The parser has parsed a global nested-name-specifier '::'.
6975   ///
6976   /// \param CCLoc The location of the '::'.
6977   ///
6978   /// \param SS The nested-name-specifier, which will be updated in-place
6979   /// to reflect the parsed nested-name-specifier.
6980   ///
6981   /// \returns true if an error occurred, false otherwise.
6982   bool ActOnCXXGlobalScopeSpecifier(SourceLocation CCLoc, CXXScopeSpec &SS);
6983 
6984   /// The parser has parsed a '__super' nested-name-specifier.
6985   ///
6986   /// \param SuperLoc The location of the '__super' keyword.
6987   ///
6988   /// \param ColonColonLoc The location of the '::'.
6989   ///
6990   /// \param SS The nested-name-specifier, which will be updated in-place
6991   /// to reflect the parsed nested-name-specifier.
6992   ///
6993   /// \returns true if an error occurred, false otherwise.
6994   bool ActOnSuperScopeSpecifier(SourceLocation SuperLoc,
6995                                 SourceLocation ColonColonLoc, CXXScopeSpec &SS);
6996 
6997   bool isAcceptableNestedNameSpecifier(const NamedDecl *SD,
6998                                        bool *CanCorrect = nullptr);
6999   NamedDecl *FindFirstQualifierInScope(Scope *S, NestedNameSpecifier *NNS);
7000 
7001   /// Keeps information about an identifier in a nested-name-spec.
7002   ///
7003   struct NestedNameSpecInfo {
7004     /// The type of the object, if we're parsing nested-name-specifier in
7005     /// a member access expression.
7006     ParsedType ObjectType;
7007 
7008     /// The identifier preceding the '::'.
7009     IdentifierInfo *Identifier;
7010 
7011     /// The location of the identifier.
7012     SourceLocation IdentifierLoc;
7013 
7014     /// The location of the '::'.
7015     SourceLocation CCLoc;
7016 
7017     /// Creates info object for the most typical case.
7018     NestedNameSpecInfo(IdentifierInfo *II, SourceLocation IdLoc,
7019              SourceLocation ColonColonLoc, ParsedType ObjectType = ParsedType())
7020       : ObjectType(ObjectType), Identifier(II), IdentifierLoc(IdLoc),
7021         CCLoc(ColonColonLoc) {
7022     }
7023 
7024     NestedNameSpecInfo(IdentifierInfo *II, SourceLocation IdLoc,
7025                        SourceLocation ColonColonLoc, QualType ObjectType)
7026       : ObjectType(ParsedType::make(ObjectType)), Identifier(II),
7027         IdentifierLoc(IdLoc), CCLoc(ColonColonLoc) {
7028     }
7029   };
7030 
7031   bool BuildCXXNestedNameSpecifier(Scope *S,
7032                                    NestedNameSpecInfo &IdInfo,
7033                                    bool EnteringContext,
7034                                    CXXScopeSpec &SS,
7035                                    NamedDecl *ScopeLookupResult,
7036                                    bool ErrorRecoveryLookup,
7037                                    bool *IsCorrectedToColon = nullptr,
7038                                    bool OnlyNamespace = false);
7039 
7040   /// The parser has parsed a nested-name-specifier 'identifier::'.
7041   ///
7042   /// \param S The scope in which this nested-name-specifier occurs.
7043   ///
7044   /// \param IdInfo Parser information about an identifier in the
7045   /// nested-name-spec.
7046   ///
7047   /// \param EnteringContext Whether we're entering the context nominated by
7048   /// this nested-name-specifier.
7049   ///
7050   /// \param SS The nested-name-specifier, which is both an input
7051   /// parameter (the nested-name-specifier before this type) and an
7052   /// output parameter (containing the full nested-name-specifier,
7053   /// including this new type).
7054   ///
7055   /// \param IsCorrectedToColon If not null, suggestions to replace '::' -> ':'
7056   /// are allowed.  The bool value pointed by this parameter is set to 'true'
7057   /// if the identifier is treated as if it was followed by ':', not '::'.
7058   ///
7059   /// \param OnlyNamespace If true, only considers namespaces in lookup.
7060   ///
7061   /// \returns true if an error occurred, false otherwise.
7062   bool ActOnCXXNestedNameSpecifier(Scope *S,
7063                                    NestedNameSpecInfo &IdInfo,
7064                                    bool EnteringContext,
7065                                    CXXScopeSpec &SS,
7066                                    bool *IsCorrectedToColon = nullptr,
7067                                    bool OnlyNamespace = false);
7068 
7069   ExprResult ActOnDecltypeExpression(Expr *E);
7070 
7071   bool ActOnCXXNestedNameSpecifierDecltype(CXXScopeSpec &SS,
7072                                            const DeclSpec &DS,
7073                                            SourceLocation ColonColonLoc);
7074 
7075   bool IsInvalidUnlessNestedName(Scope *S, CXXScopeSpec &SS,
7076                                  NestedNameSpecInfo &IdInfo,
7077                                  bool EnteringContext);
7078 
7079   /// The parser has parsed a nested-name-specifier
7080   /// 'template[opt] template-name < template-args >::'.
7081   ///
7082   /// \param S The scope in which this nested-name-specifier occurs.
7083   ///
7084   /// \param SS The nested-name-specifier, which is both an input
7085   /// parameter (the nested-name-specifier before this type) and an
7086   /// output parameter (containing the full nested-name-specifier,
7087   /// including this new type).
7088   ///
7089   /// \param TemplateKWLoc the location of the 'template' keyword, if any.
7090   /// \param TemplateName the template name.
7091   /// \param TemplateNameLoc The location of the template name.
7092   /// \param LAngleLoc The location of the opening angle bracket  ('<').
7093   /// \param TemplateArgs The template arguments.
7094   /// \param RAngleLoc The location of the closing angle bracket  ('>').
7095   /// \param CCLoc The location of the '::'.
7096   ///
7097   /// \param EnteringContext Whether we're entering the context of the
7098   /// nested-name-specifier.
7099   ///
7100   ///
7101   /// \returns true if an error occurred, false otherwise.
7102   bool ActOnCXXNestedNameSpecifier(Scope *S,
7103                                    CXXScopeSpec &SS,
7104                                    SourceLocation TemplateKWLoc,
7105                                    TemplateTy TemplateName,
7106                                    SourceLocation TemplateNameLoc,
7107                                    SourceLocation LAngleLoc,
7108                                    ASTTemplateArgsPtr TemplateArgs,
7109                                    SourceLocation RAngleLoc,
7110                                    SourceLocation CCLoc,
7111                                    bool EnteringContext);
7112 
7113   /// Given a C++ nested-name-specifier, produce an annotation value
7114   /// that the parser can use later to reconstruct the given
7115   /// nested-name-specifier.
7116   ///
7117   /// \param SS A nested-name-specifier.
7118   ///
7119   /// \returns A pointer containing all of the information in the
7120   /// nested-name-specifier \p SS.
7121   void *SaveNestedNameSpecifierAnnotation(CXXScopeSpec &SS);
7122 
7123   /// Given an annotation pointer for a nested-name-specifier, restore
7124   /// the nested-name-specifier structure.
7125   ///
7126   /// \param Annotation The annotation pointer, produced by
7127   /// \c SaveNestedNameSpecifierAnnotation().
7128   ///
7129   /// \param AnnotationRange The source range corresponding to the annotation.
7130   ///
7131   /// \param SS The nested-name-specifier that will be updated with the contents
7132   /// of the annotation pointer.
7133   void RestoreNestedNameSpecifierAnnotation(void *Annotation,
7134                                             SourceRange AnnotationRange,
7135                                             CXXScopeSpec &SS);
7136 
7137   bool ShouldEnterDeclaratorScope(Scope *S, const CXXScopeSpec &SS);
7138 
7139   /// ActOnCXXEnterDeclaratorScope - Called when a C++ scope specifier (global
7140   /// scope or nested-name-specifier) is parsed, part of a declarator-id.
7141   /// After this method is called, according to [C++ 3.4.3p3], names should be
7142   /// looked up in the declarator-id's scope, until the declarator is parsed and
7143   /// ActOnCXXExitDeclaratorScope is called.
7144   /// The 'SS' should be a non-empty valid CXXScopeSpec.
7145   bool ActOnCXXEnterDeclaratorScope(Scope *S, CXXScopeSpec &SS);
7146 
7147   /// ActOnCXXExitDeclaratorScope - Called when a declarator that previously
7148   /// invoked ActOnCXXEnterDeclaratorScope(), is finished. 'SS' is the same
7149   /// CXXScopeSpec that was passed to ActOnCXXEnterDeclaratorScope as well.
7150   /// Used to indicate that names should revert to being looked up in the
7151   /// defining scope.
7152   void ActOnCXXExitDeclaratorScope(Scope *S, const CXXScopeSpec &SS);
7153 
7154   /// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse an
7155   /// initializer for the declaration 'Dcl'.
7156   /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
7157   /// static data member of class X, names should be looked up in the scope of
7158   /// class X.
7159   void ActOnCXXEnterDeclInitializer(Scope *S, Decl *Dcl);
7160 
7161   /// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
7162   /// initializer for the declaration 'Dcl'.
7163   void ActOnCXXExitDeclInitializer(Scope *S, Decl *Dcl);
7164 
7165   /// Create a new lambda closure type.
7166   CXXRecordDecl *createLambdaClosureType(SourceRange IntroducerRange,
7167                                          TypeSourceInfo *Info,
7168                                          unsigned LambdaDependencyKind,
7169                                          LambdaCaptureDefault CaptureDefault);
7170 
7171   /// Number lambda for linkage purposes if necessary.
7172   void handleLambdaNumbering(CXXRecordDecl *Class, CXXMethodDecl *Method,
7173                              std::optional<CXXRecordDecl::LambdaNumbering>
7174                                  NumberingOverride = std::nullopt);
7175 
7176   /// Endow the lambda scope info with the relevant properties.
7177   void buildLambdaScope(sema::LambdaScopeInfo *LSI, CXXMethodDecl *CallOperator,
7178                         SourceRange IntroducerRange,
7179                         LambdaCaptureDefault CaptureDefault,
7180                         SourceLocation CaptureDefaultLoc, bool ExplicitParams,
7181                         bool Mutable);
7182 
7183   CXXMethodDecl *CreateLambdaCallOperator(SourceRange IntroducerRange,
7184                                           CXXRecordDecl *Class);
7185   void CompleteLambdaCallOperator(
7186       CXXMethodDecl *Method, SourceLocation LambdaLoc,
7187       SourceLocation CallOperatorLoc, Expr *TrailingRequiresClause,
7188       TypeSourceInfo *MethodTyInfo, ConstexprSpecKind ConstexprKind,
7189       StorageClass SC, ArrayRef<ParmVarDecl *> Params,
7190       bool HasExplicitResultType);
7191 
7192   /// Perform initialization analysis of the init-capture and perform
7193   /// any implicit conversions such as an lvalue-to-rvalue conversion if
7194   /// not being used to initialize a reference.
7195   ParsedType actOnLambdaInitCaptureInitialization(
7196       SourceLocation Loc, bool ByRef, SourceLocation EllipsisLoc,
7197       IdentifierInfo *Id, LambdaCaptureInitKind InitKind, Expr *&Init) {
7198     return ParsedType::make(buildLambdaInitCaptureInitialization(
7199         Loc, ByRef, EllipsisLoc, std::nullopt, Id,
7200         InitKind != LambdaCaptureInitKind::CopyInit, Init));
7201   }
7202   QualType buildLambdaInitCaptureInitialization(
7203       SourceLocation Loc, bool ByRef, SourceLocation EllipsisLoc,
7204       std::optional<unsigned> NumExpansions, IdentifierInfo *Id,
7205       bool DirectInit, Expr *&Init);
7206 
7207   /// Create a dummy variable within the declcontext of the lambda's
7208   ///  call operator, for name lookup purposes for a lambda init capture.
7209   ///
7210   ///  CodeGen handles emission of lambda captures, ignoring these dummy
7211   ///  variables appropriately.
7212   VarDecl *createLambdaInitCaptureVarDecl(
7213       SourceLocation Loc, QualType InitCaptureType, SourceLocation EllipsisLoc,
7214       IdentifierInfo *Id, unsigned InitStyle, Expr *Init, DeclContext *DeclCtx);
7215 
7216   /// Add an init-capture to a lambda scope.
7217   void addInitCapture(sema::LambdaScopeInfo *LSI, VarDecl *Var, bool ByRef);
7218 
7219   /// Note that we have finished the explicit captures for the
7220   /// given lambda.
7221   void finishLambdaExplicitCaptures(sema::LambdaScopeInfo *LSI);
7222 
7223   /// Deduce a block or lambda's return type based on the return
7224   /// statements present in the body.
7225   void deduceClosureReturnType(sema::CapturingScopeInfo &CSI);
7226 
7227   /// Once the Lambdas capture are known, we can start to create the closure,
7228   /// call operator method, and keep track of the captures.
7229   /// We do the capture lookup here, but they are not actually captured until
7230   /// after we know what the qualifiers of the call operator are.
7231   void ActOnLambdaExpressionAfterIntroducer(LambdaIntroducer &Intro,
7232                                             Scope *CurContext);
7233 
7234   /// This is called after parsing the explicit template parameter list
7235   /// on a lambda (if it exists) in C++2a.
7236   void ActOnLambdaExplicitTemplateParameterList(LambdaIntroducer &Intro,
7237                                                 SourceLocation LAngleLoc,
7238                                                 ArrayRef<NamedDecl *> TParams,
7239                                                 SourceLocation RAngleLoc,
7240                                                 ExprResult RequiresClause);
7241 
7242   void ActOnLambdaClosureQualifiers(LambdaIntroducer &Intro,
7243                                     SourceLocation MutableLoc);
7244 
7245   void ActOnLambdaClosureParameters(
7246       Scope *LambdaScope,
7247       MutableArrayRef<DeclaratorChunk::ParamInfo> ParamInfo);
7248 
7249   /// ActOnStartOfLambdaDefinition - This is called just before we start
7250   /// parsing the body of a lambda; it analyzes the explicit captures and
7251   /// arguments, and sets up various data-structures for the body of the
7252   /// lambda.
7253   void ActOnStartOfLambdaDefinition(LambdaIntroducer &Intro,
7254                                     Declarator &ParamInfo, const DeclSpec &DS);
7255 
7256   /// ActOnLambdaError - If there is an error parsing a lambda, this callback
7257   /// is invoked to pop the information about the lambda.
7258   void ActOnLambdaError(SourceLocation StartLoc, Scope *CurScope,
7259                         bool IsInstantiation = false);
7260 
7261   /// ActOnLambdaExpr - This is called when the body of a lambda expression
7262   /// was successfully completed.
7263   ExprResult ActOnLambdaExpr(SourceLocation StartLoc, Stmt *Body,
7264                              Scope *CurScope);
7265 
7266   /// Does copying/destroying the captured variable have side effects?
7267   bool CaptureHasSideEffects(const sema::Capture &From);
7268 
7269   /// Diagnose if an explicit lambda capture is unused. Returns true if a
7270   /// diagnostic is emitted.
7271   bool DiagnoseUnusedLambdaCapture(SourceRange CaptureRange,
7272                                    const sema::Capture &From);
7273 
7274   /// Build a FieldDecl suitable to hold the given capture.
7275   FieldDecl *BuildCaptureField(RecordDecl *RD, const sema::Capture &Capture);
7276 
7277   /// Initialize the given capture with a suitable expression.
7278   ExprResult BuildCaptureInit(const sema::Capture &Capture,
7279                               SourceLocation ImplicitCaptureLoc,
7280                               bool IsOpenMPMapping = false);
7281 
7282   /// Complete a lambda-expression having processed and attached the
7283   /// lambda body.
7284   ExprResult BuildLambdaExpr(SourceLocation StartLoc, SourceLocation EndLoc,
7285                              sema::LambdaScopeInfo *LSI);
7286 
7287   /// Get the return type to use for a lambda's conversion function(s) to
7288   /// function pointer type, given the type of the call operator.
7289   QualType
7290   getLambdaConversionFunctionResultType(const FunctionProtoType *CallOpType,
7291                                         CallingConv CC);
7292 
7293   /// Define the "body" of the conversion from a lambda object to a
7294   /// function pointer.
7295   ///
7296   /// This routine doesn't actually define a sensible body; rather, it fills
7297   /// in the initialization expression needed to copy the lambda object into
7298   /// the block, and IR generation actually generates the real body of the
7299   /// block pointer conversion.
7300   void DefineImplicitLambdaToFunctionPointerConversion(
7301          SourceLocation CurrentLoc, CXXConversionDecl *Conv);
7302 
7303   /// Define the "body" of the conversion from a lambda object to a
7304   /// block pointer.
7305   ///
7306   /// This routine doesn't actually define a sensible body; rather, it fills
7307   /// in the initialization expression needed to copy the lambda object into
7308   /// the block, and IR generation actually generates the real body of the
7309   /// block pointer conversion.
7310   void DefineImplicitLambdaToBlockPointerConversion(SourceLocation CurrentLoc,
7311                                                     CXXConversionDecl *Conv);
7312 
7313   ExprResult BuildBlockForLambdaConversion(SourceLocation CurrentLocation,
7314                                            SourceLocation ConvLocation,
7315                                            CXXConversionDecl *Conv,
7316                                            Expr *Src);
7317 
7318   sema::LambdaScopeInfo *RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator);
7319 
7320   class LambdaScopeForCallOperatorInstantiationRAII
7321       : private FunctionScopeRAII {
7322   public:
7323     LambdaScopeForCallOperatorInstantiationRAII(
7324         Sema &SemasRef, FunctionDecl *FD, MultiLevelTemplateArgumentList MLTAL,
7325         LocalInstantiationScope &Scope);
7326   };
7327 
7328   /// Check whether the given expression is a valid constraint expression.
7329   /// A diagnostic is emitted if it is not, false is returned, and
7330   /// PossibleNonPrimary will be set to true if the failure might be due to a
7331   /// non-primary expression being used as an atomic constraint.
7332   bool CheckConstraintExpression(const Expr *CE, Token NextToken = Token(),
7333                                  bool *PossibleNonPrimary = nullptr,
7334                                  bool IsTrailingRequiresClause = false);
7335 
7336 private:
7337   /// Caches pairs of template-like decls whose associated constraints were
7338   /// checked for subsumption and whether or not the first's constraints did in
7339   /// fact subsume the second's.
7340   llvm::DenseMap<std::pair<NamedDecl *, NamedDecl *>, bool> SubsumptionCache;
7341   /// Caches the normalized associated constraints of declarations (concepts or
7342   /// constrained declarations). If an error occurred while normalizing the
7343   /// associated constraints of the template or concept, nullptr will be cached
7344   /// here.
7345   llvm::DenseMap<NamedDecl *, NormalizedConstraint *>
7346       NormalizationCache;
7347 
7348   llvm::ContextualFoldingSet<ConstraintSatisfaction, const ASTContext &>
7349       SatisfactionCache;
7350 
7351   /// Introduce the instantiated function parameters into the local
7352   /// instantiation scope, and set the parameter names to those used
7353   /// in the template.
7354   bool addInstantiatedParametersToScope(
7355       FunctionDecl *Function, const FunctionDecl *PatternDecl,
7356       LocalInstantiationScope &Scope,
7357       const MultiLevelTemplateArgumentList &TemplateArgs);
7358 
7359   /// Introduce the instantiated captures of the lambda into the local
7360   /// instantiation scope.
7361   bool addInstantiatedCapturesToScope(
7362       FunctionDecl *Function, const FunctionDecl *PatternDecl,
7363       LocalInstantiationScope &Scope,
7364       const MultiLevelTemplateArgumentList &TemplateArgs);
7365 
7366   /// used by SetupConstraintCheckingTemplateArgumentsAndScope to recursively(in
7367   /// the case of lambdas) set up the LocalInstantiationScope of the current
7368   /// function.
7369   bool SetupConstraintScope(
7370       FunctionDecl *FD, std::optional<ArrayRef<TemplateArgument>> TemplateArgs,
7371       MultiLevelTemplateArgumentList MLTAL, LocalInstantiationScope &Scope);
7372 
7373   /// Used during constraint checking, sets up the constraint template argument
7374   /// lists, and calls SetupConstraintScope to set up the
7375   /// LocalInstantiationScope to have the proper set of ParVarDecls configured.
7376   std::optional<MultiLevelTemplateArgumentList>
7377   SetupConstraintCheckingTemplateArgumentsAndScope(
7378       FunctionDecl *FD, std::optional<ArrayRef<TemplateArgument>> TemplateArgs,
7379       LocalInstantiationScope &Scope);
7380 
7381 private:
7382   // The current stack of constraint satisfactions, so we can exit-early.
7383   using SatisfactionStackEntryTy =
7384       std::pair<const NamedDecl *, llvm::FoldingSetNodeID>;
7385   llvm::SmallVector<SatisfactionStackEntryTy, 10>
7386       SatisfactionStack;
7387 
7388 public:
7389   void PushSatisfactionStackEntry(const NamedDecl *D,
7390                                   const llvm::FoldingSetNodeID &ID) {
7391     const NamedDecl *Can = cast<NamedDecl>(D->getCanonicalDecl());
7392     SatisfactionStack.emplace_back(Can, ID);
7393   }
7394 
7395   void PopSatisfactionStackEntry() { SatisfactionStack.pop_back(); }
7396 
7397   bool SatisfactionStackContains(const NamedDecl *D,
7398                                  const llvm::FoldingSetNodeID &ID) const {
7399     const NamedDecl *Can = cast<NamedDecl>(D->getCanonicalDecl());
7400     return llvm::find(SatisfactionStack,
7401                       SatisfactionStackEntryTy{Can, ID}) !=
7402            SatisfactionStack.end();
7403   }
7404 
7405   // Resets the current SatisfactionStack for cases where we are instantiating
7406   // constraints as a 'side effect' of normal instantiation in a way that is not
7407   // indicative of recursive definition.
7408   class SatisfactionStackResetRAII {
7409     llvm::SmallVector<SatisfactionStackEntryTy, 10>
7410         BackupSatisfactionStack;
7411     Sema &SemaRef;
7412 
7413   public:
7414     SatisfactionStackResetRAII(Sema &S) : SemaRef(S) {
7415       SemaRef.SwapSatisfactionStack(BackupSatisfactionStack);
7416     }
7417 
7418     ~SatisfactionStackResetRAII() {
7419       SemaRef.SwapSatisfactionStack(BackupSatisfactionStack);
7420     }
7421   };
7422 
7423   void SwapSatisfactionStack(
7424       llvm::SmallVectorImpl<SatisfactionStackEntryTy> &NewSS) {
7425     SatisfactionStack.swap(NewSS);
7426   }
7427 
7428   const NormalizedConstraint *
7429   getNormalizedAssociatedConstraints(
7430       NamedDecl *ConstrainedDecl, ArrayRef<const Expr *> AssociatedConstraints);
7431 
7432   /// \brief Check whether the given declaration's associated constraints are
7433   /// at least as constrained than another declaration's according to the
7434   /// partial ordering of constraints.
7435   ///
7436   /// \param Result If no error occurred, receives the result of true if D1 is
7437   /// at least constrained than D2, and false otherwise.
7438   ///
7439   /// \returns true if an error occurred, false otherwise.
7440   bool IsAtLeastAsConstrained(NamedDecl *D1, MutableArrayRef<const Expr *> AC1,
7441                               NamedDecl *D2, MutableArrayRef<const Expr *> AC2,
7442                               bool &Result);
7443 
7444   /// If D1 was not at least as constrained as D2, but would've been if a pair
7445   /// of atomic constraints involved had been declared in a concept and not
7446   /// repeated in two separate places in code.
7447   /// \returns true if such a diagnostic was emitted, false otherwise.
7448   bool MaybeEmitAmbiguousAtomicConstraintsDiagnostic(NamedDecl *D1,
7449       ArrayRef<const Expr *> AC1, NamedDecl *D2, ArrayRef<const Expr *> AC2);
7450 
7451   /// \brief Check whether the given list of constraint expressions are
7452   /// satisfied (as if in a 'conjunction') given template arguments.
7453   /// \param Template the template-like entity that triggered the constraints
7454   /// check (either a concept or a constrained entity).
7455   /// \param ConstraintExprs a list of constraint expressions, treated as if
7456   /// they were 'AND'ed together.
7457   /// \param TemplateArgLists the list of template arguments to substitute into
7458   /// the constraint expression.
7459   /// \param TemplateIDRange The source range of the template id that
7460   /// caused the constraints check.
7461   /// \param Satisfaction if true is returned, will contain details of the
7462   /// satisfaction, with enough information to diagnose an unsatisfied
7463   /// expression.
7464   /// \returns true if an error occurred and satisfaction could not be checked,
7465   /// false otherwise.
7466   bool CheckConstraintSatisfaction(
7467       const NamedDecl *Template, ArrayRef<const Expr *> ConstraintExprs,
7468       const MultiLevelTemplateArgumentList &TemplateArgLists,
7469       SourceRange TemplateIDRange, ConstraintSatisfaction &Satisfaction) {
7470     llvm::SmallVector<Expr *, 4> Converted;
7471     return CheckConstraintSatisfaction(Template, ConstraintExprs, Converted,
7472                                        TemplateArgLists, TemplateIDRange,
7473                                        Satisfaction);
7474   }
7475 
7476   /// \brief Check whether the given list of constraint expressions are
7477   /// satisfied (as if in a 'conjunction') given template arguments.
7478   /// Additionally, takes an empty list of Expressions which is populated with
7479   /// the instantiated versions of the ConstraintExprs.
7480   /// \param Template the template-like entity that triggered the constraints
7481   /// check (either a concept or a constrained entity).
7482   /// \param ConstraintExprs a list of constraint expressions, treated as if
7483   /// they were 'AND'ed together.
7484   /// \param ConvertedConstraints a out parameter that will get populated with
7485   /// the instantiated version of the ConstraintExprs if we successfully checked
7486   /// satisfaction.
7487   /// \param TemplateArgList the multi-level list of template arguments to
7488   /// substitute into the constraint expression. This should be relative to the
7489   /// top-level (hence multi-level), since we need to instantiate fully at the
7490   /// time of checking.
7491   /// \param TemplateIDRange The source range of the template id that
7492   /// caused the constraints check.
7493   /// \param Satisfaction if true is returned, will contain details of the
7494   /// satisfaction, with enough information to diagnose an unsatisfied
7495   /// expression.
7496   /// \returns true if an error occurred and satisfaction could not be checked,
7497   /// false otherwise.
7498   bool CheckConstraintSatisfaction(
7499       const NamedDecl *Template, ArrayRef<const Expr *> ConstraintExprs,
7500       llvm::SmallVectorImpl<Expr *> &ConvertedConstraints,
7501       const MultiLevelTemplateArgumentList &TemplateArgList,
7502       SourceRange TemplateIDRange, ConstraintSatisfaction &Satisfaction);
7503 
7504   /// \brief Check whether the given non-dependent constraint expression is
7505   /// satisfied. Returns false and updates Satisfaction with the satisfaction
7506   /// verdict if successful, emits a diagnostic and returns true if an error
7507   /// occurred and satisfaction could not be determined.
7508   ///
7509   /// \returns true if an error occurred, false otherwise.
7510   bool CheckConstraintSatisfaction(const Expr *ConstraintExpr,
7511                                    ConstraintSatisfaction &Satisfaction);
7512 
7513   /// Check whether the given function decl's trailing requires clause is
7514   /// satisfied, if any. Returns false and updates Satisfaction with the
7515   /// satisfaction verdict if successful, emits a diagnostic and returns true if
7516   /// an error occurred and satisfaction could not be determined.
7517   ///
7518   /// \returns true if an error occurred, false otherwise.
7519   bool CheckFunctionConstraints(const FunctionDecl *FD,
7520                                 ConstraintSatisfaction &Satisfaction,
7521                                 SourceLocation UsageLoc = SourceLocation(),
7522                                 bool ForOverloadResolution = false);
7523 
7524   /// \brief Ensure that the given template arguments satisfy the constraints
7525   /// associated with the given template, emitting a diagnostic if they do not.
7526   ///
7527   /// \param Template The template to which the template arguments are being
7528   /// provided.
7529   ///
7530   /// \param TemplateArgs The converted, canonicalized template arguments.
7531   ///
7532   /// \param TemplateIDRange The source range of the template id that
7533   /// caused the constraints check.
7534   ///
7535   /// \returns true if the constrains are not satisfied or could not be checked
7536   /// for satisfaction, false if the constraints are satisfied.
7537   bool EnsureTemplateArgumentListConstraints(
7538       TemplateDecl *Template,
7539       const MultiLevelTemplateArgumentList &TemplateArgs,
7540       SourceRange TemplateIDRange);
7541 
7542   /// \brief Emit diagnostics explaining why a constraint expression was deemed
7543   /// unsatisfied.
7544   /// \param First whether this is the first time an unsatisfied constraint is
7545   /// diagnosed for this error.
7546   void
7547   DiagnoseUnsatisfiedConstraint(const ConstraintSatisfaction &Satisfaction,
7548                                 bool First = true);
7549 
7550   /// \brief Emit diagnostics explaining why a constraint expression was deemed
7551   /// unsatisfied.
7552   void
7553   DiagnoseUnsatisfiedConstraint(const ASTConstraintSatisfaction &Satisfaction,
7554                                 bool First = true);
7555 
7556   // ParseObjCStringLiteral - Parse Objective-C string literals.
7557   ExprResult ParseObjCStringLiteral(SourceLocation *AtLocs,
7558                                     ArrayRef<Expr *> Strings);
7559 
7560   ExprResult BuildObjCStringLiteral(SourceLocation AtLoc, StringLiteral *S);
7561 
7562   /// BuildObjCNumericLiteral - builds an ObjCBoxedExpr AST node for the
7563   /// numeric literal expression. Type of the expression will be "NSNumber *"
7564   /// or "id" if NSNumber is unavailable.
7565   ExprResult BuildObjCNumericLiteral(SourceLocation AtLoc, Expr *Number);
7566   ExprResult ActOnObjCBoolLiteral(SourceLocation AtLoc, SourceLocation ValueLoc,
7567                                   bool Value);
7568   ExprResult BuildObjCArrayLiteral(SourceRange SR, MultiExprArg Elements);
7569 
7570   /// BuildObjCBoxedExpr - builds an ObjCBoxedExpr AST node for the
7571   /// '@' prefixed parenthesized expression. The type of the expression will
7572   /// either be "NSNumber *", "NSString *" or "NSValue *" depending on the type
7573   /// of ValueType, which is allowed to be a built-in numeric type, "char *",
7574   /// "const char *" or C structure with attribute 'objc_boxable'.
7575   ExprResult BuildObjCBoxedExpr(SourceRange SR, Expr *ValueExpr);
7576 
7577   ExprResult BuildObjCSubscriptExpression(SourceLocation RB, Expr *BaseExpr,
7578                                           Expr *IndexExpr,
7579                                           ObjCMethodDecl *getterMethod,
7580                                           ObjCMethodDecl *setterMethod);
7581 
7582   ExprResult BuildObjCDictionaryLiteral(SourceRange SR,
7583                                MutableArrayRef<ObjCDictionaryElement> Elements);
7584 
7585   ExprResult BuildObjCEncodeExpression(SourceLocation AtLoc,
7586                                   TypeSourceInfo *EncodedTypeInfo,
7587                                   SourceLocation RParenLoc);
7588   ExprResult BuildCXXMemberCallExpr(Expr *Exp, NamedDecl *FoundDecl,
7589                                     CXXConversionDecl *Method,
7590                                     bool HadMultipleCandidates);
7591 
7592   ExprResult ParseObjCEncodeExpression(SourceLocation AtLoc,
7593                                        SourceLocation EncodeLoc,
7594                                        SourceLocation LParenLoc,
7595                                        ParsedType Ty,
7596                                        SourceLocation RParenLoc);
7597 
7598   /// ParseObjCSelectorExpression - Build selector expression for \@selector
7599   ExprResult ParseObjCSelectorExpression(Selector Sel,
7600                                          SourceLocation AtLoc,
7601                                          SourceLocation SelLoc,
7602                                          SourceLocation LParenLoc,
7603                                          SourceLocation RParenLoc,
7604                                          bool WarnMultipleSelectors);
7605 
7606   /// ParseObjCProtocolExpression - Build protocol expression for \@protocol
7607   ExprResult ParseObjCProtocolExpression(IdentifierInfo * ProtocolName,
7608                                          SourceLocation AtLoc,
7609                                          SourceLocation ProtoLoc,
7610                                          SourceLocation LParenLoc,
7611                                          SourceLocation ProtoIdLoc,
7612                                          SourceLocation RParenLoc);
7613 
7614   //===--------------------------------------------------------------------===//
7615   // C++ Declarations
7616   //
7617   Decl *ActOnStartLinkageSpecification(Scope *S,
7618                                        SourceLocation ExternLoc,
7619                                        Expr *LangStr,
7620                                        SourceLocation LBraceLoc);
7621   Decl *ActOnFinishLinkageSpecification(Scope *S,
7622                                         Decl *LinkageSpec,
7623                                         SourceLocation RBraceLoc);
7624 
7625 
7626   //===--------------------------------------------------------------------===//
7627   // C++ Classes
7628   //
7629   CXXRecordDecl *getCurrentClass(Scope *S, const CXXScopeSpec *SS);
7630   bool isCurrentClassName(const IdentifierInfo &II, Scope *S,
7631                           const CXXScopeSpec *SS = nullptr);
7632   bool isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS);
7633 
7634   bool ActOnAccessSpecifier(AccessSpecifier Access, SourceLocation ASLoc,
7635                             SourceLocation ColonLoc,
7636                             const ParsedAttributesView &Attrs);
7637 
7638   NamedDecl *ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS,
7639                                  Declarator &D,
7640                                  MultiTemplateParamsArg TemplateParameterLists,
7641                                  Expr *BitfieldWidth, const VirtSpecifiers &VS,
7642                                  InClassInitStyle InitStyle);
7643 
7644   void ActOnStartCXXInClassMemberInitializer();
7645   void ActOnFinishCXXInClassMemberInitializer(Decl *VarDecl,
7646                                               SourceLocation EqualLoc,
7647                                               Expr *Init);
7648 
7649   MemInitResult ActOnMemInitializer(Decl *ConstructorD,
7650                                     Scope *S,
7651                                     CXXScopeSpec &SS,
7652                                     IdentifierInfo *MemberOrBase,
7653                                     ParsedType TemplateTypeTy,
7654                                     const DeclSpec &DS,
7655                                     SourceLocation IdLoc,
7656                                     SourceLocation LParenLoc,
7657                                     ArrayRef<Expr *> Args,
7658                                     SourceLocation RParenLoc,
7659                                     SourceLocation EllipsisLoc);
7660 
7661   MemInitResult ActOnMemInitializer(Decl *ConstructorD,
7662                                     Scope *S,
7663                                     CXXScopeSpec &SS,
7664                                     IdentifierInfo *MemberOrBase,
7665                                     ParsedType TemplateTypeTy,
7666                                     const DeclSpec &DS,
7667                                     SourceLocation IdLoc,
7668                                     Expr *InitList,
7669                                     SourceLocation EllipsisLoc);
7670 
7671   MemInitResult BuildMemInitializer(Decl *ConstructorD,
7672                                     Scope *S,
7673                                     CXXScopeSpec &SS,
7674                                     IdentifierInfo *MemberOrBase,
7675                                     ParsedType TemplateTypeTy,
7676                                     const DeclSpec &DS,
7677                                     SourceLocation IdLoc,
7678                                     Expr *Init,
7679                                     SourceLocation EllipsisLoc);
7680 
7681   MemInitResult BuildMemberInitializer(ValueDecl *Member,
7682                                        Expr *Init,
7683                                        SourceLocation IdLoc);
7684 
7685   MemInitResult BuildBaseInitializer(QualType BaseType,
7686                                      TypeSourceInfo *BaseTInfo,
7687                                      Expr *Init,
7688                                      CXXRecordDecl *ClassDecl,
7689                                      SourceLocation EllipsisLoc);
7690 
7691   MemInitResult BuildDelegatingInitializer(TypeSourceInfo *TInfo,
7692                                            Expr *Init,
7693                                            CXXRecordDecl *ClassDecl);
7694 
7695   bool SetDelegatingInitializer(CXXConstructorDecl *Constructor,
7696                                 CXXCtorInitializer *Initializer);
7697 
7698   bool SetCtorInitializers(
7699       CXXConstructorDecl *Constructor, bool AnyErrors,
7700       ArrayRef<CXXCtorInitializer *> Initializers = std::nullopt);
7701 
7702   void SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation);
7703 
7704 
7705   /// MarkBaseAndMemberDestructorsReferenced - Given a record decl,
7706   /// mark all the non-trivial destructors of its members and bases as
7707   /// referenced.
7708   void MarkBaseAndMemberDestructorsReferenced(SourceLocation Loc,
7709                                               CXXRecordDecl *Record);
7710 
7711   /// Mark destructors of virtual bases of this class referenced. In the Itanium
7712   /// C++ ABI, this is done when emitting a destructor for any non-abstract
7713   /// class. In the Microsoft C++ ABI, this is done any time a class's
7714   /// destructor is referenced.
7715   void MarkVirtualBaseDestructorsReferenced(
7716       SourceLocation Location, CXXRecordDecl *ClassDecl,
7717       llvm::SmallPtrSetImpl<const RecordType *> *DirectVirtualBases = nullptr);
7718 
7719   /// Do semantic checks to allow the complete destructor variant to be emitted
7720   /// when the destructor is defined in another translation unit. In the Itanium
7721   /// C++ ABI, destructor variants are emitted together. In the MS C++ ABI, they
7722   /// can be emitted in separate TUs. To emit the complete variant, run a subset
7723   /// of the checks performed when emitting a regular destructor.
7724   void CheckCompleteDestructorVariant(SourceLocation CurrentLocation,
7725                                       CXXDestructorDecl *Dtor);
7726 
7727   /// The list of classes whose vtables have been used within
7728   /// this translation unit, and the source locations at which the
7729   /// first use occurred.
7730   typedef std::pair<CXXRecordDecl*, SourceLocation> VTableUse;
7731 
7732   /// The list of vtables that are required but have not yet been
7733   /// materialized.
7734   SmallVector<VTableUse, 16> VTableUses;
7735 
7736   /// The set of classes whose vtables have been used within
7737   /// this translation unit, and a bit that will be true if the vtable is
7738   /// required to be emitted (otherwise, it should be emitted only if needed
7739   /// by code generation).
7740   llvm::DenseMap<CXXRecordDecl *, bool> VTablesUsed;
7741 
7742   /// Load any externally-stored vtable uses.
7743   void LoadExternalVTableUses();
7744 
7745   /// Note that the vtable for the given class was used at the
7746   /// given location.
7747   void MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
7748                       bool DefinitionRequired = false);
7749 
7750   /// Mark the exception specifications of all virtual member functions
7751   /// in the given class as needed.
7752   void MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
7753                                              const CXXRecordDecl *RD);
7754 
7755   /// MarkVirtualMembersReferenced - Will mark all members of the given
7756   /// CXXRecordDecl referenced.
7757   void MarkVirtualMembersReferenced(SourceLocation Loc, const CXXRecordDecl *RD,
7758                                     bool ConstexprOnly = false);
7759 
7760   /// Define all of the vtables that have been used in this
7761   /// translation unit and reference any virtual members used by those
7762   /// vtables.
7763   ///
7764   /// \returns true if any work was done, false otherwise.
7765   bool DefineUsedVTables();
7766 
7767   void AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl);
7768 
7769   void ActOnMemInitializers(Decl *ConstructorDecl,
7770                             SourceLocation ColonLoc,
7771                             ArrayRef<CXXCtorInitializer*> MemInits,
7772                             bool AnyErrors);
7773 
7774   /// Check class-level dllimport/dllexport attribute. The caller must
7775   /// ensure that referenceDLLExportedClassMethods is called some point later
7776   /// when all outer classes of Class are complete.
7777   void checkClassLevelDLLAttribute(CXXRecordDecl *Class);
7778   void checkClassLevelCodeSegAttribute(CXXRecordDecl *Class);
7779 
7780   void referenceDLLExportedClassMethods();
7781 
7782   void propagateDLLAttrToBaseClassTemplate(
7783       CXXRecordDecl *Class, Attr *ClassAttr,
7784       ClassTemplateSpecializationDecl *BaseTemplateSpec,
7785       SourceLocation BaseLoc);
7786 
7787   /// Add gsl::Pointer attribute to std::container::iterator
7788   /// \param ND The declaration that introduces the name
7789   /// std::container::iterator. \param UnderlyingRecord The record named by ND.
7790   void inferGslPointerAttribute(NamedDecl *ND, CXXRecordDecl *UnderlyingRecord);
7791 
7792   /// Add [[gsl::Owner]] and [[gsl::Pointer]] attributes for std:: types.
7793   void inferGslOwnerPointerAttribute(CXXRecordDecl *Record);
7794 
7795   /// Add [[gsl::Pointer]] attributes for std:: types.
7796   void inferGslPointerAttribute(TypedefNameDecl *TD);
7797 
7798   void CheckCompletedCXXClass(Scope *S, CXXRecordDecl *Record);
7799 
7800   /// Check that the C++ class annoated with "trivial_abi" satisfies all the
7801   /// conditions that are needed for the attribute to have an effect.
7802   void checkIllFormedTrivialABIStruct(CXXRecordDecl &RD);
7803 
7804   void ActOnFinishCXXMemberSpecification(Scope *S, SourceLocation RLoc,
7805                                          Decl *TagDecl, SourceLocation LBrac,
7806                                          SourceLocation RBrac,
7807                                          const ParsedAttributesView &AttrList);
7808   void ActOnFinishCXXMemberDecls();
7809   void ActOnFinishCXXNonNestedClass();
7810 
7811   void ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param);
7812   unsigned ActOnReenterTemplateScope(Decl *Template,
7813                                      llvm::function_ref<Scope *()> EnterScope);
7814   void ActOnStartDelayedMemberDeclarations(Scope *S, Decl *Record);
7815   void ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *Method);
7816   void ActOnDelayedCXXMethodParameter(Scope *S, Decl *Param);
7817   void ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *Record);
7818   void ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *Method);
7819   void ActOnFinishDelayedMemberInitializers(Decl *Record);
7820   void MarkAsLateParsedTemplate(FunctionDecl *FD, Decl *FnD,
7821                                 CachedTokens &Toks);
7822   void UnmarkAsLateParsedTemplate(FunctionDecl *FD);
7823   bool IsInsideALocalClassWithinATemplateFunction();
7824 
7825   bool EvaluateStaticAssertMessageAsString(Expr *Message, std::string &Result,
7826                                            ASTContext &Ctx,
7827                                            bool ErrorOnInvalidMessage);
7828   Decl *ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
7829                                      Expr *AssertExpr,
7830                                      Expr *AssertMessageExpr,
7831                                      SourceLocation RParenLoc);
7832   Decl *BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
7833                                      Expr *AssertExpr, Expr *AssertMessageExpr,
7834                                      SourceLocation RParenLoc, bool Failed);
7835   void DiagnoseStaticAssertDetails(const Expr *E);
7836 
7837   FriendDecl *CheckFriendTypeDecl(SourceLocation LocStart,
7838                                   SourceLocation FriendLoc,
7839                                   TypeSourceInfo *TSInfo);
7840   Decl *ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
7841                             MultiTemplateParamsArg TemplateParams);
7842   NamedDecl *ActOnFriendFunctionDecl(Scope *S, Declarator &D,
7843                                      MultiTemplateParamsArg TemplateParams);
7844 
7845   QualType CheckConstructorDeclarator(Declarator &D, QualType R,
7846                                       StorageClass& SC);
7847   void CheckConstructor(CXXConstructorDecl *Constructor);
7848   QualType CheckDestructorDeclarator(Declarator &D, QualType R,
7849                                      StorageClass& SC);
7850   bool CheckDestructor(CXXDestructorDecl *Destructor);
7851   void CheckConversionDeclarator(Declarator &D, QualType &R,
7852                                  StorageClass& SC);
7853   Decl *ActOnConversionDeclarator(CXXConversionDecl *Conversion);
7854   bool CheckDeductionGuideDeclarator(Declarator &D, QualType &R,
7855                                      StorageClass &SC);
7856   void CheckDeductionGuideTemplate(FunctionTemplateDecl *TD);
7857 
7858   void CheckExplicitlyDefaultedFunction(Scope *S, FunctionDecl *MD);
7859 
7860   bool CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD,
7861                                              CXXSpecialMember CSM,
7862                                              SourceLocation DefaultLoc);
7863   void CheckDelayedMemberExceptionSpecs();
7864 
7865   bool CheckExplicitlyDefaultedComparison(Scope *S, FunctionDecl *MD,
7866                                           DefaultedComparisonKind DCK);
7867   void DeclareImplicitEqualityComparison(CXXRecordDecl *RD,
7868                                          FunctionDecl *Spaceship);
7869   void DefineDefaultedComparison(SourceLocation Loc, FunctionDecl *FD,
7870                                  DefaultedComparisonKind DCK);
7871 
7872   //===--------------------------------------------------------------------===//
7873   // C++ Derived Classes
7874   //
7875 
7876   /// ActOnBaseSpecifier - Parsed a base specifier
7877   CXXBaseSpecifier *CheckBaseSpecifier(CXXRecordDecl *Class,
7878                                        SourceRange SpecifierRange,
7879                                        bool Virtual, AccessSpecifier Access,
7880                                        TypeSourceInfo *TInfo,
7881                                        SourceLocation EllipsisLoc);
7882 
7883   BaseResult ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
7884                                 const ParsedAttributesView &Attrs, bool Virtual,
7885                                 AccessSpecifier Access, ParsedType basetype,
7886                                 SourceLocation BaseLoc,
7887                                 SourceLocation EllipsisLoc);
7888 
7889   bool AttachBaseSpecifiers(CXXRecordDecl *Class,
7890                             MutableArrayRef<CXXBaseSpecifier *> Bases);
7891   void ActOnBaseSpecifiers(Decl *ClassDecl,
7892                            MutableArrayRef<CXXBaseSpecifier *> Bases);
7893 
7894   bool IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base);
7895   bool IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base,
7896                      CXXBasePaths &Paths);
7897 
7898   // FIXME: I don't like this name.
7899   void BuildBasePathArray(const CXXBasePaths &Paths, CXXCastPath &BasePath);
7900 
7901   bool CheckDerivedToBaseConversion(QualType Derived, QualType Base,
7902                                     SourceLocation Loc, SourceRange Range,
7903                                     CXXCastPath *BasePath = nullptr,
7904                                     bool IgnoreAccess = false);
7905   bool CheckDerivedToBaseConversion(QualType Derived, QualType Base,
7906                                     unsigned InaccessibleBaseID,
7907                                     unsigned AmbiguousBaseConvID,
7908                                     SourceLocation Loc, SourceRange Range,
7909                                     DeclarationName Name,
7910                                     CXXCastPath *BasePath,
7911                                     bool IgnoreAccess = false);
7912 
7913   std::string getAmbiguousPathsDisplayString(CXXBasePaths &Paths);
7914 
7915   bool CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
7916                                          const CXXMethodDecl *Old);
7917 
7918   /// CheckOverridingFunctionReturnType - Checks whether the return types are
7919   /// covariant, according to C++ [class.virtual]p5.
7920   bool CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
7921                                          const CXXMethodDecl *Old);
7922 
7923   /// CheckOverridingFunctionExceptionSpec - Checks whether the exception
7924   /// spec is a subset of base spec.
7925   bool CheckOverridingFunctionExceptionSpec(const CXXMethodDecl *New,
7926                                             const CXXMethodDecl *Old);
7927 
7928   bool CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange);
7929 
7930   /// CheckOverrideControl - Check C++11 override control semantics.
7931   void CheckOverrideControl(NamedDecl *D);
7932 
7933   /// DiagnoseAbsenceOfOverrideControl - Diagnose if 'override' keyword was
7934   /// not used in the declaration of an overriding method.
7935   void DiagnoseAbsenceOfOverrideControl(NamedDecl *D, bool Inconsistent);
7936 
7937   /// CheckForFunctionMarkedFinal - Checks whether a virtual member function
7938   /// overrides a virtual member function marked 'final', according to
7939   /// C++11 [class.virtual]p4.
7940   bool CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
7941                                               const CXXMethodDecl *Old);
7942 
7943 
7944   //===--------------------------------------------------------------------===//
7945   // C++ Access Control
7946   //
7947 
7948   enum AccessResult {
7949     AR_accessible,
7950     AR_inaccessible,
7951     AR_dependent,
7952     AR_delayed
7953   };
7954 
7955   bool SetMemberAccessSpecifier(NamedDecl *MemberDecl,
7956                                 NamedDecl *PrevMemberDecl,
7957                                 AccessSpecifier LexicalAS);
7958 
7959   AccessResult CheckUnresolvedMemberAccess(UnresolvedMemberExpr *E,
7960                                            DeclAccessPair FoundDecl);
7961   AccessResult CheckUnresolvedLookupAccess(UnresolvedLookupExpr *E,
7962                                            DeclAccessPair FoundDecl);
7963   AccessResult CheckAllocationAccess(SourceLocation OperatorLoc,
7964                                      SourceRange PlacementRange,
7965                                      CXXRecordDecl *NamingClass,
7966                                      DeclAccessPair FoundDecl,
7967                                      bool Diagnose = true);
7968   AccessResult CheckConstructorAccess(SourceLocation Loc,
7969                                       CXXConstructorDecl *D,
7970                                       DeclAccessPair FoundDecl,
7971                                       const InitializedEntity &Entity,
7972                                       bool IsCopyBindingRefToTemp = false);
7973   AccessResult CheckConstructorAccess(SourceLocation Loc,
7974                                       CXXConstructorDecl *D,
7975                                       DeclAccessPair FoundDecl,
7976                                       const InitializedEntity &Entity,
7977                                       const PartialDiagnostic &PDiag);
7978   AccessResult CheckDestructorAccess(SourceLocation Loc,
7979                                      CXXDestructorDecl *Dtor,
7980                                      const PartialDiagnostic &PDiag,
7981                                      QualType objectType = QualType());
7982   AccessResult CheckFriendAccess(NamedDecl *D);
7983   AccessResult CheckMemberAccess(SourceLocation UseLoc,
7984                                  CXXRecordDecl *NamingClass,
7985                                  DeclAccessPair Found);
7986   AccessResult
7987   CheckStructuredBindingMemberAccess(SourceLocation UseLoc,
7988                                      CXXRecordDecl *DecomposedClass,
7989                                      DeclAccessPair Field);
7990   AccessResult CheckMemberOperatorAccess(SourceLocation Loc, Expr *ObjectExpr,
7991                                          const SourceRange &,
7992                                          DeclAccessPair FoundDecl);
7993   AccessResult CheckMemberOperatorAccess(SourceLocation Loc,
7994                                          Expr *ObjectExpr,
7995                                          Expr *ArgExpr,
7996                                          DeclAccessPair FoundDecl);
7997   AccessResult CheckMemberOperatorAccess(SourceLocation Loc, Expr *ObjectExpr,
7998                                          ArrayRef<Expr *> ArgExprs,
7999                                          DeclAccessPair FoundDecl);
8000   AccessResult CheckAddressOfMemberAccess(Expr *OvlExpr,
8001                                           DeclAccessPair FoundDecl);
8002   AccessResult CheckBaseClassAccess(SourceLocation AccessLoc,
8003                                     QualType Base, QualType Derived,
8004                                     const CXXBasePath &Path,
8005                                     unsigned DiagID,
8006                                     bool ForceCheck = false,
8007                                     bool ForceUnprivileged = false);
8008   void CheckLookupAccess(const LookupResult &R);
8009   bool IsSimplyAccessible(NamedDecl *Decl, CXXRecordDecl *NamingClass,
8010                           QualType BaseType);
8011   bool isMemberAccessibleForDeletion(CXXRecordDecl *NamingClass,
8012                                      DeclAccessPair Found, QualType ObjectType,
8013                                      SourceLocation Loc,
8014                                      const PartialDiagnostic &Diag);
8015   bool isMemberAccessibleForDeletion(CXXRecordDecl *NamingClass,
8016                                      DeclAccessPair Found,
8017                                      QualType ObjectType) {
8018     return isMemberAccessibleForDeletion(NamingClass, Found, ObjectType,
8019                                          SourceLocation(), PDiag());
8020   }
8021 
8022   void HandleDependentAccessCheck(const DependentDiagnostic &DD,
8023                          const MultiLevelTemplateArgumentList &TemplateArgs);
8024   void PerformDependentDiagnostics(const DeclContext *Pattern,
8025                         const MultiLevelTemplateArgumentList &TemplateArgs);
8026 
8027   void HandleDelayedAccessCheck(sema::DelayedDiagnostic &DD, Decl *Ctx);
8028 
8029   /// When true, access checking violations are treated as SFINAE
8030   /// failures rather than hard errors.
8031   bool AccessCheckingSFINAE;
8032 
8033   enum AbstractDiagSelID {
8034     AbstractNone = -1,
8035     AbstractReturnType,
8036     AbstractParamType,
8037     AbstractVariableType,
8038     AbstractFieldType,
8039     AbstractIvarType,
8040     AbstractSynthesizedIvarType,
8041     AbstractArrayType
8042   };
8043 
8044   bool isAbstractType(SourceLocation Loc, QualType T);
8045   bool RequireNonAbstractType(SourceLocation Loc, QualType T,
8046                               TypeDiagnoser &Diagnoser);
8047   template <typename... Ts>
8048   bool RequireNonAbstractType(SourceLocation Loc, QualType T, unsigned DiagID,
8049                               const Ts &...Args) {
8050     BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
8051     return RequireNonAbstractType(Loc, T, Diagnoser);
8052   }
8053 
8054   void DiagnoseAbstractType(const CXXRecordDecl *RD);
8055 
8056   //===--------------------------------------------------------------------===//
8057   // C++ Overloaded Operators [C++ 13.5]
8058   //
8059 
8060   bool CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl);
8061 
8062   bool CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl);
8063 
8064   //===--------------------------------------------------------------------===//
8065   // C++ Templates [C++ 14]
8066   //
8067   void FilterAcceptableTemplateNames(LookupResult &R,
8068                                      bool AllowFunctionTemplates = true,
8069                                      bool AllowDependent = true);
8070   bool hasAnyAcceptableTemplateNames(LookupResult &R,
8071                                      bool AllowFunctionTemplates = true,
8072                                      bool AllowDependent = true,
8073                                      bool AllowNonTemplateFunctions = false);
8074   /// Try to interpret the lookup result D as a template-name.
8075   ///
8076   /// \param D A declaration found by name lookup.
8077   /// \param AllowFunctionTemplates Whether function templates should be
8078   ///        considered valid results.
8079   /// \param AllowDependent Whether unresolved using declarations (that might
8080   ///        name templates) should be considered valid results.
8081   static NamedDecl *getAsTemplateNameDecl(NamedDecl *D,
8082                                           bool AllowFunctionTemplates = true,
8083                                           bool AllowDependent = true);
8084 
8085   enum TemplateNameIsRequiredTag { TemplateNameIsRequired };
8086   /// Whether and why a template name is required in this lookup.
8087   class RequiredTemplateKind {
8088   public:
8089     /// Template name is required if TemplateKWLoc is valid.
8090     RequiredTemplateKind(SourceLocation TemplateKWLoc = SourceLocation())
8091         : TemplateKW(TemplateKWLoc) {}
8092     /// Template name is unconditionally required.
8093     RequiredTemplateKind(TemplateNameIsRequiredTag) {}
8094 
8095     SourceLocation getTemplateKeywordLoc() const {
8096       return TemplateKW.value_or(SourceLocation());
8097     }
8098     bool hasTemplateKeyword() const { return getTemplateKeywordLoc().isValid(); }
8099     bool isRequired() const { return TemplateKW != SourceLocation(); }
8100     explicit operator bool() const { return isRequired(); }
8101 
8102   private:
8103     std::optional<SourceLocation> TemplateKW;
8104   };
8105 
8106   enum class AssumedTemplateKind {
8107     /// This is not assumed to be a template name.
8108     None,
8109     /// This is assumed to be a template name because lookup found nothing.
8110     FoundNothing,
8111     /// This is assumed to be a template name because lookup found one or more
8112     /// functions (but no function templates).
8113     FoundFunctions,
8114   };
8115   bool LookupTemplateName(
8116       LookupResult &R, Scope *S, CXXScopeSpec &SS, QualType ObjectType,
8117       bool EnteringContext, bool &MemberOfUnknownSpecialization,
8118       RequiredTemplateKind RequiredTemplate = SourceLocation(),
8119       AssumedTemplateKind *ATK = nullptr, bool AllowTypoCorrection = true);
8120 
8121   TemplateNameKind isTemplateName(Scope *S,
8122                                   CXXScopeSpec &SS,
8123                                   bool hasTemplateKeyword,
8124                                   const UnqualifiedId &Name,
8125                                   ParsedType ObjectType,
8126                                   bool EnteringContext,
8127                                   TemplateTy &Template,
8128                                   bool &MemberOfUnknownSpecialization,
8129                                   bool Disambiguation = false);
8130 
8131   /// Try to resolve an undeclared template name as a type template.
8132   ///
8133   /// Sets II to the identifier corresponding to the template name, and updates
8134   /// Name to a corresponding (typo-corrected) type template name and TNK to
8135   /// the corresponding kind, if possible.
8136   void ActOnUndeclaredTypeTemplateName(Scope *S, TemplateTy &Name,
8137                                        TemplateNameKind &TNK,
8138                                        SourceLocation NameLoc,
8139                                        IdentifierInfo *&II);
8140 
8141   bool resolveAssumedTemplateNameAsType(Scope *S, TemplateName &Name,
8142                                         SourceLocation NameLoc,
8143                                         bool Diagnose = true);
8144 
8145   /// Determine whether a particular identifier might be the name in a C++1z
8146   /// deduction-guide declaration.
8147   bool isDeductionGuideName(Scope *S, const IdentifierInfo &Name,
8148                             SourceLocation NameLoc, CXXScopeSpec &SS,
8149                             ParsedTemplateTy *Template = nullptr);
8150 
8151   bool DiagnoseUnknownTemplateName(const IdentifierInfo &II,
8152                                    SourceLocation IILoc,
8153                                    Scope *S,
8154                                    const CXXScopeSpec *SS,
8155                                    TemplateTy &SuggestedTemplate,
8156                                    TemplateNameKind &SuggestedKind);
8157 
8158   bool DiagnoseUninstantiableTemplate(SourceLocation PointOfInstantiation,
8159                                       NamedDecl *Instantiation,
8160                                       bool InstantiatedFromMember,
8161                                       const NamedDecl *Pattern,
8162                                       const NamedDecl *PatternDef,
8163                                       TemplateSpecializationKind TSK,
8164                                       bool Complain = true);
8165 
8166   void DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl);
8167   TemplateDecl *AdjustDeclIfTemplate(Decl *&Decl);
8168 
8169   NamedDecl *ActOnTypeParameter(Scope *S, bool Typename,
8170                                 SourceLocation EllipsisLoc,
8171                                 SourceLocation KeyLoc,
8172                                 IdentifierInfo *ParamName,
8173                                 SourceLocation ParamNameLoc,
8174                                 unsigned Depth, unsigned Position,
8175                                 SourceLocation EqualLoc,
8176                                 ParsedType DefaultArg, bool HasTypeConstraint);
8177 
8178   bool CheckTypeConstraint(TemplateIdAnnotation *TypeConstraint);
8179 
8180   bool ActOnTypeConstraint(const CXXScopeSpec &SS,
8181                            TemplateIdAnnotation *TypeConstraint,
8182                            TemplateTypeParmDecl *ConstrainedParameter,
8183                            SourceLocation EllipsisLoc);
8184   bool BuildTypeConstraint(const CXXScopeSpec &SS,
8185                            TemplateIdAnnotation *TypeConstraint,
8186                            TemplateTypeParmDecl *ConstrainedParameter,
8187                            SourceLocation EllipsisLoc,
8188                            bool AllowUnexpandedPack);
8189 
8190   bool AttachTypeConstraint(NestedNameSpecifierLoc NS,
8191                             DeclarationNameInfo NameInfo,
8192                             ConceptDecl *NamedConcept,
8193                             const TemplateArgumentListInfo *TemplateArgs,
8194                             TemplateTypeParmDecl *ConstrainedParameter,
8195                             SourceLocation EllipsisLoc);
8196 
8197   bool AttachTypeConstraint(AutoTypeLoc TL,
8198                             NonTypeTemplateParmDecl *NewConstrainedParm,
8199                             NonTypeTemplateParmDecl *OrigConstrainedParm,
8200                             SourceLocation EllipsisLoc);
8201 
8202   bool RequireStructuralType(QualType T, SourceLocation Loc);
8203 
8204   QualType CheckNonTypeTemplateParameterType(TypeSourceInfo *&TSI,
8205                                              SourceLocation Loc);
8206   QualType CheckNonTypeTemplateParameterType(QualType T, SourceLocation Loc);
8207 
8208   NamedDecl *ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
8209                                       unsigned Depth,
8210                                       unsigned Position,
8211                                       SourceLocation EqualLoc,
8212                                       Expr *DefaultArg);
8213   NamedDecl *ActOnTemplateTemplateParameter(Scope *S,
8214                                        SourceLocation TmpLoc,
8215                                        TemplateParameterList *Params,
8216                                        SourceLocation EllipsisLoc,
8217                                        IdentifierInfo *ParamName,
8218                                        SourceLocation ParamNameLoc,
8219                                        unsigned Depth,
8220                                        unsigned Position,
8221                                        SourceLocation EqualLoc,
8222                                        ParsedTemplateArgument DefaultArg);
8223 
8224   TemplateParameterList *
8225   ActOnTemplateParameterList(unsigned Depth,
8226                              SourceLocation ExportLoc,
8227                              SourceLocation TemplateLoc,
8228                              SourceLocation LAngleLoc,
8229                              ArrayRef<NamedDecl *> Params,
8230                              SourceLocation RAngleLoc,
8231                              Expr *RequiresClause);
8232 
8233   /// The context in which we are checking a template parameter list.
8234   enum TemplateParamListContext {
8235     TPC_ClassTemplate,
8236     TPC_VarTemplate,
8237     TPC_FunctionTemplate,
8238     TPC_ClassTemplateMember,
8239     TPC_FriendClassTemplate,
8240     TPC_FriendFunctionTemplate,
8241     TPC_FriendFunctionTemplateDefinition,
8242     TPC_TypeAliasTemplate
8243   };
8244 
8245   bool CheckTemplateParameterList(TemplateParameterList *NewParams,
8246                                   TemplateParameterList *OldParams,
8247                                   TemplateParamListContext TPC,
8248                                   SkipBodyInfo *SkipBody = nullptr);
8249   TemplateParameterList *MatchTemplateParametersToScopeSpecifier(
8250       SourceLocation DeclStartLoc, SourceLocation DeclLoc,
8251       const CXXScopeSpec &SS, TemplateIdAnnotation *TemplateId,
8252       ArrayRef<TemplateParameterList *> ParamLists,
8253       bool IsFriend, bool &IsMemberSpecialization, bool &Invalid,
8254       bool SuppressDiagnostic = false);
8255 
8256   DeclResult CheckClassTemplate(
8257       Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc,
8258       CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc,
8259       const ParsedAttributesView &Attr, TemplateParameterList *TemplateParams,
8260       AccessSpecifier AS, SourceLocation ModulePrivateLoc,
8261       SourceLocation FriendLoc, unsigned NumOuterTemplateParamLists,
8262       TemplateParameterList **OuterTemplateParamLists,
8263       SkipBodyInfo *SkipBody = nullptr);
8264 
8265   TemplateArgumentLoc getTrivialTemplateArgumentLoc(const TemplateArgument &Arg,
8266                                                     QualType NTTPType,
8267                                                     SourceLocation Loc);
8268 
8269   /// Get a template argument mapping the given template parameter to itself,
8270   /// e.g. for X in \c template<int X>, this would return an expression template
8271   /// argument referencing X.
8272   TemplateArgumentLoc getIdentityTemplateArgumentLoc(NamedDecl *Param,
8273                                                      SourceLocation Location);
8274 
8275   void translateTemplateArguments(const ASTTemplateArgsPtr &In,
8276                                   TemplateArgumentListInfo &Out);
8277 
8278   ParsedTemplateArgument ActOnTemplateTypeArgument(TypeResult ParsedType);
8279 
8280   void NoteAllFoundTemplates(TemplateName Name);
8281 
8282   QualType CheckTemplateIdType(TemplateName Template,
8283                                SourceLocation TemplateLoc,
8284                               TemplateArgumentListInfo &TemplateArgs);
8285 
8286   TypeResult
8287   ActOnTemplateIdType(Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
8288                       TemplateTy Template, IdentifierInfo *TemplateII,
8289                       SourceLocation TemplateIILoc, SourceLocation LAngleLoc,
8290                       ASTTemplateArgsPtr TemplateArgs, SourceLocation RAngleLoc,
8291                       bool IsCtorOrDtorName = false, bool IsClassName = false,
8292                       ImplicitTypenameContext AllowImplicitTypename =
8293                           ImplicitTypenameContext::No);
8294 
8295   /// Parsed an elaborated-type-specifier that refers to a template-id,
8296   /// such as \c class T::template apply<U>.
8297   TypeResult ActOnTagTemplateIdType(TagUseKind TUK,
8298                                     TypeSpecifierType TagSpec,
8299                                     SourceLocation TagLoc,
8300                                     CXXScopeSpec &SS,
8301                                     SourceLocation TemplateKWLoc,
8302                                     TemplateTy TemplateD,
8303                                     SourceLocation TemplateLoc,
8304                                     SourceLocation LAngleLoc,
8305                                     ASTTemplateArgsPtr TemplateArgsIn,
8306                                     SourceLocation RAngleLoc);
8307 
8308   DeclResult ActOnVarTemplateSpecialization(
8309       Scope *S, Declarator &D, TypeSourceInfo *DI,
8310       SourceLocation TemplateKWLoc, TemplateParameterList *TemplateParams,
8311       StorageClass SC, bool IsPartialSpecialization);
8312 
8313   /// Get the specialization of the given variable template corresponding to
8314   /// the specified argument list, or a null-but-valid result if the arguments
8315   /// are dependent.
8316   DeclResult CheckVarTemplateId(VarTemplateDecl *Template,
8317                                 SourceLocation TemplateLoc,
8318                                 SourceLocation TemplateNameLoc,
8319                                 const TemplateArgumentListInfo &TemplateArgs);
8320 
8321   /// Form a reference to the specialization of the given variable template
8322   /// corresponding to the specified argument list, or a null-but-valid result
8323   /// if the arguments are dependent.
8324   ExprResult CheckVarTemplateId(const CXXScopeSpec &SS,
8325                                 const DeclarationNameInfo &NameInfo,
8326                                 VarTemplateDecl *Template,
8327                                 SourceLocation TemplateLoc,
8328                                 const TemplateArgumentListInfo *TemplateArgs);
8329 
8330   ExprResult
8331   CheckConceptTemplateId(const CXXScopeSpec &SS,
8332                          SourceLocation TemplateKWLoc,
8333                          const DeclarationNameInfo &ConceptNameInfo,
8334                          NamedDecl *FoundDecl, ConceptDecl *NamedConcept,
8335                          const TemplateArgumentListInfo *TemplateArgs);
8336 
8337   void diagnoseMissingTemplateArguments(TemplateName Name, SourceLocation Loc);
8338 
8339   ExprResult BuildTemplateIdExpr(const CXXScopeSpec &SS,
8340                                  SourceLocation TemplateKWLoc,
8341                                  LookupResult &R,
8342                                  bool RequiresADL,
8343                                const TemplateArgumentListInfo *TemplateArgs);
8344 
8345   ExprResult BuildQualifiedTemplateIdExpr(CXXScopeSpec &SS,
8346                                           SourceLocation TemplateKWLoc,
8347                                const DeclarationNameInfo &NameInfo,
8348                                const TemplateArgumentListInfo *TemplateArgs);
8349 
8350   TemplateNameKind ActOnTemplateName(
8351       Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
8352       const UnqualifiedId &Name, ParsedType ObjectType, bool EnteringContext,
8353       TemplateTy &Template, bool AllowInjectedClassName = false);
8354 
8355   DeclResult ActOnClassTemplateSpecialization(
8356       Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc,
8357       SourceLocation ModulePrivateLoc, CXXScopeSpec &SS,
8358       TemplateIdAnnotation &TemplateId, const ParsedAttributesView &Attr,
8359       MultiTemplateParamsArg TemplateParameterLists,
8360       SkipBodyInfo *SkipBody = nullptr);
8361 
8362   bool CheckTemplatePartialSpecializationArgs(SourceLocation Loc,
8363                                               TemplateDecl *PrimaryTemplate,
8364                                               unsigned NumExplicitArgs,
8365                                               ArrayRef<TemplateArgument> Args);
8366   void CheckTemplatePartialSpecialization(
8367       ClassTemplatePartialSpecializationDecl *Partial);
8368   void CheckTemplatePartialSpecialization(
8369       VarTemplatePartialSpecializationDecl *Partial);
8370 
8371   Decl *ActOnTemplateDeclarator(Scope *S,
8372                                 MultiTemplateParamsArg TemplateParameterLists,
8373                                 Declarator &D);
8374 
8375   bool
8376   CheckSpecializationInstantiationRedecl(SourceLocation NewLoc,
8377                                          TemplateSpecializationKind NewTSK,
8378                                          NamedDecl *PrevDecl,
8379                                          TemplateSpecializationKind PrevTSK,
8380                                          SourceLocation PrevPtOfInstantiation,
8381                                          bool &SuppressNew);
8382 
8383   bool CheckDependentFunctionTemplateSpecialization(FunctionDecl *FD,
8384                     const TemplateArgumentListInfo &ExplicitTemplateArgs,
8385                                                     LookupResult &Previous);
8386 
8387   bool CheckFunctionTemplateSpecialization(
8388       FunctionDecl *FD, TemplateArgumentListInfo *ExplicitTemplateArgs,
8389       LookupResult &Previous, bool QualifiedFriend = false);
8390   bool CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous);
8391   void CompleteMemberSpecialization(NamedDecl *Member, LookupResult &Previous);
8392 
8393   DeclResult ActOnExplicitInstantiation(
8394       Scope *S, SourceLocation ExternLoc, SourceLocation TemplateLoc,
8395       unsigned TagSpec, SourceLocation KWLoc, const CXXScopeSpec &SS,
8396       TemplateTy Template, SourceLocation TemplateNameLoc,
8397       SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgs,
8398       SourceLocation RAngleLoc, const ParsedAttributesView &Attr);
8399 
8400   DeclResult ActOnExplicitInstantiation(Scope *S, SourceLocation ExternLoc,
8401                                         SourceLocation TemplateLoc,
8402                                         unsigned TagSpec, SourceLocation KWLoc,
8403                                         CXXScopeSpec &SS, IdentifierInfo *Name,
8404                                         SourceLocation NameLoc,
8405                                         const ParsedAttributesView &Attr);
8406 
8407   DeclResult ActOnExplicitInstantiation(Scope *S,
8408                                         SourceLocation ExternLoc,
8409                                         SourceLocation TemplateLoc,
8410                                         Declarator &D);
8411 
8412   TemplateArgumentLoc SubstDefaultTemplateArgumentIfAvailable(
8413       TemplateDecl *Template, SourceLocation TemplateLoc,
8414       SourceLocation RAngleLoc, Decl *Param,
8415       ArrayRef<TemplateArgument> SugaredConverted,
8416       ArrayRef<TemplateArgument> CanonicalConverted, bool &HasDefaultArg);
8417 
8418   /// Specifies the context in which a particular template
8419   /// argument is being checked.
8420   enum CheckTemplateArgumentKind {
8421     /// The template argument was specified in the code or was
8422     /// instantiated with some deduced template arguments.
8423     CTAK_Specified,
8424 
8425     /// The template argument was deduced via template argument
8426     /// deduction.
8427     CTAK_Deduced,
8428 
8429     /// The template argument was deduced from an array bound
8430     /// via template argument deduction.
8431     CTAK_DeducedFromArrayBound
8432   };
8433 
8434   bool
8435   CheckTemplateArgument(NamedDecl *Param, TemplateArgumentLoc &Arg,
8436                         NamedDecl *Template, SourceLocation TemplateLoc,
8437                         SourceLocation RAngleLoc, unsigned ArgumentPackIndex,
8438                         SmallVectorImpl<TemplateArgument> &SugaredConverted,
8439                         SmallVectorImpl<TemplateArgument> &CanonicalConverted,
8440                         CheckTemplateArgumentKind CTAK);
8441 
8442   /// Check that the given template arguments can be provided to
8443   /// the given template, converting the arguments along the way.
8444   ///
8445   /// \param Template The template to which the template arguments are being
8446   /// provided.
8447   ///
8448   /// \param TemplateLoc The location of the template name in the source.
8449   ///
8450   /// \param TemplateArgs The list of template arguments. If the template is
8451   /// a template template parameter, this function may extend the set of
8452   /// template arguments to also include substituted, defaulted template
8453   /// arguments.
8454   ///
8455   /// \param PartialTemplateArgs True if the list of template arguments is
8456   /// intentionally partial, e.g., because we're checking just the initial
8457   /// set of template arguments.
8458   ///
8459   /// \param Converted Will receive the converted, canonicalized template
8460   /// arguments.
8461   ///
8462   /// \param UpdateArgsWithConversions If \c true, update \p TemplateArgs to
8463   /// contain the converted forms of the template arguments as written.
8464   /// Otherwise, \p TemplateArgs will not be modified.
8465   ///
8466   /// \param ConstraintsNotSatisfied If provided, and an error occurred, will
8467   /// receive true if the cause for the error is the associated constraints of
8468   /// the template not being satisfied by the template arguments.
8469   ///
8470   /// \returns true if an error occurred, false otherwise.
8471   bool CheckTemplateArgumentList(
8472       TemplateDecl *Template, SourceLocation TemplateLoc,
8473       TemplateArgumentListInfo &TemplateArgs, bool PartialTemplateArgs,
8474       SmallVectorImpl<TemplateArgument> &SugaredConverted,
8475       SmallVectorImpl<TemplateArgument> &CanonicalConverted,
8476       bool UpdateArgsWithConversions = true,
8477       bool *ConstraintsNotSatisfied = nullptr);
8478 
8479   bool CheckTemplateTypeArgument(
8480       TemplateTypeParmDecl *Param, TemplateArgumentLoc &Arg,
8481       SmallVectorImpl<TemplateArgument> &SugaredConverted,
8482       SmallVectorImpl<TemplateArgument> &CanonicalConverted);
8483 
8484   bool CheckTemplateArgument(TypeSourceInfo *Arg);
8485   ExprResult CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
8486                                    QualType InstantiatedParamType, Expr *Arg,
8487                                    TemplateArgument &SugaredConverted,
8488                                    TemplateArgument &CanonicalConverted,
8489                                    CheckTemplateArgumentKind CTAK);
8490   bool CheckTemplateTemplateArgument(TemplateTemplateParmDecl *Param,
8491                                      TemplateParameterList *Params,
8492                                      TemplateArgumentLoc &Arg);
8493 
8494   ExprResult
8495   BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg,
8496                                           QualType ParamType,
8497                                           SourceLocation Loc);
8498   ExprResult
8499   BuildExpressionFromIntegralTemplateArgument(const TemplateArgument &Arg,
8500                                               SourceLocation Loc);
8501 
8502   /// Enumeration describing how template parameter lists are compared
8503   /// for equality.
8504   enum TemplateParameterListEqualKind {
8505     /// We are matching the template parameter lists of two templates
8506     /// that might be redeclarations.
8507     ///
8508     /// \code
8509     /// template<typename T> struct X;
8510     /// template<typename T> struct X;
8511     /// \endcode
8512     TPL_TemplateMatch,
8513 
8514     /// We are matching the template parameter lists of two template
8515     /// template parameters as part of matching the template parameter lists
8516     /// of two templates that might be redeclarations.
8517     ///
8518     /// \code
8519     /// template<template<int I> class TT> struct X;
8520     /// template<template<int Value> class Other> struct X;
8521     /// \endcode
8522     TPL_TemplateTemplateParmMatch,
8523 
8524     /// We are matching the template parameter lists of a template
8525     /// template argument against the template parameter lists of a template
8526     /// template parameter.
8527     ///
8528     /// \code
8529     /// template<template<int Value> class Metafun> struct X;
8530     /// template<int Value> struct integer_c;
8531     /// X<integer_c> xic;
8532     /// \endcode
8533     TPL_TemplateTemplateArgumentMatch,
8534 
8535     /// We are determining whether the template-parameters are equivalent
8536     /// according to C++ [temp.over.link]/6. This comparison does not consider
8537     /// constraints.
8538     ///
8539     /// \code
8540     /// template<C1 T> void f(T);
8541     /// template<C2 T> void f(T);
8542     /// \endcode
8543     TPL_TemplateParamsEquivalent,
8544   };
8545 
8546   bool TemplateParameterListsAreEqual(
8547       const NamedDecl *NewInstFrom, TemplateParameterList *New,
8548       const NamedDecl *OldInstFrom, TemplateParameterList *Old, bool Complain,
8549       TemplateParameterListEqualKind Kind,
8550       SourceLocation TemplateArgLoc = SourceLocation());
8551 
8552   bool TemplateParameterListsAreEqual(
8553       TemplateParameterList *New, TemplateParameterList *Old, bool Complain,
8554       TemplateParameterListEqualKind Kind,
8555       SourceLocation TemplateArgLoc = SourceLocation()) {
8556     return TemplateParameterListsAreEqual(nullptr, New, nullptr, Old, Complain,
8557                                           Kind, TemplateArgLoc);
8558   }
8559 
8560   bool CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams);
8561 
8562   /// Called when the parser has parsed a C++ typename
8563   /// specifier, e.g., "typename T::type".
8564   ///
8565   /// \param S The scope in which this typename type occurs.
8566   /// \param TypenameLoc the location of the 'typename' keyword
8567   /// \param SS the nested-name-specifier following the typename (e.g., 'T::').
8568   /// \param II the identifier we're retrieving (e.g., 'type' in the example).
8569   /// \param IdLoc the location of the identifier.
8570   /// \param IsImplicitTypename context where T::type refers to a type.
8571   TypeResult ActOnTypenameType(
8572       Scope *S, SourceLocation TypenameLoc, const CXXScopeSpec &SS,
8573       const IdentifierInfo &II, SourceLocation IdLoc,
8574       ImplicitTypenameContext IsImplicitTypename = ImplicitTypenameContext::No);
8575 
8576   /// Called when the parser has parsed a C++ typename
8577   /// specifier that ends in a template-id, e.g.,
8578   /// "typename MetaFun::template apply<T1, T2>".
8579   ///
8580   /// \param S The scope in which this typename type occurs.
8581   /// \param TypenameLoc the location of the 'typename' keyword
8582   /// \param SS the nested-name-specifier following the typename (e.g., 'T::').
8583   /// \param TemplateLoc the location of the 'template' keyword, if any.
8584   /// \param TemplateName The template name.
8585   /// \param TemplateII The identifier used to name the template.
8586   /// \param TemplateIILoc The location of the template name.
8587   /// \param LAngleLoc The location of the opening angle bracket  ('<').
8588   /// \param TemplateArgs The template arguments.
8589   /// \param RAngleLoc The location of the closing angle bracket  ('>').
8590   TypeResult
8591   ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
8592                     const CXXScopeSpec &SS,
8593                     SourceLocation TemplateLoc,
8594                     TemplateTy TemplateName,
8595                     IdentifierInfo *TemplateII,
8596                     SourceLocation TemplateIILoc,
8597                     SourceLocation LAngleLoc,
8598                     ASTTemplateArgsPtr TemplateArgs,
8599                     SourceLocation RAngleLoc);
8600 
8601   QualType CheckTypenameType(ElaboratedTypeKeyword Keyword,
8602                              SourceLocation KeywordLoc,
8603                              NestedNameSpecifierLoc QualifierLoc,
8604                              const IdentifierInfo &II,
8605                              SourceLocation IILoc,
8606                              TypeSourceInfo **TSI,
8607                              bool DeducedTSTContext);
8608 
8609   QualType CheckTypenameType(ElaboratedTypeKeyword Keyword,
8610                              SourceLocation KeywordLoc,
8611                              NestedNameSpecifierLoc QualifierLoc,
8612                              const IdentifierInfo &II,
8613                              SourceLocation IILoc,
8614                              bool DeducedTSTContext = true);
8615 
8616 
8617   TypeSourceInfo *RebuildTypeInCurrentInstantiation(TypeSourceInfo *T,
8618                                                     SourceLocation Loc,
8619                                                     DeclarationName Name);
8620   bool RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS);
8621 
8622   ExprResult RebuildExprInCurrentInstantiation(Expr *E);
8623   bool RebuildTemplateParamsInCurrentInstantiation(
8624                                                 TemplateParameterList *Params);
8625 
8626   std::string
8627   getTemplateArgumentBindingsText(const TemplateParameterList *Params,
8628                                   const TemplateArgumentList &Args);
8629 
8630   std::string
8631   getTemplateArgumentBindingsText(const TemplateParameterList *Params,
8632                                   const TemplateArgument *Args,
8633                                   unsigned NumArgs);
8634 
8635   //===--------------------------------------------------------------------===//
8636   // C++ Concepts
8637   //===--------------------------------------------------------------------===//
8638   Decl *ActOnConceptDefinition(
8639       Scope *S, MultiTemplateParamsArg TemplateParameterLists,
8640       IdentifierInfo *Name, SourceLocation NameLoc, Expr *ConstraintExpr);
8641 
8642   void CheckConceptRedefinition(ConceptDecl *NewDecl, LookupResult &Previous,
8643                                 bool &AddToScope);
8644 
8645   RequiresExprBodyDecl *
8646   ActOnStartRequiresExpr(SourceLocation RequiresKWLoc,
8647                          ArrayRef<ParmVarDecl *> LocalParameters,
8648                          Scope *BodyScope);
8649   void ActOnFinishRequiresExpr();
8650   concepts::Requirement *ActOnSimpleRequirement(Expr *E);
8651   concepts::Requirement *ActOnTypeRequirement(
8652       SourceLocation TypenameKWLoc, CXXScopeSpec &SS, SourceLocation NameLoc,
8653       IdentifierInfo *TypeName, TemplateIdAnnotation *TemplateId);
8654   concepts::Requirement *ActOnCompoundRequirement(Expr *E,
8655                                                   SourceLocation NoexceptLoc);
8656   concepts::Requirement *
8657   ActOnCompoundRequirement(
8658       Expr *E, SourceLocation NoexceptLoc, CXXScopeSpec &SS,
8659       TemplateIdAnnotation *TypeConstraint, unsigned Depth);
8660   concepts::Requirement *ActOnNestedRequirement(Expr *Constraint);
8661   concepts::ExprRequirement *
8662   BuildExprRequirement(
8663       Expr *E, bool IsSatisfied, SourceLocation NoexceptLoc,
8664       concepts::ExprRequirement::ReturnTypeRequirement ReturnTypeRequirement);
8665   concepts::ExprRequirement *
8666   BuildExprRequirement(
8667       concepts::Requirement::SubstitutionDiagnostic *ExprSubstDiag,
8668       bool IsSatisfied, SourceLocation NoexceptLoc,
8669       concepts::ExprRequirement::ReturnTypeRequirement ReturnTypeRequirement);
8670   concepts::TypeRequirement *BuildTypeRequirement(TypeSourceInfo *Type);
8671   concepts::TypeRequirement *
8672   BuildTypeRequirement(
8673       concepts::Requirement::SubstitutionDiagnostic *SubstDiag);
8674   concepts::NestedRequirement *BuildNestedRequirement(Expr *E);
8675   concepts::NestedRequirement *
8676   BuildNestedRequirement(StringRef InvalidConstraintEntity,
8677                          const ASTConstraintSatisfaction &Satisfaction);
8678   ExprResult ActOnRequiresExpr(SourceLocation RequiresKWLoc,
8679                                RequiresExprBodyDecl *Body,
8680                                ArrayRef<ParmVarDecl *> LocalParameters,
8681                                ArrayRef<concepts::Requirement *> Requirements,
8682                                SourceLocation ClosingBraceLoc);
8683 
8684   //===--------------------------------------------------------------------===//
8685   // C++ Variadic Templates (C++0x [temp.variadic])
8686   //===--------------------------------------------------------------------===//
8687 
8688   /// Determine whether an unexpanded parameter pack might be permitted in this
8689   /// location. Useful for error recovery.
8690   bool isUnexpandedParameterPackPermitted();
8691 
8692   /// The context in which an unexpanded parameter pack is
8693   /// being diagnosed.
8694   ///
8695   /// Note that the values of this enumeration line up with the first
8696   /// argument to the \c err_unexpanded_parameter_pack diagnostic.
8697   enum UnexpandedParameterPackContext {
8698     /// An arbitrary expression.
8699     UPPC_Expression = 0,
8700 
8701     /// The base type of a class type.
8702     UPPC_BaseType,
8703 
8704     /// The type of an arbitrary declaration.
8705     UPPC_DeclarationType,
8706 
8707     /// The type of a data member.
8708     UPPC_DataMemberType,
8709 
8710     /// The size of a bit-field.
8711     UPPC_BitFieldWidth,
8712 
8713     /// The expression in a static assertion.
8714     UPPC_StaticAssertExpression,
8715 
8716     /// The fixed underlying type of an enumeration.
8717     UPPC_FixedUnderlyingType,
8718 
8719     /// The enumerator value.
8720     UPPC_EnumeratorValue,
8721 
8722     /// A using declaration.
8723     UPPC_UsingDeclaration,
8724 
8725     /// A friend declaration.
8726     UPPC_FriendDeclaration,
8727 
8728     /// A declaration qualifier.
8729     UPPC_DeclarationQualifier,
8730 
8731     /// An initializer.
8732     UPPC_Initializer,
8733 
8734     /// A default argument.
8735     UPPC_DefaultArgument,
8736 
8737     /// The type of a non-type template parameter.
8738     UPPC_NonTypeTemplateParameterType,
8739 
8740     /// The type of an exception.
8741     UPPC_ExceptionType,
8742 
8743     /// Partial specialization.
8744     UPPC_PartialSpecialization,
8745 
8746     /// Microsoft __if_exists.
8747     UPPC_IfExists,
8748 
8749     /// Microsoft __if_not_exists.
8750     UPPC_IfNotExists,
8751 
8752     /// Lambda expression.
8753     UPPC_Lambda,
8754 
8755     /// Block expression.
8756     UPPC_Block,
8757 
8758     /// A type constraint.
8759     UPPC_TypeConstraint,
8760 
8761     // A requirement in a requires-expression.
8762     UPPC_Requirement,
8763 
8764     // A requires-clause.
8765     UPPC_RequiresClause,
8766   };
8767 
8768   /// Diagnose unexpanded parameter packs.
8769   ///
8770   /// \param Loc The location at which we should emit the diagnostic.
8771   ///
8772   /// \param UPPC The context in which we are diagnosing unexpanded
8773   /// parameter packs.
8774   ///
8775   /// \param Unexpanded the set of unexpanded parameter packs.
8776   ///
8777   /// \returns true if an error occurred, false otherwise.
8778   bool DiagnoseUnexpandedParameterPacks(SourceLocation Loc,
8779                                         UnexpandedParameterPackContext UPPC,
8780                                   ArrayRef<UnexpandedParameterPack> Unexpanded);
8781 
8782   /// If the given type contains an unexpanded parameter pack,
8783   /// diagnose the error.
8784   ///
8785   /// \param Loc The source location where a diagnostc should be emitted.
8786   ///
8787   /// \param T The type that is being checked for unexpanded parameter
8788   /// packs.
8789   ///
8790   /// \returns true if an error occurred, false otherwise.
8791   bool DiagnoseUnexpandedParameterPack(SourceLocation Loc, TypeSourceInfo *T,
8792                                        UnexpandedParameterPackContext UPPC);
8793 
8794   /// If the given expression contains an unexpanded parameter
8795   /// pack, diagnose the error.
8796   ///
8797   /// \param E The expression that is being checked for unexpanded
8798   /// parameter packs.
8799   ///
8800   /// \returns true if an error occurred, false otherwise.
8801   bool DiagnoseUnexpandedParameterPack(Expr *E,
8802                        UnexpandedParameterPackContext UPPC = UPPC_Expression);
8803 
8804   /// If the given requirees-expression contains an unexpanded reference to one
8805   /// of its own parameter packs, diagnose the error.
8806   ///
8807   /// \param RE The requiress-expression that is being checked for unexpanded
8808   /// parameter packs.
8809   ///
8810   /// \returns true if an error occurred, false otherwise.
8811   bool DiagnoseUnexpandedParameterPackInRequiresExpr(RequiresExpr *RE);
8812 
8813   /// If the given nested-name-specifier contains an unexpanded
8814   /// parameter pack, diagnose the error.
8815   ///
8816   /// \param SS The nested-name-specifier that is being checked for
8817   /// unexpanded parameter packs.
8818   ///
8819   /// \returns true if an error occurred, false otherwise.
8820   bool DiagnoseUnexpandedParameterPack(const CXXScopeSpec &SS,
8821                                        UnexpandedParameterPackContext UPPC);
8822 
8823   /// If the given name contains an unexpanded parameter pack,
8824   /// diagnose the error.
8825   ///
8826   /// \param NameInfo The name (with source location information) that
8827   /// is being checked for unexpanded parameter packs.
8828   ///
8829   /// \returns true if an error occurred, false otherwise.
8830   bool DiagnoseUnexpandedParameterPack(const DeclarationNameInfo &NameInfo,
8831                                        UnexpandedParameterPackContext UPPC);
8832 
8833   /// If the given template name contains an unexpanded parameter pack,
8834   /// diagnose the error.
8835   ///
8836   /// \param Loc The location of the template name.
8837   ///
8838   /// \param Template The template name that is being checked for unexpanded
8839   /// parameter packs.
8840   ///
8841   /// \returns true if an error occurred, false otherwise.
8842   bool DiagnoseUnexpandedParameterPack(SourceLocation Loc,
8843                                        TemplateName Template,
8844                                        UnexpandedParameterPackContext UPPC);
8845 
8846   /// If the given template argument contains an unexpanded parameter
8847   /// pack, diagnose the error.
8848   ///
8849   /// \param Arg The template argument that is being checked for unexpanded
8850   /// parameter packs.
8851   ///
8852   /// \returns true if an error occurred, false otherwise.
8853   bool DiagnoseUnexpandedParameterPack(TemplateArgumentLoc Arg,
8854                                        UnexpandedParameterPackContext UPPC);
8855 
8856   /// Collect the set of unexpanded parameter packs within the given
8857   /// template argument.
8858   ///
8859   /// \param Arg The template argument that will be traversed to find
8860   /// unexpanded parameter packs.
8861   void collectUnexpandedParameterPacks(TemplateArgument Arg,
8862                    SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
8863 
8864   /// Collect the set of unexpanded parameter packs within the given
8865   /// template argument.
8866   ///
8867   /// \param Arg The template argument that will be traversed to find
8868   /// unexpanded parameter packs.
8869   void collectUnexpandedParameterPacks(TemplateArgumentLoc Arg,
8870                     SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
8871 
8872   /// Collect the set of unexpanded parameter packs within the given
8873   /// type.
8874   ///
8875   /// \param T The type that will be traversed to find
8876   /// unexpanded parameter packs.
8877   void collectUnexpandedParameterPacks(QualType T,
8878                    SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
8879 
8880   /// Collect the set of unexpanded parameter packs within the given
8881   /// type.
8882   ///
8883   /// \param TL The type that will be traversed to find
8884   /// unexpanded parameter packs.
8885   void collectUnexpandedParameterPacks(TypeLoc TL,
8886                    SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
8887 
8888   /// Collect the set of unexpanded parameter packs within the given
8889   /// nested-name-specifier.
8890   ///
8891   /// \param NNS The nested-name-specifier that will be traversed to find
8892   /// unexpanded parameter packs.
8893   void collectUnexpandedParameterPacks(NestedNameSpecifierLoc NNS,
8894                          SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
8895 
8896   /// Collect the set of unexpanded parameter packs within the given
8897   /// name.
8898   ///
8899   /// \param NameInfo The name that will be traversed to find
8900   /// unexpanded parameter packs.
8901   void collectUnexpandedParameterPacks(const DeclarationNameInfo &NameInfo,
8902                          SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
8903 
8904   /// Invoked when parsing a template argument followed by an
8905   /// ellipsis, which creates a pack expansion.
8906   ///
8907   /// \param Arg The template argument preceding the ellipsis, which
8908   /// may already be invalid.
8909   ///
8910   /// \param EllipsisLoc The location of the ellipsis.
8911   ParsedTemplateArgument ActOnPackExpansion(const ParsedTemplateArgument &Arg,
8912                                             SourceLocation EllipsisLoc);
8913 
8914   /// Invoked when parsing a type followed by an ellipsis, which
8915   /// creates a pack expansion.
8916   ///
8917   /// \param Type The type preceding the ellipsis, which will become
8918   /// the pattern of the pack expansion.
8919   ///
8920   /// \param EllipsisLoc The location of the ellipsis.
8921   TypeResult ActOnPackExpansion(ParsedType Type, SourceLocation EllipsisLoc);
8922 
8923   /// Construct a pack expansion type from the pattern of the pack
8924   /// expansion.
8925   TypeSourceInfo *CheckPackExpansion(TypeSourceInfo *Pattern,
8926                                      SourceLocation EllipsisLoc,
8927                                      std::optional<unsigned> NumExpansions);
8928 
8929   /// Construct a pack expansion type from the pattern of the pack
8930   /// expansion.
8931   QualType CheckPackExpansion(QualType Pattern, SourceRange PatternRange,
8932                               SourceLocation EllipsisLoc,
8933                               std::optional<unsigned> NumExpansions);
8934 
8935   /// Invoked when parsing an expression followed by an ellipsis, which
8936   /// creates a pack expansion.
8937   ///
8938   /// \param Pattern The expression preceding the ellipsis, which will become
8939   /// the pattern of the pack expansion.
8940   ///
8941   /// \param EllipsisLoc The location of the ellipsis.
8942   ExprResult ActOnPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc);
8943 
8944   /// Invoked when parsing an expression followed by an ellipsis, which
8945   /// creates a pack expansion.
8946   ///
8947   /// \param Pattern The expression preceding the ellipsis, which will become
8948   /// the pattern of the pack expansion.
8949   ///
8950   /// \param EllipsisLoc The location of the ellipsis.
8951   ExprResult CheckPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc,
8952                                 std::optional<unsigned> NumExpansions);
8953 
8954   /// Determine whether we could expand a pack expansion with the
8955   /// given set of parameter packs into separate arguments by repeatedly
8956   /// transforming the pattern.
8957   ///
8958   /// \param EllipsisLoc The location of the ellipsis that identifies the
8959   /// pack expansion.
8960   ///
8961   /// \param PatternRange The source range that covers the entire pattern of
8962   /// the pack expansion.
8963   ///
8964   /// \param Unexpanded The set of unexpanded parameter packs within the
8965   /// pattern.
8966   ///
8967   /// \param ShouldExpand Will be set to \c true if the transformer should
8968   /// expand the corresponding pack expansions into separate arguments. When
8969   /// set, \c NumExpansions must also be set.
8970   ///
8971   /// \param RetainExpansion Whether the caller should add an unexpanded
8972   /// pack expansion after all of the expanded arguments. This is used
8973   /// when extending explicitly-specified template argument packs per
8974   /// C++0x [temp.arg.explicit]p9.
8975   ///
8976   /// \param NumExpansions The number of separate arguments that will be in
8977   /// the expanded form of the corresponding pack expansion. This is both an
8978   /// input and an output parameter, which can be set by the caller if the
8979   /// number of expansions is known a priori (e.g., due to a prior substitution)
8980   /// and will be set by the callee when the number of expansions is known.
8981   /// The callee must set this value when \c ShouldExpand is \c true; it may
8982   /// set this value in other cases.
8983   ///
8984   /// \returns true if an error occurred (e.g., because the parameter packs
8985   /// are to be instantiated with arguments of different lengths), false
8986   /// otherwise. If false, \c ShouldExpand (and possibly \c NumExpansions)
8987   /// must be set.
8988   bool CheckParameterPacksForExpansion(
8989       SourceLocation EllipsisLoc, SourceRange PatternRange,
8990       ArrayRef<UnexpandedParameterPack> Unexpanded,
8991       const MultiLevelTemplateArgumentList &TemplateArgs, bool &ShouldExpand,
8992       bool &RetainExpansion, std::optional<unsigned> &NumExpansions);
8993 
8994   /// Determine the number of arguments in the given pack expansion
8995   /// type.
8996   ///
8997   /// This routine assumes that the number of arguments in the expansion is
8998   /// consistent across all of the unexpanded parameter packs in its pattern.
8999   ///
9000   /// Returns an empty Optional if the type can't be expanded.
9001   std::optional<unsigned> getNumArgumentsInExpansion(
9002       QualType T, const MultiLevelTemplateArgumentList &TemplateArgs);
9003 
9004   /// Determine whether the given declarator contains any unexpanded
9005   /// parameter packs.
9006   ///
9007   /// This routine is used by the parser to disambiguate function declarators
9008   /// with an ellipsis prior to the ')', e.g.,
9009   ///
9010   /// \code
9011   ///   void f(T...);
9012   /// \endcode
9013   ///
9014   /// To determine whether we have an (unnamed) function parameter pack or
9015   /// a variadic function.
9016   ///
9017   /// \returns true if the declarator contains any unexpanded parameter packs,
9018   /// false otherwise.
9019   bool containsUnexpandedParameterPacks(Declarator &D);
9020 
9021   /// Returns the pattern of the pack expansion for a template argument.
9022   ///
9023   /// \param OrigLoc The template argument to expand.
9024   ///
9025   /// \param Ellipsis Will be set to the location of the ellipsis.
9026   ///
9027   /// \param NumExpansions Will be set to the number of expansions that will
9028   /// be generated from this pack expansion, if known a priori.
9029   TemplateArgumentLoc getTemplateArgumentPackExpansionPattern(
9030       TemplateArgumentLoc OrigLoc, SourceLocation &Ellipsis,
9031       std::optional<unsigned> &NumExpansions) const;
9032 
9033   /// Given a template argument that contains an unexpanded parameter pack, but
9034   /// which has already been substituted, attempt to determine the number of
9035   /// elements that will be produced once this argument is fully-expanded.
9036   ///
9037   /// This is intended for use when transforming 'sizeof...(Arg)' in order to
9038   /// avoid actually expanding the pack where possible.
9039   std::optional<unsigned> getFullyPackExpandedSize(TemplateArgument Arg);
9040 
9041   //===--------------------------------------------------------------------===//
9042   // C++ Template Argument Deduction (C++ [temp.deduct])
9043   //===--------------------------------------------------------------------===//
9044 
9045   /// Adjust the type \p ArgFunctionType to match the calling convention,
9046   /// noreturn, and optionally the exception specification of \p FunctionType.
9047   /// Deduction often wants to ignore these properties when matching function
9048   /// types.
9049   QualType adjustCCAndNoReturn(QualType ArgFunctionType, QualType FunctionType,
9050                                bool AdjustExceptionSpec = false);
9051 
9052   /// Describes the result of template argument deduction.
9053   ///
9054   /// The TemplateDeductionResult enumeration describes the result of
9055   /// template argument deduction, as returned from
9056   /// DeduceTemplateArguments(). The separate TemplateDeductionInfo
9057   /// structure provides additional information about the results of
9058   /// template argument deduction, e.g., the deduced template argument
9059   /// list (if successful) or the specific template parameters or
9060   /// deduced arguments that were involved in the failure.
9061   enum TemplateDeductionResult {
9062     /// Template argument deduction was successful.
9063     TDK_Success = 0,
9064     /// The declaration was invalid; do nothing.
9065     TDK_Invalid,
9066     /// Template argument deduction exceeded the maximum template
9067     /// instantiation depth (which has already been diagnosed).
9068     TDK_InstantiationDepth,
9069     /// Template argument deduction did not deduce a value
9070     /// for every template parameter.
9071     TDK_Incomplete,
9072     /// Template argument deduction did not deduce a value for every
9073     /// expansion of an expanded template parameter pack.
9074     TDK_IncompletePack,
9075     /// Template argument deduction produced inconsistent
9076     /// deduced values for the given template parameter.
9077     TDK_Inconsistent,
9078     /// Template argument deduction failed due to inconsistent
9079     /// cv-qualifiers on a template parameter type that would
9080     /// otherwise be deduced, e.g., we tried to deduce T in "const T"
9081     /// but were given a non-const "X".
9082     TDK_Underqualified,
9083     /// Substitution of the deduced template argument values
9084     /// resulted in an error.
9085     TDK_SubstitutionFailure,
9086     /// After substituting deduced template arguments, a dependent
9087     /// parameter type did not match the corresponding argument.
9088     TDK_DeducedMismatch,
9089     /// After substituting deduced template arguments, an element of
9090     /// a dependent parameter type did not match the corresponding element
9091     /// of the corresponding argument (when deducing from an initializer list).
9092     TDK_DeducedMismatchNested,
9093     /// A non-depnedent component of the parameter did not match the
9094     /// corresponding component of the argument.
9095     TDK_NonDeducedMismatch,
9096     /// When performing template argument deduction for a function
9097     /// template, there were too many call arguments.
9098     TDK_TooManyArguments,
9099     /// When performing template argument deduction for a function
9100     /// template, there were too few call arguments.
9101     TDK_TooFewArguments,
9102     /// The explicitly-specified template arguments were not valid
9103     /// template arguments for the given template.
9104     TDK_InvalidExplicitArguments,
9105     /// Checking non-dependent argument conversions failed.
9106     TDK_NonDependentConversionFailure,
9107     /// The deduced arguments did not satisfy the constraints associated
9108     /// with the template.
9109     TDK_ConstraintsNotSatisfied,
9110     /// Deduction failed; that's all we know.
9111     TDK_MiscellaneousDeductionFailure,
9112     /// CUDA Target attributes do not match.
9113     TDK_CUDATargetMismatch,
9114     /// Some error which was already diagnosed.
9115     TDK_AlreadyDiagnosed
9116   };
9117 
9118   TemplateDeductionResult
9119   DeduceTemplateArguments(ClassTemplatePartialSpecializationDecl *Partial,
9120                           const TemplateArgumentList &TemplateArgs,
9121                           sema::TemplateDeductionInfo &Info);
9122 
9123   TemplateDeductionResult
9124   DeduceTemplateArguments(VarTemplatePartialSpecializationDecl *Partial,
9125                           const TemplateArgumentList &TemplateArgs,
9126                           sema::TemplateDeductionInfo &Info);
9127 
9128   TemplateDeductionResult SubstituteExplicitTemplateArguments(
9129       FunctionTemplateDecl *FunctionTemplate,
9130       TemplateArgumentListInfo &ExplicitTemplateArgs,
9131       SmallVectorImpl<DeducedTemplateArgument> &Deduced,
9132       SmallVectorImpl<QualType> &ParamTypes, QualType *FunctionType,
9133       sema::TemplateDeductionInfo &Info);
9134 
9135   /// brief A function argument from which we performed template argument
9136   // deduction for a call.
9137   struct OriginalCallArg {
9138     OriginalCallArg(QualType OriginalParamType, bool DecomposedParam,
9139                     unsigned ArgIdx, QualType OriginalArgType)
9140         : OriginalParamType(OriginalParamType),
9141           DecomposedParam(DecomposedParam), ArgIdx(ArgIdx),
9142           OriginalArgType(OriginalArgType) {}
9143 
9144     QualType OriginalParamType;
9145     bool DecomposedParam;
9146     unsigned ArgIdx;
9147     QualType OriginalArgType;
9148   };
9149 
9150   TemplateDeductionResult FinishTemplateArgumentDeduction(
9151       FunctionTemplateDecl *FunctionTemplate,
9152       SmallVectorImpl<DeducedTemplateArgument> &Deduced,
9153       unsigned NumExplicitlySpecified, FunctionDecl *&Specialization,
9154       sema::TemplateDeductionInfo &Info,
9155       SmallVectorImpl<OriginalCallArg> const *OriginalCallArgs = nullptr,
9156       bool PartialOverloading = false,
9157       llvm::function_ref<bool()> CheckNonDependent = []{ return false; });
9158 
9159   TemplateDeductionResult DeduceTemplateArguments(
9160       FunctionTemplateDecl *FunctionTemplate,
9161       TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
9162       FunctionDecl *&Specialization, sema::TemplateDeductionInfo &Info,
9163       bool PartialOverloading, bool AggregateDeductionCandidate,
9164       llvm::function_ref<bool(ArrayRef<QualType>)> CheckNonDependent);
9165 
9166   TemplateDeductionResult
9167   DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
9168                           TemplateArgumentListInfo *ExplicitTemplateArgs,
9169                           QualType ArgFunctionType,
9170                           FunctionDecl *&Specialization,
9171                           sema::TemplateDeductionInfo &Info,
9172                           bool IsAddressOfFunction = false);
9173 
9174   TemplateDeductionResult
9175   DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
9176                           QualType ToType,
9177                           CXXConversionDecl *&Specialization,
9178                           sema::TemplateDeductionInfo &Info);
9179 
9180   TemplateDeductionResult
9181   DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
9182                           TemplateArgumentListInfo *ExplicitTemplateArgs,
9183                           FunctionDecl *&Specialization,
9184                           sema::TemplateDeductionInfo &Info,
9185                           bool IsAddressOfFunction = false);
9186 
9187   /// Substitute Replacement for \p auto in \p TypeWithAuto
9188   QualType SubstAutoType(QualType TypeWithAuto, QualType Replacement);
9189   /// Substitute Replacement for auto in TypeWithAuto
9190   TypeSourceInfo* SubstAutoTypeSourceInfo(TypeSourceInfo *TypeWithAuto,
9191                                           QualType Replacement);
9192 
9193   // Substitute auto in TypeWithAuto for a Dependent auto type
9194   QualType SubstAutoTypeDependent(QualType TypeWithAuto);
9195 
9196   // Substitute auto in TypeWithAuto for a Dependent auto type
9197   TypeSourceInfo *
9198   SubstAutoTypeSourceInfoDependent(TypeSourceInfo *TypeWithAuto);
9199 
9200   /// Completely replace the \c auto in \p TypeWithAuto by
9201   /// \p Replacement. This does not retain any \c auto type sugar.
9202   QualType ReplaceAutoType(QualType TypeWithAuto, QualType Replacement);
9203   TypeSourceInfo *ReplaceAutoTypeSourceInfo(TypeSourceInfo *TypeWithAuto,
9204                                             QualType Replacement);
9205 
9206   TemplateDeductionResult
9207   DeduceAutoType(TypeLoc AutoTypeLoc, Expr *Initializer, QualType &Result,
9208                  sema::TemplateDeductionInfo &Info,
9209                  bool DependentDeduction = false,
9210                  bool IgnoreConstraints = false,
9211                  TemplateSpecCandidateSet *FailedTSC = nullptr);
9212   void DiagnoseAutoDeductionFailure(VarDecl *VDecl, Expr *Init);
9213   bool DeduceReturnType(FunctionDecl *FD, SourceLocation Loc,
9214                         bool Diagnose = true);
9215 
9216   bool CheckIfFunctionSpecializationIsImmediate(FunctionDecl *FD,
9217                                                 SourceLocation Loc);
9218 
9219   /// Declare implicit deduction guides for a class template if we've
9220   /// not already done so.
9221   void DeclareImplicitDeductionGuides(TemplateDecl *Template,
9222                                       SourceLocation Loc);
9223   FunctionTemplateDecl *DeclareImplicitDeductionGuideFromInitList(
9224       TemplateDecl *Template, MutableArrayRef<QualType> ParamTypes,
9225       SourceLocation Loc);
9226   llvm::DenseMap<unsigned, CXXDeductionGuideDecl *>
9227       AggregateDeductionCandidates;
9228 
9229   QualType DeduceTemplateSpecializationFromInitializer(
9230       TypeSourceInfo *TInfo, const InitializedEntity &Entity,
9231       const InitializationKind &Kind, MultiExprArg Init,
9232       ParenListExpr *PL = nullptr);
9233 
9234   QualType deduceVarTypeFromInitializer(VarDecl *VDecl, DeclarationName Name,
9235                                         QualType Type, TypeSourceInfo *TSI,
9236                                         SourceRange Range, bool DirectInit,
9237                                         Expr *Init);
9238 
9239   TypeLoc getReturnTypeLoc(FunctionDecl *FD) const;
9240 
9241   bool DeduceFunctionTypeFromReturnExpr(FunctionDecl *FD,
9242                                         SourceLocation ReturnLoc, Expr *RetExpr,
9243                                         const AutoType *AT);
9244 
9245   FunctionTemplateDecl *getMoreSpecializedTemplate(
9246       FunctionTemplateDecl *FT1, FunctionTemplateDecl *FT2, SourceLocation Loc,
9247       TemplatePartialOrderingContext TPOC, unsigned NumCallArguments1,
9248       unsigned NumCallArguments2, bool Reversed = false);
9249   UnresolvedSetIterator
9250   getMostSpecialized(UnresolvedSetIterator SBegin, UnresolvedSetIterator SEnd,
9251                      TemplateSpecCandidateSet &FailedCandidates,
9252                      SourceLocation Loc,
9253                      const PartialDiagnostic &NoneDiag,
9254                      const PartialDiagnostic &AmbigDiag,
9255                      const PartialDiagnostic &CandidateDiag,
9256                      bool Complain = true, QualType TargetType = QualType());
9257 
9258   ClassTemplatePartialSpecializationDecl *
9259   getMoreSpecializedPartialSpecialization(
9260                                   ClassTemplatePartialSpecializationDecl *PS1,
9261                                   ClassTemplatePartialSpecializationDecl *PS2,
9262                                   SourceLocation Loc);
9263 
9264   bool isMoreSpecializedThanPrimary(ClassTemplatePartialSpecializationDecl *T,
9265                                     sema::TemplateDeductionInfo &Info);
9266 
9267   VarTemplatePartialSpecializationDecl *getMoreSpecializedPartialSpecialization(
9268       VarTemplatePartialSpecializationDecl *PS1,
9269       VarTemplatePartialSpecializationDecl *PS2, SourceLocation Loc);
9270 
9271   bool isMoreSpecializedThanPrimary(VarTemplatePartialSpecializationDecl *T,
9272                                     sema::TemplateDeductionInfo &Info);
9273 
9274   bool isTemplateTemplateParameterAtLeastAsSpecializedAs(
9275       TemplateParameterList *PParam, TemplateDecl *AArg, SourceLocation Loc);
9276 
9277   void MarkUsedTemplateParameters(const Expr *E, bool OnlyDeduced,
9278                                   unsigned Depth, llvm::SmallBitVector &Used);
9279 
9280   void MarkUsedTemplateParameters(const TemplateArgumentList &TemplateArgs,
9281                                   bool OnlyDeduced,
9282                                   unsigned Depth,
9283                                   llvm::SmallBitVector &Used);
9284   void MarkDeducedTemplateParameters(
9285                                   const FunctionTemplateDecl *FunctionTemplate,
9286                                   llvm::SmallBitVector &Deduced) {
9287     return MarkDeducedTemplateParameters(Context, FunctionTemplate, Deduced);
9288   }
9289   static void MarkDeducedTemplateParameters(ASTContext &Ctx,
9290                                   const FunctionTemplateDecl *FunctionTemplate,
9291                                   llvm::SmallBitVector &Deduced);
9292 
9293   //===--------------------------------------------------------------------===//
9294   // C++ Template Instantiation
9295   //
9296 
9297   MultiLevelTemplateArgumentList
9298   getTemplateInstantiationArgs(const NamedDecl *D, bool Final = false,
9299                                const TemplateArgumentList *Innermost = nullptr,
9300                                bool RelativeToPrimary = false,
9301                                const FunctionDecl *Pattern = nullptr,
9302                                bool ForConstraintInstantiation = false,
9303                                bool SkipForSpecialization = false);
9304 
9305   /// A context in which code is being synthesized (where a source location
9306   /// alone is not sufficient to identify the context). This covers template
9307   /// instantiation and various forms of implicitly-generated functions.
9308   struct CodeSynthesisContext {
9309     /// The kind of template instantiation we are performing
9310     enum SynthesisKind {
9311       /// We are instantiating a template declaration. The entity is
9312       /// the declaration we're instantiating (e.g., a CXXRecordDecl).
9313       TemplateInstantiation,
9314 
9315       /// We are instantiating a default argument for a template
9316       /// parameter. The Entity is the template parameter whose argument is
9317       /// being instantiated, the Template is the template, and the
9318       /// TemplateArgs/NumTemplateArguments provide the template arguments as
9319       /// specified.
9320       DefaultTemplateArgumentInstantiation,
9321 
9322       /// We are instantiating a default argument for a function.
9323       /// The Entity is the ParmVarDecl, and TemplateArgs/NumTemplateArgs
9324       /// provides the template arguments as specified.
9325       DefaultFunctionArgumentInstantiation,
9326 
9327       /// We are substituting explicit template arguments provided for
9328       /// a function template. The entity is a FunctionTemplateDecl.
9329       ExplicitTemplateArgumentSubstitution,
9330 
9331       /// We are substituting template argument determined as part of
9332       /// template argument deduction for either a class template
9333       /// partial specialization or a function template. The
9334       /// Entity is either a {Class|Var}TemplatePartialSpecializationDecl or
9335       /// a TemplateDecl.
9336       DeducedTemplateArgumentSubstitution,
9337 
9338       /// We are substituting into a lambda expression.
9339       LambdaExpressionSubstitution,
9340 
9341       /// We are substituting prior template arguments into a new
9342       /// template parameter. The template parameter itself is either a
9343       /// NonTypeTemplateParmDecl or a TemplateTemplateParmDecl.
9344       PriorTemplateArgumentSubstitution,
9345 
9346       /// We are checking the validity of a default template argument that
9347       /// has been used when naming a template-id.
9348       DefaultTemplateArgumentChecking,
9349 
9350       /// We are computing the exception specification for a defaulted special
9351       /// member function.
9352       ExceptionSpecEvaluation,
9353 
9354       /// We are instantiating the exception specification for a function
9355       /// template which was deferred until it was needed.
9356       ExceptionSpecInstantiation,
9357 
9358       /// We are instantiating a requirement of a requires expression.
9359       RequirementInstantiation,
9360 
9361       /// We are checking the satisfaction of a nested requirement of a requires
9362       /// expression.
9363       NestedRequirementConstraintsCheck,
9364 
9365       /// We are declaring an implicit special member function.
9366       DeclaringSpecialMember,
9367 
9368       /// We are declaring an implicit 'operator==' for a defaulted
9369       /// 'operator<=>'.
9370       DeclaringImplicitEqualityComparison,
9371 
9372       /// We are defining a synthesized function (such as a defaulted special
9373       /// member).
9374       DefiningSynthesizedFunction,
9375 
9376       // We are checking the constraints associated with a constrained entity or
9377       // the constraint expression of a concept. This includes the checks that
9378       // atomic constraints have the type 'bool' and that they can be constant
9379       // evaluated.
9380       ConstraintsCheck,
9381 
9382       // We are substituting template arguments into a constraint expression.
9383       ConstraintSubstitution,
9384 
9385       // We are normalizing a constraint expression.
9386       ConstraintNormalization,
9387 
9388       // Instantiating a Requires Expression parameter clause.
9389       RequirementParameterInstantiation,
9390 
9391       // We are substituting into the parameter mapping of an atomic constraint
9392       // during normalization.
9393       ParameterMappingSubstitution,
9394 
9395       /// We are rewriting a comparison operator in terms of an operator<=>.
9396       RewritingOperatorAsSpaceship,
9397 
9398       /// We are initializing a structured binding.
9399       InitializingStructuredBinding,
9400 
9401       /// We are marking a class as __dllexport.
9402       MarkingClassDllexported,
9403 
9404       /// We are building an implied call from __builtin_dump_struct. The
9405       /// arguments are in CallArgs.
9406       BuildingBuiltinDumpStructCall,
9407 
9408       /// Added for Template instantiation observation.
9409       /// Memoization means we are _not_ instantiating a template because
9410       /// it is already instantiated (but we entered a context where we
9411       /// would have had to if it was not already instantiated).
9412       Memoization,
9413 
9414       /// We are building deduction guides for a class.
9415       BuildingDeductionGuides,
9416     } Kind;
9417 
9418     /// Was the enclosing context a non-instantiation SFINAE context?
9419     bool SavedInNonInstantiationSFINAEContext;
9420 
9421     /// The point of instantiation or synthesis within the source code.
9422     SourceLocation PointOfInstantiation;
9423 
9424     /// The entity that is being synthesized.
9425     Decl *Entity;
9426 
9427     /// The template (or partial specialization) in which we are
9428     /// performing the instantiation, for substitutions of prior template
9429     /// arguments.
9430     NamedDecl *Template;
9431 
9432     union {
9433       /// The list of template arguments we are substituting, if they
9434       /// are not part of the entity.
9435       const TemplateArgument *TemplateArgs;
9436 
9437       /// The list of argument expressions in a synthesized call.
9438       const Expr *const *CallArgs;
9439     };
9440 
9441     // FIXME: Wrap this union around more members, or perhaps store the
9442     // kind-specific members in the RAII object owning the context.
9443     union {
9444       /// The number of template arguments in TemplateArgs.
9445       unsigned NumTemplateArgs;
9446 
9447       /// The number of expressions in CallArgs.
9448       unsigned NumCallArgs;
9449 
9450       /// The special member being declared or defined.
9451       CXXSpecialMember SpecialMember;
9452     };
9453 
9454     ArrayRef<TemplateArgument> template_arguments() const {
9455       assert(Kind != DeclaringSpecialMember);
9456       return {TemplateArgs, NumTemplateArgs};
9457     }
9458 
9459     /// The template deduction info object associated with the
9460     /// substitution or checking of explicit or deduced template arguments.
9461     sema::TemplateDeductionInfo *DeductionInfo;
9462 
9463     /// The source range that covers the construct that cause
9464     /// the instantiation, e.g., the template-id that causes a class
9465     /// template instantiation.
9466     SourceRange InstantiationRange;
9467 
9468     CodeSynthesisContext()
9469         : Kind(TemplateInstantiation),
9470           SavedInNonInstantiationSFINAEContext(false), Entity(nullptr),
9471           Template(nullptr), TemplateArgs(nullptr), NumTemplateArgs(0),
9472           DeductionInfo(nullptr) {}
9473 
9474     /// Determines whether this template is an actual instantiation
9475     /// that should be counted toward the maximum instantiation depth.
9476     bool isInstantiationRecord() const;
9477   };
9478 
9479   /// List of active code synthesis contexts.
9480   ///
9481   /// This vector is treated as a stack. As synthesis of one entity requires
9482   /// synthesis of another, additional contexts are pushed onto the stack.
9483   SmallVector<CodeSynthesisContext, 16> CodeSynthesisContexts;
9484 
9485   /// Specializations whose definitions are currently being instantiated.
9486   llvm::DenseSet<std::pair<Decl *, unsigned>> InstantiatingSpecializations;
9487 
9488   /// Non-dependent types used in templates that have already been instantiated
9489   /// by some template instantiation.
9490   llvm::DenseSet<QualType> InstantiatedNonDependentTypes;
9491 
9492   /// Extra modules inspected when performing a lookup during a template
9493   /// instantiation. Computed lazily.
9494   SmallVector<Module*, 16> CodeSynthesisContextLookupModules;
9495 
9496   /// Cache of additional modules that should be used for name lookup
9497   /// within the current template instantiation. Computed lazily; use
9498   /// getLookupModules() to get a complete set.
9499   llvm::DenseSet<Module*> LookupModulesCache;
9500 
9501   /// Get the set of additional modules that should be checked during
9502   /// name lookup. A module and its imports become visible when instanting a
9503   /// template defined within it.
9504   llvm::DenseSet<Module*> &getLookupModules();
9505 
9506   /// Map from the most recent declaration of a namespace to the most
9507   /// recent visible declaration of that namespace.
9508   llvm::DenseMap<NamedDecl*, NamedDecl*> VisibleNamespaceCache;
9509 
9510   /// Whether we are in a SFINAE context that is not associated with
9511   /// template instantiation.
9512   ///
9513   /// This is used when setting up a SFINAE trap (\c see SFINAETrap) outside
9514   /// of a template instantiation or template argument deduction.
9515   bool InNonInstantiationSFINAEContext;
9516 
9517   /// The number of \p CodeSynthesisContexts that are not template
9518   /// instantiations and, therefore, should not be counted as part of the
9519   /// instantiation depth.
9520   ///
9521   /// When the instantiation depth reaches the user-configurable limit
9522   /// \p LangOptions::InstantiationDepth we will abort instantiation.
9523   // FIXME: Should we have a similar limit for other forms of synthesis?
9524   unsigned NonInstantiationEntries;
9525 
9526   /// The depth of the context stack at the point when the most recent
9527   /// error or warning was produced.
9528   ///
9529   /// This value is used to suppress printing of redundant context stacks
9530   /// when there are multiple errors or warnings in the same instantiation.
9531   // FIXME: Does this belong in Sema? It's tough to implement it anywhere else.
9532   unsigned LastEmittedCodeSynthesisContextDepth = 0;
9533 
9534   /// The template instantiation callbacks to trace or track
9535   /// instantiations (objects can be chained).
9536   ///
9537   /// This callbacks is used to print, trace or track template
9538   /// instantiations as they are being constructed.
9539   std::vector<std::unique_ptr<TemplateInstantiationCallback>>
9540       TemplateInstCallbacks;
9541 
9542   /// The current index into pack expansion arguments that will be
9543   /// used for substitution of parameter packs.
9544   ///
9545   /// The pack expansion index will be -1 to indicate that parameter packs
9546   /// should be instantiated as themselves. Otherwise, the index specifies
9547   /// which argument within the parameter pack will be used for substitution.
9548   int ArgumentPackSubstitutionIndex;
9549 
9550   /// RAII object used to change the argument pack substitution index
9551   /// within a \c Sema object.
9552   ///
9553   /// See \c ArgumentPackSubstitutionIndex for more information.
9554   class ArgumentPackSubstitutionIndexRAII {
9555     Sema &Self;
9556     int OldSubstitutionIndex;
9557 
9558   public:
9559     ArgumentPackSubstitutionIndexRAII(Sema &Self, int NewSubstitutionIndex)
9560       : Self(Self), OldSubstitutionIndex(Self.ArgumentPackSubstitutionIndex) {
9561       Self.ArgumentPackSubstitutionIndex = NewSubstitutionIndex;
9562     }
9563 
9564     ~ArgumentPackSubstitutionIndexRAII() {
9565       Self.ArgumentPackSubstitutionIndex = OldSubstitutionIndex;
9566     }
9567   };
9568 
9569   friend class ArgumentPackSubstitutionRAII;
9570 
9571   /// For each declaration that involved template argument deduction, the
9572   /// set of diagnostics that were suppressed during that template argument
9573   /// deduction.
9574   ///
9575   /// FIXME: Serialize this structure to the AST file.
9576   typedef llvm::DenseMap<Decl *, SmallVector<PartialDiagnosticAt, 1> >
9577     SuppressedDiagnosticsMap;
9578   SuppressedDiagnosticsMap SuppressedDiagnostics;
9579 
9580   /// A stack object to be created when performing template
9581   /// instantiation.
9582   ///
9583   /// Construction of an object of type \c InstantiatingTemplate
9584   /// pushes the current instantiation onto the stack of active
9585   /// instantiations. If the size of this stack exceeds the maximum
9586   /// number of recursive template instantiations, construction
9587   /// produces an error and evaluates true.
9588   ///
9589   /// Destruction of this object will pop the named instantiation off
9590   /// the stack.
9591   struct InstantiatingTemplate {
9592     /// Note that we are instantiating a class template,
9593     /// function template, variable template, alias template,
9594     /// or a member thereof.
9595     InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
9596                           Decl *Entity,
9597                           SourceRange InstantiationRange = SourceRange());
9598 
9599     struct ExceptionSpecification {};
9600     /// Note that we are instantiating an exception specification
9601     /// of a function template.
9602     InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
9603                           FunctionDecl *Entity, ExceptionSpecification,
9604                           SourceRange InstantiationRange = SourceRange());
9605 
9606     /// Note that we are instantiating a default argument in a
9607     /// template-id.
9608     InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
9609                           TemplateParameter Param, TemplateDecl *Template,
9610                           ArrayRef<TemplateArgument> TemplateArgs,
9611                           SourceRange InstantiationRange = SourceRange());
9612 
9613     /// Note that we are substituting either explicitly-specified or
9614     /// deduced template arguments during function template argument deduction.
9615     InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
9616                           FunctionTemplateDecl *FunctionTemplate,
9617                           ArrayRef<TemplateArgument> TemplateArgs,
9618                           CodeSynthesisContext::SynthesisKind Kind,
9619                           sema::TemplateDeductionInfo &DeductionInfo,
9620                           SourceRange InstantiationRange = SourceRange());
9621 
9622     /// Note that we are instantiating as part of template
9623     /// argument deduction for a class template declaration.
9624     InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
9625                           TemplateDecl *Template,
9626                           ArrayRef<TemplateArgument> TemplateArgs,
9627                           sema::TemplateDeductionInfo &DeductionInfo,
9628                           SourceRange InstantiationRange = SourceRange());
9629 
9630     /// Note that we are instantiating as part of template
9631     /// argument deduction for a class template partial
9632     /// specialization.
9633     InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
9634                           ClassTemplatePartialSpecializationDecl *PartialSpec,
9635                           ArrayRef<TemplateArgument> TemplateArgs,
9636                           sema::TemplateDeductionInfo &DeductionInfo,
9637                           SourceRange InstantiationRange = SourceRange());
9638 
9639     /// Note that we are instantiating as part of template
9640     /// argument deduction for a variable template partial
9641     /// specialization.
9642     InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
9643                           VarTemplatePartialSpecializationDecl *PartialSpec,
9644                           ArrayRef<TemplateArgument> TemplateArgs,
9645                           sema::TemplateDeductionInfo &DeductionInfo,
9646                           SourceRange InstantiationRange = SourceRange());
9647 
9648     /// Note that we are instantiating a default argument for a function
9649     /// parameter.
9650     InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
9651                           ParmVarDecl *Param,
9652                           ArrayRef<TemplateArgument> TemplateArgs,
9653                           SourceRange InstantiationRange = SourceRange());
9654 
9655     /// Note that we are substituting prior template arguments into a
9656     /// non-type parameter.
9657     InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
9658                           NamedDecl *Template,
9659                           NonTypeTemplateParmDecl *Param,
9660                           ArrayRef<TemplateArgument> TemplateArgs,
9661                           SourceRange InstantiationRange);
9662 
9663     /// Note that we are substituting prior template arguments into a
9664     /// template template parameter.
9665     InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
9666                           NamedDecl *Template,
9667                           TemplateTemplateParmDecl *Param,
9668                           ArrayRef<TemplateArgument> TemplateArgs,
9669                           SourceRange InstantiationRange);
9670 
9671     /// Note that we are checking the default template argument
9672     /// against the template parameter for a given template-id.
9673     InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
9674                           TemplateDecl *Template,
9675                           NamedDecl *Param,
9676                           ArrayRef<TemplateArgument> TemplateArgs,
9677                           SourceRange InstantiationRange);
9678 
9679     struct ConstraintsCheck {};
9680     /// \brief Note that we are checking the constraints associated with some
9681     /// constrained entity (a concept declaration or a template with associated
9682     /// constraints).
9683     InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
9684                           ConstraintsCheck, NamedDecl *Template,
9685                           ArrayRef<TemplateArgument> TemplateArgs,
9686                           SourceRange InstantiationRange);
9687 
9688     struct ConstraintSubstitution {};
9689     /// \brief Note that we are checking a constraint expression associated
9690     /// with a template declaration or as part of the satisfaction check of a
9691     /// concept.
9692     InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
9693                           ConstraintSubstitution, NamedDecl *Template,
9694                           sema::TemplateDeductionInfo &DeductionInfo,
9695                           SourceRange InstantiationRange);
9696 
9697     struct ConstraintNormalization {};
9698     /// \brief Note that we are normalizing a constraint expression.
9699     InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
9700                           ConstraintNormalization, NamedDecl *Template,
9701                           SourceRange InstantiationRange);
9702 
9703     struct ParameterMappingSubstitution {};
9704     /// \brief Note that we are subtituting into the parameter mapping of an
9705     /// atomic constraint during constraint normalization.
9706     InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
9707                           ParameterMappingSubstitution, NamedDecl *Template,
9708                           SourceRange InstantiationRange);
9709 
9710     /// \brief Note that we are substituting template arguments into a part of
9711     /// a requirement of a requires expression.
9712     InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
9713                           concepts::Requirement *Req,
9714                           sema::TemplateDeductionInfo &DeductionInfo,
9715                           SourceRange InstantiationRange = SourceRange());
9716 
9717     /// \brief Note that we are checking the satisfaction of the constraint
9718     /// expression inside of a nested requirement.
9719     InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
9720                           concepts::NestedRequirement *Req, ConstraintsCheck,
9721                           SourceRange InstantiationRange = SourceRange());
9722 
9723     /// \brief Note that we are checking a requires clause.
9724     InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
9725                           const RequiresExpr *E,
9726                           sema::TemplateDeductionInfo &DeductionInfo,
9727                           SourceRange InstantiationRange);
9728 
9729     struct BuildingDeductionGuidesTag {};
9730     /// \brief Note that we are building deduction guides.
9731     InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
9732                           TemplateDecl *Entity, BuildingDeductionGuidesTag,
9733                           SourceRange InstantiationRange = SourceRange());
9734 
9735     /// Note that we have finished instantiating this template.
9736     void Clear();
9737 
9738     ~InstantiatingTemplate() { Clear(); }
9739 
9740     /// Determines whether we have exceeded the maximum
9741     /// recursive template instantiations.
9742     bool isInvalid() const { return Invalid; }
9743 
9744     /// Determine whether we are already instantiating this
9745     /// specialization in some surrounding active instantiation.
9746     bool isAlreadyInstantiating() const { return AlreadyInstantiating; }
9747 
9748   private:
9749     Sema &SemaRef;
9750     bool Invalid;
9751     bool AlreadyInstantiating;
9752     bool CheckInstantiationDepth(SourceLocation PointOfInstantiation,
9753                                  SourceRange InstantiationRange);
9754 
9755     InstantiatingTemplate(
9756         Sema &SemaRef, CodeSynthesisContext::SynthesisKind Kind,
9757         SourceLocation PointOfInstantiation, SourceRange InstantiationRange,
9758         Decl *Entity, NamedDecl *Template = nullptr,
9759         ArrayRef<TemplateArgument> TemplateArgs = std::nullopt,
9760         sema::TemplateDeductionInfo *DeductionInfo = nullptr);
9761 
9762     InstantiatingTemplate(const InstantiatingTemplate&) = delete;
9763 
9764     InstantiatingTemplate&
9765     operator=(const InstantiatingTemplate&) = delete;
9766   };
9767 
9768   void pushCodeSynthesisContext(CodeSynthesisContext Ctx);
9769   void popCodeSynthesisContext();
9770 
9771   /// Determine whether we are currently performing template instantiation.
9772   bool inTemplateInstantiation() const {
9773     return CodeSynthesisContexts.size() > NonInstantiationEntries;
9774   }
9775 
9776   void PrintContextStack() {
9777     if (!CodeSynthesisContexts.empty() &&
9778         CodeSynthesisContexts.size() != LastEmittedCodeSynthesisContextDepth) {
9779       PrintInstantiationStack();
9780       LastEmittedCodeSynthesisContextDepth = CodeSynthesisContexts.size();
9781     }
9782     if (PragmaAttributeCurrentTargetDecl)
9783       PrintPragmaAttributeInstantiationPoint();
9784   }
9785   void PrintInstantiationStack();
9786 
9787   void PrintPragmaAttributeInstantiationPoint();
9788 
9789   /// Determines whether we are currently in a context where
9790   /// template argument substitution failures are not considered
9791   /// errors.
9792   ///
9793   /// \returns An empty \c Optional if we're not in a SFINAE context.
9794   /// Otherwise, contains a pointer that, if non-NULL, contains the nearest
9795   /// template-deduction context object, which can be used to capture
9796   /// diagnostics that will be suppressed.
9797   std::optional<sema::TemplateDeductionInfo *> isSFINAEContext() const;
9798 
9799   /// Determines whether we are currently in a context that
9800   /// is not evaluated as per C++ [expr] p5.
9801   bool isUnevaluatedContext() const {
9802     assert(!ExprEvalContexts.empty() &&
9803            "Must be in an expression evaluation context");
9804     return ExprEvalContexts.back().isUnevaluated();
9805   }
9806 
9807   bool isConstantEvaluatedContext() const {
9808     assert(!ExprEvalContexts.empty() &&
9809            "Must be in an expression evaluation context");
9810     return ExprEvalContexts.back().isConstantEvaluated();
9811   }
9812 
9813   bool isImmediateFunctionContext() const {
9814     assert(!ExprEvalContexts.empty() &&
9815            "Must be in an expression evaluation context");
9816     return ExprEvalContexts.back().isImmediateFunctionContext();
9817   }
9818 
9819   bool isCheckingDefaultArgumentOrInitializer() const {
9820     assert(!ExprEvalContexts.empty() &&
9821            "Must be in an expression evaluation context");
9822     const ExpressionEvaluationContextRecord &Ctx = ExprEvalContexts.back();
9823     return (Ctx.Context ==
9824             ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed) ||
9825            Ctx.IsCurrentlyCheckingDefaultArgumentOrInitializer;
9826   }
9827 
9828   std::optional<ExpressionEvaluationContextRecord::InitializationContext>
9829   InnermostDeclarationWithDelayedImmediateInvocations() const {
9830     assert(!ExprEvalContexts.empty() &&
9831            "Must be in an expression evaluation context");
9832     for (const auto &Ctx : llvm::reverse(ExprEvalContexts)) {
9833       if (Ctx.Context == ExpressionEvaluationContext::PotentiallyEvaluated &&
9834           Ctx.DelayedDefaultInitializationContext)
9835         return Ctx.DelayedDefaultInitializationContext;
9836       if (Ctx.isConstantEvaluated() || Ctx.isImmediateFunctionContext() ||
9837           Ctx.isUnevaluated())
9838         break;
9839     }
9840     return std::nullopt;
9841   }
9842 
9843   std::optional<ExpressionEvaluationContextRecord::InitializationContext>
9844   OutermostDeclarationWithDelayedImmediateInvocations() const {
9845     assert(!ExprEvalContexts.empty() &&
9846            "Must be in an expression evaluation context");
9847     std::optional<ExpressionEvaluationContextRecord::InitializationContext> Res;
9848     for (auto &Ctx : llvm::reverse(ExprEvalContexts)) {
9849       if (Ctx.Context == ExpressionEvaluationContext::PotentiallyEvaluated &&
9850           !Ctx.DelayedDefaultInitializationContext && Res)
9851         break;
9852       if (Ctx.isConstantEvaluated() || Ctx.isImmediateFunctionContext() ||
9853           Ctx.isUnevaluated())
9854         break;
9855       Res = Ctx.DelayedDefaultInitializationContext;
9856     }
9857     return Res;
9858   }
9859 
9860   /// RAII class used to determine whether SFINAE has
9861   /// trapped any errors that occur during template argument
9862   /// deduction.
9863   class SFINAETrap {
9864     Sema &SemaRef;
9865     unsigned PrevSFINAEErrors;
9866     bool PrevInNonInstantiationSFINAEContext;
9867     bool PrevAccessCheckingSFINAE;
9868     bool PrevLastDiagnosticIgnored;
9869 
9870   public:
9871     explicit SFINAETrap(Sema &SemaRef, bool AccessCheckingSFINAE = false)
9872       : SemaRef(SemaRef), PrevSFINAEErrors(SemaRef.NumSFINAEErrors),
9873         PrevInNonInstantiationSFINAEContext(
9874                                       SemaRef.InNonInstantiationSFINAEContext),
9875         PrevAccessCheckingSFINAE(SemaRef.AccessCheckingSFINAE),
9876         PrevLastDiagnosticIgnored(
9877             SemaRef.getDiagnostics().isLastDiagnosticIgnored())
9878     {
9879       if (!SemaRef.isSFINAEContext())
9880         SemaRef.InNonInstantiationSFINAEContext = true;
9881       SemaRef.AccessCheckingSFINAE = AccessCheckingSFINAE;
9882     }
9883 
9884     ~SFINAETrap() {
9885       SemaRef.NumSFINAEErrors = PrevSFINAEErrors;
9886       SemaRef.InNonInstantiationSFINAEContext
9887         = PrevInNonInstantiationSFINAEContext;
9888       SemaRef.AccessCheckingSFINAE = PrevAccessCheckingSFINAE;
9889       SemaRef.getDiagnostics().setLastDiagnosticIgnored(
9890           PrevLastDiagnosticIgnored);
9891     }
9892 
9893     /// Determine whether any SFINAE errors have been trapped.
9894     bool hasErrorOccurred() const {
9895       return SemaRef.NumSFINAEErrors > PrevSFINAEErrors;
9896     }
9897   };
9898 
9899   /// RAII class used to indicate that we are performing provisional
9900   /// semantic analysis to determine the validity of a construct, so
9901   /// typo-correction and diagnostics in the immediate context (not within
9902   /// implicitly-instantiated templates) should be suppressed.
9903   class TentativeAnalysisScope {
9904     Sema &SemaRef;
9905     // FIXME: Using a SFINAETrap for this is a hack.
9906     SFINAETrap Trap;
9907     bool PrevDisableTypoCorrection;
9908   public:
9909     explicit TentativeAnalysisScope(Sema &SemaRef)
9910         : SemaRef(SemaRef), Trap(SemaRef, true),
9911           PrevDisableTypoCorrection(SemaRef.DisableTypoCorrection) {
9912       SemaRef.DisableTypoCorrection = true;
9913     }
9914     ~TentativeAnalysisScope() {
9915       SemaRef.DisableTypoCorrection = PrevDisableTypoCorrection;
9916     }
9917   };
9918 
9919   /// The current instantiation scope used to store local
9920   /// variables.
9921   LocalInstantiationScope *CurrentInstantiationScope;
9922 
9923   /// Tracks whether we are in a context where typo correction is
9924   /// disabled.
9925   bool DisableTypoCorrection;
9926 
9927   /// The number of typos corrected by CorrectTypo.
9928   unsigned TyposCorrected;
9929 
9930   typedef llvm::SmallSet<SourceLocation, 2> SrcLocSet;
9931   typedef llvm::DenseMap<IdentifierInfo *, SrcLocSet> IdentifierSourceLocations;
9932 
9933   /// A cache containing identifiers for which typo correction failed and
9934   /// their locations, so that repeated attempts to correct an identifier in a
9935   /// given location are ignored if typo correction already failed for it.
9936   IdentifierSourceLocations TypoCorrectionFailures;
9937 
9938   /// Worker object for performing CFG-based warnings.
9939   sema::AnalysisBasedWarnings AnalysisWarnings;
9940   threadSafety::BeforeSet *ThreadSafetyDeclCache;
9941 
9942   /// An entity for which implicit template instantiation is required.
9943   ///
9944   /// The source location associated with the declaration is the first place in
9945   /// the source code where the declaration was "used". It is not necessarily
9946   /// the point of instantiation (which will be either before or after the
9947   /// namespace-scope declaration that triggered this implicit instantiation),
9948   /// However, it is the location that diagnostics should generally refer to,
9949   /// because users will need to know what code triggered the instantiation.
9950   typedef std::pair<ValueDecl *, SourceLocation> PendingImplicitInstantiation;
9951 
9952   /// The queue of implicit template instantiations that are required
9953   /// but have not yet been performed.
9954   std::deque<PendingImplicitInstantiation> PendingInstantiations;
9955 
9956   /// Queue of implicit template instantiations that cannot be performed
9957   /// eagerly.
9958   SmallVector<PendingImplicitInstantiation, 1> LateParsedInstantiations;
9959 
9960   SmallVector<SmallVector<VTableUse, 16>, 8> SavedVTableUses;
9961   SmallVector<std::deque<PendingImplicitInstantiation>, 8>
9962       SavedPendingInstantiations;
9963 
9964   class GlobalEagerInstantiationScope {
9965   public:
9966     GlobalEagerInstantiationScope(Sema &S, bool Enabled)
9967         : S(S), Enabled(Enabled) {
9968       if (!Enabled) return;
9969 
9970       S.SavedPendingInstantiations.emplace_back();
9971       S.SavedPendingInstantiations.back().swap(S.PendingInstantiations);
9972 
9973       S.SavedVTableUses.emplace_back();
9974       S.SavedVTableUses.back().swap(S.VTableUses);
9975     }
9976 
9977     void perform() {
9978       if (Enabled) {
9979         S.DefineUsedVTables();
9980         S.PerformPendingInstantiations();
9981       }
9982     }
9983 
9984     ~GlobalEagerInstantiationScope() {
9985       if (!Enabled) return;
9986 
9987       // Restore the set of pending vtables.
9988       assert(S.VTableUses.empty() &&
9989              "VTableUses should be empty before it is discarded.");
9990       S.VTableUses.swap(S.SavedVTableUses.back());
9991       S.SavedVTableUses.pop_back();
9992 
9993       // Restore the set of pending implicit instantiations.
9994       if (S.TUKind != TU_Prefix || !S.LangOpts.PCHInstantiateTemplates) {
9995         assert(S.PendingInstantiations.empty() &&
9996                "PendingInstantiations should be empty before it is discarded.");
9997         S.PendingInstantiations.swap(S.SavedPendingInstantiations.back());
9998         S.SavedPendingInstantiations.pop_back();
9999       } else {
10000         // Template instantiations in the PCH may be delayed until the TU.
10001         S.PendingInstantiations.swap(S.SavedPendingInstantiations.back());
10002         S.PendingInstantiations.insert(
10003             S.PendingInstantiations.end(),
10004             S.SavedPendingInstantiations.back().begin(),
10005             S.SavedPendingInstantiations.back().end());
10006         S.SavedPendingInstantiations.pop_back();
10007       }
10008     }
10009 
10010   private:
10011     Sema &S;
10012     bool Enabled;
10013   };
10014 
10015   /// The queue of implicit template instantiations that are required
10016   /// and must be performed within the current local scope.
10017   ///
10018   /// This queue is only used for member functions of local classes in
10019   /// templates, which must be instantiated in the same scope as their
10020   /// enclosing function, so that they can reference function-local
10021   /// types, static variables, enumerators, etc.
10022   std::deque<PendingImplicitInstantiation> PendingLocalImplicitInstantiations;
10023 
10024   class LocalEagerInstantiationScope {
10025   public:
10026     LocalEagerInstantiationScope(Sema &S) : S(S) {
10027       SavedPendingLocalImplicitInstantiations.swap(
10028           S.PendingLocalImplicitInstantiations);
10029     }
10030 
10031     void perform() { S.PerformPendingInstantiations(/*LocalOnly=*/true); }
10032 
10033     ~LocalEagerInstantiationScope() {
10034       assert(S.PendingLocalImplicitInstantiations.empty() &&
10035              "there shouldn't be any pending local implicit instantiations");
10036       SavedPendingLocalImplicitInstantiations.swap(
10037           S.PendingLocalImplicitInstantiations);
10038     }
10039 
10040   private:
10041     Sema &S;
10042     std::deque<PendingImplicitInstantiation>
10043         SavedPendingLocalImplicitInstantiations;
10044   };
10045 
10046   /// A helper class for building up ExtParameterInfos.
10047   class ExtParameterInfoBuilder {
10048     SmallVector<FunctionProtoType::ExtParameterInfo, 16> Infos;
10049     bool HasInteresting = false;
10050 
10051   public:
10052     /// Set the ExtParameterInfo for the parameter at the given index,
10053     ///
10054     void set(unsigned index, FunctionProtoType::ExtParameterInfo info) {
10055       assert(Infos.size() <= index);
10056       Infos.resize(index);
10057       Infos.push_back(info);
10058 
10059       if (!HasInteresting)
10060         HasInteresting = (info != FunctionProtoType::ExtParameterInfo());
10061     }
10062 
10063     /// Return a pointer (suitable for setting in an ExtProtoInfo) to the
10064     /// ExtParameterInfo array we've built up.
10065     const FunctionProtoType::ExtParameterInfo *
10066     getPointerOrNull(unsigned numParams) {
10067       if (!HasInteresting) return nullptr;
10068       Infos.resize(numParams);
10069       return Infos.data();
10070     }
10071   };
10072 
10073   void PerformPendingInstantiations(bool LocalOnly = false);
10074 
10075   TypeSourceInfo *SubstType(TypeSourceInfo *T,
10076                             const MultiLevelTemplateArgumentList &TemplateArgs,
10077                             SourceLocation Loc, DeclarationName Entity,
10078                             bool AllowDeducedTST = false);
10079 
10080   QualType SubstType(QualType T,
10081                      const MultiLevelTemplateArgumentList &TemplateArgs,
10082                      SourceLocation Loc, DeclarationName Entity);
10083 
10084   TypeSourceInfo *SubstType(TypeLoc TL,
10085                             const MultiLevelTemplateArgumentList &TemplateArgs,
10086                             SourceLocation Loc, DeclarationName Entity);
10087 
10088   TypeSourceInfo *SubstFunctionDeclType(
10089       TypeSourceInfo *T, const MultiLevelTemplateArgumentList &TemplateArgs,
10090       SourceLocation Loc, DeclarationName Entity, CXXRecordDecl *ThisContext,
10091       Qualifiers ThisTypeQuals, bool EvaluateConstraints = true);
10092   void SubstExceptionSpec(FunctionDecl *New, const FunctionProtoType *Proto,
10093                           const MultiLevelTemplateArgumentList &Args);
10094   bool SubstExceptionSpec(SourceLocation Loc,
10095                           FunctionProtoType::ExceptionSpecInfo &ESI,
10096                           SmallVectorImpl<QualType> &ExceptionStorage,
10097                           const MultiLevelTemplateArgumentList &Args);
10098   ParmVarDecl *
10099   SubstParmVarDecl(ParmVarDecl *D,
10100                    const MultiLevelTemplateArgumentList &TemplateArgs,
10101                    int indexAdjustment, std::optional<unsigned> NumExpansions,
10102                    bool ExpectParameterPack, bool EvaluateConstraints = true);
10103   bool SubstParmTypes(SourceLocation Loc, ArrayRef<ParmVarDecl *> Params,
10104                       const FunctionProtoType::ExtParameterInfo *ExtParamInfos,
10105                       const MultiLevelTemplateArgumentList &TemplateArgs,
10106                       SmallVectorImpl<QualType> &ParamTypes,
10107                       SmallVectorImpl<ParmVarDecl *> *OutParams,
10108                       ExtParameterInfoBuilder &ParamInfos);
10109   bool SubstDefaultArgument(SourceLocation Loc, ParmVarDecl *Param,
10110                             const MultiLevelTemplateArgumentList &TemplateArgs,
10111                             bool ForCallExpr = false);
10112   ExprResult SubstExpr(Expr *E,
10113                        const MultiLevelTemplateArgumentList &TemplateArgs);
10114 
10115   // A RAII type used by the TemplateDeclInstantiator and TemplateInstantiator
10116   // to disable constraint evaluation, then restore the state.
10117   template <typename InstTy> struct ConstraintEvalRAII {
10118     InstTy &TI;
10119     bool OldValue;
10120 
10121     ConstraintEvalRAII(InstTy &TI)
10122         : TI(TI), OldValue(TI.getEvaluateConstraints()) {
10123       TI.setEvaluateConstraints(false);
10124     }
10125     ~ConstraintEvalRAII() { TI.setEvaluateConstraints(OldValue); }
10126   };
10127 
10128   // Unlike the above, this evaluates constraints, which should only happen at
10129   // 'constraint checking' time.
10130   ExprResult
10131   SubstConstraintExpr(Expr *E,
10132                       const MultiLevelTemplateArgumentList &TemplateArgs);
10133 
10134   /// Substitute the given template arguments into a list of
10135   /// expressions, expanding pack expansions if required.
10136   ///
10137   /// \param Exprs The list of expressions to substitute into.
10138   ///
10139   /// \param IsCall Whether this is some form of call, in which case
10140   /// default arguments will be dropped.
10141   ///
10142   /// \param TemplateArgs The set of template arguments to substitute.
10143   ///
10144   /// \param Outputs Will receive all of the substituted arguments.
10145   ///
10146   /// \returns true if an error occurred, false otherwise.
10147   bool SubstExprs(ArrayRef<Expr *> Exprs, bool IsCall,
10148                   const MultiLevelTemplateArgumentList &TemplateArgs,
10149                   SmallVectorImpl<Expr *> &Outputs);
10150 
10151   StmtResult SubstStmt(Stmt *S,
10152                        const MultiLevelTemplateArgumentList &TemplateArgs);
10153 
10154   TemplateParameterList *
10155   SubstTemplateParams(TemplateParameterList *Params, DeclContext *Owner,
10156                       const MultiLevelTemplateArgumentList &TemplateArgs,
10157                       bool EvaluateConstraints = true);
10158 
10159   bool
10160   SubstTemplateArguments(ArrayRef<TemplateArgumentLoc> Args,
10161                          const MultiLevelTemplateArgumentList &TemplateArgs,
10162                          TemplateArgumentListInfo &Outputs);
10163 
10164   Decl *SubstDecl(Decl *D, DeclContext *Owner,
10165                   const MultiLevelTemplateArgumentList &TemplateArgs);
10166 
10167   /// Substitute the name and return type of a defaulted 'operator<=>' to form
10168   /// an implicit 'operator=='.
10169   FunctionDecl *SubstSpaceshipAsEqualEqual(CXXRecordDecl *RD,
10170                                            FunctionDecl *Spaceship);
10171 
10172   ExprResult SubstInitializer(Expr *E,
10173                        const MultiLevelTemplateArgumentList &TemplateArgs,
10174                        bool CXXDirectInit);
10175 
10176   bool
10177   SubstBaseSpecifiers(CXXRecordDecl *Instantiation,
10178                       CXXRecordDecl *Pattern,
10179                       const MultiLevelTemplateArgumentList &TemplateArgs);
10180 
10181   bool
10182   InstantiateClass(SourceLocation PointOfInstantiation,
10183                    CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern,
10184                    const MultiLevelTemplateArgumentList &TemplateArgs,
10185                    TemplateSpecializationKind TSK,
10186                    bool Complain = true);
10187 
10188   bool InstantiateEnum(SourceLocation PointOfInstantiation,
10189                        EnumDecl *Instantiation, EnumDecl *Pattern,
10190                        const MultiLevelTemplateArgumentList &TemplateArgs,
10191                        TemplateSpecializationKind TSK);
10192 
10193   bool InstantiateInClassInitializer(
10194       SourceLocation PointOfInstantiation, FieldDecl *Instantiation,
10195       FieldDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs);
10196 
10197   struct LateInstantiatedAttribute {
10198     const Attr *TmplAttr;
10199     LocalInstantiationScope *Scope;
10200     Decl *NewDecl;
10201 
10202     LateInstantiatedAttribute(const Attr *A, LocalInstantiationScope *S,
10203                               Decl *D)
10204       : TmplAttr(A), Scope(S), NewDecl(D)
10205     { }
10206   };
10207   typedef SmallVector<LateInstantiatedAttribute, 16> LateInstantiatedAttrVec;
10208 
10209   void InstantiateAttrs(const MultiLevelTemplateArgumentList &TemplateArgs,
10210                         const Decl *Pattern, Decl *Inst,
10211                         LateInstantiatedAttrVec *LateAttrs = nullptr,
10212                         LocalInstantiationScope *OuterMostScope = nullptr);
10213   void updateAttrsForLateParsedTemplate(const Decl *Pattern, Decl *Inst);
10214 
10215   void
10216   InstantiateAttrsForDecl(const MultiLevelTemplateArgumentList &TemplateArgs,
10217                           const Decl *Pattern, Decl *Inst,
10218                           LateInstantiatedAttrVec *LateAttrs = nullptr,
10219                           LocalInstantiationScope *OuterMostScope = nullptr);
10220 
10221   void InstantiateDefaultCtorDefaultArgs(CXXConstructorDecl *Ctor);
10222 
10223   bool usesPartialOrExplicitSpecialization(
10224       SourceLocation Loc, ClassTemplateSpecializationDecl *ClassTemplateSpec);
10225 
10226   bool
10227   InstantiateClassTemplateSpecialization(SourceLocation PointOfInstantiation,
10228                            ClassTemplateSpecializationDecl *ClassTemplateSpec,
10229                            TemplateSpecializationKind TSK,
10230                            bool Complain = true);
10231 
10232   void InstantiateClassMembers(SourceLocation PointOfInstantiation,
10233                                CXXRecordDecl *Instantiation,
10234                             const MultiLevelTemplateArgumentList &TemplateArgs,
10235                                TemplateSpecializationKind TSK);
10236 
10237   void InstantiateClassTemplateSpecializationMembers(
10238                                           SourceLocation PointOfInstantiation,
10239                            ClassTemplateSpecializationDecl *ClassTemplateSpec,
10240                                                 TemplateSpecializationKind TSK);
10241 
10242   NestedNameSpecifierLoc
10243   SubstNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS,
10244                            const MultiLevelTemplateArgumentList &TemplateArgs);
10245 
10246   DeclarationNameInfo
10247   SubstDeclarationNameInfo(const DeclarationNameInfo &NameInfo,
10248                            const MultiLevelTemplateArgumentList &TemplateArgs);
10249   TemplateName
10250   SubstTemplateName(NestedNameSpecifierLoc QualifierLoc, TemplateName Name,
10251                     SourceLocation Loc,
10252                     const MultiLevelTemplateArgumentList &TemplateArgs);
10253 
10254   bool SubstTypeConstraint(TemplateTypeParmDecl *Inst, const TypeConstraint *TC,
10255                            const MultiLevelTemplateArgumentList &TemplateArgs,
10256                            bool EvaluateConstraint);
10257 
10258   bool InstantiateDefaultArgument(SourceLocation CallLoc, FunctionDecl *FD,
10259                                   ParmVarDecl *Param);
10260   void InstantiateExceptionSpec(SourceLocation PointOfInstantiation,
10261                                 FunctionDecl *Function);
10262   bool CheckInstantiatedFunctionTemplateConstraints(
10263       SourceLocation PointOfInstantiation, FunctionDecl *Decl,
10264       ArrayRef<TemplateArgument> TemplateArgs,
10265       ConstraintSatisfaction &Satisfaction);
10266   FunctionDecl *InstantiateFunctionDeclaration(FunctionTemplateDecl *FTD,
10267                                                const TemplateArgumentList *Args,
10268                                                SourceLocation Loc);
10269   void InstantiateFunctionDefinition(SourceLocation PointOfInstantiation,
10270                                      FunctionDecl *Function,
10271                                      bool Recursive = false,
10272                                      bool DefinitionRequired = false,
10273                                      bool AtEndOfTU = false);
10274   VarTemplateSpecializationDecl *BuildVarTemplateInstantiation(
10275       VarTemplateDecl *VarTemplate, VarDecl *FromVar,
10276       const TemplateArgumentList &TemplateArgList,
10277       const TemplateArgumentListInfo &TemplateArgsInfo,
10278       SmallVectorImpl<TemplateArgument> &Converted,
10279       SourceLocation PointOfInstantiation,
10280       LateInstantiatedAttrVec *LateAttrs = nullptr,
10281       LocalInstantiationScope *StartingScope = nullptr);
10282   VarTemplateSpecializationDecl *CompleteVarTemplateSpecializationDecl(
10283       VarTemplateSpecializationDecl *VarSpec, VarDecl *PatternDecl,
10284       const MultiLevelTemplateArgumentList &TemplateArgs);
10285   void
10286   BuildVariableInstantiation(VarDecl *NewVar, VarDecl *OldVar,
10287                              const MultiLevelTemplateArgumentList &TemplateArgs,
10288                              LateInstantiatedAttrVec *LateAttrs,
10289                              DeclContext *Owner,
10290                              LocalInstantiationScope *StartingScope,
10291                              bool InstantiatingVarTemplate = false,
10292                              VarTemplateSpecializationDecl *PrevVTSD = nullptr);
10293 
10294   void InstantiateVariableInitializer(
10295       VarDecl *Var, VarDecl *OldVar,
10296       const MultiLevelTemplateArgumentList &TemplateArgs);
10297   void InstantiateVariableDefinition(SourceLocation PointOfInstantiation,
10298                                      VarDecl *Var, bool Recursive = false,
10299                                      bool DefinitionRequired = false,
10300                                      bool AtEndOfTU = false);
10301 
10302   void InstantiateMemInitializers(CXXConstructorDecl *New,
10303                                   const CXXConstructorDecl *Tmpl,
10304                             const MultiLevelTemplateArgumentList &TemplateArgs);
10305 
10306   NamedDecl *FindInstantiatedDecl(SourceLocation Loc, NamedDecl *D,
10307                           const MultiLevelTemplateArgumentList &TemplateArgs,
10308                           bool FindingInstantiatedContext = false);
10309   DeclContext *FindInstantiatedContext(SourceLocation Loc, DeclContext *DC,
10310                           const MultiLevelTemplateArgumentList &TemplateArgs);
10311 
10312   // Objective-C declarations.
10313   enum ObjCContainerKind {
10314     OCK_None = -1,
10315     OCK_Interface = 0,
10316     OCK_Protocol,
10317     OCK_Category,
10318     OCK_ClassExtension,
10319     OCK_Implementation,
10320     OCK_CategoryImplementation
10321   };
10322   ObjCContainerKind getObjCContainerKind() const;
10323 
10324   DeclResult actOnObjCTypeParam(Scope *S,
10325                                 ObjCTypeParamVariance variance,
10326                                 SourceLocation varianceLoc,
10327                                 unsigned index,
10328                                 IdentifierInfo *paramName,
10329                                 SourceLocation paramLoc,
10330                                 SourceLocation colonLoc,
10331                                 ParsedType typeBound);
10332 
10333   ObjCTypeParamList *actOnObjCTypeParamList(Scope *S, SourceLocation lAngleLoc,
10334                                             ArrayRef<Decl *> typeParams,
10335                                             SourceLocation rAngleLoc);
10336   void popObjCTypeParamList(Scope *S, ObjCTypeParamList *typeParamList);
10337 
10338   ObjCInterfaceDecl *ActOnStartClassInterface(
10339       Scope *S, SourceLocation AtInterfaceLoc, IdentifierInfo *ClassName,
10340       SourceLocation ClassLoc, ObjCTypeParamList *typeParamList,
10341       IdentifierInfo *SuperName, SourceLocation SuperLoc,
10342       ArrayRef<ParsedType> SuperTypeArgs, SourceRange SuperTypeArgsRange,
10343       Decl *const *ProtoRefs, unsigned NumProtoRefs,
10344       const SourceLocation *ProtoLocs, SourceLocation EndProtoLoc,
10345       const ParsedAttributesView &AttrList, SkipBodyInfo *SkipBody);
10346 
10347   void ActOnSuperClassOfClassInterface(Scope *S,
10348                                        SourceLocation AtInterfaceLoc,
10349                                        ObjCInterfaceDecl *IDecl,
10350                                        IdentifierInfo *ClassName,
10351                                        SourceLocation ClassLoc,
10352                                        IdentifierInfo *SuperName,
10353                                        SourceLocation SuperLoc,
10354                                        ArrayRef<ParsedType> SuperTypeArgs,
10355                                        SourceRange SuperTypeArgsRange);
10356 
10357   void ActOnTypedefedProtocols(SmallVectorImpl<Decl *> &ProtocolRefs,
10358                                SmallVectorImpl<SourceLocation> &ProtocolLocs,
10359                                IdentifierInfo *SuperName,
10360                                SourceLocation SuperLoc);
10361 
10362   Decl *ActOnCompatibilityAlias(
10363                     SourceLocation AtCompatibilityAliasLoc,
10364                     IdentifierInfo *AliasName,  SourceLocation AliasLocation,
10365                     IdentifierInfo *ClassName, SourceLocation ClassLocation);
10366 
10367   bool CheckForwardProtocolDeclarationForCircularDependency(
10368     IdentifierInfo *PName,
10369     SourceLocation &PLoc, SourceLocation PrevLoc,
10370     const ObjCList<ObjCProtocolDecl> &PList);
10371 
10372   ObjCProtocolDecl *ActOnStartProtocolInterface(
10373       SourceLocation AtProtoInterfaceLoc, IdentifierInfo *ProtocolName,
10374       SourceLocation ProtocolLoc, Decl *const *ProtoRefNames,
10375       unsigned NumProtoRefs, const SourceLocation *ProtoLocs,
10376       SourceLocation EndProtoLoc, const ParsedAttributesView &AttrList,
10377       SkipBodyInfo *SkipBody);
10378 
10379   ObjCCategoryDecl *ActOnStartCategoryInterface(
10380       SourceLocation AtInterfaceLoc, IdentifierInfo *ClassName,
10381       SourceLocation ClassLoc, ObjCTypeParamList *typeParamList,
10382       IdentifierInfo *CategoryName, SourceLocation CategoryLoc,
10383       Decl *const *ProtoRefs, unsigned NumProtoRefs,
10384       const SourceLocation *ProtoLocs, SourceLocation EndProtoLoc,
10385       const ParsedAttributesView &AttrList);
10386 
10387   ObjCImplementationDecl *ActOnStartClassImplementation(
10388       SourceLocation AtClassImplLoc, IdentifierInfo *ClassName,
10389       SourceLocation ClassLoc, IdentifierInfo *SuperClassname,
10390       SourceLocation SuperClassLoc, const ParsedAttributesView &AttrList);
10391 
10392   ObjCCategoryImplDecl *ActOnStartCategoryImplementation(
10393       SourceLocation AtCatImplLoc, IdentifierInfo *ClassName,
10394       SourceLocation ClassLoc, IdentifierInfo *CatName, SourceLocation CatLoc,
10395       const ParsedAttributesView &AttrList);
10396 
10397   DeclGroupPtrTy ActOnFinishObjCImplementation(Decl *ObjCImpDecl,
10398                                                ArrayRef<Decl *> Decls);
10399 
10400   DeclGroupPtrTy ActOnForwardClassDeclaration(SourceLocation Loc,
10401                    IdentifierInfo **IdentList,
10402                    SourceLocation *IdentLocs,
10403                    ArrayRef<ObjCTypeParamList *> TypeParamLists,
10404                    unsigned NumElts);
10405 
10406   DeclGroupPtrTy
10407   ActOnForwardProtocolDeclaration(SourceLocation AtProtoclLoc,
10408                                   ArrayRef<IdentifierLocPair> IdentList,
10409                                   const ParsedAttributesView &attrList);
10410 
10411   void FindProtocolDeclaration(bool WarnOnDeclarations, bool ForObjCContainer,
10412                                ArrayRef<IdentifierLocPair> ProtocolId,
10413                                SmallVectorImpl<Decl *> &Protocols);
10414 
10415   void DiagnoseTypeArgsAndProtocols(IdentifierInfo *ProtocolId,
10416                                     SourceLocation ProtocolLoc,
10417                                     IdentifierInfo *TypeArgId,
10418                                     SourceLocation TypeArgLoc,
10419                                     bool SelectProtocolFirst = false);
10420 
10421   /// Given a list of identifiers (and their locations), resolve the
10422   /// names to either Objective-C protocol qualifiers or type
10423   /// arguments, as appropriate.
10424   void actOnObjCTypeArgsOrProtocolQualifiers(
10425          Scope *S,
10426          ParsedType baseType,
10427          SourceLocation lAngleLoc,
10428          ArrayRef<IdentifierInfo *> identifiers,
10429          ArrayRef<SourceLocation> identifierLocs,
10430          SourceLocation rAngleLoc,
10431          SourceLocation &typeArgsLAngleLoc,
10432          SmallVectorImpl<ParsedType> &typeArgs,
10433          SourceLocation &typeArgsRAngleLoc,
10434          SourceLocation &protocolLAngleLoc,
10435          SmallVectorImpl<Decl *> &protocols,
10436          SourceLocation &protocolRAngleLoc,
10437          bool warnOnIncompleteProtocols);
10438 
10439   /// Build a an Objective-C protocol-qualified 'id' type where no
10440   /// base type was specified.
10441   TypeResult actOnObjCProtocolQualifierType(
10442                SourceLocation lAngleLoc,
10443                ArrayRef<Decl *> protocols,
10444                ArrayRef<SourceLocation> protocolLocs,
10445                SourceLocation rAngleLoc);
10446 
10447   /// Build a specialized and/or protocol-qualified Objective-C type.
10448   TypeResult actOnObjCTypeArgsAndProtocolQualifiers(
10449                Scope *S,
10450                SourceLocation Loc,
10451                ParsedType BaseType,
10452                SourceLocation TypeArgsLAngleLoc,
10453                ArrayRef<ParsedType> TypeArgs,
10454                SourceLocation TypeArgsRAngleLoc,
10455                SourceLocation ProtocolLAngleLoc,
10456                ArrayRef<Decl *> Protocols,
10457                ArrayRef<SourceLocation> ProtocolLocs,
10458                SourceLocation ProtocolRAngleLoc);
10459 
10460   /// Build an Objective-C type parameter type.
10461   QualType BuildObjCTypeParamType(const ObjCTypeParamDecl *Decl,
10462                                   SourceLocation ProtocolLAngleLoc,
10463                                   ArrayRef<ObjCProtocolDecl *> Protocols,
10464                                   ArrayRef<SourceLocation> ProtocolLocs,
10465                                   SourceLocation ProtocolRAngleLoc,
10466                                   bool FailOnError = false);
10467 
10468   /// Build an Objective-C object pointer type.
10469   QualType BuildObjCObjectType(
10470       QualType BaseType, SourceLocation Loc, SourceLocation TypeArgsLAngleLoc,
10471       ArrayRef<TypeSourceInfo *> TypeArgs, SourceLocation TypeArgsRAngleLoc,
10472       SourceLocation ProtocolLAngleLoc, ArrayRef<ObjCProtocolDecl *> Protocols,
10473       ArrayRef<SourceLocation> ProtocolLocs, SourceLocation ProtocolRAngleLoc,
10474       bool FailOnError, bool Rebuilding);
10475 
10476   /// Ensure attributes are consistent with type.
10477   /// \param [in, out] Attributes The attributes to check; they will
10478   /// be modified to be consistent with \p PropertyTy.
10479   void CheckObjCPropertyAttributes(Decl *PropertyPtrTy,
10480                                    SourceLocation Loc,
10481                                    unsigned &Attributes,
10482                                    bool propertyInPrimaryClass);
10483 
10484   /// Process the specified property declaration and create decls for the
10485   /// setters and getters as needed.
10486   /// \param property The property declaration being processed
10487   void ProcessPropertyDecl(ObjCPropertyDecl *property);
10488 
10489 
10490   void DiagnosePropertyMismatch(ObjCPropertyDecl *Property,
10491                                 ObjCPropertyDecl *SuperProperty,
10492                                 const IdentifierInfo *Name,
10493                                 bool OverridingProtocolProperty);
10494 
10495   void DiagnoseClassExtensionDupMethods(ObjCCategoryDecl *CAT,
10496                                         ObjCInterfaceDecl *ID);
10497 
10498   Decl *ActOnAtEnd(Scope *S, SourceRange AtEnd,
10499                    ArrayRef<Decl *> allMethods = std::nullopt,
10500                    ArrayRef<DeclGroupPtrTy> allTUVars = std::nullopt);
10501 
10502   Decl *ActOnProperty(Scope *S, SourceLocation AtLoc,
10503                       SourceLocation LParenLoc,
10504                       FieldDeclarator &FD, ObjCDeclSpec &ODS,
10505                       Selector GetterSel, Selector SetterSel,
10506                       tok::ObjCKeywordKind MethodImplKind,
10507                       DeclContext *lexicalDC = nullptr);
10508 
10509   Decl *ActOnPropertyImplDecl(Scope *S,
10510                               SourceLocation AtLoc,
10511                               SourceLocation PropertyLoc,
10512                               bool ImplKind,
10513                               IdentifierInfo *PropertyId,
10514                               IdentifierInfo *PropertyIvar,
10515                               SourceLocation PropertyIvarLoc,
10516                               ObjCPropertyQueryKind QueryKind);
10517 
10518   enum ObjCSpecialMethodKind {
10519     OSMK_None,
10520     OSMK_Alloc,
10521     OSMK_New,
10522     OSMK_Copy,
10523     OSMK_RetainingInit,
10524     OSMK_NonRetainingInit
10525   };
10526 
10527   struct ObjCArgInfo {
10528     IdentifierInfo *Name;
10529     SourceLocation NameLoc;
10530     // The Type is null if no type was specified, and the DeclSpec is invalid
10531     // in this case.
10532     ParsedType Type;
10533     ObjCDeclSpec DeclSpec;
10534 
10535     /// ArgAttrs - Attribute list for this argument.
10536     ParsedAttributesView ArgAttrs;
10537   };
10538 
10539   Decl *ActOnMethodDeclaration(
10540       Scope *S,
10541       SourceLocation BeginLoc, // location of the + or -.
10542       SourceLocation EndLoc,   // location of the ; or {.
10543       tok::TokenKind MethodType, ObjCDeclSpec &ReturnQT, ParsedType ReturnType,
10544       ArrayRef<SourceLocation> SelectorLocs, Selector Sel,
10545       // optional arguments. The number of types/arguments is obtained
10546       // from the Sel.getNumArgs().
10547       ObjCArgInfo *ArgInfo, DeclaratorChunk::ParamInfo *CParamInfo,
10548       unsigned CNumArgs, // c-style args
10549       const ParsedAttributesView &AttrList, tok::ObjCKeywordKind MethodImplKind,
10550       bool isVariadic, bool MethodDefinition);
10551 
10552   ObjCMethodDecl *LookupMethodInQualifiedType(Selector Sel,
10553                                               const ObjCObjectPointerType *OPT,
10554                                               bool IsInstance);
10555   ObjCMethodDecl *LookupMethodInObjectType(Selector Sel, QualType Ty,
10556                                            bool IsInstance);
10557 
10558   bool CheckARCMethodDecl(ObjCMethodDecl *method);
10559   bool inferObjCARCLifetime(ValueDecl *decl);
10560 
10561   void deduceOpenCLAddressSpace(ValueDecl *decl);
10562 
10563   ExprResult
10564   HandleExprPropertyRefExpr(const ObjCObjectPointerType *OPT,
10565                             Expr *BaseExpr,
10566                             SourceLocation OpLoc,
10567                             DeclarationName MemberName,
10568                             SourceLocation MemberLoc,
10569                             SourceLocation SuperLoc, QualType SuperType,
10570                             bool Super);
10571 
10572   ExprResult
10573   ActOnClassPropertyRefExpr(IdentifierInfo &receiverName,
10574                             IdentifierInfo &propertyName,
10575                             SourceLocation receiverNameLoc,
10576                             SourceLocation propertyNameLoc);
10577 
10578   ObjCMethodDecl *tryCaptureObjCSelf(SourceLocation Loc);
10579 
10580   /// Describes the kind of message expression indicated by a message
10581   /// send that starts with an identifier.
10582   enum ObjCMessageKind {
10583     /// The message is sent to 'super'.
10584     ObjCSuperMessage,
10585     /// The message is an instance message.
10586     ObjCInstanceMessage,
10587     /// The message is a class message, and the identifier is a type
10588     /// name.
10589     ObjCClassMessage
10590   };
10591 
10592   ObjCMessageKind getObjCMessageKind(Scope *S,
10593                                      IdentifierInfo *Name,
10594                                      SourceLocation NameLoc,
10595                                      bool IsSuper,
10596                                      bool HasTrailingDot,
10597                                      ParsedType &ReceiverType);
10598 
10599   ExprResult ActOnSuperMessage(Scope *S, SourceLocation SuperLoc,
10600                                Selector Sel,
10601                                SourceLocation LBracLoc,
10602                                ArrayRef<SourceLocation> SelectorLocs,
10603                                SourceLocation RBracLoc,
10604                                MultiExprArg Args);
10605 
10606   ExprResult BuildClassMessage(TypeSourceInfo *ReceiverTypeInfo,
10607                                QualType ReceiverType,
10608                                SourceLocation SuperLoc,
10609                                Selector Sel,
10610                                ObjCMethodDecl *Method,
10611                                SourceLocation LBracLoc,
10612                                ArrayRef<SourceLocation> SelectorLocs,
10613                                SourceLocation RBracLoc,
10614                                MultiExprArg Args,
10615                                bool isImplicit = false);
10616 
10617   ExprResult BuildClassMessageImplicit(QualType ReceiverType,
10618                                        bool isSuperReceiver,
10619                                        SourceLocation Loc,
10620                                        Selector Sel,
10621                                        ObjCMethodDecl *Method,
10622                                        MultiExprArg Args);
10623 
10624   ExprResult ActOnClassMessage(Scope *S,
10625                                ParsedType Receiver,
10626                                Selector Sel,
10627                                SourceLocation LBracLoc,
10628                                ArrayRef<SourceLocation> SelectorLocs,
10629                                SourceLocation RBracLoc,
10630                                MultiExprArg Args);
10631 
10632   ExprResult BuildInstanceMessage(Expr *Receiver,
10633                                   QualType ReceiverType,
10634                                   SourceLocation SuperLoc,
10635                                   Selector Sel,
10636                                   ObjCMethodDecl *Method,
10637                                   SourceLocation LBracLoc,
10638                                   ArrayRef<SourceLocation> SelectorLocs,
10639                                   SourceLocation RBracLoc,
10640                                   MultiExprArg Args,
10641                                   bool isImplicit = false);
10642 
10643   ExprResult BuildInstanceMessageImplicit(Expr *Receiver,
10644                                           QualType ReceiverType,
10645                                           SourceLocation Loc,
10646                                           Selector Sel,
10647                                           ObjCMethodDecl *Method,
10648                                           MultiExprArg Args);
10649 
10650   ExprResult ActOnInstanceMessage(Scope *S,
10651                                   Expr *Receiver,
10652                                   Selector Sel,
10653                                   SourceLocation LBracLoc,
10654                                   ArrayRef<SourceLocation> SelectorLocs,
10655                                   SourceLocation RBracLoc,
10656                                   MultiExprArg Args);
10657 
10658   ExprResult BuildObjCBridgedCast(SourceLocation LParenLoc,
10659                                   ObjCBridgeCastKind Kind,
10660                                   SourceLocation BridgeKeywordLoc,
10661                                   TypeSourceInfo *TSInfo,
10662                                   Expr *SubExpr);
10663 
10664   ExprResult ActOnObjCBridgedCast(Scope *S,
10665                                   SourceLocation LParenLoc,
10666                                   ObjCBridgeCastKind Kind,
10667                                   SourceLocation BridgeKeywordLoc,
10668                                   ParsedType Type,
10669                                   SourceLocation RParenLoc,
10670                                   Expr *SubExpr);
10671 
10672   void CheckTollFreeBridgeCast(QualType castType, Expr *castExpr);
10673 
10674   void CheckObjCBridgeRelatedCast(QualType castType, Expr *castExpr);
10675 
10676   bool CheckTollFreeBridgeStaticCast(QualType castType, Expr *castExpr,
10677                                      CastKind &Kind);
10678 
10679   bool checkObjCBridgeRelatedComponents(SourceLocation Loc,
10680                                         QualType DestType, QualType SrcType,
10681                                         ObjCInterfaceDecl *&RelatedClass,
10682                                         ObjCMethodDecl *&ClassMethod,
10683                                         ObjCMethodDecl *&InstanceMethod,
10684                                         TypedefNameDecl *&TDNDecl,
10685                                         bool CfToNs, bool Diagnose = true);
10686 
10687   bool CheckObjCBridgeRelatedConversions(SourceLocation Loc,
10688                                          QualType DestType, QualType SrcType,
10689                                          Expr *&SrcExpr, bool Diagnose = true);
10690 
10691   bool CheckConversionToObjCLiteral(QualType DstType, Expr *&SrcExpr,
10692                                     bool Diagnose = true);
10693 
10694   bool checkInitMethod(ObjCMethodDecl *method, QualType receiverTypeIfCall);
10695 
10696   /// Check whether the given new method is a valid override of the
10697   /// given overridden method, and set any properties that should be inherited.
10698   void CheckObjCMethodOverride(ObjCMethodDecl *NewMethod,
10699                                const ObjCMethodDecl *Overridden);
10700 
10701   /// Describes the compatibility of a result type with its method.
10702   enum ResultTypeCompatibilityKind {
10703     RTC_Compatible,
10704     RTC_Incompatible,
10705     RTC_Unknown
10706   };
10707 
10708   void CheckObjCMethodDirectOverrides(ObjCMethodDecl *method,
10709                                       ObjCMethodDecl *overridden);
10710 
10711   void CheckObjCMethodOverrides(ObjCMethodDecl *ObjCMethod,
10712                                 ObjCInterfaceDecl *CurrentClass,
10713                                 ResultTypeCompatibilityKind RTC);
10714 
10715   enum PragmaOptionsAlignKind {
10716     POAK_Native,  // #pragma options align=native
10717     POAK_Natural, // #pragma options align=natural
10718     POAK_Packed,  // #pragma options align=packed
10719     POAK_Power,   // #pragma options align=power
10720     POAK_Mac68k,  // #pragma options align=mac68k
10721     POAK_Reset    // #pragma options align=reset
10722   };
10723 
10724   /// ActOnPragmaClangSection - Called on well formed \#pragma clang section
10725   void ActOnPragmaClangSection(SourceLocation PragmaLoc,
10726                                PragmaClangSectionAction Action,
10727                                PragmaClangSectionKind SecKind, StringRef SecName);
10728 
10729   /// ActOnPragmaOptionsAlign - Called on well formed \#pragma options align.
10730   void ActOnPragmaOptionsAlign(PragmaOptionsAlignKind Kind,
10731                                SourceLocation PragmaLoc);
10732 
10733   /// ActOnPragmaPack - Called on well formed \#pragma pack(...).
10734   void ActOnPragmaPack(SourceLocation PragmaLoc, PragmaMsStackAction Action,
10735                        StringRef SlotLabel, Expr *Alignment);
10736 
10737   enum class PragmaAlignPackDiagnoseKind {
10738     NonDefaultStateAtInclude,
10739     ChangedStateAtExit
10740   };
10741 
10742   void DiagnoseNonDefaultPragmaAlignPack(PragmaAlignPackDiagnoseKind Kind,
10743                                          SourceLocation IncludeLoc);
10744   void DiagnoseUnterminatedPragmaAlignPack();
10745 
10746   /// ActOnPragmaMSStrictGuardStackCheck - Called on well formed \#pragma
10747   /// strict_gs_check.
10748   void ActOnPragmaMSStrictGuardStackCheck(SourceLocation PragmaLocation,
10749                                           PragmaMsStackAction Action,
10750                                           bool Value);
10751 
10752   /// ActOnPragmaMSStruct - Called on well formed \#pragma ms_struct [on|off].
10753   void ActOnPragmaMSStruct(PragmaMSStructKind Kind);
10754 
10755   /// ActOnPragmaMSComment - Called on well formed
10756   /// \#pragma comment(kind, "arg").
10757   void ActOnPragmaMSComment(SourceLocation CommentLoc, PragmaMSCommentKind Kind,
10758                             StringRef Arg);
10759 
10760   /// ActOnPragmaMSPointersToMembers - called on well formed \#pragma
10761   /// pointers_to_members(representation method[, general purpose
10762   /// representation]).
10763   void ActOnPragmaMSPointersToMembers(
10764       LangOptions::PragmaMSPointersToMembersKind Kind,
10765       SourceLocation PragmaLoc);
10766 
10767   /// Called on well formed \#pragma vtordisp().
10768   void ActOnPragmaMSVtorDisp(PragmaMsStackAction Action,
10769                              SourceLocation PragmaLoc,
10770                              MSVtorDispMode Value);
10771 
10772   enum PragmaSectionKind {
10773     PSK_DataSeg,
10774     PSK_BSSSeg,
10775     PSK_ConstSeg,
10776     PSK_CodeSeg,
10777   };
10778 
10779   bool UnifySection(StringRef SectionName, int SectionFlags,
10780                     NamedDecl *TheDecl);
10781   bool UnifySection(StringRef SectionName,
10782                     int SectionFlags,
10783                     SourceLocation PragmaSectionLocation);
10784 
10785   /// Called on well formed \#pragma bss_seg/data_seg/const_seg/code_seg.
10786   void ActOnPragmaMSSeg(SourceLocation PragmaLocation,
10787                         PragmaMsStackAction Action,
10788                         llvm::StringRef StackSlotLabel,
10789                         StringLiteral *SegmentName,
10790                         llvm::StringRef PragmaName);
10791 
10792   /// Called on well formed \#pragma section().
10793   void ActOnPragmaMSSection(SourceLocation PragmaLocation,
10794                             int SectionFlags, StringLiteral *SegmentName);
10795 
10796   /// Called on well-formed \#pragma init_seg().
10797   void ActOnPragmaMSInitSeg(SourceLocation PragmaLocation,
10798                             StringLiteral *SegmentName);
10799 
10800   /// Called on well-formed \#pragma alloc_text().
10801   void ActOnPragmaMSAllocText(
10802       SourceLocation PragmaLocation, StringRef Section,
10803       const SmallVector<std::tuple<IdentifierInfo *, SourceLocation>>
10804           &Functions);
10805 
10806   /// Called on #pragma clang __debug dump II
10807   void ActOnPragmaDump(Scope *S, SourceLocation Loc, IdentifierInfo *II);
10808 
10809   /// Called on #pragma clang __debug dump E
10810   void ActOnPragmaDump(Expr *E);
10811 
10812   /// ActOnPragmaDetectMismatch - Call on well-formed \#pragma detect_mismatch
10813   void ActOnPragmaDetectMismatch(SourceLocation Loc, StringRef Name,
10814                                  StringRef Value);
10815 
10816   /// Are precise floating point semantics currently enabled?
10817   bool isPreciseFPEnabled() {
10818     return !CurFPFeatures.getAllowFPReassociate() &&
10819            !CurFPFeatures.getNoSignedZero() &&
10820            !CurFPFeatures.getAllowReciprocal() &&
10821            !CurFPFeatures.getAllowApproxFunc();
10822   }
10823 
10824   void ActOnPragmaFPEvalMethod(SourceLocation Loc,
10825                                LangOptions::FPEvalMethodKind Value);
10826 
10827   /// ActOnPragmaFloatControl - Call on well-formed \#pragma float_control
10828   void ActOnPragmaFloatControl(SourceLocation Loc, PragmaMsStackAction Action,
10829                                PragmaFloatControlKind Value);
10830 
10831   /// ActOnPragmaUnused - Called on well-formed '\#pragma unused'.
10832   void ActOnPragmaUnused(const Token &Identifier,
10833                          Scope *curScope,
10834                          SourceLocation PragmaLoc);
10835 
10836   /// ActOnPragmaVisibility - Called on well formed \#pragma GCC visibility... .
10837   void ActOnPragmaVisibility(const IdentifierInfo* VisType,
10838                              SourceLocation PragmaLoc);
10839 
10840   NamedDecl *DeclClonePragmaWeak(NamedDecl *ND, const IdentifierInfo *II,
10841                                  SourceLocation Loc);
10842   void DeclApplyPragmaWeak(Scope *S, NamedDecl *ND, const WeakInfo &W);
10843 
10844   /// ActOnPragmaWeakID - Called on well formed \#pragma weak ident.
10845   void ActOnPragmaWeakID(IdentifierInfo* WeakName,
10846                          SourceLocation PragmaLoc,
10847                          SourceLocation WeakNameLoc);
10848 
10849   /// ActOnPragmaRedefineExtname - Called on well formed
10850   /// \#pragma redefine_extname oldname newname.
10851   void ActOnPragmaRedefineExtname(IdentifierInfo* WeakName,
10852                                   IdentifierInfo* AliasName,
10853                                   SourceLocation PragmaLoc,
10854                                   SourceLocation WeakNameLoc,
10855                                   SourceLocation AliasNameLoc);
10856 
10857   /// ActOnPragmaWeakAlias - Called on well formed \#pragma weak ident = ident.
10858   void ActOnPragmaWeakAlias(IdentifierInfo* WeakName,
10859                             IdentifierInfo* AliasName,
10860                             SourceLocation PragmaLoc,
10861                             SourceLocation WeakNameLoc,
10862                             SourceLocation AliasNameLoc);
10863 
10864   /// ActOnPragmaFPContract - Called on well formed
10865   /// \#pragma {STDC,OPENCL} FP_CONTRACT and
10866   /// \#pragma clang fp contract
10867   void ActOnPragmaFPContract(SourceLocation Loc, LangOptions::FPModeKind FPC);
10868 
10869   /// Called on well formed
10870   /// \#pragma clang fp reassociate
10871   void ActOnPragmaFPReassociate(SourceLocation Loc, bool IsEnabled);
10872 
10873   /// ActOnPragmaFenvAccess - Called on well formed
10874   /// \#pragma STDC FENV_ACCESS
10875   void ActOnPragmaFEnvAccess(SourceLocation Loc, bool IsEnabled);
10876 
10877   /// Called on well formed '\#pragma clang fp' that has option 'exceptions'.
10878   void ActOnPragmaFPExceptions(SourceLocation Loc,
10879                                LangOptions::FPExceptionModeKind);
10880 
10881   /// Called to set constant rounding mode for floating point operations.
10882   void ActOnPragmaFEnvRound(SourceLocation Loc, llvm::RoundingMode);
10883 
10884   /// Called to set exception behavior for floating point operations.
10885   void setExceptionMode(SourceLocation Loc, LangOptions::FPExceptionModeKind);
10886 
10887   /// AddAlignmentAttributesForRecord - Adds any needed alignment attributes to
10888   /// a the record decl, to handle '\#pragma pack' and '\#pragma options align'.
10889   void AddAlignmentAttributesForRecord(RecordDecl *RD);
10890 
10891   /// AddMsStructLayoutForRecord - Adds ms_struct layout attribute to record.
10892   void AddMsStructLayoutForRecord(RecordDecl *RD);
10893 
10894   /// PushNamespaceVisibilityAttr - Note that we've entered a
10895   /// namespace with a visibility attribute.
10896   void PushNamespaceVisibilityAttr(const VisibilityAttr *Attr,
10897                                    SourceLocation Loc);
10898 
10899   /// AddPushedVisibilityAttribute - If '\#pragma GCC visibility' was used,
10900   /// add an appropriate visibility attribute.
10901   void AddPushedVisibilityAttribute(Decl *RD);
10902 
10903   /// PopPragmaVisibility - Pop the top element of the visibility stack; used
10904   /// for '\#pragma GCC visibility' and visibility attributes on namespaces.
10905   void PopPragmaVisibility(bool IsNamespaceEnd, SourceLocation EndLoc);
10906 
10907   /// FreeVisContext - Deallocate and null out VisContext.
10908   void FreeVisContext();
10909 
10910   /// AddCFAuditedAttribute - Check whether we're currently within
10911   /// '\#pragma clang arc_cf_code_audited' and, if so, consider adding
10912   /// the appropriate attribute.
10913   void AddCFAuditedAttribute(Decl *D);
10914 
10915   void ActOnPragmaAttributeAttribute(ParsedAttr &Attribute,
10916                                      SourceLocation PragmaLoc,
10917                                      attr::ParsedSubjectMatchRuleSet Rules);
10918   void ActOnPragmaAttributeEmptyPush(SourceLocation PragmaLoc,
10919                                      const IdentifierInfo *Namespace);
10920 
10921   /// Called on well-formed '\#pragma clang attribute pop'.
10922   void ActOnPragmaAttributePop(SourceLocation PragmaLoc,
10923                                const IdentifierInfo *Namespace);
10924 
10925   /// Adds the attributes that have been specified using the
10926   /// '\#pragma clang attribute push' directives to the given declaration.
10927   void AddPragmaAttributes(Scope *S, Decl *D);
10928 
10929   void DiagnoseUnterminatedPragmaAttribute();
10930 
10931   /// Called on well formed \#pragma clang optimize.
10932   void ActOnPragmaOptimize(bool On, SourceLocation PragmaLoc);
10933 
10934   /// #pragma optimize("[optimization-list]", on | off).
10935   void ActOnPragmaMSOptimize(SourceLocation Loc, bool IsOn);
10936 
10937   /// Call on well formed \#pragma function.
10938   void
10939   ActOnPragmaMSFunction(SourceLocation Loc,
10940                         const llvm::SmallVectorImpl<StringRef> &NoBuiltins);
10941 
10942   /// Get the location for the currently active "\#pragma clang optimize
10943   /// off". If this location is invalid, then the state of the pragma is "on".
10944   SourceLocation getOptimizeOffPragmaLocation() const {
10945     return OptimizeOffPragmaLocation;
10946   }
10947 
10948   /// Only called on function definitions; if there is a pragma in scope
10949   /// with the effect of a range-based optnone, consider marking the function
10950   /// with attribute optnone.
10951   void AddRangeBasedOptnone(FunctionDecl *FD);
10952 
10953   /// Only called on function definitions; if there is a `#pragma alloc_text`
10954   /// that decides which code section the function should be in, add
10955   /// attribute section to the function.
10956   void AddSectionMSAllocText(FunctionDecl *FD);
10957 
10958   /// Adds the 'optnone' attribute to the function declaration if there
10959   /// are no conflicts; Loc represents the location causing the 'optnone'
10960   /// attribute to be added (usually because of a pragma).
10961   void AddOptnoneAttributeIfNoConflicts(FunctionDecl *FD, SourceLocation Loc);
10962 
10963   /// Only called on function definitions; if there is a MSVC #pragma optimize
10964   /// in scope, consider changing the function's attributes based on the
10965   /// optimization list passed to the pragma.
10966   void ModifyFnAttributesMSPragmaOptimize(FunctionDecl *FD);
10967 
10968   /// Only called on function definitions; if there is a pragma in scope
10969   /// with the effect of a range-based no_builtin, consider marking the function
10970   /// with attribute no_builtin.
10971   void AddImplicitMSFunctionNoBuiltinAttr(FunctionDecl *FD);
10972 
10973   /// AddAlignedAttr - Adds an aligned attribute to a particular declaration.
10974   void AddAlignedAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E,
10975                       bool IsPackExpansion);
10976   void AddAlignedAttr(Decl *D, const AttributeCommonInfo &CI, TypeSourceInfo *T,
10977                       bool IsPackExpansion);
10978 
10979   /// AddAssumeAlignedAttr - Adds an assume_aligned attribute to a particular
10980   /// declaration.
10981   void AddAssumeAlignedAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E,
10982                             Expr *OE);
10983 
10984   /// AddAllocAlignAttr - Adds an alloc_align attribute to a particular
10985   /// declaration.
10986   void AddAllocAlignAttr(Decl *D, const AttributeCommonInfo &CI,
10987                          Expr *ParamExpr);
10988 
10989   /// AddAlignValueAttr - Adds an align_value attribute to a particular
10990   /// declaration.
10991   void AddAlignValueAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E);
10992 
10993   /// AddAnnotationAttr - Adds an annotation Annot with Args arguments to D.
10994   void AddAnnotationAttr(Decl *D, const AttributeCommonInfo &CI,
10995                          StringRef Annot, MutableArrayRef<Expr *> Args);
10996 
10997   /// ConstantFoldAttrArgs - Folds attribute arguments into ConstantExprs
10998   /// (unless they are value dependent or type dependent). Returns false
10999   /// and emits a diagnostic if one or more of the arguments could not be
11000   /// folded into a constant.
11001   bool ConstantFoldAttrArgs(const AttributeCommonInfo &CI,
11002                             MutableArrayRef<Expr *> Args);
11003 
11004   /// AddLaunchBoundsAttr - Adds a launch_bounds attribute to a particular
11005   /// declaration.
11006   void AddLaunchBoundsAttr(Decl *D, const AttributeCommonInfo &CI,
11007                            Expr *MaxThreads, Expr *MinBlocks);
11008 
11009   /// AddModeAttr - Adds a mode attribute to a particular declaration.
11010   void AddModeAttr(Decl *D, const AttributeCommonInfo &CI, IdentifierInfo *Name,
11011                    bool InInstantiation = false);
11012 
11013   void AddParameterABIAttr(Decl *D, const AttributeCommonInfo &CI,
11014                            ParameterABI ABI);
11015 
11016   enum class RetainOwnershipKind {NS, CF, OS};
11017   void AddXConsumedAttr(Decl *D, const AttributeCommonInfo &CI,
11018                         RetainOwnershipKind K, bool IsTemplateInstantiation);
11019 
11020   /// addAMDGPUFlatWorkGroupSizeAttr - Adds an amdgpu_flat_work_group_size
11021   /// attribute to a particular declaration.
11022   void addAMDGPUFlatWorkGroupSizeAttr(Decl *D, const AttributeCommonInfo &CI,
11023                                       Expr *Min, Expr *Max);
11024 
11025   /// addAMDGPUWavePersEUAttr - Adds an amdgpu_waves_per_eu attribute to a
11026   /// particular declaration.
11027   void addAMDGPUWavesPerEUAttr(Decl *D, const AttributeCommonInfo &CI,
11028                                Expr *Min, Expr *Max);
11029 
11030   bool checkNSReturnsRetainedReturnType(SourceLocation loc, QualType type);
11031 
11032   //===--------------------------------------------------------------------===//
11033   // C++ Coroutines
11034   //
11035   bool ActOnCoroutineBodyStart(Scope *S, SourceLocation KwLoc,
11036                                StringRef Keyword);
11037   ExprResult ActOnCoawaitExpr(Scope *S, SourceLocation KwLoc, Expr *E);
11038   ExprResult ActOnCoyieldExpr(Scope *S, SourceLocation KwLoc, Expr *E);
11039   StmtResult ActOnCoreturnStmt(Scope *S, SourceLocation KwLoc, Expr *E);
11040 
11041   ExprResult BuildOperatorCoawaitLookupExpr(Scope *S, SourceLocation Loc);
11042   ExprResult BuildOperatorCoawaitCall(SourceLocation Loc, Expr *E,
11043                                       UnresolvedLookupExpr *Lookup);
11044   ExprResult BuildResolvedCoawaitExpr(SourceLocation KwLoc, Expr *Operand,
11045                                       Expr *Awaiter, bool IsImplicit = false);
11046   ExprResult BuildUnresolvedCoawaitExpr(SourceLocation KwLoc, Expr *Operand,
11047                                         UnresolvedLookupExpr *Lookup);
11048   ExprResult BuildCoyieldExpr(SourceLocation KwLoc, Expr *E);
11049   StmtResult BuildCoreturnStmt(SourceLocation KwLoc, Expr *E,
11050                                bool IsImplicit = false);
11051   StmtResult BuildCoroutineBodyStmt(CoroutineBodyStmt::CtorArgs);
11052   bool buildCoroutineParameterMoves(SourceLocation Loc);
11053   VarDecl *buildCoroutinePromise(SourceLocation Loc);
11054   void CheckCompletedCoroutineBody(FunctionDecl *FD, Stmt *&Body);
11055   /// Lookup 'coroutine_traits' in std namespace and std::experimental
11056   /// namespace. The namespace found is recorded in Namespace.
11057   ClassTemplateDecl *lookupCoroutineTraits(SourceLocation KwLoc,
11058                                            SourceLocation FuncLoc);
11059   /// Check that the expression co_await promise.final_suspend() shall not be
11060   /// potentially-throwing.
11061   bool checkFinalSuspendNoThrow(const Stmt *FinalSuspend);
11062 
11063   //===--------------------------------------------------------------------===//
11064   // OpenMP directives and clauses.
11065   //
11066 private:
11067   void *VarDataSharingAttributesStack;
11068 
11069   struct DeclareTargetContextInfo {
11070     struct MapInfo {
11071       OMPDeclareTargetDeclAttr::MapTypeTy MT;
11072       SourceLocation Loc;
11073     };
11074     /// Explicitly listed variables and functions in a 'to' or 'link' clause.
11075     llvm::DenseMap<NamedDecl *, MapInfo> ExplicitlyMapped;
11076 
11077     /// The 'device_type' as parsed from the clause.
11078     OMPDeclareTargetDeclAttr::DevTypeTy DT = OMPDeclareTargetDeclAttr::DT_Any;
11079 
11080     /// The directive kind, `begin declare target` or `declare target`.
11081     OpenMPDirectiveKind Kind;
11082 
11083     /// The directive with indirect clause.
11084     std::optional<Expr *> Indirect;
11085 
11086     /// The directive location.
11087     SourceLocation Loc;
11088 
11089     DeclareTargetContextInfo(OpenMPDirectiveKind Kind, SourceLocation Loc)
11090         : Kind(Kind), Loc(Loc) {}
11091   };
11092 
11093   /// Number of nested '#pragma omp declare target' directives.
11094   SmallVector<DeclareTargetContextInfo, 4> DeclareTargetNesting;
11095 
11096   /// Initialization of data-sharing attributes stack.
11097   void InitDataSharingAttributesStack();
11098   void DestroyDataSharingAttributesStack();
11099 
11100   /// Returns OpenMP nesting level for current directive.
11101   unsigned getOpenMPNestingLevel() const;
11102 
11103   /// Adjusts the function scopes index for the target-based regions.
11104   void adjustOpenMPTargetScopeIndex(unsigned &FunctionScopesIndex,
11105                                     unsigned Level) const;
11106 
11107   /// Returns the number of scopes associated with the construct on the given
11108   /// OpenMP level.
11109   int getNumberOfConstructScopes(unsigned Level) const;
11110 
11111   /// Push new OpenMP function region for non-capturing function.
11112   void pushOpenMPFunctionRegion();
11113 
11114   /// Pop OpenMP function region for non-capturing function.
11115   void popOpenMPFunctionRegion(const sema::FunctionScopeInfo *OldFSI);
11116 
11117   /// Analyzes and checks a loop nest for use by a loop transformation.
11118   ///
11119   /// \param Kind          The loop transformation directive kind.
11120   /// \param NumLoops      How many nested loops the directive is expecting.
11121   /// \param AStmt         Associated statement of the transformation directive.
11122   /// \param LoopHelpers   [out] The loop analysis result.
11123   /// \param Body          [out] The body code nested in \p NumLoops loop.
11124   /// \param OriginalInits [out] Collection of statements and declarations that
11125   ///                      must have been executed/declared before entering the
11126   ///                      loop.
11127   ///
11128   /// \return Whether there was any error.
11129   bool checkTransformableLoopNest(
11130       OpenMPDirectiveKind Kind, Stmt *AStmt, int NumLoops,
11131       SmallVectorImpl<OMPLoopBasedDirective::HelperExprs> &LoopHelpers,
11132       Stmt *&Body,
11133       SmallVectorImpl<SmallVector<llvm::PointerUnion<Stmt *, Decl *>, 0>>
11134           &OriginalInits);
11135 
11136   /// Helper to keep information about the current `omp begin/end declare
11137   /// variant` nesting.
11138   struct OMPDeclareVariantScope {
11139     /// The associated OpenMP context selector.
11140     OMPTraitInfo *TI;
11141 
11142     /// The associated OpenMP context selector mangling.
11143     std::string NameSuffix;
11144 
11145     OMPDeclareVariantScope(OMPTraitInfo &TI);
11146   };
11147 
11148   /// Return the OMPTraitInfo for the surrounding scope, if any.
11149   OMPTraitInfo *getOMPTraitInfoForSurroundingScope() {
11150     return OMPDeclareVariantScopes.empty() ? nullptr
11151                                            : OMPDeclareVariantScopes.back().TI;
11152   }
11153 
11154   /// The current `omp begin/end declare variant` scopes.
11155   SmallVector<OMPDeclareVariantScope, 4> OMPDeclareVariantScopes;
11156 
11157   /// The current `omp begin/end assumes` scopes.
11158   SmallVector<AssumptionAttr *, 4> OMPAssumeScoped;
11159 
11160   /// All `omp assumes` we encountered so far.
11161   SmallVector<AssumptionAttr *, 4> OMPAssumeGlobal;
11162 
11163 public:
11164   /// The declarator \p D defines a function in the scope \p S which is nested
11165   /// in an `omp begin/end declare variant` scope. In this method we create a
11166   /// declaration for \p D and rename \p D according to the OpenMP context
11167   /// selector of the surrounding scope. Return all base functions in \p Bases.
11168   void ActOnStartOfFunctionDefinitionInOpenMPDeclareVariantScope(
11169       Scope *S, Declarator &D, MultiTemplateParamsArg TemplateParameterLists,
11170       SmallVectorImpl<FunctionDecl *> &Bases);
11171 
11172   /// Register \p D as specialization of all base functions in \p Bases in the
11173   /// current `omp begin/end declare variant` scope.
11174   void ActOnFinishedFunctionDefinitionInOpenMPDeclareVariantScope(
11175       Decl *D, SmallVectorImpl<FunctionDecl *> &Bases);
11176 
11177   /// Act on \p D, a function definition inside of an `omp [begin/end] assumes`.
11178   void ActOnFinishedFunctionDefinitionInOpenMPAssumeScope(Decl *D);
11179 
11180   /// Can we exit an OpenMP declare variant scope at the moment.
11181   bool isInOpenMPDeclareVariantScope() const {
11182     return !OMPDeclareVariantScopes.empty();
11183   }
11184 
11185   ExprResult
11186   VerifyPositiveIntegerConstantInClause(Expr *Op, OpenMPClauseKind CKind,
11187                                         bool StrictlyPositive = true,
11188                                         bool SuppressExprDiags = false);
11189 
11190   /// Given the potential call expression \p Call, determine if there is a
11191   /// specialization via the OpenMP declare variant mechanism available. If
11192   /// there is, return the specialized call expression, otherwise return the
11193   /// original \p Call.
11194   ExprResult ActOnOpenMPCall(ExprResult Call, Scope *Scope,
11195                              SourceLocation LParenLoc, MultiExprArg ArgExprs,
11196                              SourceLocation RParenLoc, Expr *ExecConfig);
11197 
11198   /// Handle a `omp begin declare variant`.
11199   void ActOnOpenMPBeginDeclareVariant(SourceLocation Loc, OMPTraitInfo &TI);
11200 
11201   /// Handle a `omp end declare variant`.
11202   void ActOnOpenMPEndDeclareVariant();
11203 
11204   /// Checks if the variant/multiversion functions are compatible.
11205   bool areMultiversionVariantFunctionsCompatible(
11206       const FunctionDecl *OldFD, const FunctionDecl *NewFD,
11207       const PartialDiagnostic &NoProtoDiagID,
11208       const PartialDiagnosticAt &NoteCausedDiagIDAt,
11209       const PartialDiagnosticAt &NoSupportDiagIDAt,
11210       const PartialDiagnosticAt &DiffDiagIDAt, bool TemplatesSupported,
11211       bool ConstexprSupported, bool CLinkageMayDiffer);
11212 
11213   /// Function tries to capture lambda's captured variables in the OpenMP region
11214   /// before the original lambda is captured.
11215   void tryCaptureOpenMPLambdas(ValueDecl *V);
11216 
11217   /// Return true if the provided declaration \a VD should be captured by
11218   /// reference.
11219   /// \param Level Relative level of nested OpenMP construct for that the check
11220   /// is performed.
11221   /// \param OpenMPCaptureLevel Capture level within an OpenMP construct.
11222   bool isOpenMPCapturedByRef(const ValueDecl *D, unsigned Level,
11223                              unsigned OpenMPCaptureLevel) const;
11224 
11225   /// Check if the specified variable is used in one of the private
11226   /// clauses (private, firstprivate, lastprivate, reduction etc.) in OpenMP
11227   /// constructs.
11228   VarDecl *isOpenMPCapturedDecl(ValueDecl *D, bool CheckScopeInfo = false,
11229                                 unsigned StopAt = 0);
11230 
11231   /// The member expression(this->fd) needs to be rebuilt in the template
11232   /// instantiation to generate private copy for OpenMP when default
11233   /// clause is used. The function will return true if default
11234   /// cluse is used.
11235   bool isOpenMPRebuildMemberExpr(ValueDecl *D);
11236 
11237   ExprResult getOpenMPCapturedExpr(VarDecl *Capture, ExprValueKind VK,
11238                                    ExprObjectKind OK, SourceLocation Loc);
11239 
11240   /// If the current region is a loop-based region, mark the start of the loop
11241   /// construct.
11242   void startOpenMPLoop();
11243 
11244   /// If the current region is a range loop-based region, mark the start of the
11245   /// loop construct.
11246   void startOpenMPCXXRangeFor();
11247 
11248   /// Check if the specified variable is used in 'private' clause.
11249   /// \param Level Relative level of nested OpenMP construct for that the check
11250   /// is performed.
11251   OpenMPClauseKind isOpenMPPrivateDecl(ValueDecl *D, unsigned Level,
11252                                        unsigned CapLevel) const;
11253 
11254   /// Sets OpenMP capture kind (OMPC_private, OMPC_firstprivate, OMPC_map etc.)
11255   /// for \p FD based on DSA for the provided corresponding captured declaration
11256   /// \p D.
11257   void setOpenMPCaptureKind(FieldDecl *FD, const ValueDecl *D, unsigned Level);
11258 
11259   /// Check if the specified variable is captured  by 'target' directive.
11260   /// \param Level Relative level of nested OpenMP construct for that the check
11261   /// is performed.
11262   bool isOpenMPTargetCapturedDecl(const ValueDecl *D, unsigned Level,
11263                                   unsigned CaptureLevel) const;
11264 
11265   /// Check if the specified global variable must be captured  by outer capture
11266   /// regions.
11267   /// \param Level Relative level of nested OpenMP construct for that
11268   /// the check is performed.
11269   bool isOpenMPGlobalCapturedDecl(ValueDecl *D, unsigned Level,
11270                                   unsigned CaptureLevel) const;
11271 
11272   ExprResult PerformOpenMPImplicitIntegerConversion(SourceLocation OpLoc,
11273                                                     Expr *Op);
11274   /// Called on start of new data sharing attribute block.
11275   void StartOpenMPDSABlock(OpenMPDirectiveKind K,
11276                            const DeclarationNameInfo &DirName, Scope *CurScope,
11277                            SourceLocation Loc);
11278   /// Start analysis of clauses.
11279   void StartOpenMPClause(OpenMPClauseKind K);
11280   /// End analysis of clauses.
11281   void EndOpenMPClause();
11282   /// Called on end of data sharing attribute block.
11283   void EndOpenMPDSABlock(Stmt *CurDirective);
11284 
11285   /// Check if the current region is an OpenMP loop region and if it is,
11286   /// mark loop control variable, used in \p Init for loop initialization, as
11287   /// private by default.
11288   /// \param Init First part of the for loop.
11289   void ActOnOpenMPLoopInitialization(SourceLocation ForLoc, Stmt *Init);
11290 
11291   /// Called on well-formed '\#pragma omp metadirective' after parsing
11292   /// of the  associated statement.
11293   StmtResult ActOnOpenMPMetaDirective(ArrayRef<OMPClause *> Clauses,
11294                                       Stmt *AStmt, SourceLocation StartLoc,
11295                                       SourceLocation EndLoc);
11296 
11297   // OpenMP directives and clauses.
11298   /// Called on correct id-expression from the '#pragma omp
11299   /// threadprivate'.
11300   ExprResult ActOnOpenMPIdExpression(Scope *CurScope, CXXScopeSpec &ScopeSpec,
11301                                      const DeclarationNameInfo &Id,
11302                                      OpenMPDirectiveKind Kind);
11303   /// Called on well-formed '#pragma omp threadprivate'.
11304   DeclGroupPtrTy ActOnOpenMPThreadprivateDirective(
11305                                      SourceLocation Loc,
11306                                      ArrayRef<Expr *> VarList);
11307   /// Builds a new OpenMPThreadPrivateDecl and checks its correctness.
11308   OMPThreadPrivateDecl *CheckOMPThreadPrivateDecl(SourceLocation Loc,
11309                                                   ArrayRef<Expr *> VarList);
11310   /// Called on well-formed '#pragma omp allocate'.
11311   DeclGroupPtrTy ActOnOpenMPAllocateDirective(SourceLocation Loc,
11312                                               ArrayRef<Expr *> VarList,
11313                                               ArrayRef<OMPClause *> Clauses,
11314                                               DeclContext *Owner = nullptr);
11315 
11316   /// Called on well-formed '#pragma omp [begin] assume[s]'.
11317   void ActOnOpenMPAssumesDirective(SourceLocation Loc,
11318                                    OpenMPDirectiveKind DKind,
11319                                    ArrayRef<std::string> Assumptions,
11320                                    bool SkippedClauses);
11321 
11322   /// Check if there is an active global `omp begin assumes` directive.
11323   bool isInOpenMPAssumeScope() const { return !OMPAssumeScoped.empty(); }
11324 
11325   /// Check if there is an active global `omp assumes` directive.
11326   bool hasGlobalOpenMPAssumes() const { return !OMPAssumeGlobal.empty(); }
11327 
11328   /// Called on well-formed '#pragma omp end assumes'.
11329   void ActOnOpenMPEndAssumesDirective();
11330 
11331   /// Called on well-formed '#pragma omp requires'.
11332   DeclGroupPtrTy ActOnOpenMPRequiresDirective(SourceLocation Loc,
11333                                               ArrayRef<OMPClause *> ClauseList);
11334   /// Check restrictions on Requires directive
11335   OMPRequiresDecl *CheckOMPRequiresDecl(SourceLocation Loc,
11336                                         ArrayRef<OMPClause *> Clauses);
11337   /// Check if the specified type is allowed to be used in 'omp declare
11338   /// reduction' construct.
11339   QualType ActOnOpenMPDeclareReductionType(SourceLocation TyLoc,
11340                                            TypeResult ParsedType);
11341   /// Called on start of '#pragma omp declare reduction'.
11342   DeclGroupPtrTy ActOnOpenMPDeclareReductionDirectiveStart(
11343       Scope *S, DeclContext *DC, DeclarationName Name,
11344       ArrayRef<std::pair<QualType, SourceLocation>> ReductionTypes,
11345       AccessSpecifier AS, Decl *PrevDeclInScope = nullptr);
11346   /// Initialize declare reduction construct initializer.
11347   void ActOnOpenMPDeclareReductionCombinerStart(Scope *S, Decl *D);
11348   /// Finish current declare reduction construct initializer.
11349   void ActOnOpenMPDeclareReductionCombinerEnd(Decl *D, Expr *Combiner);
11350   /// Initialize declare reduction construct initializer.
11351   /// \return omp_priv variable.
11352   VarDecl *ActOnOpenMPDeclareReductionInitializerStart(Scope *S, Decl *D);
11353   /// Finish current declare reduction construct initializer.
11354   void ActOnOpenMPDeclareReductionInitializerEnd(Decl *D, Expr *Initializer,
11355                                                  VarDecl *OmpPrivParm);
11356   /// Called at the end of '#pragma omp declare reduction'.
11357   DeclGroupPtrTy ActOnOpenMPDeclareReductionDirectiveEnd(
11358       Scope *S, DeclGroupPtrTy DeclReductions, bool IsValid);
11359 
11360   /// Check variable declaration in 'omp declare mapper' construct.
11361   TypeResult ActOnOpenMPDeclareMapperVarDecl(Scope *S, Declarator &D);
11362   /// Check if the specified type is allowed to be used in 'omp declare
11363   /// mapper' construct.
11364   QualType ActOnOpenMPDeclareMapperType(SourceLocation TyLoc,
11365                                         TypeResult ParsedType);
11366   /// Called on start of '#pragma omp declare mapper'.
11367   DeclGroupPtrTy ActOnOpenMPDeclareMapperDirective(
11368       Scope *S, DeclContext *DC, DeclarationName Name, QualType MapperType,
11369       SourceLocation StartLoc, DeclarationName VN, AccessSpecifier AS,
11370       Expr *MapperVarRef, ArrayRef<OMPClause *> Clauses,
11371       Decl *PrevDeclInScope = nullptr);
11372   /// Build the mapper variable of '#pragma omp declare mapper'.
11373   ExprResult ActOnOpenMPDeclareMapperDirectiveVarDecl(Scope *S,
11374                                                       QualType MapperType,
11375                                                       SourceLocation StartLoc,
11376                                                       DeclarationName VN);
11377   void ActOnOpenMPIteratorVarDecl(VarDecl *VD);
11378   bool isOpenMPDeclareMapperVarDeclAllowed(const VarDecl *VD) const;
11379   const ValueDecl *getOpenMPDeclareMapperVarName() const;
11380 
11381   /// Called on the start of target region i.e. '#pragma omp declare target'.
11382   bool ActOnStartOpenMPDeclareTargetContext(DeclareTargetContextInfo &DTCI);
11383 
11384   /// Called at the end of target region i.e. '#pragma omp end declare target'.
11385   const DeclareTargetContextInfo ActOnOpenMPEndDeclareTargetDirective();
11386 
11387   /// Called once a target context is completed, that can be when a
11388   /// '#pragma omp end declare target' was encountered or when a
11389   /// '#pragma omp declare target' without declaration-definition-seq was
11390   /// encountered.
11391   void ActOnFinishedOpenMPDeclareTargetContext(DeclareTargetContextInfo &DTCI);
11392 
11393   /// Report unterminated 'omp declare target' or 'omp begin declare target' at
11394   /// the end of a compilation unit.
11395   void DiagnoseUnterminatedOpenMPDeclareTarget();
11396 
11397   /// Searches for the provided declaration name for OpenMP declare target
11398   /// directive.
11399   NamedDecl *lookupOpenMPDeclareTargetName(Scope *CurScope,
11400                                            CXXScopeSpec &ScopeSpec,
11401                                            const DeclarationNameInfo &Id);
11402 
11403   /// Called on correct id-expression from the '#pragma omp declare target'.
11404   void ActOnOpenMPDeclareTargetName(NamedDecl *ND, SourceLocation Loc,
11405                                     OMPDeclareTargetDeclAttr::MapTypeTy MT,
11406                                     DeclareTargetContextInfo &DTCI);
11407 
11408   /// Check declaration inside target region.
11409   void
11410   checkDeclIsAllowedInOpenMPTarget(Expr *E, Decl *D,
11411                                    SourceLocation IdLoc = SourceLocation());
11412 
11413   /// Adds OMPDeclareTargetDeclAttr to referenced variables in declare target
11414   /// directive.
11415   void ActOnOpenMPDeclareTargetInitializer(Decl *D);
11416 
11417   /// Finishes analysis of the deferred functions calls that may be declared as
11418   /// host/nohost during device/host compilation.
11419   void finalizeOpenMPDelayedAnalysis(const FunctionDecl *Caller,
11420                                      const FunctionDecl *Callee,
11421                                      SourceLocation Loc);
11422 
11423   /// Return true if currently in OpenMP task with untied clause context.
11424   bool isInOpenMPTaskUntiedContext() const;
11425 
11426   /// Return true inside OpenMP declare target region.
11427   bool isInOpenMPDeclareTargetContext() const {
11428     return !DeclareTargetNesting.empty();
11429   }
11430   /// Return true inside OpenMP target region.
11431   bool isInOpenMPTargetExecutionDirective() const;
11432 
11433   /// Return the number of captured regions created for an OpenMP directive.
11434   static int getOpenMPCaptureLevels(OpenMPDirectiveKind Kind);
11435 
11436   /// Initialization of captured region for OpenMP region.
11437   void ActOnOpenMPRegionStart(OpenMPDirectiveKind DKind, Scope *CurScope);
11438 
11439   /// Called for syntactical loops (ForStmt or CXXForRangeStmt) associated to
11440   /// an OpenMP loop directive.
11441   StmtResult ActOnOpenMPCanonicalLoop(Stmt *AStmt);
11442 
11443   /// Process a canonical OpenMP loop nest that can either be a canonical
11444   /// literal loop (ForStmt or CXXForRangeStmt), or the generated loop of an
11445   /// OpenMP loop transformation construct.
11446   StmtResult ActOnOpenMPLoopnest(Stmt *AStmt);
11447 
11448   /// End of OpenMP region.
11449   ///
11450   /// \param S Statement associated with the current OpenMP region.
11451   /// \param Clauses List of clauses for the current OpenMP region.
11452   ///
11453   /// \returns Statement for finished OpenMP region.
11454   StmtResult ActOnOpenMPRegionEnd(StmtResult S, ArrayRef<OMPClause *> Clauses);
11455   StmtResult ActOnOpenMPExecutableDirective(
11456       OpenMPDirectiveKind Kind, const DeclarationNameInfo &DirName,
11457       OpenMPDirectiveKind CancelRegion, ArrayRef<OMPClause *> Clauses,
11458       Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc);
11459   /// Called on well-formed '\#pragma omp parallel' after parsing
11460   /// of the  associated statement.
11461   StmtResult ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses,
11462                                           Stmt *AStmt,
11463                                           SourceLocation StartLoc,
11464                                           SourceLocation EndLoc);
11465   using VarsWithInheritedDSAType =
11466       llvm::SmallDenseMap<const ValueDecl *, const Expr *, 4>;
11467   /// Called on well-formed '\#pragma omp simd' after parsing
11468   /// of the associated statement.
11469   StmtResult
11470   ActOnOpenMPSimdDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
11471                            SourceLocation StartLoc, SourceLocation EndLoc,
11472                            VarsWithInheritedDSAType &VarsWithImplicitDSA);
11473   /// Called on well-formed '#pragma omp tile' after parsing of its clauses and
11474   /// the associated statement.
11475   StmtResult ActOnOpenMPTileDirective(ArrayRef<OMPClause *> Clauses,
11476                                       Stmt *AStmt, SourceLocation StartLoc,
11477                                       SourceLocation EndLoc);
11478   /// Called on well-formed '#pragma omp unroll' after parsing of its clauses
11479   /// and the associated statement.
11480   StmtResult ActOnOpenMPUnrollDirective(ArrayRef<OMPClause *> Clauses,
11481                                         Stmt *AStmt, SourceLocation StartLoc,
11482                                         SourceLocation EndLoc);
11483   /// Called on well-formed '\#pragma omp for' after parsing
11484   /// of the associated statement.
11485   StmtResult
11486   ActOnOpenMPForDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
11487                           SourceLocation StartLoc, SourceLocation EndLoc,
11488                           VarsWithInheritedDSAType &VarsWithImplicitDSA);
11489   /// Called on well-formed '\#pragma omp for simd' after parsing
11490   /// of the associated statement.
11491   StmtResult
11492   ActOnOpenMPForSimdDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
11493                               SourceLocation StartLoc, SourceLocation EndLoc,
11494                               VarsWithInheritedDSAType &VarsWithImplicitDSA);
11495   /// Called on well-formed '\#pragma omp sections' after parsing
11496   /// of the associated statement.
11497   StmtResult ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses,
11498                                           Stmt *AStmt, SourceLocation StartLoc,
11499                                           SourceLocation EndLoc);
11500   /// Called on well-formed '\#pragma omp section' after parsing of the
11501   /// associated statement.
11502   StmtResult ActOnOpenMPSectionDirective(Stmt *AStmt, SourceLocation StartLoc,
11503                                          SourceLocation EndLoc);
11504   /// Called on well-formed '\#pragma omp single' after parsing of the
11505   /// associated statement.
11506   StmtResult ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses,
11507                                         Stmt *AStmt, SourceLocation StartLoc,
11508                                         SourceLocation EndLoc);
11509   /// Called on well-formed '\#pragma omp master' after parsing of the
11510   /// associated statement.
11511   StmtResult ActOnOpenMPMasterDirective(Stmt *AStmt, SourceLocation StartLoc,
11512                                         SourceLocation EndLoc);
11513   /// Called on well-formed '\#pragma omp critical' after parsing of the
11514   /// associated statement.
11515   StmtResult ActOnOpenMPCriticalDirective(const DeclarationNameInfo &DirName,
11516                                           ArrayRef<OMPClause *> Clauses,
11517                                           Stmt *AStmt, SourceLocation StartLoc,
11518                                           SourceLocation EndLoc);
11519   /// Called on well-formed '\#pragma omp parallel for' after parsing
11520   /// of the  associated statement.
11521   StmtResult ActOnOpenMPParallelForDirective(
11522       ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11523       SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
11524   /// Called on well-formed '\#pragma omp parallel for simd' after
11525   /// parsing of the  associated statement.
11526   StmtResult ActOnOpenMPParallelForSimdDirective(
11527       ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11528       SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
11529   /// Called on well-formed '\#pragma omp parallel master' after
11530   /// parsing of the  associated statement.
11531   StmtResult ActOnOpenMPParallelMasterDirective(ArrayRef<OMPClause *> Clauses,
11532                                                 Stmt *AStmt,
11533                                                 SourceLocation StartLoc,
11534                                                 SourceLocation EndLoc);
11535   /// Called on well-formed '\#pragma omp parallel masked' after
11536   /// parsing of the associated statement.
11537   StmtResult ActOnOpenMPParallelMaskedDirective(ArrayRef<OMPClause *> Clauses,
11538                                                 Stmt *AStmt,
11539                                                 SourceLocation StartLoc,
11540                                                 SourceLocation EndLoc);
11541   /// Called on well-formed '\#pragma omp parallel sections' after
11542   /// parsing of the  associated statement.
11543   StmtResult ActOnOpenMPParallelSectionsDirective(ArrayRef<OMPClause *> Clauses,
11544                                                   Stmt *AStmt,
11545                                                   SourceLocation StartLoc,
11546                                                   SourceLocation EndLoc);
11547   /// Called on well-formed '\#pragma omp task' after parsing of the
11548   /// associated statement.
11549   StmtResult ActOnOpenMPTaskDirective(ArrayRef<OMPClause *> Clauses,
11550                                       Stmt *AStmt, SourceLocation StartLoc,
11551                                       SourceLocation EndLoc);
11552   /// Called on well-formed '\#pragma omp taskyield'.
11553   StmtResult ActOnOpenMPTaskyieldDirective(SourceLocation StartLoc,
11554                                            SourceLocation EndLoc);
11555   /// Called on well-formed '\#pragma omp error'.
11556   /// Error direcitive is allowed in both declared and excutable contexts.
11557   /// Adding InExContext to identify which context is called from.
11558   StmtResult ActOnOpenMPErrorDirective(ArrayRef<OMPClause *> Clauses,
11559                                        SourceLocation StartLoc,
11560                                        SourceLocation EndLoc,
11561                                        bool InExContext = true);
11562   /// Called on well-formed '\#pragma omp barrier'.
11563   StmtResult ActOnOpenMPBarrierDirective(SourceLocation StartLoc,
11564                                          SourceLocation EndLoc);
11565   /// Called on well-formed '\#pragma omp taskwait'.
11566   StmtResult ActOnOpenMPTaskwaitDirective(ArrayRef<OMPClause *> Clauses,
11567                                           SourceLocation StartLoc,
11568                                           SourceLocation EndLoc);
11569   /// Called on well-formed '\#pragma omp taskgroup'.
11570   StmtResult ActOnOpenMPTaskgroupDirective(ArrayRef<OMPClause *> Clauses,
11571                                            Stmt *AStmt, SourceLocation StartLoc,
11572                                            SourceLocation EndLoc);
11573   /// Called on well-formed '\#pragma omp flush'.
11574   StmtResult ActOnOpenMPFlushDirective(ArrayRef<OMPClause *> Clauses,
11575                                        SourceLocation StartLoc,
11576                                        SourceLocation EndLoc);
11577   /// Called on well-formed '\#pragma omp depobj'.
11578   StmtResult ActOnOpenMPDepobjDirective(ArrayRef<OMPClause *> Clauses,
11579                                         SourceLocation StartLoc,
11580                                         SourceLocation EndLoc);
11581   /// Called on well-formed '\#pragma omp scan'.
11582   StmtResult ActOnOpenMPScanDirective(ArrayRef<OMPClause *> Clauses,
11583                                       SourceLocation StartLoc,
11584                                       SourceLocation EndLoc);
11585   /// Called on well-formed '\#pragma omp ordered' after parsing of the
11586   /// associated statement.
11587   StmtResult ActOnOpenMPOrderedDirective(ArrayRef<OMPClause *> Clauses,
11588                                          Stmt *AStmt, SourceLocation StartLoc,
11589                                          SourceLocation EndLoc);
11590   /// Called on well-formed '\#pragma omp atomic' after parsing of the
11591   /// associated statement.
11592   StmtResult ActOnOpenMPAtomicDirective(ArrayRef<OMPClause *> Clauses,
11593                                         Stmt *AStmt, SourceLocation StartLoc,
11594                                         SourceLocation EndLoc);
11595   /// Called on well-formed '\#pragma omp target' after parsing of the
11596   /// associated statement.
11597   StmtResult ActOnOpenMPTargetDirective(ArrayRef<OMPClause *> Clauses,
11598                                         Stmt *AStmt, SourceLocation StartLoc,
11599                                         SourceLocation EndLoc);
11600   /// Called on well-formed '\#pragma omp target data' after parsing of
11601   /// the associated statement.
11602   StmtResult ActOnOpenMPTargetDataDirective(ArrayRef<OMPClause *> Clauses,
11603                                             Stmt *AStmt, SourceLocation StartLoc,
11604                                             SourceLocation EndLoc);
11605   /// Called on well-formed '\#pragma omp target enter data' after
11606   /// parsing of the associated statement.
11607   StmtResult ActOnOpenMPTargetEnterDataDirective(ArrayRef<OMPClause *> Clauses,
11608                                                  SourceLocation StartLoc,
11609                                                  SourceLocation EndLoc,
11610                                                  Stmt *AStmt);
11611   /// Called on well-formed '\#pragma omp target exit data' after
11612   /// parsing of the associated statement.
11613   StmtResult ActOnOpenMPTargetExitDataDirective(ArrayRef<OMPClause *> Clauses,
11614                                                 SourceLocation StartLoc,
11615                                                 SourceLocation EndLoc,
11616                                                 Stmt *AStmt);
11617   /// Called on well-formed '\#pragma omp target parallel' after
11618   /// parsing of the associated statement.
11619   StmtResult ActOnOpenMPTargetParallelDirective(ArrayRef<OMPClause *> Clauses,
11620                                                 Stmt *AStmt,
11621                                                 SourceLocation StartLoc,
11622                                                 SourceLocation EndLoc);
11623   /// Called on well-formed '\#pragma omp target parallel for' after
11624   /// parsing of the  associated statement.
11625   StmtResult ActOnOpenMPTargetParallelForDirective(
11626       ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11627       SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
11628   /// Called on well-formed '\#pragma omp teams' after parsing of the
11629   /// associated statement.
11630   StmtResult ActOnOpenMPTeamsDirective(ArrayRef<OMPClause *> Clauses,
11631                                        Stmt *AStmt, SourceLocation StartLoc,
11632                                        SourceLocation EndLoc);
11633   /// Called on well-formed '\#pragma omp teams loop' after parsing of the
11634   /// associated statement.
11635   StmtResult ActOnOpenMPTeamsGenericLoopDirective(
11636       ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11637       SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
11638   /// Called on well-formed '\#pragma omp target teams loop' after parsing of
11639   /// the associated statement.
11640   StmtResult ActOnOpenMPTargetTeamsGenericLoopDirective(
11641       ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11642       SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
11643   /// Called on well-formed '\#pragma omp parallel loop' after parsing of the
11644   /// associated statement.
11645   StmtResult ActOnOpenMPParallelGenericLoopDirective(
11646       ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11647       SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
11648   /// Called on well-formed '\#pragma omp target parallel loop' after parsing
11649   /// of the associated statement.
11650   StmtResult ActOnOpenMPTargetParallelGenericLoopDirective(
11651       ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11652       SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
11653   /// Called on well-formed '\#pragma omp cancellation point'.
11654   StmtResult
11655   ActOnOpenMPCancellationPointDirective(SourceLocation StartLoc,
11656                                         SourceLocation EndLoc,
11657                                         OpenMPDirectiveKind CancelRegion);
11658   /// Called on well-formed '\#pragma omp cancel'.
11659   StmtResult ActOnOpenMPCancelDirective(ArrayRef<OMPClause *> Clauses,
11660                                         SourceLocation StartLoc,
11661                                         SourceLocation EndLoc,
11662                                         OpenMPDirectiveKind CancelRegion);
11663   /// Called on well-formed '\#pragma omp taskloop' after parsing of the
11664   /// associated statement.
11665   StmtResult
11666   ActOnOpenMPTaskLoopDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
11667                                SourceLocation StartLoc, SourceLocation EndLoc,
11668                                VarsWithInheritedDSAType &VarsWithImplicitDSA);
11669   /// Called on well-formed '\#pragma omp taskloop simd' after parsing of
11670   /// the associated statement.
11671   StmtResult ActOnOpenMPTaskLoopSimdDirective(
11672       ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11673       SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
11674   /// Called on well-formed '\#pragma omp master taskloop' after parsing of the
11675   /// associated statement.
11676   StmtResult ActOnOpenMPMasterTaskLoopDirective(
11677       ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11678       SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
11679   /// Called on well-formed '\#pragma omp master taskloop simd' after parsing of
11680   /// the associated statement.
11681   StmtResult ActOnOpenMPMasterTaskLoopSimdDirective(
11682       ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11683       SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
11684   /// Called on well-formed '\#pragma omp parallel master taskloop' after
11685   /// parsing of the associated statement.
11686   StmtResult ActOnOpenMPParallelMasterTaskLoopDirective(
11687       ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11688       SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
11689   /// Called on well-formed '\#pragma omp parallel master taskloop simd' after
11690   /// parsing of the associated statement.
11691   StmtResult ActOnOpenMPParallelMasterTaskLoopSimdDirective(
11692       ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11693       SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
11694   /// Called on well-formed '\#pragma omp masked taskloop' after parsing of the
11695   /// associated statement.
11696   StmtResult ActOnOpenMPMaskedTaskLoopDirective(
11697       ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11698       SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
11699   /// Called on well-formed '\#pragma omp masked taskloop simd' after parsing of
11700   /// the associated statement.
11701   StmtResult ActOnOpenMPMaskedTaskLoopSimdDirective(
11702       ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11703       SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
11704   /// Called on well-formed '\#pragma omp parallel masked taskloop' after
11705   /// parsing of the associated statement.
11706   StmtResult ActOnOpenMPParallelMaskedTaskLoopDirective(
11707       ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11708       SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
11709   /// Called on well-formed '\#pragma omp parallel masked taskloop simd' after
11710   /// parsing of the associated statement.
11711   StmtResult ActOnOpenMPParallelMaskedTaskLoopSimdDirective(
11712       ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11713       SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
11714   /// Called on well-formed '\#pragma omp distribute' after parsing
11715   /// of the associated statement.
11716   StmtResult
11717   ActOnOpenMPDistributeDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
11718                                  SourceLocation StartLoc, SourceLocation EndLoc,
11719                                  VarsWithInheritedDSAType &VarsWithImplicitDSA);
11720   /// Called on well-formed '\#pragma omp target update'.
11721   StmtResult ActOnOpenMPTargetUpdateDirective(ArrayRef<OMPClause *> Clauses,
11722                                               SourceLocation StartLoc,
11723                                               SourceLocation EndLoc,
11724                                               Stmt *AStmt);
11725   /// Called on well-formed '\#pragma omp distribute parallel for' after
11726   /// parsing of the associated statement.
11727   StmtResult ActOnOpenMPDistributeParallelForDirective(
11728       ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11729       SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
11730   /// Called on well-formed '\#pragma omp distribute parallel for simd'
11731   /// after parsing of the associated statement.
11732   StmtResult ActOnOpenMPDistributeParallelForSimdDirective(
11733       ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11734       SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
11735   /// Called on well-formed '\#pragma omp distribute simd' after
11736   /// parsing of the associated statement.
11737   StmtResult ActOnOpenMPDistributeSimdDirective(
11738       ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11739       SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
11740   /// Called on well-formed '\#pragma omp target parallel for simd' after
11741   /// parsing of the associated statement.
11742   StmtResult ActOnOpenMPTargetParallelForSimdDirective(
11743       ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11744       SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
11745   /// Called on well-formed '\#pragma omp target simd' after parsing of
11746   /// the associated statement.
11747   StmtResult
11748   ActOnOpenMPTargetSimdDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
11749                                  SourceLocation StartLoc, SourceLocation EndLoc,
11750                                  VarsWithInheritedDSAType &VarsWithImplicitDSA);
11751   /// Called on well-formed '\#pragma omp teams distribute' after parsing of
11752   /// the associated statement.
11753   StmtResult ActOnOpenMPTeamsDistributeDirective(
11754       ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11755       SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
11756   /// Called on well-formed '\#pragma omp teams distribute simd' after parsing
11757   /// of the associated statement.
11758   StmtResult ActOnOpenMPTeamsDistributeSimdDirective(
11759       ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11760       SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
11761   /// Called on well-formed '\#pragma omp teams distribute parallel for simd'
11762   /// after parsing of the associated statement.
11763   StmtResult ActOnOpenMPTeamsDistributeParallelForSimdDirective(
11764       ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11765       SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
11766   /// Called on well-formed '\#pragma omp teams distribute parallel for'
11767   /// after parsing of the associated statement.
11768   StmtResult ActOnOpenMPTeamsDistributeParallelForDirective(
11769       ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11770       SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
11771   /// Called on well-formed '\#pragma omp target teams' after parsing of the
11772   /// associated statement.
11773   StmtResult ActOnOpenMPTargetTeamsDirective(ArrayRef<OMPClause *> Clauses,
11774                                              Stmt *AStmt,
11775                                              SourceLocation StartLoc,
11776                                              SourceLocation EndLoc);
11777   /// Called on well-formed '\#pragma omp target teams distribute' after parsing
11778   /// of the associated statement.
11779   StmtResult ActOnOpenMPTargetTeamsDistributeDirective(
11780       ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11781       SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
11782   /// Called on well-formed '\#pragma omp target teams distribute parallel for'
11783   /// after parsing of the associated statement.
11784   StmtResult ActOnOpenMPTargetTeamsDistributeParallelForDirective(
11785       ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11786       SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
11787   /// Called on well-formed '\#pragma omp target teams distribute parallel for
11788   /// simd' after parsing of the associated statement.
11789   StmtResult ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective(
11790       ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11791       SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
11792   /// Called on well-formed '\#pragma omp target teams distribute simd' after
11793   /// parsing of the associated statement.
11794   StmtResult ActOnOpenMPTargetTeamsDistributeSimdDirective(
11795       ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11796       SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
11797   /// Called on well-formed '\#pragma omp interop'.
11798   StmtResult ActOnOpenMPInteropDirective(ArrayRef<OMPClause *> Clauses,
11799                                          SourceLocation StartLoc,
11800                                          SourceLocation EndLoc);
11801   /// Called on well-formed '\#pragma omp dispatch' after parsing of the
11802   // /associated statement.
11803   StmtResult ActOnOpenMPDispatchDirective(ArrayRef<OMPClause *> Clauses,
11804                                           Stmt *AStmt, SourceLocation StartLoc,
11805                                           SourceLocation EndLoc);
11806   /// Called on well-formed '\#pragma omp masked' after parsing of the
11807   // /associated statement.
11808   StmtResult ActOnOpenMPMaskedDirective(ArrayRef<OMPClause *> Clauses,
11809                                         Stmt *AStmt, SourceLocation StartLoc,
11810                                         SourceLocation EndLoc);
11811 
11812   /// Called on well-formed '\#pragma omp loop' after parsing of the
11813   /// associated statement.
11814   StmtResult ActOnOpenMPGenericLoopDirective(
11815       ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11816       SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
11817 
11818   /// Checks correctness of linear modifiers.
11819   bool CheckOpenMPLinearModifier(OpenMPLinearClauseKind LinKind,
11820                                  SourceLocation LinLoc);
11821   /// Checks that the specified declaration matches requirements for the linear
11822   /// decls.
11823   bool CheckOpenMPLinearDecl(const ValueDecl *D, SourceLocation ELoc,
11824                              OpenMPLinearClauseKind LinKind, QualType Type,
11825                              bool IsDeclareSimd = false);
11826 
11827   /// Called on well-formed '\#pragma omp declare simd' after parsing of
11828   /// the associated method/function.
11829   DeclGroupPtrTy ActOnOpenMPDeclareSimdDirective(
11830       DeclGroupPtrTy DG, OMPDeclareSimdDeclAttr::BranchStateTy BS,
11831       Expr *Simdlen, ArrayRef<Expr *> Uniforms, ArrayRef<Expr *> Aligneds,
11832       ArrayRef<Expr *> Alignments, ArrayRef<Expr *> Linears,
11833       ArrayRef<unsigned> LinModifiers, ArrayRef<Expr *> Steps, SourceRange SR);
11834 
11835   /// Checks '\#pragma omp declare variant' variant function and original
11836   /// functions after parsing of the associated method/function.
11837   /// \param DG Function declaration to which declare variant directive is
11838   /// applied to.
11839   /// \param VariantRef Expression that references the variant function, which
11840   /// must be used instead of the original one, specified in \p DG.
11841   /// \param TI The trait info object representing the match clause.
11842   /// \param NumAppendArgs The number of omp_interop_t arguments to account for
11843   /// in checking.
11844   /// \returns std::nullopt, if the function/variant function are not compatible
11845   /// with the pragma, pair of original function/variant ref expression
11846   /// otherwise.
11847   std::optional<std::pair<FunctionDecl *, Expr *>>
11848   checkOpenMPDeclareVariantFunction(DeclGroupPtrTy DG, Expr *VariantRef,
11849                                     OMPTraitInfo &TI, unsigned NumAppendArgs,
11850                                     SourceRange SR);
11851 
11852   /// Called on well-formed '\#pragma omp declare variant' after parsing of
11853   /// the associated method/function.
11854   /// \param FD Function declaration to which declare variant directive is
11855   /// applied to.
11856   /// \param VariantRef Expression that references the variant function, which
11857   /// must be used instead of the original one, specified in \p DG.
11858   /// \param TI The context traits associated with the function variant.
11859   /// \param AdjustArgsNothing The list of 'nothing' arguments.
11860   /// \param AdjustArgsNeedDevicePtr The list of 'need_device_ptr' arguments.
11861   /// \param AppendArgs The list of 'append_args' arguments.
11862   /// \param AdjustArgsLoc The Location of an 'adjust_args' clause.
11863   /// \param AppendArgsLoc The Location of an 'append_args' clause.
11864   /// \param SR The SourceRange of the 'declare variant' directive.
11865   void ActOnOpenMPDeclareVariantDirective(
11866       FunctionDecl *FD, Expr *VariantRef, OMPTraitInfo &TI,
11867       ArrayRef<Expr *> AdjustArgsNothing,
11868       ArrayRef<Expr *> AdjustArgsNeedDevicePtr,
11869       ArrayRef<OMPInteropInfo> AppendArgs, SourceLocation AdjustArgsLoc,
11870       SourceLocation AppendArgsLoc, SourceRange SR);
11871 
11872   OMPClause *ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind,
11873                                          Expr *Expr,
11874                                          SourceLocation StartLoc,
11875                                          SourceLocation LParenLoc,
11876                                          SourceLocation EndLoc);
11877   /// Called on well-formed 'allocator' clause.
11878   OMPClause *ActOnOpenMPAllocatorClause(Expr *Allocator,
11879                                         SourceLocation StartLoc,
11880                                         SourceLocation LParenLoc,
11881                                         SourceLocation EndLoc);
11882   /// Called on well-formed 'if' clause.
11883   OMPClause *ActOnOpenMPIfClause(OpenMPDirectiveKind NameModifier,
11884                                  Expr *Condition, SourceLocation StartLoc,
11885                                  SourceLocation LParenLoc,
11886                                  SourceLocation NameModifierLoc,
11887                                  SourceLocation ColonLoc,
11888                                  SourceLocation EndLoc);
11889   /// Called on well-formed 'final' clause.
11890   OMPClause *ActOnOpenMPFinalClause(Expr *Condition, SourceLocation StartLoc,
11891                                     SourceLocation LParenLoc,
11892                                     SourceLocation EndLoc);
11893   /// Called on well-formed 'num_threads' clause.
11894   OMPClause *ActOnOpenMPNumThreadsClause(Expr *NumThreads,
11895                                          SourceLocation StartLoc,
11896                                          SourceLocation LParenLoc,
11897                                          SourceLocation EndLoc);
11898   /// Called on well-formed 'align' clause.
11899   OMPClause *ActOnOpenMPAlignClause(Expr *Alignment, SourceLocation StartLoc,
11900                                     SourceLocation LParenLoc,
11901                                     SourceLocation EndLoc);
11902   /// Called on well-formed 'safelen' clause.
11903   OMPClause *ActOnOpenMPSafelenClause(Expr *Length,
11904                                       SourceLocation StartLoc,
11905                                       SourceLocation LParenLoc,
11906                                       SourceLocation EndLoc);
11907   /// Called on well-formed 'simdlen' clause.
11908   OMPClause *ActOnOpenMPSimdlenClause(Expr *Length, SourceLocation StartLoc,
11909                                       SourceLocation LParenLoc,
11910                                       SourceLocation EndLoc);
11911   /// Called on well-form 'sizes' clause.
11912   OMPClause *ActOnOpenMPSizesClause(ArrayRef<Expr *> SizeExprs,
11913                                     SourceLocation StartLoc,
11914                                     SourceLocation LParenLoc,
11915                                     SourceLocation EndLoc);
11916   /// Called on well-form 'full' clauses.
11917   OMPClause *ActOnOpenMPFullClause(SourceLocation StartLoc,
11918                                    SourceLocation EndLoc);
11919   /// Called on well-form 'partial' clauses.
11920   OMPClause *ActOnOpenMPPartialClause(Expr *FactorExpr, SourceLocation StartLoc,
11921                                       SourceLocation LParenLoc,
11922                                       SourceLocation EndLoc);
11923   /// Called on well-formed 'collapse' clause.
11924   OMPClause *ActOnOpenMPCollapseClause(Expr *NumForLoops,
11925                                        SourceLocation StartLoc,
11926                                        SourceLocation LParenLoc,
11927                                        SourceLocation EndLoc);
11928   /// Called on well-formed 'ordered' clause.
11929   OMPClause *
11930   ActOnOpenMPOrderedClause(SourceLocation StartLoc, SourceLocation EndLoc,
11931                            SourceLocation LParenLoc = SourceLocation(),
11932                            Expr *NumForLoops = nullptr);
11933   /// Called on well-formed 'grainsize' clause.
11934   OMPClause *ActOnOpenMPGrainsizeClause(OpenMPGrainsizeClauseModifier Modifier,
11935                                         Expr *Size, SourceLocation StartLoc,
11936                                         SourceLocation LParenLoc,
11937                                         SourceLocation ModifierLoc,
11938                                         SourceLocation EndLoc);
11939   /// Called on well-formed 'num_tasks' clause.
11940   OMPClause *ActOnOpenMPNumTasksClause(OpenMPNumTasksClauseModifier Modifier,
11941                                        Expr *NumTasks, SourceLocation StartLoc,
11942                                        SourceLocation LParenLoc,
11943                                        SourceLocation ModifierLoc,
11944                                        SourceLocation EndLoc);
11945   /// Called on well-formed 'hint' clause.
11946   OMPClause *ActOnOpenMPHintClause(Expr *Hint, SourceLocation StartLoc,
11947                                    SourceLocation LParenLoc,
11948                                    SourceLocation EndLoc);
11949   /// Called on well-formed 'detach' clause.
11950   OMPClause *ActOnOpenMPDetachClause(Expr *Evt, SourceLocation StartLoc,
11951                                      SourceLocation LParenLoc,
11952                                      SourceLocation EndLoc);
11953 
11954   OMPClause *ActOnOpenMPSimpleClause(OpenMPClauseKind Kind,
11955                                      unsigned Argument,
11956                                      SourceLocation ArgumentLoc,
11957                                      SourceLocation StartLoc,
11958                                      SourceLocation LParenLoc,
11959                                      SourceLocation EndLoc);
11960   /// Called on well-formed 'when' clause.
11961   OMPClause *ActOnOpenMPWhenClause(OMPTraitInfo &TI, SourceLocation StartLoc,
11962                                    SourceLocation LParenLoc,
11963                                    SourceLocation EndLoc);
11964   /// Called on well-formed 'default' clause.
11965   OMPClause *ActOnOpenMPDefaultClause(llvm::omp::DefaultKind Kind,
11966                                       SourceLocation KindLoc,
11967                                       SourceLocation StartLoc,
11968                                       SourceLocation LParenLoc,
11969                                       SourceLocation EndLoc);
11970   /// Called on well-formed 'proc_bind' clause.
11971   OMPClause *ActOnOpenMPProcBindClause(llvm::omp::ProcBindKind Kind,
11972                                        SourceLocation KindLoc,
11973                                        SourceLocation StartLoc,
11974                                        SourceLocation LParenLoc,
11975                                        SourceLocation EndLoc);
11976   /// Called on well-formed 'order' clause.
11977   OMPClause *ActOnOpenMPOrderClause(OpenMPOrderClauseModifier Modifier,
11978                                     OpenMPOrderClauseKind Kind,
11979                                     SourceLocation StartLoc,
11980                                     SourceLocation LParenLoc,
11981                                     SourceLocation MLoc, SourceLocation KindLoc,
11982                                     SourceLocation EndLoc);
11983   /// Called on well-formed 'update' clause.
11984   OMPClause *ActOnOpenMPUpdateClause(OpenMPDependClauseKind Kind,
11985                                      SourceLocation KindLoc,
11986                                      SourceLocation StartLoc,
11987                                      SourceLocation LParenLoc,
11988                                      SourceLocation EndLoc);
11989 
11990   OMPClause *ActOnOpenMPSingleExprWithArgClause(
11991       OpenMPClauseKind Kind, ArrayRef<unsigned> Arguments, Expr *Expr,
11992       SourceLocation StartLoc, SourceLocation LParenLoc,
11993       ArrayRef<SourceLocation> ArgumentsLoc, SourceLocation DelimLoc,
11994       SourceLocation EndLoc);
11995   /// Called on well-formed 'schedule' clause.
11996   OMPClause *ActOnOpenMPScheduleClause(
11997       OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2,
11998       OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
11999       SourceLocation LParenLoc, SourceLocation M1Loc, SourceLocation M2Loc,
12000       SourceLocation KindLoc, SourceLocation CommaLoc, SourceLocation EndLoc);
12001 
12002   OMPClause *ActOnOpenMPClause(OpenMPClauseKind Kind, SourceLocation StartLoc,
12003                                SourceLocation EndLoc);
12004   /// Called on well-formed 'nowait' clause.
12005   OMPClause *ActOnOpenMPNowaitClause(SourceLocation StartLoc,
12006                                      SourceLocation EndLoc);
12007   /// Called on well-formed 'untied' clause.
12008   OMPClause *ActOnOpenMPUntiedClause(SourceLocation StartLoc,
12009                                      SourceLocation EndLoc);
12010   /// Called on well-formed 'mergeable' clause.
12011   OMPClause *ActOnOpenMPMergeableClause(SourceLocation StartLoc,
12012                                         SourceLocation EndLoc);
12013   /// Called on well-formed 'read' clause.
12014   OMPClause *ActOnOpenMPReadClause(SourceLocation StartLoc,
12015                                    SourceLocation EndLoc);
12016   /// Called on well-formed 'write' clause.
12017   OMPClause *ActOnOpenMPWriteClause(SourceLocation StartLoc,
12018                                     SourceLocation EndLoc);
12019   /// Called on well-formed 'update' clause.
12020   OMPClause *ActOnOpenMPUpdateClause(SourceLocation StartLoc,
12021                                      SourceLocation EndLoc);
12022   /// Called on well-formed 'capture' clause.
12023   OMPClause *ActOnOpenMPCaptureClause(SourceLocation StartLoc,
12024                                       SourceLocation EndLoc);
12025   /// Called on well-formed 'compare' clause.
12026   OMPClause *ActOnOpenMPCompareClause(SourceLocation StartLoc,
12027                                       SourceLocation EndLoc);
12028   /// Called on well-formed 'seq_cst' clause.
12029   OMPClause *ActOnOpenMPSeqCstClause(SourceLocation StartLoc,
12030                                      SourceLocation EndLoc);
12031   /// Called on well-formed 'acq_rel' clause.
12032   OMPClause *ActOnOpenMPAcqRelClause(SourceLocation StartLoc,
12033                                      SourceLocation EndLoc);
12034   /// Called on well-formed 'acquire' clause.
12035   OMPClause *ActOnOpenMPAcquireClause(SourceLocation StartLoc,
12036                                       SourceLocation EndLoc);
12037   /// Called on well-formed 'release' clause.
12038   OMPClause *ActOnOpenMPReleaseClause(SourceLocation StartLoc,
12039                                       SourceLocation EndLoc);
12040   /// Called on well-formed 'relaxed' clause.
12041   OMPClause *ActOnOpenMPRelaxedClause(SourceLocation StartLoc,
12042                                       SourceLocation EndLoc);
12043 
12044   /// Called on well-formed 'init' clause.
12045   OMPClause *
12046   ActOnOpenMPInitClause(Expr *InteropVar, OMPInteropInfo &InteropInfo,
12047                         SourceLocation StartLoc, SourceLocation LParenLoc,
12048                         SourceLocation VarLoc, SourceLocation EndLoc);
12049 
12050   /// Called on well-formed 'use' clause.
12051   OMPClause *ActOnOpenMPUseClause(Expr *InteropVar, SourceLocation StartLoc,
12052                                   SourceLocation LParenLoc,
12053                                   SourceLocation VarLoc, SourceLocation EndLoc);
12054 
12055   /// Called on well-formed 'destroy' clause.
12056   OMPClause *ActOnOpenMPDestroyClause(Expr *InteropVar, SourceLocation StartLoc,
12057                                       SourceLocation LParenLoc,
12058                                       SourceLocation VarLoc,
12059                                       SourceLocation EndLoc);
12060   /// Called on well-formed 'novariants' clause.
12061   OMPClause *ActOnOpenMPNovariantsClause(Expr *Condition,
12062                                          SourceLocation StartLoc,
12063                                          SourceLocation LParenLoc,
12064                                          SourceLocation EndLoc);
12065   /// Called on well-formed 'nocontext' clause.
12066   OMPClause *ActOnOpenMPNocontextClause(Expr *Condition,
12067                                         SourceLocation StartLoc,
12068                                         SourceLocation LParenLoc,
12069                                         SourceLocation EndLoc);
12070   /// Called on well-formed 'filter' clause.
12071   OMPClause *ActOnOpenMPFilterClause(Expr *ThreadID, SourceLocation StartLoc,
12072                                      SourceLocation LParenLoc,
12073                                      SourceLocation EndLoc);
12074   /// Called on well-formed 'threads' clause.
12075   OMPClause *ActOnOpenMPThreadsClause(SourceLocation StartLoc,
12076                                       SourceLocation EndLoc);
12077   /// Called on well-formed 'simd' clause.
12078   OMPClause *ActOnOpenMPSIMDClause(SourceLocation StartLoc,
12079                                    SourceLocation EndLoc);
12080   /// Called on well-formed 'nogroup' clause.
12081   OMPClause *ActOnOpenMPNogroupClause(SourceLocation StartLoc,
12082                                       SourceLocation EndLoc);
12083   /// Called on well-formed 'unified_address' clause.
12084   OMPClause *ActOnOpenMPUnifiedAddressClause(SourceLocation StartLoc,
12085                                              SourceLocation EndLoc);
12086 
12087   /// Called on well-formed 'unified_address' clause.
12088   OMPClause *ActOnOpenMPUnifiedSharedMemoryClause(SourceLocation StartLoc,
12089                                                   SourceLocation EndLoc);
12090 
12091   /// Called on well-formed 'reverse_offload' clause.
12092   OMPClause *ActOnOpenMPReverseOffloadClause(SourceLocation StartLoc,
12093                                              SourceLocation EndLoc);
12094 
12095   /// Called on well-formed 'dynamic_allocators' clause.
12096   OMPClause *ActOnOpenMPDynamicAllocatorsClause(SourceLocation StartLoc,
12097                                                 SourceLocation EndLoc);
12098 
12099   /// Called on well-formed 'atomic_default_mem_order' clause.
12100   OMPClause *ActOnOpenMPAtomicDefaultMemOrderClause(
12101       OpenMPAtomicDefaultMemOrderClauseKind Kind, SourceLocation KindLoc,
12102       SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc);
12103 
12104   /// Called on well-formed 'at' clause.
12105   OMPClause *ActOnOpenMPAtClause(OpenMPAtClauseKind Kind,
12106                                  SourceLocation KindLoc,
12107                                  SourceLocation StartLoc,
12108                                  SourceLocation LParenLoc,
12109                                  SourceLocation EndLoc);
12110 
12111   /// Called on well-formed 'severity' clause.
12112   OMPClause *ActOnOpenMPSeverityClause(OpenMPSeverityClauseKind Kind,
12113                                        SourceLocation KindLoc,
12114                                        SourceLocation StartLoc,
12115                                        SourceLocation LParenLoc,
12116                                        SourceLocation EndLoc);
12117 
12118   /// Called on well-formed 'message' clause.
12119   /// passing string for message.
12120   OMPClause *ActOnOpenMPMessageClause(Expr *MS, SourceLocation StartLoc,
12121                                       SourceLocation LParenLoc,
12122                                       SourceLocation EndLoc);
12123 
12124   /// Data used for processing a list of variables in OpenMP clauses.
12125   struct OpenMPVarListDataTy final {
12126     Expr *DepModOrTailExpr = nullptr;
12127     Expr *IteratorExpr = nullptr;
12128     SourceLocation ColonLoc;
12129     SourceLocation RLoc;
12130     CXXScopeSpec ReductionOrMapperIdScopeSpec;
12131     DeclarationNameInfo ReductionOrMapperId;
12132     int ExtraModifier = -1; ///< Additional modifier for linear, map, depend or
12133                             ///< lastprivate clause.
12134     SmallVector<OpenMPMapModifierKind, NumberOfOMPMapClauseModifiers>
12135         MapTypeModifiers;
12136     SmallVector<SourceLocation, NumberOfOMPMapClauseModifiers>
12137         MapTypeModifiersLoc;
12138     SmallVector<OpenMPMotionModifierKind, NumberOfOMPMotionModifiers>
12139         MotionModifiers;
12140     SmallVector<SourceLocation, NumberOfOMPMotionModifiers> MotionModifiersLoc;
12141     bool IsMapTypeImplicit = false;
12142     SourceLocation ExtraModifierLoc;
12143     SourceLocation OmpAllMemoryLoc;
12144   };
12145 
12146   OMPClause *ActOnOpenMPVarListClause(OpenMPClauseKind Kind,
12147                                       ArrayRef<Expr *> Vars,
12148                                       const OMPVarListLocTy &Locs,
12149                                       OpenMPVarListDataTy &Data);
12150   /// Called on well-formed 'inclusive' clause.
12151   OMPClause *ActOnOpenMPInclusiveClause(ArrayRef<Expr *> VarList,
12152                                         SourceLocation StartLoc,
12153                                         SourceLocation LParenLoc,
12154                                         SourceLocation EndLoc);
12155   /// Called on well-formed 'exclusive' clause.
12156   OMPClause *ActOnOpenMPExclusiveClause(ArrayRef<Expr *> VarList,
12157                                         SourceLocation StartLoc,
12158                                         SourceLocation LParenLoc,
12159                                         SourceLocation EndLoc);
12160   /// Called on well-formed 'allocate' clause.
12161   OMPClause *
12162   ActOnOpenMPAllocateClause(Expr *Allocator, ArrayRef<Expr *> VarList,
12163                             SourceLocation StartLoc, SourceLocation ColonLoc,
12164                             SourceLocation LParenLoc, SourceLocation EndLoc);
12165   /// Called on well-formed 'private' clause.
12166   OMPClause *ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList,
12167                                       SourceLocation StartLoc,
12168                                       SourceLocation LParenLoc,
12169                                       SourceLocation EndLoc);
12170   /// Called on well-formed 'firstprivate' clause.
12171   OMPClause *ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList,
12172                                            SourceLocation StartLoc,
12173                                            SourceLocation LParenLoc,
12174                                            SourceLocation EndLoc);
12175   /// Called on well-formed 'lastprivate' clause.
12176   OMPClause *ActOnOpenMPLastprivateClause(
12177       ArrayRef<Expr *> VarList, OpenMPLastprivateModifier LPKind,
12178       SourceLocation LPKindLoc, SourceLocation ColonLoc,
12179       SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc);
12180   /// Called on well-formed 'shared' clause.
12181   OMPClause *ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList,
12182                                      SourceLocation StartLoc,
12183                                      SourceLocation LParenLoc,
12184                                      SourceLocation EndLoc);
12185   /// Called on well-formed 'reduction' clause.
12186   OMPClause *ActOnOpenMPReductionClause(
12187       ArrayRef<Expr *> VarList, OpenMPReductionClauseModifier Modifier,
12188       SourceLocation StartLoc, SourceLocation LParenLoc,
12189       SourceLocation ModifierLoc, SourceLocation ColonLoc,
12190       SourceLocation EndLoc, CXXScopeSpec &ReductionIdScopeSpec,
12191       const DeclarationNameInfo &ReductionId,
12192       ArrayRef<Expr *> UnresolvedReductions = std::nullopt);
12193   /// Called on well-formed 'task_reduction' clause.
12194   OMPClause *ActOnOpenMPTaskReductionClause(
12195       ArrayRef<Expr *> VarList, SourceLocation StartLoc,
12196       SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc,
12197       CXXScopeSpec &ReductionIdScopeSpec,
12198       const DeclarationNameInfo &ReductionId,
12199       ArrayRef<Expr *> UnresolvedReductions = std::nullopt);
12200   /// Called on well-formed 'in_reduction' clause.
12201   OMPClause *ActOnOpenMPInReductionClause(
12202       ArrayRef<Expr *> VarList, SourceLocation StartLoc,
12203       SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc,
12204       CXXScopeSpec &ReductionIdScopeSpec,
12205       const DeclarationNameInfo &ReductionId,
12206       ArrayRef<Expr *> UnresolvedReductions = std::nullopt);
12207   /// Called on well-formed 'linear' clause.
12208   OMPClause *
12209   ActOnOpenMPLinearClause(ArrayRef<Expr *> VarList, Expr *Step,
12210                           SourceLocation StartLoc, SourceLocation LParenLoc,
12211                           OpenMPLinearClauseKind LinKind, SourceLocation LinLoc,
12212                           SourceLocation ColonLoc, SourceLocation EndLoc);
12213   /// Called on well-formed 'aligned' clause.
12214   OMPClause *ActOnOpenMPAlignedClause(ArrayRef<Expr *> VarList,
12215                                       Expr *Alignment,
12216                                       SourceLocation StartLoc,
12217                                       SourceLocation LParenLoc,
12218                                       SourceLocation ColonLoc,
12219                                       SourceLocation EndLoc);
12220   /// Called on well-formed 'copyin' clause.
12221   OMPClause *ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList,
12222                                      SourceLocation StartLoc,
12223                                      SourceLocation LParenLoc,
12224                                      SourceLocation EndLoc);
12225   /// Called on well-formed 'copyprivate' clause.
12226   OMPClause *ActOnOpenMPCopyprivateClause(ArrayRef<Expr *> VarList,
12227                                           SourceLocation StartLoc,
12228                                           SourceLocation LParenLoc,
12229                                           SourceLocation EndLoc);
12230   /// Called on well-formed 'flush' pseudo clause.
12231   OMPClause *ActOnOpenMPFlushClause(ArrayRef<Expr *> VarList,
12232                                     SourceLocation StartLoc,
12233                                     SourceLocation LParenLoc,
12234                                     SourceLocation EndLoc);
12235   /// Called on well-formed 'depobj' pseudo clause.
12236   OMPClause *ActOnOpenMPDepobjClause(Expr *Depobj, SourceLocation StartLoc,
12237                                      SourceLocation LParenLoc,
12238                                      SourceLocation EndLoc);
12239   /// Called on well-formed 'depend' clause.
12240   OMPClause *ActOnOpenMPDependClause(const OMPDependClause::DependDataTy &Data,
12241                                      Expr *DepModifier,
12242                                      ArrayRef<Expr *> VarList,
12243                                      SourceLocation StartLoc,
12244                                      SourceLocation LParenLoc,
12245                                      SourceLocation EndLoc);
12246   /// Called on well-formed 'device' clause.
12247   OMPClause *ActOnOpenMPDeviceClause(OpenMPDeviceClauseModifier Modifier,
12248                                      Expr *Device, SourceLocation StartLoc,
12249                                      SourceLocation LParenLoc,
12250                                      SourceLocation ModifierLoc,
12251                                      SourceLocation EndLoc);
12252   /// Called on well-formed 'map' clause.
12253   OMPClause *ActOnOpenMPMapClause(
12254       Expr *IteratorModifier, ArrayRef<OpenMPMapModifierKind> MapTypeModifiers,
12255       ArrayRef<SourceLocation> MapTypeModifiersLoc,
12256       CXXScopeSpec &MapperIdScopeSpec, DeclarationNameInfo &MapperId,
12257       OpenMPMapClauseKind MapType, bool IsMapTypeImplicit,
12258       SourceLocation MapLoc, SourceLocation ColonLoc, ArrayRef<Expr *> VarList,
12259       const OMPVarListLocTy &Locs, bool NoDiagnose = false,
12260       ArrayRef<Expr *> UnresolvedMappers = std::nullopt);
12261   /// Called on well-formed 'num_teams' clause.
12262   OMPClause *ActOnOpenMPNumTeamsClause(Expr *NumTeams, SourceLocation StartLoc,
12263                                        SourceLocation LParenLoc,
12264                                        SourceLocation EndLoc);
12265   /// Called on well-formed 'thread_limit' clause.
12266   OMPClause *ActOnOpenMPThreadLimitClause(Expr *ThreadLimit,
12267                                           SourceLocation StartLoc,
12268                                           SourceLocation LParenLoc,
12269                                           SourceLocation EndLoc);
12270   /// Called on well-formed 'priority' clause.
12271   OMPClause *ActOnOpenMPPriorityClause(Expr *Priority, SourceLocation StartLoc,
12272                                        SourceLocation LParenLoc,
12273                                        SourceLocation EndLoc);
12274   /// Called on well-formed 'dist_schedule' clause.
12275   OMPClause *ActOnOpenMPDistScheduleClause(
12276       OpenMPDistScheduleClauseKind Kind, Expr *ChunkSize,
12277       SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation KindLoc,
12278       SourceLocation CommaLoc, SourceLocation EndLoc);
12279   /// Called on well-formed 'defaultmap' clause.
12280   OMPClause *ActOnOpenMPDefaultmapClause(
12281       OpenMPDefaultmapClauseModifier M, OpenMPDefaultmapClauseKind Kind,
12282       SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation MLoc,
12283       SourceLocation KindLoc, SourceLocation EndLoc);
12284   /// Called on well-formed 'to' clause.
12285   OMPClause *
12286   ActOnOpenMPToClause(ArrayRef<OpenMPMotionModifierKind> MotionModifiers,
12287                       ArrayRef<SourceLocation> MotionModifiersLoc,
12288                       CXXScopeSpec &MapperIdScopeSpec,
12289                       DeclarationNameInfo &MapperId, SourceLocation ColonLoc,
12290                       ArrayRef<Expr *> VarList, const OMPVarListLocTy &Locs,
12291                       ArrayRef<Expr *> UnresolvedMappers = std::nullopt);
12292   /// Called on well-formed 'from' clause.
12293   OMPClause *
12294   ActOnOpenMPFromClause(ArrayRef<OpenMPMotionModifierKind> MotionModifiers,
12295                         ArrayRef<SourceLocation> MotionModifiersLoc,
12296                         CXXScopeSpec &MapperIdScopeSpec,
12297                         DeclarationNameInfo &MapperId, SourceLocation ColonLoc,
12298                         ArrayRef<Expr *> VarList, const OMPVarListLocTy &Locs,
12299                         ArrayRef<Expr *> UnresolvedMappers = std::nullopt);
12300   /// Called on well-formed 'use_device_ptr' clause.
12301   OMPClause *ActOnOpenMPUseDevicePtrClause(ArrayRef<Expr *> VarList,
12302                                            const OMPVarListLocTy &Locs);
12303   /// Called on well-formed 'use_device_addr' clause.
12304   OMPClause *ActOnOpenMPUseDeviceAddrClause(ArrayRef<Expr *> VarList,
12305                                             const OMPVarListLocTy &Locs);
12306   /// Called on well-formed 'is_device_ptr' clause.
12307   OMPClause *ActOnOpenMPIsDevicePtrClause(ArrayRef<Expr *> VarList,
12308                                           const OMPVarListLocTy &Locs);
12309   /// Called on well-formed 'has_device_addr' clause.
12310   OMPClause *ActOnOpenMPHasDeviceAddrClause(ArrayRef<Expr *> VarList,
12311                                             const OMPVarListLocTy &Locs);
12312   /// Called on well-formed 'nontemporal' clause.
12313   OMPClause *ActOnOpenMPNontemporalClause(ArrayRef<Expr *> VarList,
12314                                           SourceLocation StartLoc,
12315                                           SourceLocation LParenLoc,
12316                                           SourceLocation EndLoc);
12317 
12318   /// Data for list of allocators.
12319   struct UsesAllocatorsData {
12320     /// Allocator.
12321     Expr *Allocator = nullptr;
12322     /// Allocator traits.
12323     Expr *AllocatorTraits = nullptr;
12324     /// Locations of '(' and ')' symbols.
12325     SourceLocation LParenLoc, RParenLoc;
12326   };
12327   /// Called on well-formed 'uses_allocators' clause.
12328   OMPClause *ActOnOpenMPUsesAllocatorClause(SourceLocation StartLoc,
12329                                             SourceLocation LParenLoc,
12330                                             SourceLocation EndLoc,
12331                                             ArrayRef<UsesAllocatorsData> Data);
12332   /// Called on well-formed 'affinity' clause.
12333   OMPClause *ActOnOpenMPAffinityClause(SourceLocation StartLoc,
12334                                        SourceLocation LParenLoc,
12335                                        SourceLocation ColonLoc,
12336                                        SourceLocation EndLoc, Expr *Modifier,
12337                                        ArrayRef<Expr *> Locators);
12338   /// Called on a well-formed 'bind' clause.
12339   OMPClause *ActOnOpenMPBindClause(OpenMPBindClauseKind Kind,
12340                                    SourceLocation KindLoc,
12341                                    SourceLocation StartLoc,
12342                                    SourceLocation LParenLoc,
12343                                    SourceLocation EndLoc);
12344 
12345   /// Called on a well-formed 'ompx_dyn_cgroup_mem' clause.
12346   OMPClause *ActOnOpenMPXDynCGroupMemClause(Expr *Size, SourceLocation StartLoc,
12347                                             SourceLocation LParenLoc,
12348                                             SourceLocation EndLoc);
12349 
12350   /// Called on well-formed 'doacross' clause.
12351   OMPClause *
12352   ActOnOpenMPDoacrossClause(OpenMPDoacrossClauseModifier DepType,
12353                             SourceLocation DepLoc, SourceLocation ColonLoc,
12354                             ArrayRef<Expr *> VarList, SourceLocation StartLoc,
12355                             SourceLocation LParenLoc, SourceLocation EndLoc);
12356 
12357   /// The kind of conversion being performed.
12358   enum CheckedConversionKind {
12359     /// An implicit conversion.
12360     CCK_ImplicitConversion,
12361     /// A C-style cast.
12362     CCK_CStyleCast,
12363     /// A functional-style cast.
12364     CCK_FunctionalCast,
12365     /// A cast other than a C-style cast.
12366     CCK_OtherCast,
12367     /// A conversion for an operand of a builtin overloaded operator.
12368     CCK_ForBuiltinOverloadedOp
12369   };
12370 
12371   static bool isCast(CheckedConversionKind CCK) {
12372     return CCK == CCK_CStyleCast || CCK == CCK_FunctionalCast ||
12373            CCK == CCK_OtherCast;
12374   }
12375 
12376   /// ImpCastExprToType - If Expr is not of type 'Type', insert an implicit
12377   /// cast.  If there is already an implicit cast, merge into the existing one.
12378   /// If isLvalue, the result of the cast is an lvalue.
12379   ExprResult
12380   ImpCastExprToType(Expr *E, QualType Type, CastKind CK,
12381                     ExprValueKind VK = VK_PRValue,
12382                     const CXXCastPath *BasePath = nullptr,
12383                     CheckedConversionKind CCK = CCK_ImplicitConversion);
12384 
12385   /// ScalarTypeToBooleanCastKind - Returns the cast kind corresponding
12386   /// to the conversion from scalar type ScalarTy to the Boolean type.
12387   static CastKind ScalarTypeToBooleanCastKind(QualType ScalarTy);
12388 
12389   /// IgnoredValueConversions - Given that an expression's result is
12390   /// syntactically ignored, perform any conversions that are
12391   /// required.
12392   ExprResult IgnoredValueConversions(Expr *E);
12393 
12394   // UsualUnaryConversions - promotes integers (C99 6.3.1.1p2) and converts
12395   // functions and arrays to their respective pointers (C99 6.3.2.1).
12396   ExprResult UsualUnaryConversions(Expr *E);
12397 
12398   /// CallExprUnaryConversions - a special case of an unary conversion
12399   /// performed on a function designator of a call expression.
12400   ExprResult CallExprUnaryConversions(Expr *E);
12401 
12402   // DefaultFunctionArrayConversion - converts functions and arrays
12403   // to their respective pointers (C99 6.3.2.1).
12404   ExprResult DefaultFunctionArrayConversion(Expr *E, bool Diagnose = true);
12405 
12406   // DefaultFunctionArrayLvalueConversion - converts functions and
12407   // arrays to their respective pointers and performs the
12408   // lvalue-to-rvalue conversion.
12409   ExprResult DefaultFunctionArrayLvalueConversion(Expr *E,
12410                                                   bool Diagnose = true);
12411 
12412   // DefaultLvalueConversion - performs lvalue-to-rvalue conversion on
12413   // the operand. This function is a no-op if the operand has a function type
12414   // or an array type.
12415   ExprResult DefaultLvalueConversion(Expr *E);
12416 
12417   // DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
12418   // do not have a prototype. Integer promotions are performed on each
12419   // argument, and arguments that have type float are promoted to double.
12420   ExprResult DefaultArgumentPromotion(Expr *E);
12421 
12422   /// If \p E is a prvalue denoting an unmaterialized temporary, materialize
12423   /// it as an xvalue. In C++98, the result will still be a prvalue, because
12424   /// we don't have xvalues there.
12425   ExprResult TemporaryMaterializationConversion(Expr *E);
12426 
12427   // Used for emitting the right warning by DefaultVariadicArgumentPromotion
12428   enum VariadicCallType {
12429     VariadicFunction,
12430     VariadicBlock,
12431     VariadicMethod,
12432     VariadicConstructor,
12433     VariadicDoesNotApply
12434   };
12435 
12436   VariadicCallType getVariadicCallType(FunctionDecl *FDecl,
12437                                        const FunctionProtoType *Proto,
12438                                        Expr *Fn);
12439 
12440   // Used for determining in which context a type is allowed to be passed to a
12441   // vararg function.
12442   enum VarArgKind {
12443     VAK_Valid,
12444     VAK_ValidInCXX11,
12445     VAK_Undefined,
12446     VAK_MSVCUndefined,
12447     VAK_Invalid
12448   };
12449 
12450   // Determines which VarArgKind fits an expression.
12451   VarArgKind isValidVarArgType(const QualType &Ty);
12452 
12453   /// Check to see if the given expression is a valid argument to a variadic
12454   /// function, issuing a diagnostic if not.
12455   void checkVariadicArgument(const Expr *E, VariadicCallType CT);
12456 
12457   /// Check whether the given statement can have musttail applied to it,
12458   /// issuing a diagnostic and returning false if not. In the success case,
12459   /// the statement is rewritten to remove implicit nodes from the return
12460   /// value.
12461   bool checkAndRewriteMustTailAttr(Stmt *St, const Attr &MTA);
12462 
12463 private:
12464   /// Check whether the given statement can have musttail applied to it,
12465   /// issuing a diagnostic and returning false if not.
12466   bool checkMustTailAttr(const Stmt *St, const Attr &MTA);
12467 
12468 public:
12469   /// Check to see if a given expression could have '.c_str()' called on it.
12470   bool hasCStrMethod(const Expr *E);
12471 
12472   /// GatherArgumentsForCall - Collector argument expressions for various
12473   /// form of call prototypes.
12474   bool GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl,
12475                               const FunctionProtoType *Proto,
12476                               unsigned FirstParam, ArrayRef<Expr *> Args,
12477                               SmallVectorImpl<Expr *> &AllArgs,
12478                               VariadicCallType CallType = VariadicDoesNotApply,
12479                               bool AllowExplicit = false,
12480                               bool IsListInitialization = false);
12481 
12482   // DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
12483   // will create a runtime trap if the resulting type is not a POD type.
12484   ExprResult DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
12485                                               FunctionDecl *FDecl);
12486 
12487   /// Context in which we're performing a usual arithmetic conversion.
12488   enum ArithConvKind {
12489     /// An arithmetic operation.
12490     ACK_Arithmetic,
12491     /// A bitwise operation.
12492     ACK_BitwiseOp,
12493     /// A comparison.
12494     ACK_Comparison,
12495     /// A conditional (?:) operator.
12496     ACK_Conditional,
12497     /// A compound assignment expression.
12498     ACK_CompAssign,
12499   };
12500 
12501   // UsualArithmeticConversions - performs the UsualUnaryConversions on it's
12502   // operands and then handles various conversions that are common to binary
12503   // operators (C99 6.3.1.8). If both operands aren't arithmetic, this
12504   // routine returns the first non-arithmetic type found. The client is
12505   // responsible for emitting appropriate error diagnostics.
12506   QualType UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
12507                                       SourceLocation Loc, ArithConvKind ACK);
12508 
12509   /// AssignConvertType - All of the 'assignment' semantic checks return this
12510   /// enum to indicate whether the assignment was allowed.  These checks are
12511   /// done for simple assignments, as well as initialization, return from
12512   /// function, argument passing, etc.  The query is phrased in terms of a
12513   /// source and destination type.
12514   enum AssignConvertType {
12515     /// Compatible - the types are compatible according to the standard.
12516     Compatible,
12517 
12518     /// PointerToInt - The assignment converts a pointer to an int, which we
12519     /// accept as an extension.
12520     PointerToInt,
12521 
12522     /// IntToPointer - The assignment converts an int to a pointer, which we
12523     /// accept as an extension.
12524     IntToPointer,
12525 
12526     /// FunctionVoidPointer - The assignment is between a function pointer and
12527     /// void*, which the standard doesn't allow, but we accept as an extension.
12528     FunctionVoidPointer,
12529 
12530     /// IncompatiblePointer - The assignment is between two pointers types that
12531     /// are not compatible, but we accept them as an extension.
12532     IncompatiblePointer,
12533 
12534     /// IncompatibleFunctionPointer - The assignment is between two function
12535     /// pointers types that are not compatible, but we accept them as an
12536     /// extension.
12537     IncompatibleFunctionPointer,
12538 
12539     /// IncompatibleFunctionPointerStrict - The assignment is between two
12540     /// function pointer types that are not identical, but are compatible,
12541     /// unless compiled with -fsanitize=cfi, in which case the type mismatch
12542     /// may trip an indirect call runtime check.
12543     IncompatibleFunctionPointerStrict,
12544 
12545     /// IncompatiblePointerSign - The assignment is between two pointers types
12546     /// which point to integers which have a different sign, but are otherwise
12547     /// identical. This is a subset of the above, but broken out because it's by
12548     /// far the most common case of incompatible pointers.
12549     IncompatiblePointerSign,
12550 
12551     /// CompatiblePointerDiscardsQualifiers - The assignment discards
12552     /// c/v/r qualifiers, which we accept as an extension.
12553     CompatiblePointerDiscardsQualifiers,
12554 
12555     /// IncompatiblePointerDiscardsQualifiers - The assignment
12556     /// discards qualifiers that we don't permit to be discarded,
12557     /// like address spaces.
12558     IncompatiblePointerDiscardsQualifiers,
12559 
12560     /// IncompatibleNestedPointerAddressSpaceMismatch - The assignment
12561     /// changes address spaces in nested pointer types which is not allowed.
12562     /// For instance, converting __private int ** to __generic int ** is
12563     /// illegal even though __private could be converted to __generic.
12564     IncompatibleNestedPointerAddressSpaceMismatch,
12565 
12566     /// IncompatibleNestedPointerQualifiers - The assignment is between two
12567     /// nested pointer types, and the qualifiers other than the first two
12568     /// levels differ e.g. char ** -> const char **, but we accept them as an
12569     /// extension.
12570     IncompatibleNestedPointerQualifiers,
12571 
12572     /// IncompatibleVectors - The assignment is between two vector types that
12573     /// have the same size, which we accept as an extension.
12574     IncompatibleVectors,
12575 
12576     /// IntToBlockPointer - The assignment converts an int to a block
12577     /// pointer. We disallow this.
12578     IntToBlockPointer,
12579 
12580     /// IncompatibleBlockPointer - The assignment is between two block
12581     /// pointers types that are not compatible.
12582     IncompatibleBlockPointer,
12583 
12584     /// IncompatibleObjCQualifiedId - The assignment is between a qualified
12585     /// id type and something else (that is incompatible with it). For example,
12586     /// "id <XXX>" = "Foo *", where "Foo *" doesn't implement the XXX protocol.
12587     IncompatibleObjCQualifiedId,
12588 
12589     /// IncompatibleObjCWeakRef - Assigning a weak-unavailable object to an
12590     /// object with __weak qualifier.
12591     IncompatibleObjCWeakRef,
12592 
12593     /// Incompatible - We reject this conversion outright, it is invalid to
12594     /// represent it in the AST.
12595     Incompatible
12596   };
12597 
12598   /// DiagnoseAssignmentResult - Emit a diagnostic, if required, for the
12599   /// assignment conversion type specified by ConvTy.  This returns true if the
12600   /// conversion was invalid or false if the conversion was accepted.
12601   bool DiagnoseAssignmentResult(AssignConvertType ConvTy,
12602                                 SourceLocation Loc,
12603                                 QualType DstType, QualType SrcType,
12604                                 Expr *SrcExpr, AssignmentAction Action,
12605                                 bool *Complained = nullptr);
12606 
12607   /// IsValueInFlagEnum - Determine if a value is allowed as part of a flag
12608   /// enum. If AllowMask is true, then we also allow the complement of a valid
12609   /// value, to be used as a mask.
12610   bool IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
12611                          bool AllowMask) const;
12612 
12613   /// DiagnoseAssignmentEnum - Warn if assignment to enum is a constant
12614   /// integer not in the range of enum values.
12615   void DiagnoseAssignmentEnum(QualType DstType, QualType SrcType,
12616                               Expr *SrcExpr);
12617 
12618   /// CheckAssignmentConstraints - Perform type checking for assignment,
12619   /// argument passing, variable initialization, and function return values.
12620   /// C99 6.5.16.
12621   AssignConvertType CheckAssignmentConstraints(SourceLocation Loc,
12622                                                QualType LHSType,
12623                                                QualType RHSType);
12624 
12625   /// Check assignment constraints and optionally prepare for a conversion of
12626   /// the RHS to the LHS type. The conversion is prepared for if ConvertRHS
12627   /// is true.
12628   AssignConvertType CheckAssignmentConstraints(QualType LHSType,
12629                                                ExprResult &RHS,
12630                                                CastKind &Kind,
12631                                                bool ConvertRHS = true);
12632 
12633   /// Check assignment constraints for an assignment of RHS to LHSType.
12634   ///
12635   /// \param LHSType The destination type for the assignment.
12636   /// \param RHS The source expression for the assignment.
12637   /// \param Diagnose If \c true, diagnostics may be produced when checking
12638   ///        for assignability. If a diagnostic is produced, \p RHS will be
12639   ///        set to ExprError(). Note that this function may still return
12640   ///        without producing a diagnostic, even for an invalid assignment.
12641   /// \param DiagnoseCFAudited If \c true, the target is a function parameter
12642   ///        in an audited Core Foundation API and does not need to be checked
12643   ///        for ARC retain issues.
12644   /// \param ConvertRHS If \c true, \p RHS will be updated to model the
12645   ///        conversions necessary to perform the assignment. If \c false,
12646   ///        \p Diagnose must also be \c false.
12647   AssignConvertType CheckSingleAssignmentConstraints(
12648       QualType LHSType, ExprResult &RHS, bool Diagnose = true,
12649       bool DiagnoseCFAudited = false, bool ConvertRHS = true);
12650 
12651   // If the lhs type is a transparent union, check whether we
12652   // can initialize the transparent union with the given expression.
12653   AssignConvertType CheckTransparentUnionArgumentConstraints(QualType ArgType,
12654                                                              ExprResult &RHS);
12655 
12656   bool IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType);
12657 
12658   bool CheckExceptionSpecCompatibility(Expr *From, QualType ToType);
12659 
12660   ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
12661                                        AssignmentAction Action,
12662                                        bool AllowExplicit = false);
12663   ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
12664                                        const ImplicitConversionSequence& ICS,
12665                                        AssignmentAction Action,
12666                                        CheckedConversionKind CCK
12667                                           = CCK_ImplicitConversion);
12668   ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
12669                                        const StandardConversionSequence& SCS,
12670                                        AssignmentAction Action,
12671                                        CheckedConversionKind CCK);
12672 
12673   ExprResult PerformQualificationConversion(
12674       Expr *E, QualType Ty, ExprValueKind VK = VK_PRValue,
12675       CheckedConversionKind CCK = CCK_ImplicitConversion);
12676 
12677   /// the following "Check" methods will return a valid/converted QualType
12678   /// or a null QualType (indicating an error diagnostic was issued).
12679 
12680   /// type checking binary operators (subroutines of CreateBuiltinBinOp).
12681   QualType InvalidOperands(SourceLocation Loc, ExprResult &LHS,
12682                            ExprResult &RHS);
12683   QualType InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS,
12684                                  ExprResult &RHS);
12685   QualType CheckPointerToMemberOperands( // C++ 5.5
12686     ExprResult &LHS, ExprResult &RHS, ExprValueKind &VK,
12687     SourceLocation OpLoc, bool isIndirect);
12688   QualType CheckMultiplyDivideOperands( // C99 6.5.5
12689     ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign,
12690     bool IsDivide);
12691   QualType CheckRemainderOperands( // C99 6.5.5
12692     ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
12693     bool IsCompAssign = false);
12694   QualType CheckAdditionOperands( // C99 6.5.6
12695     ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
12696     BinaryOperatorKind Opc, QualType* CompLHSTy = nullptr);
12697   QualType CheckSubtractionOperands( // C99 6.5.6
12698     ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
12699     QualType* CompLHSTy = nullptr);
12700   QualType CheckShiftOperands( // C99 6.5.7
12701     ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
12702     BinaryOperatorKind Opc, bool IsCompAssign = false);
12703   void CheckPtrComparisonWithNullChar(ExprResult &E, ExprResult &NullE);
12704   QualType CheckCompareOperands( // C99 6.5.8/9
12705       ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
12706       BinaryOperatorKind Opc);
12707   QualType CheckBitwiseOperands( // C99 6.5.[10...12]
12708       ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
12709       BinaryOperatorKind Opc);
12710   QualType CheckLogicalOperands( // C99 6.5.[13,14]
12711     ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
12712     BinaryOperatorKind Opc);
12713   // CheckAssignmentOperands is used for both simple and compound assignment.
12714   // For simple assignment, pass both expressions and a null converted type.
12715   // For compound assignment, pass both expressions and the converted type.
12716   QualType CheckAssignmentOperands( // C99 6.5.16.[1,2]
12717       Expr *LHSExpr, ExprResult &RHS, SourceLocation Loc, QualType CompoundType,
12718       BinaryOperatorKind Opc);
12719 
12720   ExprResult checkPseudoObjectIncDec(Scope *S, SourceLocation OpLoc,
12721                                      UnaryOperatorKind Opcode, Expr *Op);
12722   ExprResult checkPseudoObjectAssignment(Scope *S, SourceLocation OpLoc,
12723                                          BinaryOperatorKind Opcode,
12724                                          Expr *LHS, Expr *RHS);
12725   ExprResult checkPseudoObjectRValue(Expr *E);
12726   Expr *recreateSyntacticForm(PseudoObjectExpr *E);
12727 
12728   QualType CheckConditionalOperands( // C99 6.5.15
12729     ExprResult &Cond, ExprResult &LHS, ExprResult &RHS,
12730     ExprValueKind &VK, ExprObjectKind &OK, SourceLocation QuestionLoc);
12731   QualType CXXCheckConditionalOperands( // C++ 5.16
12732     ExprResult &cond, ExprResult &lhs, ExprResult &rhs,
12733     ExprValueKind &VK, ExprObjectKind &OK, SourceLocation questionLoc);
12734   QualType CheckVectorConditionalTypes(ExprResult &Cond, ExprResult &LHS,
12735                                        ExprResult &RHS,
12736                                        SourceLocation QuestionLoc);
12737 
12738   QualType CheckSizelessVectorConditionalTypes(ExprResult &Cond,
12739                                                ExprResult &LHS, ExprResult &RHS,
12740                                                SourceLocation QuestionLoc);
12741   QualType FindCompositePointerType(SourceLocation Loc, Expr *&E1, Expr *&E2,
12742                                     bool ConvertArgs = true);
12743   QualType FindCompositePointerType(SourceLocation Loc,
12744                                     ExprResult &E1, ExprResult &E2,
12745                                     bool ConvertArgs = true) {
12746     Expr *E1Tmp = E1.get(), *E2Tmp = E2.get();
12747     QualType Composite =
12748         FindCompositePointerType(Loc, E1Tmp, E2Tmp, ConvertArgs);
12749     E1 = E1Tmp;
12750     E2 = E2Tmp;
12751     return Composite;
12752   }
12753 
12754   QualType FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
12755                                         SourceLocation QuestionLoc);
12756 
12757   bool DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
12758                                   SourceLocation QuestionLoc);
12759 
12760   void DiagnoseAlwaysNonNullPointer(Expr *E,
12761                                     Expr::NullPointerConstantKind NullType,
12762                                     bool IsEqual, SourceRange Range);
12763 
12764   /// type checking for vector binary operators.
12765   QualType CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
12766                                SourceLocation Loc, bool IsCompAssign,
12767                                bool AllowBothBool, bool AllowBoolConversion,
12768                                bool AllowBoolOperation, bool ReportInvalid);
12769   QualType GetSignedVectorType(QualType V);
12770   QualType GetSignedSizelessVectorType(QualType V);
12771   QualType CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
12772                                       SourceLocation Loc,
12773                                       BinaryOperatorKind Opc);
12774   QualType CheckSizelessVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
12775                                               SourceLocation Loc,
12776                                               BinaryOperatorKind Opc);
12777   QualType CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
12778                                       SourceLocation Loc);
12779 
12780   // type checking for sizeless vector binary operators.
12781   QualType CheckSizelessVectorOperands(ExprResult &LHS, ExprResult &RHS,
12782                                        SourceLocation Loc, bool IsCompAssign,
12783                                        ArithConvKind OperationKind);
12784 
12785   /// Type checking for matrix binary operators.
12786   QualType CheckMatrixElementwiseOperands(ExprResult &LHS, ExprResult &RHS,
12787                                           SourceLocation Loc,
12788                                           bool IsCompAssign);
12789   QualType CheckMatrixMultiplyOperands(ExprResult &LHS, ExprResult &RHS,
12790                                        SourceLocation Loc, bool IsCompAssign);
12791 
12792   bool isValidSveBitcast(QualType srcType, QualType destType);
12793   bool isValidRVVBitcast(QualType srcType, QualType destType);
12794 
12795   bool areMatrixTypesOfTheSameDimension(QualType srcTy, QualType destTy);
12796 
12797   bool areVectorTypesSameSize(QualType srcType, QualType destType);
12798   bool areLaxCompatibleVectorTypes(QualType srcType, QualType destType);
12799   bool isLaxVectorConversion(QualType srcType, QualType destType);
12800   bool anyAltivecTypes(QualType srcType, QualType destType);
12801 
12802   /// type checking declaration initializers (C99 6.7.8)
12803   bool CheckForConstantInitializer(Expr *e, QualType t);
12804 
12805   // type checking C++ declaration initializers (C++ [dcl.init]).
12806 
12807   /// ReferenceCompareResult - Expresses the result of comparing two
12808   /// types (cv1 T1 and cv2 T2) to determine their compatibility for the
12809   /// purposes of initialization by reference (C++ [dcl.init.ref]p4).
12810   enum ReferenceCompareResult {
12811     /// Ref_Incompatible - The two types are incompatible, so direct
12812     /// reference binding is not possible.
12813     Ref_Incompatible = 0,
12814     /// Ref_Related - The two types are reference-related, which means
12815     /// that their unqualified forms (T1 and T2) are either the same
12816     /// or T1 is a base class of T2.
12817     Ref_Related,
12818     /// Ref_Compatible - The two types are reference-compatible.
12819     Ref_Compatible
12820   };
12821 
12822   // Fake up a scoped enumeration that still contextually converts to bool.
12823   struct ReferenceConversionsScope {
12824     /// The conversions that would be performed on an lvalue of type T2 when
12825     /// binding a reference of type T1 to it, as determined when evaluating
12826     /// whether T1 is reference-compatible with T2.
12827     enum ReferenceConversions {
12828       Qualification = 0x1,
12829       NestedQualification = 0x2,
12830       Function = 0x4,
12831       DerivedToBase = 0x8,
12832       ObjC = 0x10,
12833       ObjCLifetime = 0x20,
12834 
12835       LLVM_MARK_AS_BITMASK_ENUM(/*LargestValue=*/ObjCLifetime)
12836     };
12837   };
12838   using ReferenceConversions = ReferenceConversionsScope::ReferenceConversions;
12839 
12840   ReferenceCompareResult
12841   CompareReferenceRelationship(SourceLocation Loc, QualType T1, QualType T2,
12842                                ReferenceConversions *Conv = nullptr);
12843 
12844   ExprResult checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
12845                                  Expr *CastExpr, CastKind &CastKind,
12846                                  ExprValueKind &VK, CXXCastPath &Path);
12847 
12848   /// Force an expression with unknown-type to an expression of the
12849   /// given type.
12850   ExprResult forceUnknownAnyToType(Expr *E, QualType ToType);
12851 
12852   /// Type-check an expression that's being passed to an
12853   /// __unknown_anytype parameter.
12854   ExprResult checkUnknownAnyArg(SourceLocation callLoc,
12855                                 Expr *result, QualType &paramType);
12856 
12857   // CheckMatrixCast - Check type constraints for matrix casts.
12858   // We allow casting between matrixes of the same dimensions i.e. when they
12859   // have the same number of rows and column. Returns true if the cast is
12860   // invalid.
12861   bool CheckMatrixCast(SourceRange R, QualType DestTy, QualType SrcTy,
12862                        CastKind &Kind);
12863 
12864   // CheckVectorCast - check type constraints for vectors.
12865   // Since vectors are an extension, there are no C standard reference for this.
12866   // We allow casting between vectors and integer datatypes of the same size.
12867   // returns true if the cast is invalid
12868   bool CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
12869                        CastKind &Kind);
12870 
12871   /// Prepare `SplattedExpr` for a vector splat operation, adding
12872   /// implicit casts if necessary.
12873   ExprResult prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr);
12874 
12875   // CheckExtVectorCast - check type constraints for extended vectors.
12876   // Since vectors are an extension, there are no C standard reference for this.
12877   // We allow casting between vectors and integer datatypes of the same size,
12878   // or vectors and the element type of that vector.
12879   // returns the cast expr
12880   ExprResult CheckExtVectorCast(SourceRange R, QualType DestTy, Expr *CastExpr,
12881                                 CastKind &Kind);
12882 
12883   ExprResult BuildCXXFunctionalCastExpr(TypeSourceInfo *TInfo, QualType Type,
12884                                         SourceLocation LParenLoc,
12885                                         Expr *CastExpr,
12886                                         SourceLocation RParenLoc);
12887 
12888   enum ARCConversionResult { ACR_okay, ACR_unbridged, ACR_error };
12889 
12890   /// Checks for invalid conversions and casts between
12891   /// retainable pointers and other pointer kinds for ARC and Weak.
12892   ARCConversionResult CheckObjCConversion(SourceRange castRange,
12893                                           QualType castType, Expr *&op,
12894                                           CheckedConversionKind CCK,
12895                                           bool Diagnose = true,
12896                                           bool DiagnoseCFAudited = false,
12897                                           BinaryOperatorKind Opc = BO_PtrMemD
12898                                           );
12899 
12900   Expr *stripARCUnbridgedCast(Expr *e);
12901   void diagnoseARCUnbridgedCast(Expr *e);
12902 
12903   bool CheckObjCARCUnavailableWeakConversion(QualType castType,
12904                                              QualType ExprType);
12905 
12906   /// checkRetainCycles - Check whether an Objective-C message send
12907   /// might create an obvious retain cycle.
12908   void checkRetainCycles(ObjCMessageExpr *msg);
12909   void checkRetainCycles(Expr *receiver, Expr *argument);
12910   void checkRetainCycles(VarDecl *Var, Expr *Init);
12911 
12912   /// checkUnsafeAssigns - Check whether +1 expr is being assigned
12913   /// to weak/__unsafe_unretained type.
12914   bool checkUnsafeAssigns(SourceLocation Loc, QualType LHS, Expr *RHS);
12915 
12916   /// checkUnsafeExprAssigns - Check whether +1 expr is being assigned
12917   /// to weak/__unsafe_unretained expression.
12918   void checkUnsafeExprAssigns(SourceLocation Loc, Expr *LHS, Expr *RHS);
12919 
12920   /// CheckMessageArgumentTypes - Check types in an Obj-C message send.
12921   /// \param Method - May be null.
12922   /// \param [out] ReturnType - The return type of the send.
12923   /// \return true iff there were any incompatible types.
12924   bool CheckMessageArgumentTypes(const Expr *Receiver, QualType ReceiverType,
12925                                  MultiExprArg Args, Selector Sel,
12926                                  ArrayRef<SourceLocation> SelectorLocs,
12927                                  ObjCMethodDecl *Method, bool isClassMessage,
12928                                  bool isSuperMessage, SourceLocation lbrac,
12929                                  SourceLocation rbrac, SourceRange RecRange,
12930                                  QualType &ReturnType, ExprValueKind &VK);
12931 
12932   /// Determine the result of a message send expression based on
12933   /// the type of the receiver, the method expected to receive the message,
12934   /// and the form of the message send.
12935   QualType getMessageSendResultType(const Expr *Receiver, QualType ReceiverType,
12936                                     ObjCMethodDecl *Method, bool isClassMessage,
12937                                     bool isSuperMessage);
12938 
12939   /// If the given expression involves a message send to a method
12940   /// with a related result type, emit a note describing what happened.
12941   void EmitRelatedResultTypeNote(const Expr *E);
12942 
12943   /// Given that we had incompatible pointer types in a return
12944   /// statement, check whether we're in a method with a related result
12945   /// type, and if so, emit a note describing what happened.
12946   void EmitRelatedResultTypeNoteForReturn(QualType destType);
12947 
12948   class ConditionResult {
12949     Decl *ConditionVar;
12950     FullExprArg Condition;
12951     bool Invalid;
12952     std::optional<bool> KnownValue;
12953 
12954     friend class Sema;
12955     ConditionResult(Sema &S, Decl *ConditionVar, FullExprArg Condition,
12956                     bool IsConstexpr)
12957         : ConditionVar(ConditionVar), Condition(Condition), Invalid(false) {
12958       if (IsConstexpr && Condition.get()) {
12959         if (std::optional<llvm::APSInt> Val =
12960                 Condition.get()->getIntegerConstantExpr(S.Context)) {
12961           KnownValue = !!(*Val);
12962         }
12963       }
12964     }
12965     explicit ConditionResult(bool Invalid)
12966         : ConditionVar(nullptr), Condition(nullptr), Invalid(Invalid),
12967           KnownValue(std::nullopt) {}
12968 
12969   public:
12970     ConditionResult() : ConditionResult(false) {}
12971     bool isInvalid() const { return Invalid; }
12972     std::pair<VarDecl *, Expr *> get() const {
12973       return std::make_pair(cast_or_null<VarDecl>(ConditionVar),
12974                             Condition.get());
12975     }
12976     std::optional<bool> getKnownValue() const { return KnownValue; }
12977   };
12978   static ConditionResult ConditionError() { return ConditionResult(true); }
12979 
12980   enum class ConditionKind {
12981     Boolean,     ///< A boolean condition, from 'if', 'while', 'for', or 'do'.
12982     ConstexprIf, ///< A constant boolean condition from 'if constexpr'.
12983     Switch       ///< An integral condition for a 'switch' statement.
12984   };
12985   QualType PreferredConditionType(ConditionKind K) const {
12986     return K == ConditionKind::Switch ? Context.IntTy : Context.BoolTy;
12987   }
12988 
12989   ConditionResult ActOnCondition(Scope *S, SourceLocation Loc, Expr *SubExpr,
12990                                  ConditionKind CK, bool MissingOK = false);
12991 
12992   ConditionResult ActOnConditionVariable(Decl *ConditionVar,
12993                                          SourceLocation StmtLoc,
12994                                          ConditionKind CK);
12995 
12996   DeclResult ActOnCXXConditionDeclaration(Scope *S, Declarator &D);
12997 
12998   ExprResult CheckConditionVariable(VarDecl *ConditionVar,
12999                                     SourceLocation StmtLoc,
13000                                     ConditionKind CK);
13001   ExprResult CheckSwitchCondition(SourceLocation SwitchLoc, Expr *Cond);
13002 
13003   /// CheckBooleanCondition - Diagnose problems involving the use of
13004   /// the given expression as a boolean condition (e.g. in an if
13005   /// statement).  Also performs the standard function and array
13006   /// decays, possibly changing the input variable.
13007   ///
13008   /// \param Loc - A location associated with the condition, e.g. the
13009   /// 'if' keyword.
13010   /// \return true iff there were any errors
13011   ExprResult CheckBooleanCondition(SourceLocation Loc, Expr *E,
13012                                    bool IsConstexpr = false);
13013 
13014   /// ActOnExplicitBoolSpecifier - Build an ExplicitSpecifier from an expression
13015   /// found in an explicit(bool) specifier.
13016   ExplicitSpecifier ActOnExplicitBoolSpecifier(Expr *E);
13017 
13018   /// tryResolveExplicitSpecifier - Attempt to resolve the explict specifier.
13019   /// Returns true if the explicit specifier is now resolved.
13020   bool tryResolveExplicitSpecifier(ExplicitSpecifier &ExplicitSpec);
13021 
13022   /// DiagnoseAssignmentAsCondition - Given that an expression is
13023   /// being used as a boolean condition, warn if it's an assignment.
13024   void DiagnoseAssignmentAsCondition(Expr *E);
13025 
13026   /// Redundant parentheses over an equality comparison can indicate
13027   /// that the user intended an assignment used as condition.
13028   void DiagnoseEqualityWithExtraParens(ParenExpr *ParenE);
13029 
13030   /// CheckCXXBooleanCondition - Returns true if conversion to bool is invalid.
13031   ExprResult CheckCXXBooleanCondition(Expr *CondExpr, bool IsConstexpr = false);
13032 
13033   /// Checks that the Objective-C declaration is declared in the global scope.
13034   /// Emits an error and marks the declaration as invalid if it's not declared
13035   /// in the global scope.
13036   bool CheckObjCDeclScope(Decl *D);
13037 
13038   /// Abstract base class used for diagnosing integer constant
13039   /// expression violations.
13040   class VerifyICEDiagnoser {
13041   public:
13042     bool Suppress;
13043 
13044     VerifyICEDiagnoser(bool Suppress = false) : Suppress(Suppress) { }
13045 
13046     virtual SemaDiagnosticBuilder
13047     diagnoseNotICEType(Sema &S, SourceLocation Loc, QualType T);
13048     virtual SemaDiagnosticBuilder diagnoseNotICE(Sema &S,
13049                                                  SourceLocation Loc) = 0;
13050     virtual SemaDiagnosticBuilder diagnoseFold(Sema &S, SourceLocation Loc);
13051     virtual ~VerifyICEDiagnoser() {}
13052   };
13053 
13054   enum AllowFoldKind {
13055     NoFold,
13056     AllowFold,
13057   };
13058 
13059   /// VerifyIntegerConstantExpression - Verifies that an expression is an ICE,
13060   /// and reports the appropriate diagnostics. Returns false on success.
13061   /// Can optionally return the value of the expression.
13062   ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
13063                                              VerifyICEDiagnoser &Diagnoser,
13064                                              AllowFoldKind CanFold = NoFold);
13065   ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
13066                                              unsigned DiagID,
13067                                              AllowFoldKind CanFold = NoFold);
13068   ExprResult VerifyIntegerConstantExpression(Expr *E,
13069                                              llvm::APSInt *Result = nullptr,
13070                                              AllowFoldKind CanFold = NoFold);
13071   ExprResult VerifyIntegerConstantExpression(Expr *E,
13072                                              AllowFoldKind CanFold = NoFold) {
13073     return VerifyIntegerConstantExpression(E, nullptr, CanFold);
13074   }
13075 
13076   /// VerifyBitField - verifies that a bit field expression is an ICE and has
13077   /// the correct width, and that the field type is valid.
13078   /// Returns false on success.
13079   ExprResult VerifyBitField(SourceLocation FieldLoc, IdentifierInfo *FieldName,
13080                             QualType FieldTy, bool IsMsStruct, Expr *BitWidth);
13081 
13082 private:
13083   unsigned ForceCUDAHostDeviceDepth = 0;
13084 
13085 public:
13086   /// Increments our count of the number of times we've seen a pragma forcing
13087   /// functions to be __host__ __device__.  So long as this count is greater
13088   /// than zero, all functions encountered will be __host__ __device__.
13089   void PushForceCUDAHostDevice();
13090 
13091   /// Decrements our count of the number of times we've seen a pragma forcing
13092   /// functions to be __host__ __device__.  Returns false if the count is 0
13093   /// before incrementing, so you can emit an error.
13094   bool PopForceCUDAHostDevice();
13095 
13096   /// Diagnostics that are emitted only if we discover that the given function
13097   /// must be codegen'ed.  Because handling these correctly adds overhead to
13098   /// compilation, this is currently only enabled for CUDA compilations.
13099   llvm::DenseMap<CanonicalDeclPtr<const FunctionDecl>,
13100                  std::vector<PartialDiagnosticAt>>
13101       DeviceDeferredDiags;
13102 
13103   /// A pair of a canonical FunctionDecl and a SourceLocation.  When used as the
13104   /// key in a hashtable, both the FD and location are hashed.
13105   struct FunctionDeclAndLoc {
13106     CanonicalDeclPtr<const FunctionDecl> FD;
13107     SourceLocation Loc;
13108   };
13109 
13110   /// FunctionDecls and SourceLocations for which CheckCUDACall has emitted a
13111   /// (maybe deferred) "bad call" diagnostic.  We use this to avoid emitting the
13112   /// same deferred diag twice.
13113   llvm::DenseSet<FunctionDeclAndLoc> LocsWithCUDACallDiags;
13114 
13115   /// An inverse call graph, mapping known-emitted functions to one of their
13116   /// known-emitted callers (plus the location of the call).
13117   ///
13118   /// Functions that we can tell a priori must be emitted aren't added to this
13119   /// map.
13120   llvm::DenseMap</* Callee = */ CanonicalDeclPtr<const FunctionDecl>,
13121                  /* Caller = */ FunctionDeclAndLoc>
13122       DeviceKnownEmittedFns;
13123 
13124   /// Creates a SemaDiagnosticBuilder that emits the diagnostic if the current
13125   /// context is "used as device code".
13126   ///
13127   /// - If CurContext is a __host__ function, does not emit any diagnostics
13128   ///   unless \p EmitOnBothSides is true.
13129   /// - If CurContext is a __device__ or __global__ function, emits the
13130   ///   diagnostics immediately.
13131   /// - If CurContext is a __host__ __device__ function and we are compiling for
13132   ///   the device, creates a diagnostic which is emitted if and when we realize
13133   ///   that the function will be codegen'ed.
13134   ///
13135   /// Example usage:
13136   ///
13137   ///  // Variable-length arrays are not allowed in CUDA device code.
13138   ///  if (CUDADiagIfDeviceCode(Loc, diag::err_cuda_vla) << CurrentCUDATarget())
13139   ///    return ExprError();
13140   ///  // Otherwise, continue parsing as normal.
13141   SemaDiagnosticBuilder CUDADiagIfDeviceCode(SourceLocation Loc,
13142                                              unsigned DiagID);
13143 
13144   /// Creates a SemaDiagnosticBuilder that emits the diagnostic if the current
13145   /// context is "used as host code".
13146   ///
13147   /// Same as CUDADiagIfDeviceCode, with "host" and "device" switched.
13148   SemaDiagnosticBuilder CUDADiagIfHostCode(SourceLocation Loc, unsigned DiagID);
13149 
13150   /// Creates a SemaDiagnosticBuilder that emits the diagnostic if the current
13151   /// context is "used as device code".
13152   ///
13153   /// - If CurContext is a `declare target` function or it is known that the
13154   /// function is emitted for the device, emits the diagnostics immediately.
13155   /// - If CurContext is a non-`declare target` function and we are compiling
13156   ///   for the device, creates a diagnostic which is emitted if and when we
13157   ///   realize that the function will be codegen'ed.
13158   ///
13159   /// Example usage:
13160   ///
13161   ///  // Variable-length arrays are not allowed in NVPTX device code.
13162   ///  if (diagIfOpenMPDeviceCode(Loc, diag::err_vla_unsupported))
13163   ///    return ExprError();
13164   ///  // Otherwise, continue parsing as normal.
13165   SemaDiagnosticBuilder diagIfOpenMPDeviceCode(SourceLocation Loc,
13166                                                unsigned DiagID,
13167                                                const FunctionDecl *FD);
13168 
13169   /// Creates a SemaDiagnosticBuilder that emits the diagnostic if the current
13170   /// context is "used as host code".
13171   ///
13172   /// - If CurContext is a `declare target` function or it is known that the
13173   /// function is emitted for the host, emits the diagnostics immediately.
13174   /// - If CurContext is a non-host function, just ignore it.
13175   ///
13176   /// Example usage:
13177   ///
13178   ///  // Variable-length arrays are not allowed in NVPTX device code.
13179   ///  if (diagIfOpenMPHostode(Loc, diag::err_vla_unsupported))
13180   ///    return ExprError();
13181   ///  // Otherwise, continue parsing as normal.
13182   SemaDiagnosticBuilder diagIfOpenMPHostCode(SourceLocation Loc,
13183                                              unsigned DiagID,
13184                                              const FunctionDecl *FD);
13185 
13186   SemaDiagnosticBuilder targetDiag(SourceLocation Loc, unsigned DiagID,
13187                                    const FunctionDecl *FD = nullptr);
13188   SemaDiagnosticBuilder targetDiag(SourceLocation Loc,
13189                                    const PartialDiagnostic &PD,
13190                                    const FunctionDecl *FD = nullptr) {
13191     return targetDiag(Loc, PD.getDiagID(), FD) << PD;
13192   }
13193 
13194   /// Check if the type is allowed to be used for the current target.
13195   void checkTypeSupport(QualType Ty, SourceLocation Loc,
13196                         ValueDecl *D = nullptr);
13197 
13198   enum CUDAFunctionTarget {
13199     CFT_Device,
13200     CFT_Global,
13201     CFT_Host,
13202     CFT_HostDevice,
13203     CFT_InvalidTarget
13204   };
13205 
13206   /// Determines whether the given function is a CUDA device/host/kernel/etc.
13207   /// function.
13208   ///
13209   /// Use this rather than examining the function's attributes yourself -- you
13210   /// will get it wrong.  Returns CFT_Host if D is null.
13211   CUDAFunctionTarget IdentifyCUDATarget(const FunctionDecl *D,
13212                                         bool IgnoreImplicitHDAttr = false);
13213   CUDAFunctionTarget IdentifyCUDATarget(const ParsedAttributesView &Attrs);
13214 
13215   enum CUDAVariableTarget {
13216     CVT_Device,  /// Emitted on device side with a shadow variable on host side
13217     CVT_Host,    /// Emitted on host side only
13218     CVT_Both,    /// Emitted on both sides with different addresses
13219     CVT_Unified, /// Emitted as a unified address, e.g. managed variables
13220   };
13221   /// Determines whether the given variable is emitted on host or device side.
13222   CUDAVariableTarget IdentifyCUDATarget(const VarDecl *D);
13223 
13224   /// Gets the CUDA target for the current context.
13225   CUDAFunctionTarget CurrentCUDATarget() {
13226     return IdentifyCUDATarget(dyn_cast<FunctionDecl>(CurContext));
13227   }
13228 
13229   static bool isCUDAImplicitHostDeviceFunction(const FunctionDecl *D);
13230 
13231   // CUDA function call preference. Must be ordered numerically from
13232   // worst to best.
13233   enum CUDAFunctionPreference {
13234     CFP_Never,      // Invalid caller/callee combination.
13235     CFP_WrongSide,  // Calls from host-device to host or device
13236                     // function that do not match current compilation
13237                     // mode.
13238     CFP_HostDevice, // Any calls to host/device functions.
13239     CFP_SameSide,   // Calls from host-device to host or device
13240                     // function matching current compilation mode.
13241     CFP_Native,     // host-to-host or device-to-device calls.
13242   };
13243 
13244   /// Identifies relative preference of a given Caller/Callee
13245   /// combination, based on their host/device attributes.
13246   /// \param Caller function which needs address of \p Callee.
13247   ///               nullptr in case of global context.
13248   /// \param Callee target function
13249   ///
13250   /// \returns preference value for particular Caller/Callee combination.
13251   CUDAFunctionPreference IdentifyCUDAPreference(const FunctionDecl *Caller,
13252                                                 const FunctionDecl *Callee);
13253 
13254   /// Determines whether Caller may invoke Callee, based on their CUDA
13255   /// host/device attributes.  Returns false if the call is not allowed.
13256   ///
13257   /// Note: Will return true for CFP_WrongSide calls.  These may appear in
13258   /// semantically correct CUDA programs, but only if they're never codegen'ed.
13259   bool IsAllowedCUDACall(const FunctionDecl *Caller,
13260                          const FunctionDecl *Callee) {
13261     return IdentifyCUDAPreference(Caller, Callee) != CFP_Never;
13262   }
13263 
13264   /// May add implicit CUDAHostAttr and CUDADeviceAttr attributes to FD,
13265   /// depending on FD and the current compilation settings.
13266   void maybeAddCUDAHostDeviceAttrs(FunctionDecl *FD,
13267                                    const LookupResult &Previous);
13268 
13269   /// May add implicit CUDAConstantAttr attribute to VD, depending on VD
13270   /// and current compilation settings.
13271   void MaybeAddCUDAConstantAttr(VarDecl *VD);
13272 
13273 public:
13274   /// Check whether we're allowed to call Callee from the current context.
13275   ///
13276   /// - If the call is never allowed in a semantically-correct program
13277   ///   (CFP_Never), emits an error and returns false.
13278   ///
13279   /// - If the call is allowed in semantically-correct programs, but only if
13280   ///   it's never codegen'ed (CFP_WrongSide), creates a deferred diagnostic to
13281   ///   be emitted if and when the caller is codegen'ed, and returns true.
13282   ///
13283   ///   Will only create deferred diagnostics for a given SourceLocation once,
13284   ///   so you can safely call this multiple times without generating duplicate
13285   ///   deferred errors.
13286   ///
13287   /// - Otherwise, returns true without emitting any diagnostics.
13288   bool CheckCUDACall(SourceLocation Loc, FunctionDecl *Callee);
13289 
13290   void CUDACheckLambdaCapture(CXXMethodDecl *D, const sema::Capture &Capture);
13291 
13292   /// Set __device__ or __host__ __device__ attributes on the given lambda
13293   /// operator() method.
13294   ///
13295   /// CUDA lambdas by default is host device function unless it has explicit
13296   /// host or device attribute.
13297   void CUDASetLambdaAttrs(CXXMethodDecl *Method);
13298 
13299   /// Finds a function in \p Matches with highest calling priority
13300   /// from \p Caller context and erases all functions with lower
13301   /// calling priority.
13302   void EraseUnwantedCUDAMatches(
13303       const FunctionDecl *Caller,
13304       SmallVectorImpl<std::pair<DeclAccessPair, FunctionDecl *>> &Matches);
13305 
13306   /// Given a implicit special member, infer its CUDA target from the
13307   /// calls it needs to make to underlying base/field special members.
13308   /// \param ClassDecl the class for which the member is being created.
13309   /// \param CSM the kind of special member.
13310   /// \param MemberDecl the special member itself.
13311   /// \param ConstRHS true if this is a copy operation with a const object on
13312   ///        its RHS.
13313   /// \param Diagnose true if this call should emit diagnostics.
13314   /// \return true if there was an error inferring.
13315   /// The result of this call is implicit CUDA target attribute(s) attached to
13316   /// the member declaration.
13317   bool inferCUDATargetForImplicitSpecialMember(CXXRecordDecl *ClassDecl,
13318                                                CXXSpecialMember CSM,
13319                                                CXXMethodDecl *MemberDecl,
13320                                                bool ConstRHS,
13321                                                bool Diagnose);
13322 
13323   /// \return true if \p CD can be considered empty according to CUDA
13324   /// (E.2.3.1 in CUDA 7.5 Programming guide).
13325   bool isEmptyCudaConstructor(SourceLocation Loc, CXXConstructorDecl *CD);
13326   bool isEmptyCudaDestructor(SourceLocation Loc, CXXDestructorDecl *CD);
13327 
13328   // \brief Checks that initializers of \p Var satisfy CUDA restrictions. In
13329   // case of error emits appropriate diagnostic and invalidates \p Var.
13330   //
13331   // \details CUDA allows only empty constructors as initializers for global
13332   // variables (see E.2.3.1, CUDA 7.5). The same restriction also applies to all
13333   // __shared__ variables whether they are local or not (they all are implicitly
13334   // static in CUDA). One exception is that CUDA allows constant initializers
13335   // for __constant__ and __device__ variables.
13336   void checkAllowedCUDAInitializer(VarDecl *VD);
13337 
13338   /// Check whether NewFD is a valid overload for CUDA. Emits
13339   /// diagnostics and invalidates NewFD if not.
13340   void checkCUDATargetOverload(FunctionDecl *NewFD,
13341                                const LookupResult &Previous);
13342   /// Copies target attributes from the template TD to the function FD.
13343   void inheritCUDATargetAttrs(FunctionDecl *FD, const FunctionTemplateDecl &TD);
13344 
13345   /// Returns the name of the launch configuration function.  This is the name
13346   /// of the function that will be called to configure kernel call, with the
13347   /// parameters specified via <<<>>>.
13348   std::string getCudaConfigureFuncName() const;
13349 
13350   /// \name Code completion
13351   //@{
13352   /// Describes the context in which code completion occurs.
13353   enum ParserCompletionContext {
13354     /// Code completion occurs at top-level or namespace context.
13355     PCC_Namespace,
13356     /// Code completion occurs within a class, struct, or union.
13357     PCC_Class,
13358     /// Code completion occurs within an Objective-C interface, protocol,
13359     /// or category.
13360     PCC_ObjCInterface,
13361     /// Code completion occurs within an Objective-C implementation or
13362     /// category implementation
13363     PCC_ObjCImplementation,
13364     /// Code completion occurs within the list of instance variables
13365     /// in an Objective-C interface, protocol, category, or implementation.
13366     PCC_ObjCInstanceVariableList,
13367     /// Code completion occurs following one or more template
13368     /// headers.
13369     PCC_Template,
13370     /// Code completion occurs following one or more template
13371     /// headers within a class.
13372     PCC_MemberTemplate,
13373     /// Code completion occurs within an expression.
13374     PCC_Expression,
13375     /// Code completion occurs within a statement, which may
13376     /// also be an expression or a declaration.
13377     PCC_Statement,
13378     /// Code completion occurs at the beginning of the
13379     /// initialization statement (or expression) in a for loop.
13380     PCC_ForInit,
13381     /// Code completion occurs within the condition of an if,
13382     /// while, switch, or for statement.
13383     PCC_Condition,
13384     /// Code completion occurs within the body of a function on a
13385     /// recovery path, where we do not have a specific handle on our position
13386     /// in the grammar.
13387     PCC_RecoveryInFunction,
13388     /// Code completion occurs where only a type is permitted.
13389     PCC_Type,
13390     /// Code completion occurs in a parenthesized expression, which
13391     /// might also be a type cast.
13392     PCC_ParenthesizedExpression,
13393     /// Code completion occurs within a sequence of declaration
13394     /// specifiers within a function, method, or block.
13395     PCC_LocalDeclarationSpecifiers
13396   };
13397 
13398   void CodeCompleteModuleImport(SourceLocation ImportLoc, ModuleIdPath Path);
13399   void CodeCompleteOrdinaryName(Scope *S,
13400                                 ParserCompletionContext CompletionContext);
13401   void CodeCompleteDeclSpec(Scope *S, DeclSpec &DS,
13402                             bool AllowNonIdentifiers,
13403                             bool AllowNestedNameSpecifiers);
13404 
13405   struct CodeCompleteExpressionData;
13406   void CodeCompleteExpression(Scope *S,
13407                               const CodeCompleteExpressionData &Data);
13408   void CodeCompleteExpression(Scope *S, QualType PreferredType,
13409                               bool IsParenthesized = false);
13410   void CodeCompleteMemberReferenceExpr(Scope *S, Expr *Base, Expr *OtherOpBase,
13411                                        SourceLocation OpLoc, bool IsArrow,
13412                                        bool IsBaseExprStatement,
13413                                        QualType PreferredType);
13414   void CodeCompletePostfixExpression(Scope *S, ExprResult LHS,
13415                                      QualType PreferredType);
13416   void CodeCompleteTag(Scope *S, unsigned TagSpec);
13417   void CodeCompleteTypeQualifiers(DeclSpec &DS);
13418   void CodeCompleteFunctionQualifiers(DeclSpec &DS, Declarator &D,
13419                                       const VirtSpecifiers *VS = nullptr);
13420   void CodeCompleteBracketDeclarator(Scope *S);
13421   void CodeCompleteCase(Scope *S);
13422   enum class AttributeCompletion {
13423     Attribute,
13424     Scope,
13425     None,
13426   };
13427   void CodeCompleteAttribute(
13428       AttributeCommonInfo::Syntax Syntax,
13429       AttributeCompletion Completion = AttributeCompletion::Attribute,
13430       const IdentifierInfo *Scope = nullptr);
13431   /// Determines the preferred type of the current function argument, by
13432   /// examining the signatures of all possible overloads.
13433   /// Returns null if unknown or ambiguous, or if code completion is off.
13434   ///
13435   /// If the code completion point has been reached, also reports the function
13436   /// signatures that were considered.
13437   ///
13438   /// FIXME: rename to GuessCallArgumentType to reduce confusion.
13439   QualType ProduceCallSignatureHelp(Expr *Fn, ArrayRef<Expr *> Args,
13440                                     SourceLocation OpenParLoc);
13441   QualType ProduceConstructorSignatureHelp(QualType Type, SourceLocation Loc,
13442                                            ArrayRef<Expr *> Args,
13443                                            SourceLocation OpenParLoc,
13444                                            bool Braced);
13445   QualType ProduceCtorInitMemberSignatureHelp(
13446       Decl *ConstructorDecl, CXXScopeSpec SS, ParsedType TemplateTypeTy,
13447       ArrayRef<Expr *> ArgExprs, IdentifierInfo *II, SourceLocation OpenParLoc,
13448       bool Braced);
13449   QualType ProduceTemplateArgumentSignatureHelp(
13450       TemplateTy, ArrayRef<ParsedTemplateArgument>, SourceLocation LAngleLoc);
13451   void CodeCompleteInitializer(Scope *S, Decl *D);
13452   /// Trigger code completion for a record of \p BaseType. \p InitExprs are
13453   /// expressions in the initializer list seen so far and \p D is the current
13454   /// Designation being parsed.
13455   void CodeCompleteDesignator(const QualType BaseType,
13456                               llvm::ArrayRef<Expr *> InitExprs,
13457                               const Designation &D);
13458   void CodeCompleteAfterIf(Scope *S, bool IsBracedThen);
13459 
13460   void CodeCompleteQualifiedId(Scope *S, CXXScopeSpec &SS, bool EnteringContext,
13461                                bool IsUsingDeclaration, QualType BaseType,
13462                                QualType PreferredType);
13463   void CodeCompleteUsing(Scope *S);
13464   void CodeCompleteUsingDirective(Scope *S);
13465   void CodeCompleteNamespaceDecl(Scope *S);
13466   void CodeCompleteNamespaceAliasDecl(Scope *S);
13467   void CodeCompleteOperatorName(Scope *S);
13468   void CodeCompleteConstructorInitializer(
13469                                 Decl *Constructor,
13470                                 ArrayRef<CXXCtorInitializer *> Initializers);
13471 
13472   void CodeCompleteLambdaIntroducer(Scope *S, LambdaIntroducer &Intro,
13473                                     bool AfterAmpersand);
13474   void CodeCompleteAfterFunctionEquals(Declarator &D);
13475 
13476   void CodeCompleteObjCAtDirective(Scope *S);
13477   void CodeCompleteObjCAtVisibility(Scope *S);
13478   void CodeCompleteObjCAtStatement(Scope *S);
13479   void CodeCompleteObjCAtExpression(Scope *S);
13480   void CodeCompleteObjCPropertyFlags(Scope *S, ObjCDeclSpec &ODS);
13481   void CodeCompleteObjCPropertyGetter(Scope *S);
13482   void CodeCompleteObjCPropertySetter(Scope *S);
13483   void CodeCompleteObjCPassingType(Scope *S, ObjCDeclSpec &DS,
13484                                    bool IsParameter);
13485   void CodeCompleteObjCMessageReceiver(Scope *S);
13486   void CodeCompleteObjCSuperMessage(Scope *S, SourceLocation SuperLoc,
13487                                     ArrayRef<IdentifierInfo *> SelIdents,
13488                                     bool AtArgumentExpression);
13489   void CodeCompleteObjCClassMessage(Scope *S, ParsedType Receiver,
13490                                     ArrayRef<IdentifierInfo *> SelIdents,
13491                                     bool AtArgumentExpression,
13492                                     bool IsSuper = false);
13493   void CodeCompleteObjCInstanceMessage(Scope *S, Expr *Receiver,
13494                                        ArrayRef<IdentifierInfo *> SelIdents,
13495                                        bool AtArgumentExpression,
13496                                        ObjCInterfaceDecl *Super = nullptr);
13497   void CodeCompleteObjCForCollection(Scope *S,
13498                                      DeclGroupPtrTy IterationVar);
13499   void CodeCompleteObjCSelector(Scope *S,
13500                                 ArrayRef<IdentifierInfo *> SelIdents);
13501   void CodeCompleteObjCProtocolReferences(
13502                                          ArrayRef<IdentifierLocPair> Protocols);
13503   void CodeCompleteObjCProtocolDecl(Scope *S);
13504   void CodeCompleteObjCInterfaceDecl(Scope *S);
13505   void CodeCompleteObjCClassForwardDecl(Scope *S);
13506   void CodeCompleteObjCSuperclass(Scope *S,
13507                                   IdentifierInfo *ClassName,
13508                                   SourceLocation ClassNameLoc);
13509   void CodeCompleteObjCImplementationDecl(Scope *S);
13510   void CodeCompleteObjCInterfaceCategory(Scope *S,
13511                                          IdentifierInfo *ClassName,
13512                                          SourceLocation ClassNameLoc);
13513   void CodeCompleteObjCImplementationCategory(Scope *S,
13514                                               IdentifierInfo *ClassName,
13515                                               SourceLocation ClassNameLoc);
13516   void CodeCompleteObjCPropertyDefinition(Scope *S);
13517   void CodeCompleteObjCPropertySynthesizeIvar(Scope *S,
13518                                               IdentifierInfo *PropertyName);
13519   void CodeCompleteObjCMethodDecl(Scope *S,
13520                                   std::optional<bool> IsInstanceMethod,
13521                                   ParsedType ReturnType);
13522   void CodeCompleteObjCMethodDeclSelector(Scope *S,
13523                                           bool IsInstanceMethod,
13524                                           bool AtParameterName,
13525                                           ParsedType ReturnType,
13526                                           ArrayRef<IdentifierInfo *> SelIdents);
13527   void CodeCompleteObjCClassPropertyRefExpr(Scope *S, IdentifierInfo &ClassName,
13528                                             SourceLocation ClassNameLoc,
13529                                             bool IsBaseExprStatement);
13530   void CodeCompletePreprocessorDirective(bool InConditional);
13531   void CodeCompleteInPreprocessorConditionalExclusion(Scope *S);
13532   void CodeCompletePreprocessorMacroName(bool IsDefinition);
13533   void CodeCompletePreprocessorExpression();
13534   void CodeCompletePreprocessorMacroArgument(Scope *S,
13535                                              IdentifierInfo *Macro,
13536                                              MacroInfo *MacroInfo,
13537                                              unsigned Argument);
13538   void CodeCompleteIncludedFile(llvm::StringRef Dir, bool IsAngled);
13539   void CodeCompleteNaturalLanguage();
13540   void CodeCompleteAvailabilityPlatformName();
13541   void GatherGlobalCodeCompletions(CodeCompletionAllocator &Allocator,
13542                                    CodeCompletionTUInfo &CCTUInfo,
13543                   SmallVectorImpl<CodeCompletionResult> &Results);
13544   //@}
13545 
13546   //===--------------------------------------------------------------------===//
13547   // Extra semantic analysis beyond the C type system
13548 
13549 public:
13550   SourceLocation getLocationOfStringLiteralByte(const StringLiteral *SL,
13551                                                 unsigned ByteNo) const;
13552 
13553   enum FormatArgumentPassingKind {
13554     FAPK_Fixed,    // values to format are fixed (no C-style variadic arguments)
13555     FAPK_Variadic, // values to format are passed as variadic arguments
13556     FAPK_VAList,   // values to format are passed in a va_list
13557   };
13558 
13559   // Used to grab the relevant information from a FormatAttr and a
13560   // FunctionDeclaration.
13561   struct FormatStringInfo {
13562     unsigned FormatIdx;
13563     unsigned FirstDataArg;
13564     FormatArgumentPassingKind ArgPassingKind;
13565   };
13566 
13567   static bool getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
13568                                   bool IsVariadic, FormatStringInfo *FSI);
13569 
13570 private:
13571   void CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
13572                         const ArraySubscriptExpr *ASE = nullptr,
13573                         bool AllowOnePastEnd = true, bool IndexNegated = false);
13574   void CheckArrayAccess(const Expr *E);
13575 
13576   bool CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
13577                          const FunctionProtoType *Proto);
13578   bool CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation loc,
13579                            ArrayRef<const Expr *> Args);
13580   bool CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
13581                         const FunctionProtoType *Proto);
13582   bool CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto);
13583   void CheckConstructorCall(FunctionDecl *FDecl, QualType ThisType,
13584                             ArrayRef<const Expr *> Args,
13585                             const FunctionProtoType *Proto, SourceLocation Loc);
13586 
13587   void checkAIXMemberAlignment(SourceLocation Loc, const Expr *Arg);
13588 
13589   void CheckArgAlignment(SourceLocation Loc, NamedDecl *FDecl,
13590                          StringRef ParamName, QualType ArgTy, QualType ParamTy);
13591 
13592   void checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
13593                  const Expr *ThisArg, ArrayRef<const Expr *> Args,
13594                  bool IsMemberFunction, SourceLocation Loc, SourceRange Range,
13595                  VariadicCallType CallType);
13596 
13597   bool CheckObjCString(Expr *Arg);
13598   ExprResult CheckOSLogFormatStringArg(Expr *Arg);
13599 
13600   ExprResult CheckBuiltinFunctionCall(FunctionDecl *FDecl,
13601                                       unsigned BuiltinID, CallExpr *TheCall);
13602 
13603   bool CheckTSBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
13604                                   CallExpr *TheCall);
13605 
13606   void checkFortifiedBuiltinMemoryFunction(FunctionDecl *FD, CallExpr *TheCall);
13607 
13608   bool CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
13609                                     unsigned MaxWidth);
13610   bool CheckNeonBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
13611                                     CallExpr *TheCall);
13612   bool CheckMVEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
13613   bool CheckSVEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
13614   bool CheckCDEBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
13615                                    CallExpr *TheCall);
13616   bool CheckARMCoprocessorImmediate(const TargetInfo &TI, const Expr *CoprocArg,
13617                                     bool WantCDE);
13618   bool CheckARMBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
13619                                    CallExpr *TheCall);
13620 
13621   bool CheckAArch64BuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
13622                                        CallExpr *TheCall);
13623   bool CheckBPFBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
13624   bool CheckHexagonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
13625   bool CheckHexagonBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall);
13626   bool CheckMipsBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
13627                                     CallExpr *TheCall);
13628   bool CheckMipsBuiltinCpu(const TargetInfo &TI, unsigned BuiltinID,
13629                            CallExpr *TheCall);
13630   bool CheckMipsBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall);
13631   bool CheckSystemZBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
13632   bool CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall);
13633   bool CheckX86BuiltinGatherScatterScale(unsigned BuiltinID, CallExpr *TheCall);
13634   bool CheckX86BuiltinTileArguments(unsigned BuiltinID, CallExpr *TheCall);
13635   bool CheckX86BuiltinTileArgumentsRange(CallExpr *TheCall,
13636                                          ArrayRef<int> ArgNums);
13637   bool CheckX86BuiltinTileDuplicate(CallExpr *TheCall, ArrayRef<int> ArgNums);
13638   bool CheckX86BuiltinTileRangeAndDuplicate(CallExpr *TheCall,
13639                                             ArrayRef<int> ArgNums);
13640   bool CheckX86BuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
13641                                    CallExpr *TheCall);
13642   bool CheckPPCBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
13643                                    CallExpr *TheCall);
13644   bool CheckAMDGCNBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
13645   bool CheckRISCVLMUL(CallExpr *TheCall, unsigned ArgNum);
13646   bool CheckRISCVBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
13647                                      CallExpr *TheCall);
13648   void checkRVVTypeSupport(QualType Ty, SourceLocation Loc, ValueDecl *D);
13649   bool CheckLoongArchBuiltinFunctionCall(const TargetInfo &TI,
13650                                          unsigned BuiltinID, CallExpr *TheCall);
13651   bool CheckWebAssemblyBuiltinFunctionCall(const TargetInfo &TI,
13652                                            unsigned BuiltinID,
13653                                            CallExpr *TheCall);
13654   bool CheckNVPTXBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
13655                                      CallExpr *TheCall);
13656 
13657   bool SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall);
13658   bool SemaBuiltinVAStartARMMicrosoft(CallExpr *Call);
13659   bool SemaBuiltinUnorderedCompare(CallExpr *TheCall);
13660   bool SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs);
13661   bool SemaBuiltinComplex(CallExpr *TheCall);
13662   bool SemaBuiltinVSX(CallExpr *TheCall);
13663   bool SemaBuiltinOSLogFormat(CallExpr *TheCall);
13664   bool SemaValueIsRunOfOnes(CallExpr *TheCall, unsigned ArgNum);
13665 
13666 public:
13667   // Used by C++ template instantiation.
13668   ExprResult SemaBuiltinShuffleVector(CallExpr *TheCall);
13669   ExprResult SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
13670                                    SourceLocation BuiltinLoc,
13671                                    SourceLocation RParenLoc);
13672 
13673 private:
13674   bool SemaBuiltinPrefetch(CallExpr *TheCall);
13675   bool SemaBuiltinAllocaWithAlign(CallExpr *TheCall);
13676   bool SemaBuiltinArithmeticFence(CallExpr *TheCall);
13677   bool SemaBuiltinAssume(CallExpr *TheCall);
13678   bool SemaBuiltinAssumeAligned(CallExpr *TheCall);
13679   bool SemaBuiltinLongjmp(CallExpr *TheCall);
13680   bool SemaBuiltinSetjmp(CallExpr *TheCall);
13681   ExprResult SemaBuiltinAtomicOverloaded(ExprResult TheCallResult);
13682   ExprResult SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult);
13683   ExprResult SemaAtomicOpsOverloaded(ExprResult TheCallResult,
13684                                      AtomicExpr::AtomicOp Op);
13685   ExprResult SemaBuiltinOperatorNewDeleteOverloaded(ExprResult TheCallResult,
13686                                                     bool IsDelete);
13687   bool SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
13688                               llvm::APSInt &Result);
13689   bool SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum, int Low,
13690                                    int High, bool RangeIsError = true);
13691   bool SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum,
13692                                       unsigned Multiple);
13693   bool SemaBuiltinConstantArgPower2(CallExpr *TheCall, int ArgNum);
13694   bool SemaBuiltinConstantArgShiftedByte(CallExpr *TheCall, int ArgNum,
13695                                          unsigned ArgBits);
13696   bool SemaBuiltinConstantArgShiftedByteOrXXFF(CallExpr *TheCall, int ArgNum,
13697                                                unsigned ArgBits);
13698   bool SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall,
13699                                 int ArgNum, unsigned ExpectedFieldNum,
13700                                 bool AllowName);
13701   bool SemaBuiltinARMMemoryTaggingCall(unsigned BuiltinID, CallExpr *TheCall);
13702   bool SemaBuiltinPPCMMACall(CallExpr *TheCall, unsigned BuiltinID,
13703                              const char *TypeDesc);
13704 
13705   bool CheckPPCMMAType(QualType Type, SourceLocation TypeLoc);
13706 
13707   bool SemaBuiltinElementwiseMath(CallExpr *TheCall);
13708   bool SemaBuiltinElementwiseTernaryMath(CallExpr *TheCall);
13709   bool PrepareBuiltinElementwiseMathOneArgCall(CallExpr *TheCall);
13710   bool PrepareBuiltinReduceMathOneArgCall(CallExpr *TheCall);
13711 
13712   bool SemaBuiltinNonDeterministicValue(CallExpr *TheCall);
13713 
13714   // Matrix builtin handling.
13715   ExprResult SemaBuiltinMatrixTranspose(CallExpr *TheCall,
13716                                         ExprResult CallResult);
13717   ExprResult SemaBuiltinMatrixColumnMajorLoad(CallExpr *TheCall,
13718                                               ExprResult CallResult);
13719   ExprResult SemaBuiltinMatrixColumnMajorStore(CallExpr *TheCall,
13720                                                ExprResult CallResult);
13721 
13722   // WebAssembly builtin handling.
13723   bool BuiltinWasmRefNullExtern(CallExpr *TheCall);
13724   bool BuiltinWasmRefNullFunc(CallExpr *TheCall);
13725   bool BuiltinWasmTableGet(CallExpr *TheCall);
13726   bool BuiltinWasmTableSet(CallExpr *TheCall);
13727   bool BuiltinWasmTableSize(CallExpr *TheCall);
13728   bool BuiltinWasmTableGrow(CallExpr *TheCall);
13729   bool BuiltinWasmTableFill(CallExpr *TheCall);
13730   bool BuiltinWasmTableCopy(CallExpr *TheCall);
13731 
13732 public:
13733   enum FormatStringType {
13734     FST_Scanf,
13735     FST_Printf,
13736     FST_NSString,
13737     FST_Strftime,
13738     FST_Strfmon,
13739     FST_Kprintf,
13740     FST_FreeBSDKPrintf,
13741     FST_OSTrace,
13742     FST_OSLog,
13743     FST_Unknown
13744   };
13745   static FormatStringType GetFormatStringType(const FormatAttr *Format);
13746 
13747   bool FormatStringHasSArg(const StringLiteral *FExpr);
13748 
13749   static bool GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx);
13750 
13751 private:
13752   bool CheckFormatArguments(const FormatAttr *Format,
13753                             ArrayRef<const Expr *> Args, bool IsCXXMember,
13754                             VariadicCallType CallType, SourceLocation Loc,
13755                             SourceRange Range,
13756                             llvm::SmallBitVector &CheckedVarArgs);
13757   bool CheckFormatArguments(ArrayRef<const Expr *> Args,
13758                             FormatArgumentPassingKind FAPK, unsigned format_idx,
13759                             unsigned firstDataArg, FormatStringType Type,
13760                             VariadicCallType CallType, SourceLocation Loc,
13761                             SourceRange range,
13762                             llvm::SmallBitVector &CheckedVarArgs);
13763 
13764   void CheckAbsoluteValueFunction(const CallExpr *Call,
13765                                   const FunctionDecl *FDecl);
13766 
13767   void CheckMaxUnsignedZero(const CallExpr *Call, const FunctionDecl *FDecl);
13768 
13769   void CheckMemaccessArguments(const CallExpr *Call,
13770                                unsigned BId,
13771                                IdentifierInfo *FnName);
13772 
13773   void CheckStrlcpycatArguments(const CallExpr *Call,
13774                                 IdentifierInfo *FnName);
13775 
13776   void CheckStrncatArguments(const CallExpr *Call,
13777                              IdentifierInfo *FnName);
13778 
13779   void CheckFreeArguments(const CallExpr *E);
13780 
13781   void CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
13782                           SourceLocation ReturnLoc,
13783                           bool isObjCMethod = false,
13784                           const AttrVec *Attrs = nullptr,
13785                           const FunctionDecl *FD = nullptr);
13786 
13787 public:
13788   void CheckFloatComparison(SourceLocation Loc, Expr *LHS, Expr *RHS,
13789                             BinaryOperatorKind Opcode);
13790 
13791 private:
13792   void CheckImplicitConversions(Expr *E, SourceLocation CC = SourceLocation());
13793   void CheckBoolLikeConversion(Expr *E, SourceLocation CC);
13794   void CheckForIntOverflow(const Expr *E);
13795   void CheckUnsequencedOperations(const Expr *E);
13796 
13797   /// Perform semantic checks on a completed expression. This will either
13798   /// be a full-expression or a default argument expression.
13799   void CheckCompletedExpr(Expr *E, SourceLocation CheckLoc = SourceLocation(),
13800                           bool IsConstexpr = false);
13801 
13802   void CheckBitFieldInitialization(SourceLocation InitLoc, FieldDecl *Field,
13803                                    Expr *Init);
13804 
13805   /// Check if there is a field shadowing.
13806   void CheckShadowInheritedFields(const SourceLocation &Loc,
13807                                   DeclarationName FieldName,
13808                                   const CXXRecordDecl *RD,
13809                                   bool DeclIsField = true);
13810 
13811   /// Check if the given expression contains 'break' or 'continue'
13812   /// statement that produces control flow different from GCC.
13813   void CheckBreakContinueBinding(Expr *E);
13814 
13815   /// Check whether receiver is mutable ObjC container which
13816   /// attempts to add itself into the container
13817   void CheckObjCCircularContainer(ObjCMessageExpr *Message);
13818 
13819   void CheckTCBEnforcement(const SourceLocation CallExprLoc,
13820                            const NamedDecl *Callee);
13821 
13822   void AnalyzeDeleteExprMismatch(const CXXDeleteExpr *DE);
13823   void AnalyzeDeleteExprMismatch(FieldDecl *Field, SourceLocation DeleteLoc,
13824                                  bool DeleteWasArrayForm);
13825 public:
13826   /// Register a magic integral constant to be used as a type tag.
13827   void RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
13828                                   uint64_t MagicValue, QualType Type,
13829                                   bool LayoutCompatible, bool MustBeNull);
13830 
13831   struct TypeTagData {
13832     TypeTagData() {}
13833 
13834     TypeTagData(QualType Type, bool LayoutCompatible, bool MustBeNull) :
13835         Type(Type), LayoutCompatible(LayoutCompatible),
13836         MustBeNull(MustBeNull)
13837     {}
13838 
13839     QualType Type;
13840 
13841     /// If true, \c Type should be compared with other expression's types for
13842     /// layout-compatibility.
13843     unsigned LayoutCompatible : 1;
13844     unsigned MustBeNull : 1;
13845   };
13846 
13847   /// A pair of ArgumentKind identifier and magic value.  This uniquely
13848   /// identifies the magic value.
13849   typedef std::pair<const IdentifierInfo *, uint64_t> TypeTagMagicValue;
13850 
13851 private:
13852   /// A map from magic value to type information.
13853   std::unique_ptr<llvm::DenseMap<TypeTagMagicValue, TypeTagData>>
13854       TypeTagForDatatypeMagicValues;
13855 
13856   /// Peform checks on a call of a function with argument_with_type_tag
13857   /// or pointer_with_type_tag attributes.
13858   void CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
13859                                 const ArrayRef<const Expr *> ExprArgs,
13860                                 SourceLocation CallSiteLoc);
13861 
13862   /// Check if we are taking the address of a packed field
13863   /// as this may be a problem if the pointer value is dereferenced.
13864   void CheckAddressOfPackedMember(Expr *rhs);
13865 
13866   /// The parser's current scope.
13867   ///
13868   /// The parser maintains this state here.
13869   Scope *CurScope;
13870 
13871   mutable IdentifierInfo *Ident_super;
13872 
13873   /// Nullability type specifiers.
13874   IdentifierInfo *Ident__Nonnull = nullptr;
13875   IdentifierInfo *Ident__Nullable = nullptr;
13876   IdentifierInfo *Ident__Nullable_result = nullptr;
13877   IdentifierInfo *Ident__Null_unspecified = nullptr;
13878 
13879   IdentifierInfo *Ident_NSError = nullptr;
13880 
13881   /// The handler for the FileChanged preprocessor events.
13882   ///
13883   /// Used for diagnostics that implement custom semantic analysis for #include
13884   /// directives, like -Wpragma-pack.
13885   sema::SemaPPCallbacks *SemaPPCallbackHandler;
13886 
13887 protected:
13888   friend class Parser;
13889   friend class InitializationSequence;
13890   friend class ASTReader;
13891   friend class ASTDeclReader;
13892   friend class ASTWriter;
13893 
13894 public:
13895   /// Retrieve the keyword associated
13896   IdentifierInfo *getNullabilityKeyword(NullabilityKind nullability);
13897 
13898   /// The struct behind the CFErrorRef pointer.
13899   RecordDecl *CFError = nullptr;
13900   bool isCFError(RecordDecl *D);
13901 
13902   /// Retrieve the identifier "NSError".
13903   IdentifierInfo *getNSErrorIdent();
13904 
13905   /// Retrieve the parser's current scope.
13906   ///
13907   /// This routine must only be used when it is certain that semantic analysis
13908   /// and the parser are in precisely the same context, which is not the case
13909   /// when, e.g., we are performing any kind of template instantiation.
13910   /// Therefore, the only safe places to use this scope are in the parser
13911   /// itself and in routines directly invoked from the parser and *never* from
13912   /// template substitution or instantiation.
13913   Scope *getCurScope() const { return CurScope; }
13914 
13915   void incrementMSManglingNumber() const {
13916     return CurScope->incrementMSManglingNumber();
13917   }
13918 
13919   IdentifierInfo *getSuperIdentifier() const;
13920 
13921   ObjCContainerDecl *getObjCDeclContext() const;
13922 
13923   DeclContext *getCurLexicalContext() const {
13924     return OriginalLexicalContext ? OriginalLexicalContext : CurContext;
13925   }
13926 
13927   const DeclContext *getCurObjCLexicalContext() const {
13928     const DeclContext *DC = getCurLexicalContext();
13929     // A category implicitly has the attribute of the interface.
13930     if (const ObjCCategoryDecl *CatD = dyn_cast<ObjCCategoryDecl>(DC))
13931       DC = CatD->getClassInterface();
13932     return DC;
13933   }
13934 
13935   /// Determine the number of levels of enclosing template parameters. This is
13936   /// only usable while parsing. Note that this does not include dependent
13937   /// contexts in which no template parameters have yet been declared, such as
13938   /// in a terse function template or generic lambda before the first 'auto' is
13939   /// encountered.
13940   unsigned getTemplateDepth(Scope *S) const;
13941 
13942   /// To be used for checking whether the arguments being passed to
13943   /// function exceeds the number of parameters expected for it.
13944   static bool TooManyArguments(size_t NumParams, size_t NumArgs,
13945                                bool PartialOverloading = false) {
13946     // We check whether we're just after a comma in code-completion.
13947     if (NumArgs > 0 && PartialOverloading)
13948       return NumArgs + 1 > NumParams; // If so, we view as an extra argument.
13949     return NumArgs > NumParams;
13950   }
13951 
13952   // Emitting members of dllexported classes is delayed until the class
13953   // (including field initializers) is fully parsed.
13954   SmallVector<CXXRecordDecl*, 4> DelayedDllExportClasses;
13955   SmallVector<CXXMethodDecl*, 4> DelayedDllExportMemberFunctions;
13956 
13957 private:
13958   int ParsingClassDepth = 0;
13959 
13960   class SavePendingParsedClassStateRAII {
13961   public:
13962     SavePendingParsedClassStateRAII(Sema &S) : S(S) { swapSavedState(); }
13963 
13964     ~SavePendingParsedClassStateRAII() {
13965       assert(S.DelayedOverridingExceptionSpecChecks.empty() &&
13966              "there shouldn't be any pending delayed exception spec checks");
13967       assert(S.DelayedEquivalentExceptionSpecChecks.empty() &&
13968              "there shouldn't be any pending delayed exception spec checks");
13969       swapSavedState();
13970     }
13971 
13972   private:
13973     Sema &S;
13974     decltype(DelayedOverridingExceptionSpecChecks)
13975         SavedOverridingExceptionSpecChecks;
13976     decltype(DelayedEquivalentExceptionSpecChecks)
13977         SavedEquivalentExceptionSpecChecks;
13978 
13979     void swapSavedState() {
13980       SavedOverridingExceptionSpecChecks.swap(
13981           S.DelayedOverridingExceptionSpecChecks);
13982       SavedEquivalentExceptionSpecChecks.swap(
13983           S.DelayedEquivalentExceptionSpecChecks);
13984     }
13985   };
13986 
13987   /// Helper class that collects misaligned member designations and
13988   /// their location info for delayed diagnostics.
13989   struct MisalignedMember {
13990     Expr *E;
13991     RecordDecl *RD;
13992     ValueDecl *MD;
13993     CharUnits Alignment;
13994 
13995     MisalignedMember() : E(), RD(), MD() {}
13996     MisalignedMember(Expr *E, RecordDecl *RD, ValueDecl *MD,
13997                      CharUnits Alignment)
13998         : E(E), RD(RD), MD(MD), Alignment(Alignment) {}
13999     explicit MisalignedMember(Expr *E)
14000         : MisalignedMember(E, nullptr, nullptr, CharUnits()) {}
14001 
14002     bool operator==(const MisalignedMember &m) { return this->E == m.E; }
14003   };
14004   /// Small set of gathered accesses to potentially misaligned members
14005   /// due to the packed attribute.
14006   SmallVector<MisalignedMember, 4> MisalignedMembers;
14007 
14008   /// Adds an expression to the set of gathered misaligned members.
14009   void AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD,
14010                                      CharUnits Alignment);
14011 
14012 public:
14013   /// Diagnoses the current set of gathered accesses. This typically
14014   /// happens at full expression level. The set is cleared after emitting the
14015   /// diagnostics.
14016   void DiagnoseMisalignedMembers();
14017 
14018   /// This function checks if the expression is in the sef of potentially
14019   /// misaligned members and it is converted to some pointer type T with lower
14020   /// or equal alignment requirements. If so it removes it. This is used when
14021   /// we do not want to diagnose such misaligned access (e.g. in conversions to
14022   /// void*).
14023   void DiscardMisalignedMemberAddress(const Type *T, Expr *E);
14024 
14025   /// This function calls Action when it determines that E designates a
14026   /// misaligned member due to the packed attribute. This is used to emit
14027   /// local diagnostics like in reference binding.
14028   void RefersToMemberWithReducedAlignment(
14029       Expr *E,
14030       llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)>
14031           Action);
14032 
14033   /// Describes the reason a calling convention specification was ignored, used
14034   /// for diagnostics.
14035   enum class CallingConventionIgnoredReason {
14036     ForThisTarget = 0,
14037     VariadicFunction,
14038     ConstructorDestructor,
14039     BuiltinFunction
14040   };
14041   /// Creates a SemaDiagnosticBuilder that emits the diagnostic if the current
14042   /// context is "used as device code".
14043   ///
14044   /// - If CurLexicalContext is a kernel function or it is known that the
14045   ///   function will be emitted for the device, emits the diagnostics
14046   ///   immediately.
14047   /// - If CurLexicalContext is a function and we are compiling
14048   ///   for the device, but we don't know that this function will be codegen'ed
14049   ///   for devive yet, creates a diagnostic which is emitted if and when we
14050   ///   realize that the function will be codegen'ed.
14051   ///
14052   /// Example usage:
14053   ///
14054   /// Diagnose __float128 type usage only from SYCL device code if the current
14055   /// target doesn't support it
14056   /// if (!S.Context.getTargetInfo().hasFloat128Type() &&
14057   ///     S.getLangOpts().SYCLIsDevice)
14058   ///   SYCLDiagIfDeviceCode(Loc, diag::err_type_unsupported) << "__float128";
14059   SemaDiagnosticBuilder SYCLDiagIfDeviceCode(SourceLocation Loc,
14060                                              unsigned DiagID);
14061 
14062   void deepTypeCheckForSYCLDevice(SourceLocation UsedAt,
14063                                   llvm::DenseSet<QualType> Visited,
14064                                   ValueDecl *DeclToCheck);
14065 };
14066 
14067 DeductionFailureInfo
14068 MakeDeductionFailureInfo(ASTContext &Context, Sema::TemplateDeductionResult TDK,
14069                          sema::TemplateDeductionInfo &Info);
14070 
14071 /// Contains a late templated function.
14072 /// Will be parsed at the end of the translation unit, used by Sema & Parser.
14073 struct LateParsedTemplate {
14074   CachedTokens Toks;
14075   /// The template function declaration to be late parsed.
14076   Decl *D;
14077   /// Floating-point options in the point of definition.
14078   FPOptions FPO;
14079 };
14080 
14081 template <>
14082 void Sema::PragmaStack<Sema::AlignPackInfo>::Act(SourceLocation PragmaLocation,
14083                                                  PragmaMsStackAction Action,
14084                                                  llvm::StringRef StackSlotLabel,
14085                                                  AlignPackInfo Value);
14086 
14087 std::unique_ptr<sema::RISCVIntrinsicManager>
14088 CreateRISCVIntrinsicManager(Sema &S);
14089 } // end namespace clang
14090 
14091 namespace llvm {
14092 // Hash a FunctionDeclAndLoc by looking at both its FunctionDecl and its
14093 // SourceLocation.
14094 template <> struct DenseMapInfo<clang::Sema::FunctionDeclAndLoc> {
14095   using FunctionDeclAndLoc = clang::Sema::FunctionDeclAndLoc;
14096   using FDBaseInfo =
14097       DenseMapInfo<clang::CanonicalDeclPtr<const clang::FunctionDecl>>;
14098 
14099   static FunctionDeclAndLoc getEmptyKey() {
14100     return {FDBaseInfo::getEmptyKey(), clang::SourceLocation()};
14101   }
14102 
14103   static FunctionDeclAndLoc getTombstoneKey() {
14104     return {FDBaseInfo::getTombstoneKey(), clang::SourceLocation()};
14105   }
14106 
14107   static unsigned getHashValue(const FunctionDeclAndLoc &FDL) {
14108     return hash_combine(FDBaseInfo::getHashValue(FDL.FD),
14109                         FDL.Loc.getHashValue());
14110   }
14111 
14112   static bool isEqual(const FunctionDeclAndLoc &LHS,
14113                       const FunctionDeclAndLoc &RHS) {
14114     return LHS.FD == RHS.FD && LHS.Loc == RHS.Loc;
14115   }
14116 };
14117 } // namespace llvm
14118 
14119 #endif
14120