xref: /llvm-project/clang/lib/CodeGen/CodeGenModule.cpp (revision cd61d2abe0fdfcee52e16998f7f3fda82572cd6f)
1 //===--- CodeGenModule.cpp - Emit LLVM Code from ASTs for a Module --------===//
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 coordinates the per-module state used while generating code.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "CodeGenModule.h"
14 #include "ABIInfo.h"
15 #include "CGBlocks.h"
16 #include "CGCUDARuntime.h"
17 #include "CGCXXABI.h"
18 #include "CGCall.h"
19 #include "CGDebugInfo.h"
20 #include "CGHLSLRuntime.h"
21 #include "CGObjCRuntime.h"
22 #include "CGOpenCLRuntime.h"
23 #include "CGOpenMPRuntime.h"
24 #include "CGOpenMPRuntimeGPU.h"
25 #include "CodeGenFunction.h"
26 #include "CodeGenPGO.h"
27 #include "ConstantEmitter.h"
28 #include "CoverageMappingGen.h"
29 #include "TargetInfo.h"
30 #include "clang/AST/ASTContext.h"
31 #include "clang/AST/CharUnits.h"
32 #include "clang/AST/DeclCXX.h"
33 #include "clang/AST/DeclObjC.h"
34 #include "clang/AST/DeclTemplate.h"
35 #include "clang/AST/Mangle.h"
36 #include "clang/AST/RecursiveASTVisitor.h"
37 #include "clang/AST/StmtVisitor.h"
38 #include "clang/Basic/Builtins.h"
39 #include "clang/Basic/CharInfo.h"
40 #include "clang/Basic/CodeGenOptions.h"
41 #include "clang/Basic/Diagnostic.h"
42 #include "clang/Basic/FileManager.h"
43 #include "clang/Basic/Module.h"
44 #include "clang/Basic/SourceManager.h"
45 #include "clang/Basic/TargetInfo.h"
46 #include "clang/Basic/Version.h"
47 #include "clang/CodeGen/BackendUtil.h"
48 #include "clang/CodeGen/ConstantInitBuilder.h"
49 #include "clang/Frontend/FrontendDiagnostic.h"
50 #include "llvm/ADT/STLExtras.h"
51 #include "llvm/ADT/StringExtras.h"
52 #include "llvm/ADT/StringSwitch.h"
53 #include "llvm/ADT/Triple.h"
54 #include "llvm/Analysis/TargetLibraryInfo.h"
55 #include "llvm/Frontend/OpenMP/OMPIRBuilder.h"
56 #include "llvm/IR/CallingConv.h"
57 #include "llvm/IR/DataLayout.h"
58 #include "llvm/IR/Intrinsics.h"
59 #include "llvm/IR/LLVMContext.h"
60 #include "llvm/IR/Module.h"
61 #include "llvm/IR/ProfileSummary.h"
62 #include "llvm/ProfileData/InstrProfReader.h"
63 #include "llvm/ProfileData/SampleProf.h"
64 #include "llvm/Support/CRC.h"
65 #include "llvm/Support/CodeGen.h"
66 #include "llvm/Support/CommandLine.h"
67 #include "llvm/Support/ConvertUTF.h"
68 #include "llvm/Support/ErrorHandling.h"
69 #include "llvm/Support/TimeProfiler.h"
70 #include "llvm/Support/X86TargetParser.h"
71 #include "llvm/Support/xxhash.h"
72 #include <optional>
73 
74 using namespace clang;
75 using namespace CodeGen;
76 
77 static llvm::cl::opt<bool> LimitedCoverage(
78     "limited-coverage-experimental", llvm::cl::Hidden,
79     llvm::cl::desc("Emit limited coverage mapping information (experimental)"));
80 
81 static const char AnnotationSection[] = "llvm.metadata";
82 
83 static CGCXXABI *createCXXABI(CodeGenModule &CGM) {
84   switch (CGM.getContext().getCXXABIKind()) {
85   case TargetCXXABI::AppleARM64:
86   case TargetCXXABI::Fuchsia:
87   case TargetCXXABI::GenericAArch64:
88   case TargetCXXABI::GenericARM:
89   case TargetCXXABI::iOS:
90   case TargetCXXABI::WatchOS:
91   case TargetCXXABI::GenericMIPS:
92   case TargetCXXABI::GenericItanium:
93   case TargetCXXABI::WebAssembly:
94   case TargetCXXABI::XL:
95     return CreateItaniumCXXABI(CGM);
96   case TargetCXXABI::Microsoft:
97     return CreateMicrosoftCXXABI(CGM);
98   }
99 
100   llvm_unreachable("invalid C++ ABI kind");
101 }
102 
103 CodeGenModule::CodeGenModule(ASTContext &C,
104                              IntrusiveRefCntPtr<llvm::vfs::FileSystem> FS,
105                              const HeaderSearchOptions &HSO,
106                              const PreprocessorOptions &PPO,
107                              const CodeGenOptions &CGO, llvm::Module &M,
108                              DiagnosticsEngine &diags,
109                              CoverageSourceInfo *CoverageInfo)
110     : Context(C), LangOpts(C.getLangOpts()), FS(std::move(FS)),
111       HeaderSearchOpts(HSO), PreprocessorOpts(PPO), CodeGenOpts(CGO),
112       TheModule(M), Diags(diags), Target(C.getTargetInfo()),
113       ABI(createCXXABI(*this)), VMContext(M.getContext()), Types(*this),
114       VTables(*this), SanitizerMD(new SanitizerMetadata(*this)) {
115 
116   // Initialize the type cache.
117   llvm::LLVMContext &LLVMContext = M.getContext();
118   VoidTy = llvm::Type::getVoidTy(LLVMContext);
119   Int8Ty = llvm::Type::getInt8Ty(LLVMContext);
120   Int16Ty = llvm::Type::getInt16Ty(LLVMContext);
121   Int32Ty = llvm::Type::getInt32Ty(LLVMContext);
122   Int64Ty = llvm::Type::getInt64Ty(LLVMContext);
123   HalfTy = llvm::Type::getHalfTy(LLVMContext);
124   BFloatTy = llvm::Type::getBFloatTy(LLVMContext);
125   FloatTy = llvm::Type::getFloatTy(LLVMContext);
126   DoubleTy = llvm::Type::getDoubleTy(LLVMContext);
127   PointerWidthInBits = C.getTargetInfo().getPointerWidth(LangAS::Default);
128   PointerAlignInBytes =
129       C.toCharUnitsFromBits(C.getTargetInfo().getPointerAlign(LangAS::Default))
130           .getQuantity();
131   SizeSizeInBytes =
132     C.toCharUnitsFromBits(C.getTargetInfo().getMaxPointerWidth()).getQuantity();
133   IntAlignInBytes =
134     C.toCharUnitsFromBits(C.getTargetInfo().getIntAlign()).getQuantity();
135   CharTy =
136     llvm::IntegerType::get(LLVMContext, C.getTargetInfo().getCharWidth());
137   IntTy = llvm::IntegerType::get(LLVMContext, C.getTargetInfo().getIntWidth());
138   IntPtrTy = llvm::IntegerType::get(LLVMContext,
139     C.getTargetInfo().getMaxPointerWidth());
140   Int8PtrTy = Int8Ty->getPointerTo(0);
141   Int8PtrPtrTy = Int8PtrTy->getPointerTo(0);
142   const llvm::DataLayout &DL = M.getDataLayout();
143   AllocaInt8PtrTy = Int8Ty->getPointerTo(DL.getAllocaAddrSpace());
144   GlobalsInt8PtrTy = Int8Ty->getPointerTo(DL.getDefaultGlobalsAddressSpace());
145   ConstGlobalsPtrTy = Int8Ty->getPointerTo(
146       C.getTargetAddressSpace(GetGlobalConstantAddressSpace()));
147   ASTAllocaAddressSpace = getTargetCodeGenInfo().getASTAllocaAddressSpace();
148 
149   // Build C++20 Module initializers.
150   // TODO: Add Microsoft here once we know the mangling required for the
151   // initializers.
152   CXX20ModuleInits =
153       LangOpts.CPlusPlusModules && getCXXABI().getMangleContext().getKind() ==
154                                        ItaniumMangleContext::MK_Itanium;
155 
156   RuntimeCC = getTargetCodeGenInfo().getABIInfo().getRuntimeCC();
157 
158   if (LangOpts.ObjC)
159     createObjCRuntime();
160   if (LangOpts.OpenCL)
161     createOpenCLRuntime();
162   if (LangOpts.OpenMP)
163     createOpenMPRuntime();
164   if (LangOpts.CUDA)
165     createCUDARuntime();
166   if (LangOpts.HLSL)
167     createHLSLRuntime();
168 
169   // Enable TBAA unless it's suppressed. ThreadSanitizer needs TBAA even at O0.
170   if (LangOpts.Sanitize.has(SanitizerKind::Thread) ||
171       (!CodeGenOpts.RelaxedAliasing && CodeGenOpts.OptimizationLevel > 0))
172     TBAA.reset(new CodeGenTBAA(Context, TheModule, CodeGenOpts, getLangOpts(),
173                                getCXXABI().getMangleContext()));
174 
175   // If debug info or coverage generation is enabled, create the CGDebugInfo
176   // object.
177   if (CodeGenOpts.getDebugInfo() != codegenoptions::NoDebugInfo ||
178       CodeGenOpts.EmitGcovArcs || CodeGenOpts.EmitGcovNotes)
179     DebugInfo.reset(new CGDebugInfo(*this));
180 
181   Block.GlobalUniqueCount = 0;
182 
183   if (C.getLangOpts().ObjC)
184     ObjCData.reset(new ObjCEntrypoints());
185 
186   if (CodeGenOpts.hasProfileClangUse()) {
187     auto ReaderOrErr = llvm::IndexedInstrProfReader::create(
188         CodeGenOpts.ProfileInstrumentUsePath, CodeGenOpts.ProfileRemappingFile);
189     // We're checking for profile read errors in CompilerInvocation, so if
190     // there was an error it should've already been caught. If it hasn't been
191     // somehow, trip an assertion.
192     assert(ReaderOrErr);
193     PGOReader = std::move(ReaderOrErr.get());
194   }
195 
196   // If coverage mapping generation is enabled, create the
197   // CoverageMappingModuleGen object.
198   if (CodeGenOpts.CoverageMapping)
199     CoverageMapping.reset(new CoverageMappingModuleGen(*this, *CoverageInfo));
200 
201   // Generate the module name hash here if needed.
202   if (CodeGenOpts.UniqueInternalLinkageNames &&
203       !getModule().getSourceFileName().empty()) {
204     std::string Path = getModule().getSourceFileName();
205     // Check if a path substitution is needed from the MacroPrefixMap.
206     for (const auto &Entry : LangOpts.MacroPrefixMap)
207       if (Path.rfind(Entry.first, 0) != std::string::npos) {
208         Path = Entry.second + Path.substr(Entry.first.size());
209         break;
210       }
211     ModuleNameHash = llvm::getUniqueInternalLinkagePostfix(Path);
212   }
213 }
214 
215 CodeGenModule::~CodeGenModule() {}
216 
217 void CodeGenModule::createObjCRuntime() {
218   // This is just isGNUFamily(), but we want to force implementors of
219   // new ABIs to decide how best to do this.
220   switch (LangOpts.ObjCRuntime.getKind()) {
221   case ObjCRuntime::GNUstep:
222   case ObjCRuntime::GCC:
223   case ObjCRuntime::ObjFW:
224     ObjCRuntime.reset(CreateGNUObjCRuntime(*this));
225     return;
226 
227   case ObjCRuntime::FragileMacOSX:
228   case ObjCRuntime::MacOSX:
229   case ObjCRuntime::iOS:
230   case ObjCRuntime::WatchOS:
231     ObjCRuntime.reset(CreateMacObjCRuntime(*this));
232     return;
233   }
234   llvm_unreachable("bad runtime kind");
235 }
236 
237 void CodeGenModule::createOpenCLRuntime() {
238   OpenCLRuntime.reset(new CGOpenCLRuntime(*this));
239 }
240 
241 void CodeGenModule::createOpenMPRuntime() {
242   // Select a specialized code generation class based on the target, if any.
243   // If it does not exist use the default implementation.
244   switch (getTriple().getArch()) {
245   case llvm::Triple::nvptx:
246   case llvm::Triple::nvptx64:
247   case llvm::Triple::amdgcn:
248     assert(getLangOpts().OpenMPIsDevice &&
249            "OpenMP AMDGPU/NVPTX is only prepared to deal with device code.");
250     OpenMPRuntime.reset(new CGOpenMPRuntimeGPU(*this));
251     break;
252   default:
253     if (LangOpts.OpenMPSimd)
254       OpenMPRuntime.reset(new CGOpenMPSIMDRuntime(*this));
255     else
256       OpenMPRuntime.reset(new CGOpenMPRuntime(*this));
257     break;
258   }
259 }
260 
261 void CodeGenModule::createCUDARuntime() {
262   CUDARuntime.reset(CreateNVCUDARuntime(*this));
263 }
264 
265 void CodeGenModule::createHLSLRuntime() {
266   HLSLRuntime.reset(new CGHLSLRuntime(*this));
267 }
268 
269 void CodeGenModule::addReplacement(StringRef Name, llvm::Constant *C) {
270   Replacements[Name] = C;
271 }
272 
273 void CodeGenModule::applyReplacements() {
274   for (auto &I : Replacements) {
275     StringRef MangledName = I.first();
276     llvm::Constant *Replacement = I.second;
277     llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
278     if (!Entry)
279       continue;
280     auto *OldF = cast<llvm::Function>(Entry);
281     auto *NewF = dyn_cast<llvm::Function>(Replacement);
282     if (!NewF) {
283       if (auto *Alias = dyn_cast<llvm::GlobalAlias>(Replacement)) {
284         NewF = dyn_cast<llvm::Function>(Alias->getAliasee());
285       } else {
286         auto *CE = cast<llvm::ConstantExpr>(Replacement);
287         assert(CE->getOpcode() == llvm::Instruction::BitCast ||
288                CE->getOpcode() == llvm::Instruction::GetElementPtr);
289         NewF = dyn_cast<llvm::Function>(CE->getOperand(0));
290       }
291     }
292 
293     // Replace old with new, but keep the old order.
294     OldF->replaceAllUsesWith(Replacement);
295     if (NewF) {
296       NewF->removeFromParent();
297       OldF->getParent()->getFunctionList().insertAfter(OldF->getIterator(),
298                                                        NewF);
299     }
300     OldF->eraseFromParent();
301   }
302 }
303 
304 void CodeGenModule::addGlobalValReplacement(llvm::GlobalValue *GV, llvm::Constant *C) {
305   GlobalValReplacements.push_back(std::make_pair(GV, C));
306 }
307 
308 void CodeGenModule::applyGlobalValReplacements() {
309   for (auto &I : GlobalValReplacements) {
310     llvm::GlobalValue *GV = I.first;
311     llvm::Constant *C = I.second;
312 
313     GV->replaceAllUsesWith(C);
314     GV->eraseFromParent();
315   }
316 }
317 
318 // This is only used in aliases that we created and we know they have a
319 // linear structure.
320 static const llvm::GlobalValue *getAliasedGlobal(const llvm::GlobalValue *GV) {
321   const llvm::Constant *C;
322   if (auto *GA = dyn_cast<llvm::GlobalAlias>(GV))
323     C = GA->getAliasee();
324   else if (auto *GI = dyn_cast<llvm::GlobalIFunc>(GV))
325     C = GI->getResolver();
326   else
327     return GV;
328 
329   const auto *AliaseeGV = dyn_cast<llvm::GlobalValue>(C->stripPointerCasts());
330   if (!AliaseeGV)
331     return nullptr;
332 
333   const llvm::GlobalValue *FinalGV = AliaseeGV->getAliaseeObject();
334   if (FinalGV == GV)
335     return nullptr;
336 
337   return FinalGV;
338 }
339 
340 static bool checkAliasedGlobal(DiagnosticsEngine &Diags,
341                                SourceLocation Location, bool IsIFunc,
342                                const llvm::GlobalValue *Alias,
343                                const llvm::GlobalValue *&GV) {
344   GV = getAliasedGlobal(Alias);
345   if (!GV) {
346     Diags.Report(Location, diag::err_cyclic_alias) << IsIFunc;
347     return false;
348   }
349 
350   if (GV->isDeclaration()) {
351     Diags.Report(Location, diag::err_alias_to_undefined) << IsIFunc << IsIFunc;
352     return false;
353   }
354 
355   if (IsIFunc) {
356     // Check resolver function type.
357     const auto *F = dyn_cast<llvm::Function>(GV);
358     if (!F) {
359       Diags.Report(Location, diag::err_alias_to_undefined)
360           << IsIFunc << IsIFunc;
361       return false;
362     }
363 
364     llvm::FunctionType *FTy = F->getFunctionType();
365     if (!FTy->getReturnType()->isPointerTy()) {
366       Diags.Report(Location, diag::err_ifunc_resolver_return);
367       return false;
368     }
369   }
370 
371   return true;
372 }
373 
374 void CodeGenModule::checkAliases() {
375   // Check if the constructed aliases are well formed. It is really unfortunate
376   // that we have to do this in CodeGen, but we only construct mangled names
377   // and aliases during codegen.
378   bool Error = false;
379   DiagnosticsEngine &Diags = getDiags();
380   for (const GlobalDecl &GD : Aliases) {
381     const auto *D = cast<ValueDecl>(GD.getDecl());
382     SourceLocation Location;
383     bool IsIFunc = D->hasAttr<IFuncAttr>();
384     if (const Attr *A = D->getDefiningAttr())
385       Location = A->getLocation();
386     else
387       llvm_unreachable("Not an alias or ifunc?");
388 
389     StringRef MangledName = getMangledName(GD);
390     llvm::GlobalValue *Alias = GetGlobalValue(MangledName);
391     const llvm::GlobalValue *GV = nullptr;
392     if (!checkAliasedGlobal(Diags, Location, IsIFunc, Alias, GV)) {
393       Error = true;
394       continue;
395     }
396 
397     llvm::Constant *Aliasee =
398         IsIFunc ? cast<llvm::GlobalIFunc>(Alias)->getResolver()
399                 : cast<llvm::GlobalAlias>(Alias)->getAliasee();
400 
401     llvm::GlobalValue *AliaseeGV;
402     if (auto CE = dyn_cast<llvm::ConstantExpr>(Aliasee))
403       AliaseeGV = cast<llvm::GlobalValue>(CE->getOperand(0));
404     else
405       AliaseeGV = cast<llvm::GlobalValue>(Aliasee);
406 
407     if (const SectionAttr *SA = D->getAttr<SectionAttr>()) {
408       StringRef AliasSection = SA->getName();
409       if (AliasSection != AliaseeGV->getSection())
410         Diags.Report(SA->getLocation(), diag::warn_alias_with_section)
411             << AliasSection << IsIFunc << IsIFunc;
412     }
413 
414     // We have to handle alias to weak aliases in here. LLVM itself disallows
415     // this since the object semantics would not match the IL one. For
416     // compatibility with gcc we implement it by just pointing the alias
417     // to its aliasee's aliasee. We also warn, since the user is probably
418     // expecting the link to be weak.
419     if (auto *GA = dyn_cast<llvm::GlobalAlias>(AliaseeGV)) {
420       if (GA->isInterposable()) {
421         Diags.Report(Location, diag::warn_alias_to_weak_alias)
422             << GV->getName() << GA->getName() << IsIFunc;
423         Aliasee = llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
424             GA->getAliasee(), Alias->getType());
425 
426         if (IsIFunc)
427           cast<llvm::GlobalIFunc>(Alias)->setResolver(Aliasee);
428         else
429           cast<llvm::GlobalAlias>(Alias)->setAliasee(Aliasee);
430       }
431     }
432   }
433   if (!Error)
434     return;
435 
436   for (const GlobalDecl &GD : Aliases) {
437     StringRef MangledName = getMangledName(GD);
438     llvm::GlobalValue *Alias = GetGlobalValue(MangledName);
439     Alias->replaceAllUsesWith(llvm::UndefValue::get(Alias->getType()));
440     Alias->eraseFromParent();
441   }
442 }
443 
444 void CodeGenModule::clear() {
445   DeferredDeclsToEmit.clear();
446   EmittedDeferredDecls.clear();
447   if (OpenMPRuntime)
448     OpenMPRuntime->clear();
449 }
450 
451 void InstrProfStats::reportDiagnostics(DiagnosticsEngine &Diags,
452                                        StringRef MainFile) {
453   if (!hasDiagnostics())
454     return;
455   if (VisitedInMainFile > 0 && VisitedInMainFile == MissingInMainFile) {
456     if (MainFile.empty())
457       MainFile = "<stdin>";
458     Diags.Report(diag::warn_profile_data_unprofiled) << MainFile;
459   } else {
460     if (Mismatched > 0)
461       Diags.Report(diag::warn_profile_data_out_of_date) << Visited << Mismatched;
462 
463     if (Missing > 0)
464       Diags.Report(diag::warn_profile_data_missing) << Visited << Missing;
465   }
466 }
467 
468 static void setVisibilityFromDLLStorageClass(const clang::LangOptions &LO,
469                                              llvm::Module &M) {
470   if (!LO.VisibilityFromDLLStorageClass)
471     return;
472 
473   llvm::GlobalValue::VisibilityTypes DLLExportVisibility =
474       CodeGenModule::GetLLVMVisibility(LO.getDLLExportVisibility());
475   llvm::GlobalValue::VisibilityTypes NoDLLStorageClassVisibility =
476       CodeGenModule::GetLLVMVisibility(LO.getNoDLLStorageClassVisibility());
477   llvm::GlobalValue::VisibilityTypes ExternDeclDLLImportVisibility =
478       CodeGenModule::GetLLVMVisibility(LO.getExternDeclDLLImportVisibility());
479   llvm::GlobalValue::VisibilityTypes ExternDeclNoDLLStorageClassVisibility =
480       CodeGenModule::GetLLVMVisibility(
481           LO.getExternDeclNoDLLStorageClassVisibility());
482 
483   for (llvm::GlobalValue &GV : M.global_values()) {
484     if (GV.hasAppendingLinkage() || GV.hasLocalLinkage())
485       continue;
486 
487     // Reset DSO locality before setting the visibility. This removes
488     // any effects that visibility options and annotations may have
489     // had on the DSO locality. Setting the visibility will implicitly set
490     // appropriate globals to DSO Local; however, this will be pessimistic
491     // w.r.t. to the normal compiler IRGen.
492     GV.setDSOLocal(false);
493 
494     if (GV.isDeclarationForLinker()) {
495       GV.setVisibility(GV.getDLLStorageClass() ==
496                                llvm::GlobalValue::DLLImportStorageClass
497                            ? ExternDeclDLLImportVisibility
498                            : ExternDeclNoDLLStorageClassVisibility);
499     } else {
500       GV.setVisibility(GV.getDLLStorageClass() ==
501                                llvm::GlobalValue::DLLExportStorageClass
502                            ? DLLExportVisibility
503                            : NoDLLStorageClassVisibility);
504     }
505 
506     GV.setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
507   }
508 }
509 
510 void CodeGenModule::Release() {
511   Module *Primary = getContext().getModuleForCodeGen();
512   if (CXX20ModuleInits && Primary && !Primary->isHeaderLikeModule())
513     EmitModuleInitializers(Primary);
514   EmitDeferred();
515   DeferredDecls.insert(EmittedDeferredDecls.begin(),
516                        EmittedDeferredDecls.end());
517   EmittedDeferredDecls.clear();
518   EmitVTablesOpportunistically();
519   applyGlobalValReplacements();
520   applyReplacements();
521   emitMultiVersionFunctions();
522 
523   if (Context.getLangOpts().IncrementalExtensions &&
524       GlobalTopLevelStmtBlockInFlight.first) {
525     const TopLevelStmtDecl *TLSD = GlobalTopLevelStmtBlockInFlight.second;
526     GlobalTopLevelStmtBlockInFlight.first->FinishFunction(TLSD->getEndLoc());
527     GlobalTopLevelStmtBlockInFlight = {nullptr, nullptr};
528   }
529 
530   if (CXX20ModuleInits && Primary && Primary->isInterfaceOrPartition())
531     EmitCXXModuleInitFunc(Primary);
532   else
533     EmitCXXGlobalInitFunc();
534   EmitCXXGlobalCleanUpFunc();
535   registerGlobalDtorsWithAtExit();
536   EmitCXXThreadLocalInitFunc();
537   if (ObjCRuntime)
538     if (llvm::Function *ObjCInitFunction = ObjCRuntime->ModuleInitFunction())
539       AddGlobalCtor(ObjCInitFunction);
540   if (Context.getLangOpts().CUDA && CUDARuntime) {
541     if (llvm::Function *CudaCtorFunction = CUDARuntime->finalizeModule())
542       AddGlobalCtor(CudaCtorFunction);
543   }
544   if (OpenMPRuntime) {
545     if (llvm::Function *OpenMPRequiresDirectiveRegFun =
546             OpenMPRuntime->emitRequiresDirectiveRegFun()) {
547       AddGlobalCtor(OpenMPRequiresDirectiveRegFun, 0);
548     }
549     OpenMPRuntime->createOffloadEntriesAndInfoMetadata();
550     OpenMPRuntime->clear();
551   }
552   if (PGOReader) {
553     getModule().setProfileSummary(
554         PGOReader->getSummary(/* UseCS */ false).getMD(VMContext),
555         llvm::ProfileSummary::PSK_Instr);
556     if (PGOStats.hasDiagnostics())
557       PGOStats.reportDiagnostics(getDiags(), getCodeGenOpts().MainFileName);
558   }
559   llvm::stable_sort(GlobalCtors, [](const Structor &L, const Structor &R) {
560     return L.LexOrder < R.LexOrder;
561   });
562   EmitCtorList(GlobalCtors, "llvm.global_ctors");
563   EmitCtorList(GlobalDtors, "llvm.global_dtors");
564   EmitGlobalAnnotations();
565   EmitStaticExternCAliases();
566   checkAliases();
567   EmitDeferredUnusedCoverageMappings();
568   CodeGenPGO(*this).setValueProfilingFlag(getModule());
569   if (CoverageMapping)
570     CoverageMapping->emit();
571   if (CodeGenOpts.SanitizeCfiCrossDso) {
572     CodeGenFunction(*this).EmitCfiCheckFail();
573     CodeGenFunction(*this).EmitCfiCheckStub();
574   }
575   if (LangOpts.Sanitize.has(SanitizerKind::KCFI))
576     finalizeKCFITypes();
577   emitAtAvailableLinkGuard();
578   if (Context.getTargetInfo().getTriple().isWasm())
579     EmitMainVoidAlias();
580 
581   if (getTriple().isAMDGPU()) {
582     // Emit reference of __amdgpu_device_library_preserve_asan_functions to
583     // preserve ASAN functions in bitcode libraries.
584     if (LangOpts.Sanitize.has(SanitizerKind::Address)) {
585       auto *FT = llvm::FunctionType::get(VoidTy, {});
586       auto *F = llvm::Function::Create(
587           FT, llvm::GlobalValue::ExternalLinkage,
588           "__amdgpu_device_library_preserve_asan_functions", &getModule());
589       auto *Var = new llvm::GlobalVariable(
590           getModule(), FT->getPointerTo(),
591           /*isConstant=*/true, llvm::GlobalValue::WeakAnyLinkage, F,
592           "__amdgpu_device_library_preserve_asan_functions_ptr", nullptr,
593           llvm::GlobalVariable::NotThreadLocal);
594       addCompilerUsedGlobal(Var);
595     }
596     // Emit amdgpu_code_object_version module flag, which is code object version
597     // times 100.
598     if (getTarget().getTargetOpts().CodeObjectVersion !=
599         TargetOptions::COV_None) {
600       getModule().addModuleFlag(llvm::Module::Error,
601                                 "amdgpu_code_object_version",
602                                 getTarget().getTargetOpts().CodeObjectVersion);
603     }
604   }
605 
606   // Emit a global array containing all external kernels or device variables
607   // used by host functions and mark it as used for CUDA/HIP. This is necessary
608   // to get kernels or device variables in archives linked in even if these
609   // kernels or device variables are only used in host functions.
610   if (!Context.CUDAExternalDeviceDeclODRUsedByHost.empty()) {
611     SmallVector<llvm::Constant *, 8> UsedArray;
612     for (auto D : Context.CUDAExternalDeviceDeclODRUsedByHost) {
613       GlobalDecl GD;
614       if (auto *FD = dyn_cast<FunctionDecl>(D))
615         GD = GlobalDecl(FD, KernelReferenceKind::Kernel);
616       else
617         GD = GlobalDecl(D);
618       UsedArray.push_back(llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
619           GetAddrOfGlobal(GD), Int8PtrTy));
620     }
621 
622     llvm::ArrayType *ATy = llvm::ArrayType::get(Int8PtrTy, UsedArray.size());
623 
624     auto *GV = new llvm::GlobalVariable(
625         getModule(), ATy, false, llvm::GlobalValue::InternalLinkage,
626         llvm::ConstantArray::get(ATy, UsedArray), "__clang_gpu_used_external");
627     addCompilerUsedGlobal(GV);
628   }
629 
630   emitLLVMUsed();
631   if (SanStats)
632     SanStats->finish();
633 
634   if (CodeGenOpts.Autolink &&
635       (Context.getLangOpts().Modules || !LinkerOptionsMetadata.empty())) {
636     EmitModuleLinkOptions();
637   }
638 
639   // On ELF we pass the dependent library specifiers directly to the linker
640   // without manipulating them. This is in contrast to other platforms where
641   // they are mapped to a specific linker option by the compiler. This
642   // difference is a result of the greater variety of ELF linkers and the fact
643   // that ELF linkers tend to handle libraries in a more complicated fashion
644   // than on other platforms. This forces us to defer handling the dependent
645   // libs to the linker.
646   //
647   // CUDA/HIP device and host libraries are different. Currently there is no
648   // way to differentiate dependent libraries for host or device. Existing
649   // usage of #pragma comment(lib, *) is intended for host libraries on
650   // Windows. Therefore emit llvm.dependent-libraries only for host.
651   if (!ELFDependentLibraries.empty() && !Context.getLangOpts().CUDAIsDevice) {
652     auto *NMD = getModule().getOrInsertNamedMetadata("llvm.dependent-libraries");
653     for (auto *MD : ELFDependentLibraries)
654       NMD->addOperand(MD);
655   }
656 
657   // Record mregparm value now so it is visible through rest of codegen.
658   if (Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86)
659     getModule().addModuleFlag(llvm::Module::Error, "NumRegisterParameters",
660                               CodeGenOpts.NumRegisterParameters);
661 
662   if (CodeGenOpts.DwarfVersion) {
663     getModule().addModuleFlag(llvm::Module::Max, "Dwarf Version",
664                               CodeGenOpts.DwarfVersion);
665   }
666 
667   if (CodeGenOpts.Dwarf64)
668     getModule().addModuleFlag(llvm::Module::Max, "DWARF64", 1);
669 
670   if (Context.getLangOpts().SemanticInterposition)
671     // Require various optimization to respect semantic interposition.
672     getModule().setSemanticInterposition(true);
673 
674   if (CodeGenOpts.EmitCodeView) {
675     // Indicate that we want CodeView in the metadata.
676     getModule().addModuleFlag(llvm::Module::Warning, "CodeView", 1);
677   }
678   if (CodeGenOpts.CodeViewGHash) {
679     getModule().addModuleFlag(llvm::Module::Warning, "CodeViewGHash", 1);
680   }
681   if (CodeGenOpts.ControlFlowGuard) {
682     // Function ID tables and checks for Control Flow Guard (cfguard=2).
683     getModule().addModuleFlag(llvm::Module::Warning, "cfguard", 2);
684   } else if (CodeGenOpts.ControlFlowGuardNoChecks) {
685     // Function ID tables for Control Flow Guard (cfguard=1).
686     getModule().addModuleFlag(llvm::Module::Warning, "cfguard", 1);
687   }
688   if (CodeGenOpts.EHContGuard) {
689     // Function ID tables for EH Continuation Guard.
690     getModule().addModuleFlag(llvm::Module::Warning, "ehcontguard", 1);
691   }
692   if (Context.getLangOpts().Kernel) {
693     // Note if we are compiling with /kernel.
694     getModule().addModuleFlag(llvm::Module::Warning, "ms-kernel", 1);
695   }
696   if (CodeGenOpts.OptimizationLevel > 0 && CodeGenOpts.StrictVTablePointers) {
697     // We don't support LTO with 2 with different StrictVTablePointers
698     // FIXME: we could support it by stripping all the information introduced
699     // by StrictVTablePointers.
700 
701     getModule().addModuleFlag(llvm::Module::Error, "StrictVTablePointers",1);
702 
703     llvm::Metadata *Ops[2] = {
704               llvm::MDString::get(VMContext, "StrictVTablePointers"),
705               llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
706                   llvm::Type::getInt32Ty(VMContext), 1))};
707 
708     getModule().addModuleFlag(llvm::Module::Require,
709                               "StrictVTablePointersRequirement",
710                               llvm::MDNode::get(VMContext, Ops));
711   }
712   if (getModuleDebugInfo())
713     // We support a single version in the linked module. The LLVM
714     // parser will drop debug info with a different version number
715     // (and warn about it, too).
716     getModule().addModuleFlag(llvm::Module::Warning, "Debug Info Version",
717                               llvm::DEBUG_METADATA_VERSION);
718 
719   // We need to record the widths of enums and wchar_t, so that we can generate
720   // the correct build attributes in the ARM backend. wchar_size is also used by
721   // TargetLibraryInfo.
722   uint64_t WCharWidth =
723       Context.getTypeSizeInChars(Context.getWideCharType()).getQuantity();
724   getModule().addModuleFlag(llvm::Module::Error, "wchar_size", WCharWidth);
725 
726   llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch();
727   if (   Arch == llvm::Triple::arm
728       || Arch == llvm::Triple::armeb
729       || Arch == llvm::Triple::thumb
730       || Arch == llvm::Triple::thumbeb) {
731     // The minimum width of an enum in bytes
732     uint64_t EnumWidth = Context.getLangOpts().ShortEnums ? 1 : 4;
733     getModule().addModuleFlag(llvm::Module::Error, "min_enum_size", EnumWidth);
734   }
735 
736   if (Arch == llvm::Triple::riscv32 || Arch == llvm::Triple::riscv64) {
737     StringRef ABIStr = Target.getABI();
738     llvm::LLVMContext &Ctx = TheModule.getContext();
739     getModule().addModuleFlag(llvm::Module::Error, "target-abi",
740                               llvm::MDString::get(Ctx, ABIStr));
741   }
742 
743   if (CodeGenOpts.SanitizeCfiCrossDso) {
744     // Indicate that we want cross-DSO control flow integrity checks.
745     getModule().addModuleFlag(llvm::Module::Override, "Cross-DSO CFI", 1);
746   }
747 
748   if (CodeGenOpts.WholeProgramVTables) {
749     // Indicate whether VFE was enabled for this module, so that the
750     // vcall_visibility metadata added under whole program vtables is handled
751     // appropriately in the optimizer.
752     getModule().addModuleFlag(llvm::Module::Error, "Virtual Function Elim",
753                               CodeGenOpts.VirtualFunctionElimination);
754   }
755 
756   if (LangOpts.Sanitize.has(SanitizerKind::CFIICall)) {
757     getModule().addModuleFlag(llvm::Module::Override,
758                               "CFI Canonical Jump Tables",
759                               CodeGenOpts.SanitizeCfiCanonicalJumpTables);
760   }
761 
762   if (LangOpts.Sanitize.has(SanitizerKind::KCFI)) {
763     getModule().addModuleFlag(llvm::Module::Override, "kcfi", 1);
764     // KCFI assumes patchable-function-prefix is the same for all indirectly
765     // called functions. Store the expected offset for code generation.
766     if (CodeGenOpts.PatchableFunctionEntryOffset)
767       getModule().addModuleFlag(llvm::Module::Override, "kcfi-offset",
768                                 CodeGenOpts.PatchableFunctionEntryOffset);
769   }
770 
771   if (CodeGenOpts.CFProtectionReturn &&
772       Target.checkCFProtectionReturnSupported(getDiags())) {
773     // Indicate that we want to instrument return control flow protection.
774     getModule().addModuleFlag(llvm::Module::Min, "cf-protection-return",
775                               1);
776   }
777 
778   if (CodeGenOpts.CFProtectionBranch &&
779       Target.checkCFProtectionBranchSupported(getDiags())) {
780     // Indicate that we want to instrument branch control flow protection.
781     getModule().addModuleFlag(llvm::Module::Min, "cf-protection-branch",
782                               1);
783   }
784 
785   if (CodeGenOpts.FunctionReturnThunks)
786     getModule().addModuleFlag(llvm::Module::Override, "function_return_thunk_extern", 1);
787 
788   if (CodeGenOpts.IndirectBranchCSPrefix)
789     getModule().addModuleFlag(llvm::Module::Override, "indirect_branch_cs_prefix", 1);
790 
791   // Add module metadata for return address signing (ignoring
792   // non-leaf/all) and stack tagging. These are actually turned on by function
793   // attributes, but we use module metadata to emit build attributes. This is
794   // needed for LTO, where the function attributes are inside bitcode
795   // serialised into a global variable by the time build attributes are
796   // emitted, so we can't access them. LTO objects could be compiled with
797   // different flags therefore module flags are set to "Min" behavior to achieve
798   // the same end result of the normal build where e.g BTI is off if any object
799   // doesn't support it.
800   if (Context.getTargetInfo().hasFeature("ptrauth") &&
801       LangOpts.getSignReturnAddressScope() !=
802           LangOptions::SignReturnAddressScopeKind::None)
803     getModule().addModuleFlag(llvm::Module::Override,
804                               "sign-return-address-buildattr", 1);
805   if (LangOpts.Sanitize.has(SanitizerKind::MemtagStack))
806     getModule().addModuleFlag(llvm::Module::Override,
807                               "tag-stack-memory-buildattr", 1);
808 
809   if (Arch == llvm::Triple::thumb || Arch == llvm::Triple::thumbeb ||
810       Arch == llvm::Triple::arm || Arch == llvm::Triple::armeb ||
811       Arch == llvm::Triple::aarch64 || Arch == llvm::Triple::aarch64_32 ||
812       Arch == llvm::Triple::aarch64_be) {
813     if (LangOpts.BranchTargetEnforcement)
814       getModule().addModuleFlag(llvm::Module::Min, "branch-target-enforcement",
815                                 1);
816     if (LangOpts.hasSignReturnAddress())
817       getModule().addModuleFlag(llvm::Module::Min, "sign-return-address", 1);
818     if (LangOpts.isSignReturnAddressScopeAll())
819       getModule().addModuleFlag(llvm::Module::Min, "sign-return-address-all",
820                                 1);
821     if (!LangOpts.isSignReturnAddressWithAKey())
822       getModule().addModuleFlag(llvm::Module::Min,
823                                 "sign-return-address-with-bkey", 1);
824   }
825 
826   if (!CodeGenOpts.MemoryProfileOutput.empty()) {
827     llvm::LLVMContext &Ctx = TheModule.getContext();
828     getModule().addModuleFlag(
829         llvm::Module::Error, "MemProfProfileFilename",
830         llvm::MDString::get(Ctx, CodeGenOpts.MemoryProfileOutput));
831   }
832 
833   if (LangOpts.CUDAIsDevice && getTriple().isNVPTX()) {
834     // Indicate whether __nvvm_reflect should be configured to flush denormal
835     // floating point values to 0.  (This corresponds to its "__CUDA_FTZ"
836     // property.)
837     getModule().addModuleFlag(llvm::Module::Override, "nvvm-reflect-ftz",
838                               CodeGenOpts.FP32DenormalMode.Output !=
839                                   llvm::DenormalMode::IEEE);
840   }
841 
842   if (LangOpts.EHAsynch)
843     getModule().addModuleFlag(llvm::Module::Warning, "eh-asynch", 1);
844 
845   // Indicate whether this Module was compiled with -fopenmp
846   if (getLangOpts().OpenMP && !getLangOpts().OpenMPSimd)
847     getModule().addModuleFlag(llvm::Module::Max, "openmp", LangOpts.OpenMP);
848   if (getLangOpts().OpenMPIsDevice)
849     getModule().addModuleFlag(llvm::Module::Max, "openmp-device",
850                               LangOpts.OpenMP);
851 
852   // Emit OpenCL specific module metadata: OpenCL/SPIR version.
853   if (LangOpts.OpenCL || (LangOpts.CUDAIsDevice && getTriple().isSPIRV())) {
854     EmitOpenCLMetadata();
855     // Emit SPIR version.
856     if (getTriple().isSPIR()) {
857       // SPIR v2.0 s2.12 - The SPIR version used by the module is stored in the
858       // opencl.spir.version named metadata.
859       // C++ for OpenCL has a distinct mapping for version compatibility with
860       // OpenCL.
861       auto Version = LangOpts.getOpenCLCompatibleVersion();
862       llvm::Metadata *SPIRVerElts[] = {
863           llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
864               Int32Ty, Version / 100)),
865           llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
866               Int32Ty, (Version / 100 > 1) ? 0 : 2))};
867       llvm::NamedMDNode *SPIRVerMD =
868           TheModule.getOrInsertNamedMetadata("opencl.spir.version");
869       llvm::LLVMContext &Ctx = TheModule.getContext();
870       SPIRVerMD->addOperand(llvm::MDNode::get(Ctx, SPIRVerElts));
871     }
872   }
873 
874   // HLSL related end of code gen work items.
875   if (LangOpts.HLSL)
876     getHLSLRuntime().finishCodeGen();
877 
878   if (uint32_t PLevel = Context.getLangOpts().PICLevel) {
879     assert(PLevel < 3 && "Invalid PIC Level");
880     getModule().setPICLevel(static_cast<llvm::PICLevel::Level>(PLevel));
881     if (Context.getLangOpts().PIE)
882       getModule().setPIELevel(static_cast<llvm::PIELevel::Level>(PLevel));
883   }
884 
885   if (getCodeGenOpts().CodeModel.size() > 0) {
886     unsigned CM = llvm::StringSwitch<unsigned>(getCodeGenOpts().CodeModel)
887                   .Case("tiny", llvm::CodeModel::Tiny)
888                   .Case("small", llvm::CodeModel::Small)
889                   .Case("kernel", llvm::CodeModel::Kernel)
890                   .Case("medium", llvm::CodeModel::Medium)
891                   .Case("large", llvm::CodeModel::Large)
892                   .Default(~0u);
893     if (CM != ~0u) {
894       llvm::CodeModel::Model codeModel = static_cast<llvm::CodeModel::Model>(CM);
895       getModule().setCodeModel(codeModel);
896     }
897   }
898 
899   if (CodeGenOpts.NoPLT)
900     getModule().setRtLibUseGOT();
901   if (CodeGenOpts.UnwindTables)
902     getModule().setUwtable(llvm::UWTableKind(CodeGenOpts.UnwindTables));
903 
904   switch (CodeGenOpts.getFramePointer()) {
905   case CodeGenOptions::FramePointerKind::None:
906     // 0 ("none") is the default.
907     break;
908   case CodeGenOptions::FramePointerKind::NonLeaf:
909     getModule().setFramePointer(llvm::FramePointerKind::NonLeaf);
910     break;
911   case CodeGenOptions::FramePointerKind::All:
912     getModule().setFramePointer(llvm::FramePointerKind::All);
913     break;
914   }
915 
916   SimplifyPersonality();
917 
918   if (getCodeGenOpts().EmitDeclMetadata)
919     EmitDeclMetadata();
920 
921   if (getCodeGenOpts().EmitGcovArcs || getCodeGenOpts().EmitGcovNotes)
922     EmitCoverageFile();
923 
924   if (CGDebugInfo *DI = getModuleDebugInfo())
925     DI->finalize();
926 
927   if (getCodeGenOpts().EmitVersionIdentMetadata)
928     EmitVersionIdentMetadata();
929 
930   if (!getCodeGenOpts().RecordCommandLine.empty())
931     EmitCommandLineMetadata();
932 
933   if (!getCodeGenOpts().StackProtectorGuard.empty())
934     getModule().setStackProtectorGuard(getCodeGenOpts().StackProtectorGuard);
935   if (!getCodeGenOpts().StackProtectorGuardReg.empty())
936     getModule().setStackProtectorGuardReg(
937         getCodeGenOpts().StackProtectorGuardReg);
938   if (!getCodeGenOpts().StackProtectorGuardSymbol.empty())
939     getModule().setStackProtectorGuardSymbol(
940         getCodeGenOpts().StackProtectorGuardSymbol);
941   if (getCodeGenOpts().StackProtectorGuardOffset != INT_MAX)
942     getModule().setStackProtectorGuardOffset(
943         getCodeGenOpts().StackProtectorGuardOffset);
944   if (getCodeGenOpts().StackAlignment)
945     getModule().setOverrideStackAlignment(getCodeGenOpts().StackAlignment);
946   if (getCodeGenOpts().SkipRaxSetup)
947     getModule().addModuleFlag(llvm::Module::Override, "SkipRaxSetup", 1);
948 
949   getTargetCodeGenInfo().emitTargetMetadata(*this, MangledDeclNames);
950 
951   EmitBackendOptionsMetadata(getCodeGenOpts());
952 
953   // If there is device offloading code embed it in the host now.
954   EmbedObject(&getModule(), CodeGenOpts, getDiags());
955 
956   // Set visibility from DLL storage class
957   // We do this at the end of LLVM IR generation; after any operation
958   // that might affect the DLL storage class or the visibility, and
959   // before anything that might act on these.
960   setVisibilityFromDLLStorageClass(LangOpts, getModule());
961 }
962 
963 void CodeGenModule::EmitOpenCLMetadata() {
964   // SPIR v2.0 s2.13 - The OpenCL version used by the module is stored in the
965   // opencl.ocl.version named metadata node.
966   // C++ for OpenCL has a distinct mapping for versions compatibile with OpenCL.
967   auto Version = LangOpts.getOpenCLCompatibleVersion();
968   llvm::Metadata *OCLVerElts[] = {
969       llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
970           Int32Ty, Version / 100)),
971       llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
972           Int32Ty, (Version % 100) / 10))};
973   llvm::NamedMDNode *OCLVerMD =
974       TheModule.getOrInsertNamedMetadata("opencl.ocl.version");
975   llvm::LLVMContext &Ctx = TheModule.getContext();
976   OCLVerMD->addOperand(llvm::MDNode::get(Ctx, OCLVerElts));
977 }
978 
979 void CodeGenModule::EmitBackendOptionsMetadata(
980     const CodeGenOptions CodeGenOpts) {
981   if (getTriple().isRISCV()) {
982     getModule().addModuleFlag(llvm::Module::Error, "SmallDataLimit",
983                               CodeGenOpts.SmallDataLimit);
984   }
985 }
986 
987 void CodeGenModule::UpdateCompletedType(const TagDecl *TD) {
988   // Make sure that this type is translated.
989   Types.UpdateCompletedType(TD);
990 }
991 
992 void CodeGenModule::RefreshTypeCacheForClass(const CXXRecordDecl *RD) {
993   // Make sure that this type is translated.
994   Types.RefreshTypeCacheForClass(RD);
995 }
996 
997 llvm::MDNode *CodeGenModule::getTBAATypeInfo(QualType QTy) {
998   if (!TBAA)
999     return nullptr;
1000   return TBAA->getTypeInfo(QTy);
1001 }
1002 
1003 TBAAAccessInfo CodeGenModule::getTBAAAccessInfo(QualType AccessType) {
1004   if (!TBAA)
1005     return TBAAAccessInfo();
1006   if (getLangOpts().CUDAIsDevice) {
1007     // As CUDA builtin surface/texture types are replaced, skip generating TBAA
1008     // access info.
1009     if (AccessType->isCUDADeviceBuiltinSurfaceType()) {
1010       if (getTargetCodeGenInfo().getCUDADeviceBuiltinSurfaceDeviceType() !=
1011           nullptr)
1012         return TBAAAccessInfo();
1013     } else if (AccessType->isCUDADeviceBuiltinTextureType()) {
1014       if (getTargetCodeGenInfo().getCUDADeviceBuiltinTextureDeviceType() !=
1015           nullptr)
1016         return TBAAAccessInfo();
1017     }
1018   }
1019   return TBAA->getAccessInfo(AccessType);
1020 }
1021 
1022 TBAAAccessInfo
1023 CodeGenModule::getTBAAVTablePtrAccessInfo(llvm::Type *VTablePtrType) {
1024   if (!TBAA)
1025     return TBAAAccessInfo();
1026   return TBAA->getVTablePtrAccessInfo(VTablePtrType);
1027 }
1028 
1029 llvm::MDNode *CodeGenModule::getTBAAStructInfo(QualType QTy) {
1030   if (!TBAA)
1031     return nullptr;
1032   return TBAA->getTBAAStructInfo(QTy);
1033 }
1034 
1035 llvm::MDNode *CodeGenModule::getTBAABaseTypeInfo(QualType QTy) {
1036   if (!TBAA)
1037     return nullptr;
1038   return TBAA->getBaseTypeInfo(QTy);
1039 }
1040 
1041 llvm::MDNode *CodeGenModule::getTBAAAccessTagInfo(TBAAAccessInfo Info) {
1042   if (!TBAA)
1043     return nullptr;
1044   return TBAA->getAccessTagInfo(Info);
1045 }
1046 
1047 TBAAAccessInfo CodeGenModule::mergeTBAAInfoForCast(TBAAAccessInfo SourceInfo,
1048                                                    TBAAAccessInfo TargetInfo) {
1049   if (!TBAA)
1050     return TBAAAccessInfo();
1051   return TBAA->mergeTBAAInfoForCast(SourceInfo, TargetInfo);
1052 }
1053 
1054 TBAAAccessInfo
1055 CodeGenModule::mergeTBAAInfoForConditionalOperator(TBAAAccessInfo InfoA,
1056                                                    TBAAAccessInfo InfoB) {
1057   if (!TBAA)
1058     return TBAAAccessInfo();
1059   return TBAA->mergeTBAAInfoForConditionalOperator(InfoA, InfoB);
1060 }
1061 
1062 TBAAAccessInfo
1063 CodeGenModule::mergeTBAAInfoForMemoryTransfer(TBAAAccessInfo DestInfo,
1064                                               TBAAAccessInfo SrcInfo) {
1065   if (!TBAA)
1066     return TBAAAccessInfo();
1067   return TBAA->mergeTBAAInfoForConditionalOperator(DestInfo, SrcInfo);
1068 }
1069 
1070 void CodeGenModule::DecorateInstructionWithTBAA(llvm::Instruction *Inst,
1071                                                 TBAAAccessInfo TBAAInfo) {
1072   if (llvm::MDNode *Tag = getTBAAAccessTagInfo(TBAAInfo))
1073     Inst->setMetadata(llvm::LLVMContext::MD_tbaa, Tag);
1074 }
1075 
1076 void CodeGenModule::DecorateInstructionWithInvariantGroup(
1077     llvm::Instruction *I, const CXXRecordDecl *RD) {
1078   I->setMetadata(llvm::LLVMContext::MD_invariant_group,
1079                  llvm::MDNode::get(getLLVMContext(), {}));
1080 }
1081 
1082 void CodeGenModule::Error(SourceLocation loc, StringRef message) {
1083   unsigned diagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error, "%0");
1084   getDiags().Report(Context.getFullLoc(loc), diagID) << message;
1085 }
1086 
1087 /// ErrorUnsupported - Print out an error that codegen doesn't support the
1088 /// specified stmt yet.
1089 void CodeGenModule::ErrorUnsupported(const Stmt *S, const char *Type) {
1090   unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error,
1091                                                "cannot compile this %0 yet");
1092   std::string Msg = Type;
1093   getDiags().Report(Context.getFullLoc(S->getBeginLoc()), DiagID)
1094       << Msg << S->getSourceRange();
1095 }
1096 
1097 /// ErrorUnsupported - Print out an error that codegen doesn't support the
1098 /// specified decl yet.
1099 void CodeGenModule::ErrorUnsupported(const Decl *D, const char *Type) {
1100   unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error,
1101                                                "cannot compile this %0 yet");
1102   std::string Msg = Type;
1103   getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID) << Msg;
1104 }
1105 
1106 llvm::ConstantInt *CodeGenModule::getSize(CharUnits size) {
1107   return llvm::ConstantInt::get(SizeTy, size.getQuantity());
1108 }
1109 
1110 void CodeGenModule::setGlobalVisibility(llvm::GlobalValue *GV,
1111                                         const NamedDecl *D) const {
1112   // Internal definitions always have default visibility.
1113   if (GV->hasLocalLinkage()) {
1114     GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
1115     return;
1116   }
1117   if (!D)
1118     return;
1119   // Set visibility for definitions, and for declarations if requested globally
1120   // or set explicitly.
1121   LinkageInfo LV = D->getLinkageAndVisibility();
1122   if (GV->hasDLLExportStorageClass() || GV->hasDLLImportStorageClass()) {
1123     // Reject incompatible dlllstorage and visibility annotations.
1124     if (!LV.isVisibilityExplicit())
1125       return;
1126     if (GV->hasDLLExportStorageClass()) {
1127       if (LV.getVisibility() == HiddenVisibility)
1128         getDiags().Report(D->getLocation(),
1129                           diag::err_hidden_visibility_dllexport);
1130     } else if (LV.getVisibility() != DefaultVisibility) {
1131       getDiags().Report(D->getLocation(),
1132                         diag::err_non_default_visibility_dllimport);
1133     }
1134     return;
1135   }
1136 
1137   if (LV.isVisibilityExplicit() || getLangOpts().SetVisibilityForExternDecls ||
1138       !GV->isDeclarationForLinker())
1139     GV->setVisibility(GetLLVMVisibility(LV.getVisibility()));
1140 }
1141 
1142 static bool shouldAssumeDSOLocal(const CodeGenModule &CGM,
1143                                  llvm::GlobalValue *GV) {
1144   if (GV->hasLocalLinkage())
1145     return true;
1146 
1147   if (!GV->hasDefaultVisibility() && !GV->hasExternalWeakLinkage())
1148     return true;
1149 
1150   // DLLImport explicitly marks the GV as external.
1151   if (GV->hasDLLImportStorageClass())
1152     return false;
1153 
1154   const llvm::Triple &TT = CGM.getTriple();
1155   if (TT.isWindowsGNUEnvironment()) {
1156     // In MinGW, variables without DLLImport can still be automatically
1157     // imported from a DLL by the linker; don't mark variables that
1158     // potentially could come from another DLL as DSO local.
1159 
1160     // With EmulatedTLS, TLS variables can be autoimported from other DLLs
1161     // (and this actually happens in the public interface of libstdc++), so
1162     // such variables can't be marked as DSO local. (Native TLS variables
1163     // can't be dllimported at all, though.)
1164     if (GV->isDeclarationForLinker() && isa<llvm::GlobalVariable>(GV) &&
1165         (!GV->isThreadLocal() || CGM.getCodeGenOpts().EmulatedTLS))
1166       return false;
1167   }
1168 
1169   // On COFF, don't mark 'extern_weak' symbols as DSO local. If these symbols
1170   // remain unresolved in the link, they can be resolved to zero, which is
1171   // outside the current DSO.
1172   if (TT.isOSBinFormatCOFF() && GV->hasExternalWeakLinkage())
1173     return false;
1174 
1175   // Every other GV is local on COFF.
1176   // Make an exception for windows OS in the triple: Some firmware builds use
1177   // *-win32-macho triples. This (accidentally?) produced windows relocations
1178   // without GOT tables in older clang versions; Keep this behaviour.
1179   // FIXME: even thread local variables?
1180   if (TT.isOSBinFormatCOFF() || (TT.isOSWindows() && TT.isOSBinFormatMachO()))
1181     return true;
1182 
1183   // Only handle COFF and ELF for now.
1184   if (!TT.isOSBinFormatELF())
1185     return false;
1186 
1187   // If this is not an executable, don't assume anything is local.
1188   const auto &CGOpts = CGM.getCodeGenOpts();
1189   llvm::Reloc::Model RM = CGOpts.RelocationModel;
1190   const auto &LOpts = CGM.getLangOpts();
1191   if (RM != llvm::Reloc::Static && !LOpts.PIE) {
1192     // On ELF, if -fno-semantic-interposition is specified and the target
1193     // supports local aliases, there will be neither CC1
1194     // -fsemantic-interposition nor -fhalf-no-semantic-interposition. Set
1195     // dso_local on the function if using a local alias is preferable (can avoid
1196     // PLT indirection).
1197     if (!(isa<llvm::Function>(GV) && GV->canBenefitFromLocalAlias()))
1198       return false;
1199     return !(CGM.getLangOpts().SemanticInterposition ||
1200              CGM.getLangOpts().HalfNoSemanticInterposition);
1201   }
1202 
1203   // A definition cannot be preempted from an executable.
1204   if (!GV->isDeclarationForLinker())
1205     return true;
1206 
1207   // Most PIC code sequences that assume that a symbol is local cannot produce a
1208   // 0 if it turns out the symbol is undefined. While this is ABI and relocation
1209   // depended, it seems worth it to handle it here.
1210   if (RM == llvm::Reloc::PIC_ && GV->hasExternalWeakLinkage())
1211     return false;
1212 
1213   // PowerPC64 prefers TOC indirection to avoid copy relocations.
1214   if (TT.isPPC64())
1215     return false;
1216 
1217   if (CGOpts.DirectAccessExternalData) {
1218     // If -fdirect-access-external-data (default for -fno-pic), set dso_local
1219     // for non-thread-local variables. If the symbol is not defined in the
1220     // executable, a copy relocation will be needed at link time. dso_local is
1221     // excluded for thread-local variables because they generally don't support
1222     // copy relocations.
1223     if (auto *Var = dyn_cast<llvm::GlobalVariable>(GV))
1224       if (!Var->isThreadLocal())
1225         return true;
1226 
1227     // -fno-pic sets dso_local on a function declaration to allow direct
1228     // accesses when taking its address (similar to a data symbol). If the
1229     // function is not defined in the executable, a canonical PLT entry will be
1230     // needed at link time. -fno-direct-access-external-data can avoid the
1231     // canonical PLT entry. We don't generalize this condition to -fpie/-fpic as
1232     // it could just cause trouble without providing perceptible benefits.
1233     if (isa<llvm::Function>(GV) && !CGOpts.NoPLT && RM == llvm::Reloc::Static)
1234       return true;
1235   }
1236 
1237   // If we can use copy relocations we can assume it is local.
1238 
1239   // Otherwise don't assume it is local.
1240   return false;
1241 }
1242 
1243 void CodeGenModule::setDSOLocal(llvm::GlobalValue *GV) const {
1244   GV->setDSOLocal(shouldAssumeDSOLocal(*this, GV));
1245 }
1246 
1247 void CodeGenModule::setDLLImportDLLExport(llvm::GlobalValue *GV,
1248                                           GlobalDecl GD) const {
1249   const auto *D = dyn_cast<NamedDecl>(GD.getDecl());
1250   // C++ destructors have a few C++ ABI specific special cases.
1251   if (const auto *Dtor = dyn_cast_or_null<CXXDestructorDecl>(D)) {
1252     getCXXABI().setCXXDestructorDLLStorage(GV, Dtor, GD.getDtorType());
1253     return;
1254   }
1255   setDLLImportDLLExport(GV, D);
1256 }
1257 
1258 void CodeGenModule::setDLLImportDLLExport(llvm::GlobalValue *GV,
1259                                           const NamedDecl *D) const {
1260   if (D && D->isExternallyVisible()) {
1261     if (D->hasAttr<DLLImportAttr>())
1262       GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
1263     else if ((D->hasAttr<DLLExportAttr>() ||
1264               shouldMapVisibilityToDLLExport(D)) &&
1265              !GV->isDeclarationForLinker())
1266       GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass);
1267   }
1268 }
1269 
1270 void CodeGenModule::setGVProperties(llvm::GlobalValue *GV,
1271                                     GlobalDecl GD) const {
1272   setDLLImportDLLExport(GV, GD);
1273   setGVPropertiesAux(GV, dyn_cast<NamedDecl>(GD.getDecl()));
1274 }
1275 
1276 void CodeGenModule::setGVProperties(llvm::GlobalValue *GV,
1277                                     const NamedDecl *D) const {
1278   setDLLImportDLLExport(GV, D);
1279   setGVPropertiesAux(GV, D);
1280 }
1281 
1282 void CodeGenModule::setGVPropertiesAux(llvm::GlobalValue *GV,
1283                                        const NamedDecl *D) const {
1284   setGlobalVisibility(GV, D);
1285   setDSOLocal(GV);
1286   GV->setPartition(CodeGenOpts.SymbolPartition);
1287 }
1288 
1289 static llvm::GlobalVariable::ThreadLocalMode GetLLVMTLSModel(StringRef S) {
1290   return llvm::StringSwitch<llvm::GlobalVariable::ThreadLocalMode>(S)
1291       .Case("global-dynamic", llvm::GlobalVariable::GeneralDynamicTLSModel)
1292       .Case("local-dynamic", llvm::GlobalVariable::LocalDynamicTLSModel)
1293       .Case("initial-exec", llvm::GlobalVariable::InitialExecTLSModel)
1294       .Case("local-exec", llvm::GlobalVariable::LocalExecTLSModel);
1295 }
1296 
1297 llvm::GlobalVariable::ThreadLocalMode
1298 CodeGenModule::GetDefaultLLVMTLSModel() const {
1299   switch (CodeGenOpts.getDefaultTLSModel()) {
1300   case CodeGenOptions::GeneralDynamicTLSModel:
1301     return llvm::GlobalVariable::GeneralDynamicTLSModel;
1302   case CodeGenOptions::LocalDynamicTLSModel:
1303     return llvm::GlobalVariable::LocalDynamicTLSModel;
1304   case CodeGenOptions::InitialExecTLSModel:
1305     return llvm::GlobalVariable::InitialExecTLSModel;
1306   case CodeGenOptions::LocalExecTLSModel:
1307     return llvm::GlobalVariable::LocalExecTLSModel;
1308   }
1309   llvm_unreachable("Invalid TLS model!");
1310 }
1311 
1312 void CodeGenModule::setTLSMode(llvm::GlobalValue *GV, const VarDecl &D) const {
1313   assert(D.getTLSKind() && "setting TLS mode on non-TLS var!");
1314 
1315   llvm::GlobalValue::ThreadLocalMode TLM;
1316   TLM = GetDefaultLLVMTLSModel();
1317 
1318   // Override the TLS model if it is explicitly specified.
1319   if (const TLSModelAttr *Attr = D.getAttr<TLSModelAttr>()) {
1320     TLM = GetLLVMTLSModel(Attr->getModel());
1321   }
1322 
1323   GV->setThreadLocalMode(TLM);
1324 }
1325 
1326 static std::string getCPUSpecificMangling(const CodeGenModule &CGM,
1327                                           StringRef Name) {
1328   const TargetInfo &Target = CGM.getTarget();
1329   return (Twine('.') + Twine(Target.CPUSpecificManglingCharacter(Name))).str();
1330 }
1331 
1332 static void AppendCPUSpecificCPUDispatchMangling(const CodeGenModule &CGM,
1333                                                  const CPUSpecificAttr *Attr,
1334                                                  unsigned CPUIndex,
1335                                                  raw_ostream &Out) {
1336   // cpu_specific gets the current name, dispatch gets the resolver if IFunc is
1337   // supported.
1338   if (Attr)
1339     Out << getCPUSpecificMangling(CGM, Attr->getCPUName(CPUIndex)->getName());
1340   else if (CGM.getTarget().supportsIFunc())
1341     Out << ".resolver";
1342 }
1343 
1344 static void AppendTargetVersionMangling(const CodeGenModule &CGM,
1345                                         const TargetVersionAttr *Attr,
1346                                         raw_ostream &Out) {
1347   if (Attr->isDefaultVersion())
1348     return;
1349   Out << "._";
1350   llvm::SmallVector<StringRef, 8> Feats;
1351   Attr->getFeatures(Feats);
1352   for (const auto &Feat : Feats) {
1353     Out << 'M';
1354     Out << Feat;
1355   }
1356 }
1357 
1358 static void AppendTargetMangling(const CodeGenModule &CGM,
1359                                  const TargetAttr *Attr, raw_ostream &Out) {
1360   if (Attr->isDefaultVersion())
1361     return;
1362 
1363   Out << '.';
1364   const TargetInfo &Target = CGM.getTarget();
1365   ParsedTargetAttr Info = Target.parseTargetAttr(Attr->getFeaturesStr());
1366   llvm::sort(Info.Features, [&Target](StringRef LHS, StringRef RHS) {
1367     // Multiversioning doesn't allow "no-${feature}", so we can
1368     // only have "+" prefixes here.
1369     assert(LHS.startswith("+") && RHS.startswith("+") &&
1370            "Features should always have a prefix.");
1371     return Target.multiVersionSortPriority(LHS.substr(1)) >
1372            Target.multiVersionSortPriority(RHS.substr(1));
1373   });
1374 
1375   bool IsFirst = true;
1376 
1377   if (!Info.CPU.empty()) {
1378     IsFirst = false;
1379     Out << "arch_" << Info.CPU;
1380   }
1381 
1382   for (StringRef Feat : Info.Features) {
1383     if (!IsFirst)
1384       Out << '_';
1385     IsFirst = false;
1386     Out << Feat.substr(1);
1387   }
1388 }
1389 
1390 // Returns true if GD is a function decl with internal linkage and
1391 // needs a unique suffix after the mangled name.
1392 static bool isUniqueInternalLinkageDecl(GlobalDecl GD,
1393                                         CodeGenModule &CGM) {
1394   const Decl *D = GD.getDecl();
1395   return !CGM.getModuleNameHash().empty() && isa<FunctionDecl>(D) &&
1396          (CGM.getFunctionLinkage(GD) == llvm::GlobalValue::InternalLinkage);
1397 }
1398 
1399 static void AppendTargetClonesMangling(const CodeGenModule &CGM,
1400                                        const TargetClonesAttr *Attr,
1401                                        unsigned VersionIndex,
1402                                        raw_ostream &Out) {
1403   if (CGM.getTarget().getTriple().isAArch64()) {
1404     StringRef FeatureStr = Attr->getFeatureStr(VersionIndex);
1405     if (FeatureStr == "default")
1406       return;
1407     Out << "._";
1408     SmallVector<StringRef, 8> Features;
1409     FeatureStr.split(Features, "+");
1410     for (auto &Feat : Features) {
1411       Out << 'M';
1412       Out << Feat;
1413     }
1414   } else {
1415     Out << '.';
1416     StringRef FeatureStr = Attr->getFeatureStr(VersionIndex);
1417     if (FeatureStr.startswith("arch="))
1418       Out << "arch_" << FeatureStr.substr(sizeof("arch=") - 1);
1419     else
1420       Out << FeatureStr;
1421 
1422     Out << '.' << Attr->getMangledIndex(VersionIndex);
1423   }
1424 }
1425 
1426 static std::string getMangledNameImpl(CodeGenModule &CGM, GlobalDecl GD,
1427                                       const NamedDecl *ND,
1428                                       bool OmitMultiVersionMangling = false) {
1429   SmallString<256> Buffer;
1430   llvm::raw_svector_ostream Out(Buffer);
1431   MangleContext &MC = CGM.getCXXABI().getMangleContext();
1432   if (!CGM.getModuleNameHash().empty())
1433     MC.needsUniqueInternalLinkageNames();
1434   bool ShouldMangle = MC.shouldMangleDeclName(ND);
1435   if (ShouldMangle)
1436     MC.mangleName(GD.getWithDecl(ND), Out);
1437   else {
1438     IdentifierInfo *II = ND->getIdentifier();
1439     assert(II && "Attempt to mangle unnamed decl.");
1440     const auto *FD = dyn_cast<FunctionDecl>(ND);
1441 
1442     if (FD &&
1443         FD->getType()->castAs<FunctionType>()->getCallConv() == CC_X86RegCall) {
1444       Out << "__regcall3__" << II->getName();
1445     } else if (FD && FD->hasAttr<CUDAGlobalAttr>() &&
1446                GD.getKernelReferenceKind() == KernelReferenceKind::Stub) {
1447       Out << "__device_stub__" << II->getName();
1448     } else {
1449       Out << II->getName();
1450     }
1451   }
1452 
1453   // Check if the module name hash should be appended for internal linkage
1454   // symbols.   This should come before multi-version target suffixes are
1455   // appended. This is to keep the name and module hash suffix of the
1456   // internal linkage function together.  The unique suffix should only be
1457   // added when name mangling is done to make sure that the final name can
1458   // be properly demangled.  For example, for C functions without prototypes,
1459   // name mangling is not done and the unique suffix should not be appeneded
1460   // then.
1461   if (ShouldMangle && isUniqueInternalLinkageDecl(GD, CGM)) {
1462     assert(CGM.getCodeGenOpts().UniqueInternalLinkageNames &&
1463            "Hash computed when not explicitly requested");
1464     Out << CGM.getModuleNameHash();
1465   }
1466 
1467   if (const auto *FD = dyn_cast<FunctionDecl>(ND))
1468     if (FD->isMultiVersion() && !OmitMultiVersionMangling) {
1469       switch (FD->getMultiVersionKind()) {
1470       case MultiVersionKind::CPUDispatch:
1471       case MultiVersionKind::CPUSpecific:
1472         AppendCPUSpecificCPUDispatchMangling(CGM,
1473                                              FD->getAttr<CPUSpecificAttr>(),
1474                                              GD.getMultiVersionIndex(), Out);
1475         break;
1476       case MultiVersionKind::Target:
1477         AppendTargetMangling(CGM, FD->getAttr<TargetAttr>(), Out);
1478         break;
1479       case MultiVersionKind::TargetVersion:
1480         AppendTargetVersionMangling(CGM, FD->getAttr<TargetVersionAttr>(), Out);
1481         break;
1482       case MultiVersionKind::TargetClones:
1483         AppendTargetClonesMangling(CGM, FD->getAttr<TargetClonesAttr>(),
1484                                    GD.getMultiVersionIndex(), Out);
1485         break;
1486       case MultiVersionKind::None:
1487         llvm_unreachable("None multiversion type isn't valid here");
1488       }
1489     }
1490 
1491   // Make unique name for device side static file-scope variable for HIP.
1492   if (CGM.getContext().shouldExternalize(ND) &&
1493       CGM.getLangOpts().GPURelocatableDeviceCode &&
1494       CGM.getLangOpts().CUDAIsDevice)
1495     CGM.printPostfixForExternalizedDecl(Out, ND);
1496 
1497   return std::string(Out.str());
1498 }
1499 
1500 void CodeGenModule::UpdateMultiVersionNames(GlobalDecl GD,
1501                                             const FunctionDecl *FD,
1502                                             StringRef &CurName) {
1503   if (!FD->isMultiVersion())
1504     return;
1505 
1506   // Get the name of what this would be without the 'target' attribute.  This
1507   // allows us to lookup the version that was emitted when this wasn't a
1508   // multiversion function.
1509   std::string NonTargetName =
1510       getMangledNameImpl(*this, GD, FD, /*OmitMultiVersionMangling=*/true);
1511   GlobalDecl OtherGD;
1512   if (lookupRepresentativeDecl(NonTargetName, OtherGD)) {
1513     assert(OtherGD.getCanonicalDecl()
1514                .getDecl()
1515                ->getAsFunction()
1516                ->isMultiVersion() &&
1517            "Other GD should now be a multiversioned function");
1518     // OtherFD is the version of this function that was mangled BEFORE
1519     // becoming a MultiVersion function.  It potentially needs to be updated.
1520     const FunctionDecl *OtherFD = OtherGD.getCanonicalDecl()
1521                                       .getDecl()
1522                                       ->getAsFunction()
1523                                       ->getMostRecentDecl();
1524     std::string OtherName = getMangledNameImpl(*this, OtherGD, OtherFD);
1525     // This is so that if the initial version was already the 'default'
1526     // version, we don't try to update it.
1527     if (OtherName != NonTargetName) {
1528       // Remove instead of erase, since others may have stored the StringRef
1529       // to this.
1530       const auto ExistingRecord = Manglings.find(NonTargetName);
1531       if (ExistingRecord != std::end(Manglings))
1532         Manglings.remove(&(*ExistingRecord));
1533       auto Result = Manglings.insert(std::make_pair(OtherName, OtherGD));
1534       StringRef OtherNameRef = MangledDeclNames[OtherGD.getCanonicalDecl()] =
1535           Result.first->first();
1536       // If this is the current decl is being created, make sure we update the name.
1537       if (GD.getCanonicalDecl() == OtherGD.getCanonicalDecl())
1538         CurName = OtherNameRef;
1539       if (llvm::GlobalValue *Entry = GetGlobalValue(NonTargetName))
1540         Entry->setName(OtherName);
1541     }
1542   }
1543 }
1544 
1545 StringRef CodeGenModule::getMangledName(GlobalDecl GD) {
1546   GlobalDecl CanonicalGD = GD.getCanonicalDecl();
1547 
1548   // Some ABIs don't have constructor variants.  Make sure that base and
1549   // complete constructors get mangled the same.
1550   if (const auto *CD = dyn_cast<CXXConstructorDecl>(CanonicalGD.getDecl())) {
1551     if (!getTarget().getCXXABI().hasConstructorVariants()) {
1552       CXXCtorType OrigCtorType = GD.getCtorType();
1553       assert(OrigCtorType == Ctor_Base || OrigCtorType == Ctor_Complete);
1554       if (OrigCtorType == Ctor_Base)
1555         CanonicalGD = GlobalDecl(CD, Ctor_Complete);
1556     }
1557   }
1558 
1559   // In CUDA/HIP device compilation with -fgpu-rdc, the mangled name of a
1560   // static device variable depends on whether the variable is referenced by
1561   // a host or device host function. Therefore the mangled name cannot be
1562   // cached.
1563   if (!LangOpts.CUDAIsDevice || !getContext().mayExternalize(GD.getDecl())) {
1564     auto FoundName = MangledDeclNames.find(CanonicalGD);
1565     if (FoundName != MangledDeclNames.end())
1566       return FoundName->second;
1567   }
1568 
1569   // Keep the first result in the case of a mangling collision.
1570   const auto *ND = cast<NamedDecl>(GD.getDecl());
1571   std::string MangledName = getMangledNameImpl(*this, GD, ND);
1572 
1573   // Ensure either we have different ABIs between host and device compilations,
1574   // says host compilation following MSVC ABI but device compilation follows
1575   // Itanium C++ ABI or, if they follow the same ABI, kernel names after
1576   // mangling should be the same after name stubbing. The later checking is
1577   // very important as the device kernel name being mangled in host-compilation
1578   // is used to resolve the device binaries to be executed. Inconsistent naming
1579   // result in undefined behavior. Even though we cannot check that naming
1580   // directly between host- and device-compilations, the host- and
1581   // device-mangling in host compilation could help catching certain ones.
1582   assert(!isa<FunctionDecl>(ND) || !ND->hasAttr<CUDAGlobalAttr>() ||
1583          getContext().shouldExternalize(ND) || getLangOpts().CUDAIsDevice ||
1584          (getContext().getAuxTargetInfo() &&
1585           (getContext().getAuxTargetInfo()->getCXXABI() !=
1586            getContext().getTargetInfo().getCXXABI())) ||
1587          getCUDARuntime().getDeviceSideName(ND) ==
1588              getMangledNameImpl(
1589                  *this,
1590                  GD.getWithKernelReferenceKind(KernelReferenceKind::Kernel),
1591                  ND));
1592 
1593   auto Result = Manglings.insert(std::make_pair(MangledName, GD));
1594   return MangledDeclNames[CanonicalGD] = Result.first->first();
1595 }
1596 
1597 StringRef CodeGenModule::getBlockMangledName(GlobalDecl GD,
1598                                              const BlockDecl *BD) {
1599   MangleContext &MangleCtx = getCXXABI().getMangleContext();
1600   const Decl *D = GD.getDecl();
1601 
1602   SmallString<256> Buffer;
1603   llvm::raw_svector_ostream Out(Buffer);
1604   if (!D)
1605     MangleCtx.mangleGlobalBlock(BD,
1606       dyn_cast_or_null<VarDecl>(initializedGlobalDecl.getDecl()), Out);
1607   else if (const auto *CD = dyn_cast<CXXConstructorDecl>(D))
1608     MangleCtx.mangleCtorBlock(CD, GD.getCtorType(), BD, Out);
1609   else if (const auto *DD = dyn_cast<CXXDestructorDecl>(D))
1610     MangleCtx.mangleDtorBlock(DD, GD.getDtorType(), BD, Out);
1611   else
1612     MangleCtx.mangleBlock(cast<DeclContext>(D), BD, Out);
1613 
1614   auto Result = Manglings.insert(std::make_pair(Out.str(), BD));
1615   return Result.first->first();
1616 }
1617 
1618 const GlobalDecl CodeGenModule::getMangledNameDecl(StringRef Name) {
1619   auto it = MangledDeclNames.begin();
1620   while (it != MangledDeclNames.end()) {
1621     if (it->second == Name)
1622       return it->first;
1623     it++;
1624   }
1625   return GlobalDecl();
1626 }
1627 
1628 llvm::GlobalValue *CodeGenModule::GetGlobalValue(StringRef Name) {
1629   return getModule().getNamedValue(Name);
1630 }
1631 
1632 /// AddGlobalCtor - Add a function to the list that will be called before
1633 /// main() runs.
1634 void CodeGenModule::AddGlobalCtor(llvm::Function *Ctor, int Priority,
1635                                   unsigned LexOrder,
1636                                   llvm::Constant *AssociatedData) {
1637   // FIXME: Type coercion of void()* types.
1638   GlobalCtors.push_back(Structor(Priority, LexOrder, Ctor, AssociatedData));
1639 }
1640 
1641 /// AddGlobalDtor - Add a function to the list that will be called
1642 /// when the module is unloaded.
1643 void CodeGenModule::AddGlobalDtor(llvm::Function *Dtor, int Priority,
1644                                   bool IsDtorAttrFunc) {
1645   if (CodeGenOpts.RegisterGlobalDtorsWithAtExit &&
1646       (!getContext().getTargetInfo().getTriple().isOSAIX() || IsDtorAttrFunc)) {
1647     DtorsUsingAtExit[Priority].push_back(Dtor);
1648     return;
1649   }
1650 
1651   // FIXME: Type coercion of void()* types.
1652   GlobalDtors.push_back(Structor(Priority, ~0U, Dtor, nullptr));
1653 }
1654 
1655 void CodeGenModule::EmitCtorList(CtorList &Fns, const char *GlobalName) {
1656   if (Fns.empty()) return;
1657 
1658   // Ctor function type is void()*.
1659   llvm::FunctionType* CtorFTy = llvm::FunctionType::get(VoidTy, false);
1660   llvm::Type *CtorPFTy = llvm::PointerType::get(CtorFTy,
1661       TheModule.getDataLayout().getProgramAddressSpace());
1662 
1663   // Get the type of a ctor entry, { i32, void ()*, i8* }.
1664   llvm::StructType *CtorStructTy = llvm::StructType::get(
1665       Int32Ty, CtorPFTy, VoidPtrTy);
1666 
1667   // Construct the constructor and destructor arrays.
1668   ConstantInitBuilder builder(*this);
1669   auto ctors = builder.beginArray(CtorStructTy);
1670   for (const auto &I : Fns) {
1671     auto ctor = ctors.beginStruct(CtorStructTy);
1672     ctor.addInt(Int32Ty, I.Priority);
1673     ctor.add(llvm::ConstantExpr::getBitCast(I.Initializer, CtorPFTy));
1674     if (I.AssociatedData)
1675       ctor.add(llvm::ConstantExpr::getBitCast(I.AssociatedData, VoidPtrTy));
1676     else
1677       ctor.addNullPointer(VoidPtrTy);
1678     ctor.finishAndAddTo(ctors);
1679   }
1680 
1681   auto list =
1682     ctors.finishAndCreateGlobal(GlobalName, getPointerAlign(),
1683                                 /*constant*/ false,
1684                                 llvm::GlobalValue::AppendingLinkage);
1685 
1686   // The LTO linker doesn't seem to like it when we set an alignment
1687   // on appending variables.  Take it off as a workaround.
1688   list->setAlignment(std::nullopt);
1689 
1690   Fns.clear();
1691 }
1692 
1693 llvm::GlobalValue::LinkageTypes
1694 CodeGenModule::getFunctionLinkage(GlobalDecl GD) {
1695   const auto *D = cast<FunctionDecl>(GD.getDecl());
1696 
1697   GVALinkage Linkage = getContext().GetGVALinkageForFunction(D);
1698 
1699   if (const auto *Dtor = dyn_cast<CXXDestructorDecl>(D))
1700     return getCXXABI().getCXXDestructorLinkage(Linkage, Dtor, GD.getDtorType());
1701 
1702   if (isa<CXXConstructorDecl>(D) &&
1703       cast<CXXConstructorDecl>(D)->isInheritingConstructor() &&
1704       Context.getTargetInfo().getCXXABI().isMicrosoft()) {
1705     // Our approach to inheriting constructors is fundamentally different from
1706     // that used by the MS ABI, so keep our inheriting constructor thunks
1707     // internal rather than trying to pick an unambiguous mangling for them.
1708     return llvm::GlobalValue::InternalLinkage;
1709   }
1710 
1711   return getLLVMLinkageForDeclarator(D, Linkage, /*IsConstantVariable=*/false);
1712 }
1713 
1714 llvm::ConstantInt *CodeGenModule::CreateCrossDsoCfiTypeId(llvm::Metadata *MD) {
1715   llvm::MDString *MDS = dyn_cast<llvm::MDString>(MD);
1716   if (!MDS) return nullptr;
1717 
1718   return llvm::ConstantInt::get(Int64Ty, llvm::MD5Hash(MDS->getString()));
1719 }
1720 
1721 llvm::ConstantInt *CodeGenModule::CreateKCFITypeId(QualType T) {
1722   if (auto *FnType = T->getAs<FunctionProtoType>())
1723     T = getContext().getFunctionType(
1724         FnType->getReturnType(), FnType->getParamTypes(),
1725         FnType->getExtProtoInfo().withExceptionSpec(EST_None));
1726 
1727   std::string OutName;
1728   llvm::raw_string_ostream Out(OutName);
1729   getCXXABI().getMangleContext().mangleTypeName(T, Out);
1730 
1731   return llvm::ConstantInt::get(Int32Ty,
1732                                 static_cast<uint32_t>(llvm::xxHash64(OutName)));
1733 }
1734 
1735 void CodeGenModule::SetLLVMFunctionAttributes(GlobalDecl GD,
1736                                               const CGFunctionInfo &Info,
1737                                               llvm::Function *F, bool IsThunk) {
1738   unsigned CallingConv;
1739   llvm::AttributeList PAL;
1740   ConstructAttributeList(F->getName(), Info, GD, PAL, CallingConv,
1741                          /*AttrOnCallSite=*/false, IsThunk);
1742   F->setAttributes(PAL);
1743   F->setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv));
1744 }
1745 
1746 static void removeImageAccessQualifier(std::string& TyName) {
1747   std::string ReadOnlyQual("__read_only");
1748   std::string::size_type ReadOnlyPos = TyName.find(ReadOnlyQual);
1749   if (ReadOnlyPos != std::string::npos)
1750     // "+ 1" for the space after access qualifier.
1751     TyName.erase(ReadOnlyPos, ReadOnlyQual.size() + 1);
1752   else {
1753     std::string WriteOnlyQual("__write_only");
1754     std::string::size_type WriteOnlyPos = TyName.find(WriteOnlyQual);
1755     if (WriteOnlyPos != std::string::npos)
1756       TyName.erase(WriteOnlyPos, WriteOnlyQual.size() + 1);
1757     else {
1758       std::string ReadWriteQual("__read_write");
1759       std::string::size_type ReadWritePos = TyName.find(ReadWriteQual);
1760       if (ReadWritePos != std::string::npos)
1761         TyName.erase(ReadWritePos, ReadWriteQual.size() + 1);
1762     }
1763   }
1764 }
1765 
1766 // Returns the address space id that should be produced to the
1767 // kernel_arg_addr_space metadata. This is always fixed to the ids
1768 // as specified in the SPIR 2.0 specification in order to differentiate
1769 // for example in clGetKernelArgInfo() implementation between the address
1770 // spaces with targets without unique mapping to the OpenCL address spaces
1771 // (basically all single AS CPUs).
1772 static unsigned ArgInfoAddressSpace(LangAS AS) {
1773   switch (AS) {
1774   case LangAS::opencl_global:
1775     return 1;
1776   case LangAS::opencl_constant:
1777     return 2;
1778   case LangAS::opencl_local:
1779     return 3;
1780   case LangAS::opencl_generic:
1781     return 4; // Not in SPIR 2.0 specs.
1782   case LangAS::opencl_global_device:
1783     return 5;
1784   case LangAS::opencl_global_host:
1785     return 6;
1786   default:
1787     return 0; // Assume private.
1788   }
1789 }
1790 
1791 void CodeGenModule::GenKernelArgMetadata(llvm::Function *Fn,
1792                                          const FunctionDecl *FD,
1793                                          CodeGenFunction *CGF) {
1794   assert(((FD && CGF) || (!FD && !CGF)) &&
1795          "Incorrect use - FD and CGF should either be both null or not!");
1796   // Create MDNodes that represent the kernel arg metadata.
1797   // Each MDNode is a list in the form of "key", N number of values which is
1798   // the same number of values as their are kernel arguments.
1799 
1800   const PrintingPolicy &Policy = Context.getPrintingPolicy();
1801 
1802   // MDNode for the kernel argument address space qualifiers.
1803   SmallVector<llvm::Metadata *, 8> addressQuals;
1804 
1805   // MDNode for the kernel argument access qualifiers (images only).
1806   SmallVector<llvm::Metadata *, 8> accessQuals;
1807 
1808   // MDNode for the kernel argument type names.
1809   SmallVector<llvm::Metadata *, 8> argTypeNames;
1810 
1811   // MDNode for the kernel argument base type names.
1812   SmallVector<llvm::Metadata *, 8> argBaseTypeNames;
1813 
1814   // MDNode for the kernel argument type qualifiers.
1815   SmallVector<llvm::Metadata *, 8> argTypeQuals;
1816 
1817   // MDNode for the kernel argument names.
1818   SmallVector<llvm::Metadata *, 8> argNames;
1819 
1820   if (FD && CGF)
1821     for (unsigned i = 0, e = FD->getNumParams(); i != e; ++i) {
1822       const ParmVarDecl *parm = FD->getParamDecl(i);
1823       // Get argument name.
1824       argNames.push_back(llvm::MDString::get(VMContext, parm->getName()));
1825 
1826       if (!getLangOpts().OpenCL)
1827         continue;
1828       QualType ty = parm->getType();
1829       std::string typeQuals;
1830 
1831       // Get image and pipe access qualifier:
1832       if (ty->isImageType() || ty->isPipeType()) {
1833         const Decl *PDecl = parm;
1834         if (const auto *TD = ty->getAs<TypedefType>())
1835           PDecl = TD->getDecl();
1836         const OpenCLAccessAttr *A = PDecl->getAttr<OpenCLAccessAttr>();
1837         if (A && A->isWriteOnly())
1838           accessQuals.push_back(llvm::MDString::get(VMContext, "write_only"));
1839         else if (A && A->isReadWrite())
1840           accessQuals.push_back(llvm::MDString::get(VMContext, "read_write"));
1841         else
1842           accessQuals.push_back(llvm::MDString::get(VMContext, "read_only"));
1843       } else
1844         accessQuals.push_back(llvm::MDString::get(VMContext, "none"));
1845 
1846       auto getTypeSpelling = [&](QualType Ty) {
1847         auto typeName = Ty.getUnqualifiedType().getAsString(Policy);
1848 
1849         if (Ty.isCanonical()) {
1850           StringRef typeNameRef = typeName;
1851           // Turn "unsigned type" to "utype"
1852           if (typeNameRef.consume_front("unsigned "))
1853             return std::string("u") + typeNameRef.str();
1854           if (typeNameRef.consume_front("signed "))
1855             return typeNameRef.str();
1856         }
1857 
1858         return typeName;
1859       };
1860 
1861       if (ty->isPointerType()) {
1862         QualType pointeeTy = ty->getPointeeType();
1863 
1864         // Get address qualifier.
1865         addressQuals.push_back(
1866             llvm::ConstantAsMetadata::get(CGF->Builder.getInt32(
1867                 ArgInfoAddressSpace(pointeeTy.getAddressSpace()))));
1868 
1869         // Get argument type name.
1870         std::string typeName = getTypeSpelling(pointeeTy) + "*";
1871         std::string baseTypeName =
1872             getTypeSpelling(pointeeTy.getCanonicalType()) + "*";
1873         argTypeNames.push_back(llvm::MDString::get(VMContext, typeName));
1874         argBaseTypeNames.push_back(
1875             llvm::MDString::get(VMContext, baseTypeName));
1876 
1877         // Get argument type qualifiers:
1878         if (ty.isRestrictQualified())
1879           typeQuals = "restrict";
1880         if (pointeeTy.isConstQualified() ||
1881             (pointeeTy.getAddressSpace() == LangAS::opencl_constant))
1882           typeQuals += typeQuals.empty() ? "const" : " const";
1883         if (pointeeTy.isVolatileQualified())
1884           typeQuals += typeQuals.empty() ? "volatile" : " volatile";
1885       } else {
1886         uint32_t AddrSpc = 0;
1887         bool isPipe = ty->isPipeType();
1888         if (ty->isImageType() || isPipe)
1889           AddrSpc = ArgInfoAddressSpace(LangAS::opencl_global);
1890 
1891         addressQuals.push_back(
1892             llvm::ConstantAsMetadata::get(CGF->Builder.getInt32(AddrSpc)));
1893 
1894         // Get argument type name.
1895         ty = isPipe ? ty->castAs<PipeType>()->getElementType() : ty;
1896         std::string typeName = getTypeSpelling(ty);
1897         std::string baseTypeName = getTypeSpelling(ty.getCanonicalType());
1898 
1899         // Remove access qualifiers on images
1900         // (as they are inseparable from type in clang implementation,
1901         // but OpenCL spec provides a special query to get access qualifier
1902         // via clGetKernelArgInfo with CL_KERNEL_ARG_ACCESS_QUALIFIER):
1903         if (ty->isImageType()) {
1904           removeImageAccessQualifier(typeName);
1905           removeImageAccessQualifier(baseTypeName);
1906         }
1907 
1908         argTypeNames.push_back(llvm::MDString::get(VMContext, typeName));
1909         argBaseTypeNames.push_back(
1910             llvm::MDString::get(VMContext, baseTypeName));
1911 
1912         if (isPipe)
1913           typeQuals = "pipe";
1914       }
1915       argTypeQuals.push_back(llvm::MDString::get(VMContext, typeQuals));
1916     }
1917 
1918   if (getLangOpts().OpenCL) {
1919     Fn->setMetadata("kernel_arg_addr_space",
1920                     llvm::MDNode::get(VMContext, addressQuals));
1921     Fn->setMetadata("kernel_arg_access_qual",
1922                     llvm::MDNode::get(VMContext, accessQuals));
1923     Fn->setMetadata("kernel_arg_type",
1924                     llvm::MDNode::get(VMContext, argTypeNames));
1925     Fn->setMetadata("kernel_arg_base_type",
1926                     llvm::MDNode::get(VMContext, argBaseTypeNames));
1927     Fn->setMetadata("kernel_arg_type_qual",
1928                     llvm::MDNode::get(VMContext, argTypeQuals));
1929   }
1930   if (getCodeGenOpts().EmitOpenCLArgMetadata ||
1931       getCodeGenOpts().HIPSaveKernelArgName)
1932     Fn->setMetadata("kernel_arg_name",
1933                     llvm::MDNode::get(VMContext, argNames));
1934 }
1935 
1936 /// Determines whether the language options require us to model
1937 /// unwind exceptions.  We treat -fexceptions as mandating this
1938 /// except under the fragile ObjC ABI with only ObjC exceptions
1939 /// enabled.  This means, for example, that C with -fexceptions
1940 /// enables this.
1941 static bool hasUnwindExceptions(const LangOptions &LangOpts) {
1942   // If exceptions are completely disabled, obviously this is false.
1943   if (!LangOpts.Exceptions) return false;
1944 
1945   // If C++ exceptions are enabled, this is true.
1946   if (LangOpts.CXXExceptions) return true;
1947 
1948   // If ObjC exceptions are enabled, this depends on the ABI.
1949   if (LangOpts.ObjCExceptions) {
1950     return LangOpts.ObjCRuntime.hasUnwindExceptions();
1951   }
1952 
1953   return true;
1954 }
1955 
1956 static bool requiresMemberFunctionPointerTypeMetadata(CodeGenModule &CGM,
1957                                                       const CXXMethodDecl *MD) {
1958   // Check that the type metadata can ever actually be used by a call.
1959   if (!CGM.getCodeGenOpts().LTOUnit ||
1960       !CGM.HasHiddenLTOVisibility(MD->getParent()))
1961     return false;
1962 
1963   // Only functions whose address can be taken with a member function pointer
1964   // need this sort of type metadata.
1965   return !MD->isStatic() && !MD->isVirtual() && !isa<CXXConstructorDecl>(MD) &&
1966          !isa<CXXDestructorDecl>(MD);
1967 }
1968 
1969 std::vector<const CXXRecordDecl *>
1970 CodeGenModule::getMostBaseClasses(const CXXRecordDecl *RD) {
1971   llvm::SetVector<const CXXRecordDecl *> MostBases;
1972 
1973   std::function<void (const CXXRecordDecl *)> CollectMostBases;
1974   CollectMostBases = [&](const CXXRecordDecl *RD) {
1975     if (RD->getNumBases() == 0)
1976       MostBases.insert(RD);
1977     for (const CXXBaseSpecifier &B : RD->bases())
1978       CollectMostBases(B.getType()->getAsCXXRecordDecl());
1979   };
1980   CollectMostBases(RD);
1981   return MostBases.takeVector();
1982 }
1983 
1984 llvm::GlobalVariable *
1985 CodeGenModule::GetOrCreateRTTIProxyGlobalVariable(llvm::Constant *Addr) {
1986   auto It = RTTIProxyMap.find(Addr);
1987   if (It != RTTIProxyMap.end())
1988     return It->second;
1989 
1990   auto *FTRTTIProxy = new llvm::GlobalVariable(
1991       TheModule, Addr->getType(),
1992       /*isConstant=*/true, llvm::GlobalValue::PrivateLinkage, Addr,
1993       "__llvm_rtti_proxy");
1994   FTRTTIProxy->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
1995 
1996   RTTIProxyMap[Addr] = FTRTTIProxy;
1997   return FTRTTIProxy;
1998 }
1999 
2000 void CodeGenModule::SetLLVMFunctionAttributesForDefinition(const Decl *D,
2001                                                            llvm::Function *F) {
2002   llvm::AttrBuilder B(F->getContext());
2003 
2004   if ((!D || !D->hasAttr<NoUwtableAttr>()) && CodeGenOpts.UnwindTables)
2005     B.addUWTableAttr(llvm::UWTableKind(CodeGenOpts.UnwindTables));
2006 
2007   if (CodeGenOpts.StackClashProtector)
2008     B.addAttribute("probe-stack", "inline-asm");
2009 
2010   if (!hasUnwindExceptions(LangOpts))
2011     B.addAttribute(llvm::Attribute::NoUnwind);
2012 
2013   if (D && D->hasAttr<NoStackProtectorAttr>())
2014     ; // Do nothing.
2015   else if (D && D->hasAttr<StrictGuardStackCheckAttr>() &&
2016            LangOpts.getStackProtector() == LangOptions::SSPOn)
2017     B.addAttribute(llvm::Attribute::StackProtectStrong);
2018   else if (LangOpts.getStackProtector() == LangOptions::SSPOn)
2019     B.addAttribute(llvm::Attribute::StackProtect);
2020   else if (LangOpts.getStackProtector() == LangOptions::SSPStrong)
2021     B.addAttribute(llvm::Attribute::StackProtectStrong);
2022   else if (LangOpts.getStackProtector() == LangOptions::SSPReq)
2023     B.addAttribute(llvm::Attribute::StackProtectReq);
2024 
2025   if (!D) {
2026     // If we don't have a declaration to control inlining, the function isn't
2027     // explicitly marked as alwaysinline for semantic reasons, and inlining is
2028     // disabled, mark the function as noinline.
2029     if (!F->hasFnAttribute(llvm::Attribute::AlwaysInline) &&
2030         CodeGenOpts.getInlining() == CodeGenOptions::OnlyAlwaysInlining)
2031       B.addAttribute(llvm::Attribute::NoInline);
2032 
2033     F->addFnAttrs(B);
2034     return;
2035   }
2036 
2037   // Track whether we need to add the optnone LLVM attribute,
2038   // starting with the default for this optimization level.
2039   bool ShouldAddOptNone =
2040       !CodeGenOpts.DisableO0ImplyOptNone && CodeGenOpts.OptimizationLevel == 0;
2041   // We can't add optnone in the following cases, it won't pass the verifier.
2042   ShouldAddOptNone &= !D->hasAttr<MinSizeAttr>();
2043   ShouldAddOptNone &= !D->hasAttr<AlwaysInlineAttr>();
2044 
2045   // Add optnone, but do so only if the function isn't always_inline.
2046   if ((ShouldAddOptNone || D->hasAttr<OptimizeNoneAttr>()) &&
2047       !F->hasFnAttribute(llvm::Attribute::AlwaysInline)) {
2048     B.addAttribute(llvm::Attribute::OptimizeNone);
2049 
2050     // OptimizeNone implies noinline; we should not be inlining such functions.
2051     B.addAttribute(llvm::Attribute::NoInline);
2052 
2053     // We still need to handle naked functions even though optnone subsumes
2054     // much of their semantics.
2055     if (D->hasAttr<NakedAttr>())
2056       B.addAttribute(llvm::Attribute::Naked);
2057 
2058     // OptimizeNone wins over OptimizeForSize and MinSize.
2059     F->removeFnAttr(llvm::Attribute::OptimizeForSize);
2060     F->removeFnAttr(llvm::Attribute::MinSize);
2061   } else if (D->hasAttr<NakedAttr>()) {
2062     // Naked implies noinline: we should not be inlining such functions.
2063     B.addAttribute(llvm::Attribute::Naked);
2064     B.addAttribute(llvm::Attribute::NoInline);
2065   } else if (D->hasAttr<NoDuplicateAttr>()) {
2066     B.addAttribute(llvm::Attribute::NoDuplicate);
2067   } else if (D->hasAttr<NoInlineAttr>() && !F->hasFnAttribute(llvm::Attribute::AlwaysInline)) {
2068     // Add noinline if the function isn't always_inline.
2069     B.addAttribute(llvm::Attribute::NoInline);
2070   } else if (D->hasAttr<AlwaysInlineAttr>() &&
2071              !F->hasFnAttribute(llvm::Attribute::NoInline)) {
2072     // (noinline wins over always_inline, and we can't specify both in IR)
2073     B.addAttribute(llvm::Attribute::AlwaysInline);
2074   } else if (CodeGenOpts.getInlining() == CodeGenOptions::OnlyAlwaysInlining) {
2075     // If we're not inlining, then force everything that isn't always_inline to
2076     // carry an explicit noinline attribute.
2077     if (!F->hasFnAttribute(llvm::Attribute::AlwaysInline))
2078       B.addAttribute(llvm::Attribute::NoInline);
2079   } else {
2080     // Otherwise, propagate the inline hint attribute and potentially use its
2081     // absence to mark things as noinline.
2082     if (auto *FD = dyn_cast<FunctionDecl>(D)) {
2083       // Search function and template pattern redeclarations for inline.
2084       auto CheckForInline = [](const FunctionDecl *FD) {
2085         auto CheckRedeclForInline = [](const FunctionDecl *Redecl) {
2086           return Redecl->isInlineSpecified();
2087         };
2088         if (any_of(FD->redecls(), CheckRedeclForInline))
2089           return true;
2090         const FunctionDecl *Pattern = FD->getTemplateInstantiationPattern();
2091         if (!Pattern)
2092           return false;
2093         return any_of(Pattern->redecls(), CheckRedeclForInline);
2094       };
2095       if (CheckForInline(FD)) {
2096         B.addAttribute(llvm::Attribute::InlineHint);
2097       } else if (CodeGenOpts.getInlining() ==
2098                      CodeGenOptions::OnlyHintInlining &&
2099                  !FD->isInlined() &&
2100                  !F->hasFnAttribute(llvm::Attribute::AlwaysInline)) {
2101         B.addAttribute(llvm::Attribute::NoInline);
2102       }
2103     }
2104   }
2105 
2106   // Add other optimization related attributes if we are optimizing this
2107   // function.
2108   if (!D->hasAttr<OptimizeNoneAttr>()) {
2109     if (D->hasAttr<ColdAttr>()) {
2110       if (!ShouldAddOptNone)
2111         B.addAttribute(llvm::Attribute::OptimizeForSize);
2112       B.addAttribute(llvm::Attribute::Cold);
2113     }
2114     if (D->hasAttr<HotAttr>())
2115       B.addAttribute(llvm::Attribute::Hot);
2116     if (D->hasAttr<MinSizeAttr>())
2117       B.addAttribute(llvm::Attribute::MinSize);
2118   }
2119 
2120   F->addFnAttrs(B);
2121 
2122   unsigned alignment = D->getMaxAlignment() / Context.getCharWidth();
2123   if (alignment)
2124     F->setAlignment(llvm::Align(alignment));
2125 
2126   if (!D->hasAttr<AlignedAttr>())
2127     if (LangOpts.FunctionAlignment)
2128       F->setAlignment(llvm::Align(1ull << LangOpts.FunctionAlignment));
2129 
2130   // Some C++ ABIs require 2-byte alignment for member functions, in order to
2131   // reserve a bit for differentiating between virtual and non-virtual member
2132   // functions. If the current target's C++ ABI requires this and this is a
2133   // member function, set its alignment accordingly.
2134   if (getTarget().getCXXABI().areMemberFunctionsAligned()) {
2135     if (F->getAlignment() < 2 && isa<CXXMethodDecl>(D))
2136       F->setAlignment(llvm::Align(2));
2137   }
2138 
2139   // In the cross-dso CFI mode with canonical jump tables, we want !type
2140   // attributes on definitions only.
2141   if (CodeGenOpts.SanitizeCfiCrossDso &&
2142       CodeGenOpts.SanitizeCfiCanonicalJumpTables) {
2143     if (auto *FD = dyn_cast<FunctionDecl>(D)) {
2144       // Skip available_externally functions. They won't be codegen'ed in the
2145       // current module anyway.
2146       if (getContext().GetGVALinkageForFunction(FD) != GVA_AvailableExternally)
2147         CreateFunctionTypeMetadataForIcall(FD, F);
2148     }
2149   }
2150 
2151   // Emit type metadata on member functions for member function pointer checks.
2152   // These are only ever necessary on definitions; we're guaranteed that the
2153   // definition will be present in the LTO unit as a result of LTO visibility.
2154   auto *MD = dyn_cast<CXXMethodDecl>(D);
2155   if (MD && requiresMemberFunctionPointerTypeMetadata(*this, MD)) {
2156     for (const CXXRecordDecl *Base : getMostBaseClasses(MD->getParent())) {
2157       llvm::Metadata *Id =
2158           CreateMetadataIdentifierForType(Context.getMemberPointerType(
2159               MD->getType(), Context.getRecordType(Base).getTypePtr()));
2160       F->addTypeMetadata(0, Id);
2161     }
2162   }
2163 }
2164 
2165 void CodeGenModule::setLLVMFunctionFEnvAttributes(const FunctionDecl *D,
2166                                                   llvm::Function *F) {
2167   if (D->hasAttr<StrictFPAttr>()) {
2168     llvm::AttrBuilder FuncAttrs(F->getContext());
2169     FuncAttrs.addAttribute("strictfp");
2170     F->addFnAttrs(FuncAttrs);
2171   }
2172 }
2173 
2174 void CodeGenModule::SetCommonAttributes(GlobalDecl GD, llvm::GlobalValue *GV) {
2175   const Decl *D = GD.getDecl();
2176   if (isa_and_nonnull<NamedDecl>(D))
2177     setGVProperties(GV, GD);
2178   else
2179     GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
2180 
2181   if (D && D->hasAttr<UsedAttr>())
2182     addUsedOrCompilerUsedGlobal(GV);
2183 
2184   if (CodeGenOpts.KeepStaticConsts && D && isa<VarDecl>(D)) {
2185     const auto *VD = cast<VarDecl>(D);
2186     if (VD->getType().isConstQualified() &&
2187         VD->getStorageDuration() == SD_Static)
2188       addUsedOrCompilerUsedGlobal(GV);
2189   }
2190 }
2191 
2192 bool CodeGenModule::GetCPUAndFeaturesAttributes(GlobalDecl GD,
2193                                                 llvm::AttrBuilder &Attrs) {
2194   // Add target-cpu and target-features attributes to functions. If
2195   // we have a decl for the function and it has a target attribute then
2196   // parse that and add it to the feature set.
2197   StringRef TargetCPU = getTarget().getTargetOpts().CPU;
2198   StringRef TuneCPU = getTarget().getTargetOpts().TuneCPU;
2199   std::vector<std::string> Features;
2200   const auto *FD = dyn_cast_or_null<FunctionDecl>(GD.getDecl());
2201   FD = FD ? FD->getMostRecentDecl() : FD;
2202   const auto *TD = FD ? FD->getAttr<TargetAttr>() : nullptr;
2203   const auto *TV = FD ? FD->getAttr<TargetVersionAttr>() : nullptr;
2204   assert((!TD || !TV) && "both target_version and target specified");
2205   const auto *SD = FD ? FD->getAttr<CPUSpecificAttr>() : nullptr;
2206   const auto *TC = FD ? FD->getAttr<TargetClonesAttr>() : nullptr;
2207   bool AddedAttr = false;
2208   if (TD || TV || SD || TC) {
2209     llvm::StringMap<bool> FeatureMap;
2210     getContext().getFunctionFeatureMap(FeatureMap, GD);
2211 
2212     // Produce the canonical string for this set of features.
2213     for (const llvm::StringMap<bool>::value_type &Entry : FeatureMap)
2214       Features.push_back((Entry.getValue() ? "+" : "-") + Entry.getKey().str());
2215 
2216     // Now add the target-cpu and target-features to the function.
2217     // While we populated the feature map above, we still need to
2218     // get and parse the target attribute so we can get the cpu for
2219     // the function.
2220     if (TD) {
2221       ParsedTargetAttr ParsedAttr =
2222           Target.parseTargetAttr(TD->getFeaturesStr());
2223       if (!ParsedAttr.CPU.empty() &&
2224           getTarget().isValidCPUName(ParsedAttr.CPU)) {
2225         TargetCPU = ParsedAttr.CPU;
2226         TuneCPU = ""; // Clear the tune CPU.
2227       }
2228       if (!ParsedAttr.Tune.empty() &&
2229           getTarget().isValidCPUName(ParsedAttr.Tune))
2230         TuneCPU = ParsedAttr.Tune;
2231     }
2232 
2233     if (SD) {
2234       // Apply the given CPU name as the 'tune-cpu' so that the optimizer can
2235       // favor this processor.
2236       TuneCPU = getTarget().getCPUSpecificTuneName(
2237           SD->getCPUName(GD.getMultiVersionIndex())->getName());
2238     }
2239   } else {
2240     // Otherwise just add the existing target cpu and target features to the
2241     // function.
2242     Features = getTarget().getTargetOpts().Features;
2243   }
2244 
2245   if (!TargetCPU.empty()) {
2246     Attrs.addAttribute("target-cpu", TargetCPU);
2247     AddedAttr = true;
2248   }
2249   if (!TuneCPU.empty()) {
2250     Attrs.addAttribute("tune-cpu", TuneCPU);
2251     AddedAttr = true;
2252   }
2253   if (!Features.empty()) {
2254     llvm::sort(Features);
2255     Attrs.addAttribute("target-features", llvm::join(Features, ","));
2256     AddedAttr = true;
2257   }
2258 
2259   return AddedAttr;
2260 }
2261 
2262 void CodeGenModule::setNonAliasAttributes(GlobalDecl GD,
2263                                           llvm::GlobalObject *GO) {
2264   const Decl *D = GD.getDecl();
2265   SetCommonAttributes(GD, GO);
2266 
2267   if (D) {
2268     if (auto *GV = dyn_cast<llvm::GlobalVariable>(GO)) {
2269       if (D->hasAttr<RetainAttr>())
2270         addUsedGlobal(GV);
2271       if (auto *SA = D->getAttr<PragmaClangBSSSectionAttr>())
2272         GV->addAttribute("bss-section", SA->getName());
2273       if (auto *SA = D->getAttr<PragmaClangDataSectionAttr>())
2274         GV->addAttribute("data-section", SA->getName());
2275       if (auto *SA = D->getAttr<PragmaClangRodataSectionAttr>())
2276         GV->addAttribute("rodata-section", SA->getName());
2277       if (auto *SA = D->getAttr<PragmaClangRelroSectionAttr>())
2278         GV->addAttribute("relro-section", SA->getName());
2279     }
2280 
2281     if (auto *F = dyn_cast<llvm::Function>(GO)) {
2282       if (D->hasAttr<RetainAttr>())
2283         addUsedGlobal(F);
2284       if (auto *SA = D->getAttr<PragmaClangTextSectionAttr>())
2285         if (!D->getAttr<SectionAttr>())
2286           F->addFnAttr("implicit-section-name", SA->getName());
2287 
2288       llvm::AttrBuilder Attrs(F->getContext());
2289       if (GetCPUAndFeaturesAttributes(GD, Attrs)) {
2290         // We know that GetCPUAndFeaturesAttributes will always have the
2291         // newest set, since it has the newest possible FunctionDecl, so the
2292         // new ones should replace the old.
2293         llvm::AttributeMask RemoveAttrs;
2294         RemoveAttrs.addAttribute("target-cpu");
2295         RemoveAttrs.addAttribute("target-features");
2296         RemoveAttrs.addAttribute("tune-cpu");
2297         F->removeFnAttrs(RemoveAttrs);
2298         F->addFnAttrs(Attrs);
2299       }
2300     }
2301 
2302     if (const auto *CSA = D->getAttr<CodeSegAttr>())
2303       GO->setSection(CSA->getName());
2304     else if (const auto *SA = D->getAttr<SectionAttr>())
2305       GO->setSection(SA->getName());
2306   }
2307 
2308   getTargetCodeGenInfo().setTargetAttributes(D, GO, *this);
2309 }
2310 
2311 void CodeGenModule::SetInternalFunctionAttributes(GlobalDecl GD,
2312                                                   llvm::Function *F,
2313                                                   const CGFunctionInfo &FI) {
2314   const Decl *D = GD.getDecl();
2315   SetLLVMFunctionAttributes(GD, FI, F, /*IsThunk=*/false);
2316   SetLLVMFunctionAttributesForDefinition(D, F);
2317 
2318   F->setLinkage(llvm::Function::InternalLinkage);
2319 
2320   setNonAliasAttributes(GD, F);
2321 }
2322 
2323 static void setLinkageForGV(llvm::GlobalValue *GV, const NamedDecl *ND) {
2324   // Set linkage and visibility in case we never see a definition.
2325   LinkageInfo LV = ND->getLinkageAndVisibility();
2326   // Don't set internal linkage on declarations.
2327   // "extern_weak" is overloaded in LLVM; we probably should have
2328   // separate linkage types for this.
2329   if (isExternallyVisible(LV.getLinkage()) &&
2330       (ND->hasAttr<WeakAttr>() || ND->isWeakImported()))
2331     GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
2332 }
2333 
2334 void CodeGenModule::CreateFunctionTypeMetadataForIcall(const FunctionDecl *FD,
2335                                                        llvm::Function *F) {
2336   // Only if we are checking indirect calls.
2337   if (!LangOpts.Sanitize.has(SanitizerKind::CFIICall))
2338     return;
2339 
2340   // Non-static class methods are handled via vtable or member function pointer
2341   // checks elsewhere.
2342   if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
2343     return;
2344 
2345   llvm::Metadata *MD = CreateMetadataIdentifierForType(FD->getType());
2346   F->addTypeMetadata(0, MD);
2347   F->addTypeMetadata(0, CreateMetadataIdentifierGeneralized(FD->getType()));
2348 
2349   // Emit a hash-based bit set entry for cross-DSO calls.
2350   if (CodeGenOpts.SanitizeCfiCrossDso)
2351     if (auto CrossDsoTypeId = CreateCrossDsoCfiTypeId(MD))
2352       F->addTypeMetadata(0, llvm::ConstantAsMetadata::get(CrossDsoTypeId));
2353 }
2354 
2355 void CodeGenModule::setKCFIType(const FunctionDecl *FD, llvm::Function *F) {
2356   if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
2357     return;
2358 
2359   llvm::LLVMContext &Ctx = F->getContext();
2360   llvm::MDBuilder MDB(Ctx);
2361   F->setMetadata(llvm::LLVMContext::MD_kcfi_type,
2362                  llvm::MDNode::get(
2363                      Ctx, MDB.createConstant(CreateKCFITypeId(FD->getType()))));
2364 }
2365 
2366 static bool allowKCFIIdentifier(StringRef Name) {
2367   // KCFI type identifier constants are only necessary for external assembly
2368   // functions, which means it's safe to skip unusual names. Subset of
2369   // MCAsmInfo::isAcceptableChar() and MCAsmInfoXCOFF::isAcceptableChar().
2370   return llvm::all_of(Name, [](const char &C) {
2371     return llvm::isAlnum(C) || C == '_' || C == '.';
2372   });
2373 }
2374 
2375 void CodeGenModule::finalizeKCFITypes() {
2376   llvm::Module &M = getModule();
2377   for (auto &F : M.functions()) {
2378     // Remove KCFI type metadata from non-address-taken local functions.
2379     bool AddressTaken = F.hasAddressTaken();
2380     if (!AddressTaken && F.hasLocalLinkage())
2381       F.eraseMetadata(llvm::LLVMContext::MD_kcfi_type);
2382 
2383     // Generate a constant with the expected KCFI type identifier for all
2384     // address-taken function declarations to support annotating indirectly
2385     // called assembly functions.
2386     if (!AddressTaken || !F.isDeclaration())
2387       continue;
2388 
2389     const llvm::ConstantInt *Type;
2390     if (const llvm::MDNode *MD = F.getMetadata(llvm::LLVMContext::MD_kcfi_type))
2391       Type = llvm::mdconst::extract<llvm::ConstantInt>(MD->getOperand(0));
2392     else
2393       continue;
2394 
2395     StringRef Name = F.getName();
2396     if (!allowKCFIIdentifier(Name))
2397       continue;
2398 
2399     std::string Asm = (".weak __kcfi_typeid_" + Name + "\n.set __kcfi_typeid_" +
2400                        Name + ", " + Twine(Type->getZExtValue()) + "\n")
2401                           .str();
2402     M.appendModuleInlineAsm(Asm);
2403   }
2404 }
2405 
2406 void CodeGenModule::SetFunctionAttributes(GlobalDecl GD, llvm::Function *F,
2407                                           bool IsIncompleteFunction,
2408                                           bool IsThunk) {
2409 
2410   if (llvm::Intrinsic::ID IID = F->getIntrinsicID()) {
2411     // If this is an intrinsic function, set the function's attributes
2412     // to the intrinsic's attributes.
2413     F->setAttributes(llvm::Intrinsic::getAttributes(getLLVMContext(), IID));
2414     return;
2415   }
2416 
2417   const auto *FD = cast<FunctionDecl>(GD.getDecl());
2418 
2419   if (!IsIncompleteFunction)
2420     SetLLVMFunctionAttributes(GD, getTypes().arrangeGlobalDeclaration(GD), F,
2421                               IsThunk);
2422 
2423   // Add the Returned attribute for "this", except for iOS 5 and earlier
2424   // where substantial code, including the libstdc++ dylib, was compiled with
2425   // GCC and does not actually return "this".
2426   if (!IsThunk && getCXXABI().HasThisReturn(GD) &&
2427       !(getTriple().isiOS() && getTriple().isOSVersionLT(6))) {
2428     assert(!F->arg_empty() &&
2429            F->arg_begin()->getType()
2430              ->canLosslesslyBitCastTo(F->getReturnType()) &&
2431            "unexpected this return");
2432     F->addParamAttr(0, llvm::Attribute::Returned);
2433   }
2434 
2435   // Only a few attributes are set on declarations; these may later be
2436   // overridden by a definition.
2437 
2438   setLinkageForGV(F, FD);
2439   setGVProperties(F, FD);
2440 
2441   // Setup target-specific attributes.
2442   if (!IsIncompleteFunction && F->isDeclaration())
2443     getTargetCodeGenInfo().setTargetAttributes(FD, F, *this);
2444 
2445   if (const auto *CSA = FD->getAttr<CodeSegAttr>())
2446     F->setSection(CSA->getName());
2447   else if (const auto *SA = FD->getAttr<SectionAttr>())
2448      F->setSection(SA->getName());
2449 
2450   if (const auto *EA = FD->getAttr<ErrorAttr>()) {
2451     if (EA->isError())
2452       F->addFnAttr("dontcall-error", EA->getUserDiagnostic());
2453     else if (EA->isWarning())
2454       F->addFnAttr("dontcall-warn", EA->getUserDiagnostic());
2455   }
2456 
2457   // If we plan on emitting this inline builtin, we can't treat it as a builtin.
2458   if (FD->isInlineBuiltinDeclaration()) {
2459     const FunctionDecl *FDBody;
2460     bool HasBody = FD->hasBody(FDBody);
2461     (void)HasBody;
2462     assert(HasBody && "Inline builtin declarations should always have an "
2463                       "available body!");
2464     if (shouldEmitFunction(FDBody))
2465       F->addFnAttr(llvm::Attribute::NoBuiltin);
2466   }
2467 
2468   if (FD->isReplaceableGlobalAllocationFunction()) {
2469     // A replaceable global allocation function does not act like a builtin by
2470     // default, only if it is invoked by a new-expression or delete-expression.
2471     F->addFnAttr(llvm::Attribute::NoBuiltin);
2472   }
2473 
2474   if (isa<CXXConstructorDecl>(FD) || isa<CXXDestructorDecl>(FD))
2475     F->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
2476   else if (const auto *MD = dyn_cast<CXXMethodDecl>(FD))
2477     if (MD->isVirtual())
2478       F->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
2479 
2480   // Don't emit entries for function declarations in the cross-DSO mode. This
2481   // is handled with better precision by the receiving DSO. But if jump tables
2482   // are non-canonical then we need type metadata in order to produce the local
2483   // jump table.
2484   if (!CodeGenOpts.SanitizeCfiCrossDso ||
2485       !CodeGenOpts.SanitizeCfiCanonicalJumpTables)
2486     CreateFunctionTypeMetadataForIcall(FD, F);
2487 
2488   if (LangOpts.Sanitize.has(SanitizerKind::KCFI))
2489     setKCFIType(FD, F);
2490 
2491   if (getLangOpts().OpenMP && FD->hasAttr<OMPDeclareSimdDeclAttr>())
2492     getOpenMPRuntime().emitDeclareSimdFunction(FD, F);
2493 
2494   if (CodeGenOpts.InlineMaxStackSize != UINT_MAX)
2495     F->addFnAttr("inline-max-stacksize", llvm::utostr(CodeGenOpts.InlineMaxStackSize));
2496 
2497   if (const auto *CB = FD->getAttr<CallbackAttr>()) {
2498     // Annotate the callback behavior as metadata:
2499     //  - The callback callee (as argument number).
2500     //  - The callback payloads (as argument numbers).
2501     llvm::LLVMContext &Ctx = F->getContext();
2502     llvm::MDBuilder MDB(Ctx);
2503 
2504     // The payload indices are all but the first one in the encoding. The first
2505     // identifies the callback callee.
2506     int CalleeIdx = *CB->encoding_begin();
2507     ArrayRef<int> PayloadIndices(CB->encoding_begin() + 1, CB->encoding_end());
2508     F->addMetadata(llvm::LLVMContext::MD_callback,
2509                    *llvm::MDNode::get(Ctx, {MDB.createCallbackEncoding(
2510                                                CalleeIdx, PayloadIndices,
2511                                                /* VarArgsArePassed */ false)}));
2512   }
2513 }
2514 
2515 void CodeGenModule::addUsedGlobal(llvm::GlobalValue *GV) {
2516   assert((isa<llvm::Function>(GV) || !GV->isDeclaration()) &&
2517          "Only globals with definition can force usage.");
2518   LLVMUsed.emplace_back(GV);
2519 }
2520 
2521 void CodeGenModule::addCompilerUsedGlobal(llvm::GlobalValue *GV) {
2522   assert(!GV->isDeclaration() &&
2523          "Only globals with definition can force usage.");
2524   LLVMCompilerUsed.emplace_back(GV);
2525 }
2526 
2527 void CodeGenModule::addUsedOrCompilerUsedGlobal(llvm::GlobalValue *GV) {
2528   assert((isa<llvm::Function>(GV) || !GV->isDeclaration()) &&
2529          "Only globals with definition can force usage.");
2530   if (getTriple().isOSBinFormatELF())
2531     LLVMCompilerUsed.emplace_back(GV);
2532   else
2533     LLVMUsed.emplace_back(GV);
2534 }
2535 
2536 static void emitUsed(CodeGenModule &CGM, StringRef Name,
2537                      std::vector<llvm::WeakTrackingVH> &List) {
2538   // Don't create llvm.used if there is no need.
2539   if (List.empty())
2540     return;
2541 
2542   // Convert List to what ConstantArray needs.
2543   SmallVector<llvm::Constant*, 8> UsedArray;
2544   UsedArray.resize(List.size());
2545   for (unsigned i = 0, e = List.size(); i != e; ++i) {
2546     UsedArray[i] =
2547         llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
2548             cast<llvm::Constant>(&*List[i]), CGM.Int8PtrTy);
2549   }
2550 
2551   if (UsedArray.empty())
2552     return;
2553   llvm::ArrayType *ATy = llvm::ArrayType::get(CGM.Int8PtrTy, UsedArray.size());
2554 
2555   auto *GV = new llvm::GlobalVariable(
2556       CGM.getModule(), ATy, false, llvm::GlobalValue::AppendingLinkage,
2557       llvm::ConstantArray::get(ATy, UsedArray), Name);
2558 
2559   GV->setSection("llvm.metadata");
2560 }
2561 
2562 void CodeGenModule::emitLLVMUsed() {
2563   emitUsed(*this, "llvm.used", LLVMUsed);
2564   emitUsed(*this, "llvm.compiler.used", LLVMCompilerUsed);
2565 }
2566 
2567 void CodeGenModule::AppendLinkerOptions(StringRef Opts) {
2568   auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opts);
2569   LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
2570 }
2571 
2572 void CodeGenModule::AddDetectMismatch(StringRef Name, StringRef Value) {
2573   llvm::SmallString<32> Opt;
2574   getTargetCodeGenInfo().getDetectMismatchOption(Name, Value, Opt);
2575   if (Opt.empty())
2576     return;
2577   auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opt);
2578   LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
2579 }
2580 
2581 void CodeGenModule::AddDependentLib(StringRef Lib) {
2582   auto &C = getLLVMContext();
2583   if (getTarget().getTriple().isOSBinFormatELF()) {
2584       ELFDependentLibraries.push_back(
2585         llvm::MDNode::get(C, llvm::MDString::get(C, Lib)));
2586     return;
2587   }
2588 
2589   llvm::SmallString<24> Opt;
2590   getTargetCodeGenInfo().getDependentLibraryOption(Lib, Opt);
2591   auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opt);
2592   LinkerOptionsMetadata.push_back(llvm::MDNode::get(C, MDOpts));
2593 }
2594 
2595 /// Add link options implied by the given module, including modules
2596 /// it depends on, using a postorder walk.
2597 static void addLinkOptionsPostorder(CodeGenModule &CGM, Module *Mod,
2598                                     SmallVectorImpl<llvm::MDNode *> &Metadata,
2599                                     llvm::SmallPtrSet<Module *, 16> &Visited) {
2600   // Import this module's parent.
2601   if (Mod->Parent && Visited.insert(Mod->Parent).second) {
2602     addLinkOptionsPostorder(CGM, Mod->Parent, Metadata, Visited);
2603   }
2604 
2605   // Import this module's dependencies.
2606   for (Module *Import : llvm::reverse(Mod->Imports)) {
2607     if (Visited.insert(Import).second)
2608       addLinkOptionsPostorder(CGM, Import, Metadata, Visited);
2609   }
2610 
2611   // Add linker options to link against the libraries/frameworks
2612   // described by this module.
2613   llvm::LLVMContext &Context = CGM.getLLVMContext();
2614   bool IsELF = CGM.getTarget().getTriple().isOSBinFormatELF();
2615 
2616   // For modules that use export_as for linking, use that module
2617   // name instead.
2618   if (Mod->UseExportAsModuleLinkName)
2619     return;
2620 
2621   for (const Module::LinkLibrary &LL : llvm::reverse(Mod->LinkLibraries)) {
2622     // Link against a framework.  Frameworks are currently Darwin only, so we
2623     // don't to ask TargetCodeGenInfo for the spelling of the linker option.
2624     if (LL.IsFramework) {
2625       llvm::Metadata *Args[2] = {llvm::MDString::get(Context, "-framework"),
2626                                  llvm::MDString::get(Context, LL.Library)};
2627 
2628       Metadata.push_back(llvm::MDNode::get(Context, Args));
2629       continue;
2630     }
2631 
2632     // Link against a library.
2633     if (IsELF) {
2634       llvm::Metadata *Args[2] = {
2635           llvm::MDString::get(Context, "lib"),
2636           llvm::MDString::get(Context, LL.Library),
2637       };
2638       Metadata.push_back(llvm::MDNode::get(Context, Args));
2639     } else {
2640       llvm::SmallString<24> Opt;
2641       CGM.getTargetCodeGenInfo().getDependentLibraryOption(LL.Library, Opt);
2642       auto *OptString = llvm::MDString::get(Context, Opt);
2643       Metadata.push_back(llvm::MDNode::get(Context, OptString));
2644     }
2645   }
2646 }
2647 
2648 void CodeGenModule::EmitModuleInitializers(clang::Module *Primary) {
2649   // Emit the initializers in the order that sub-modules appear in the
2650   // source, first Global Module Fragments, if present.
2651   if (auto GMF = Primary->getGlobalModuleFragment()) {
2652     for (Decl *D : getContext().getModuleInitializers(GMF)) {
2653       if (isa<ImportDecl>(D))
2654         continue;
2655       assert(isa<VarDecl>(D) && "GMF initializer decl is not a var?");
2656       EmitTopLevelDecl(D);
2657     }
2658   }
2659   // Second any associated with the module, itself.
2660   for (Decl *D : getContext().getModuleInitializers(Primary)) {
2661     // Skip import decls, the inits for those are called explicitly.
2662     if (isa<ImportDecl>(D))
2663       continue;
2664     EmitTopLevelDecl(D);
2665   }
2666   // Third any associated with the Privat eMOdule Fragment, if present.
2667   if (auto PMF = Primary->getPrivateModuleFragment()) {
2668     for (Decl *D : getContext().getModuleInitializers(PMF)) {
2669       assert(isa<VarDecl>(D) && "PMF initializer decl is not a var?");
2670       EmitTopLevelDecl(D);
2671     }
2672   }
2673 }
2674 
2675 void CodeGenModule::EmitModuleLinkOptions() {
2676   // Collect the set of all of the modules we want to visit to emit link
2677   // options, which is essentially the imported modules and all of their
2678   // non-explicit child modules.
2679   llvm::SetVector<clang::Module *> LinkModules;
2680   llvm::SmallPtrSet<clang::Module *, 16> Visited;
2681   SmallVector<clang::Module *, 16> Stack;
2682 
2683   // Seed the stack with imported modules.
2684   for (Module *M : ImportedModules) {
2685     // Do not add any link flags when an implementation TU of a module imports
2686     // a header of that same module.
2687     if (M->getTopLevelModuleName() == getLangOpts().CurrentModule &&
2688         !getLangOpts().isCompilingModule())
2689       continue;
2690     if (Visited.insert(M).second)
2691       Stack.push_back(M);
2692   }
2693 
2694   // Find all of the modules to import, making a little effort to prune
2695   // non-leaf modules.
2696   while (!Stack.empty()) {
2697     clang::Module *Mod = Stack.pop_back_val();
2698 
2699     bool AnyChildren = false;
2700 
2701     // Visit the submodules of this module.
2702     for (const auto &SM : Mod->submodules()) {
2703       // Skip explicit children; they need to be explicitly imported to be
2704       // linked against.
2705       if (SM->IsExplicit)
2706         continue;
2707 
2708       if (Visited.insert(SM).second) {
2709         Stack.push_back(SM);
2710         AnyChildren = true;
2711       }
2712     }
2713 
2714     // We didn't find any children, so add this module to the list of
2715     // modules to link against.
2716     if (!AnyChildren) {
2717       LinkModules.insert(Mod);
2718     }
2719   }
2720 
2721   // Add link options for all of the imported modules in reverse topological
2722   // order.  We don't do anything to try to order import link flags with respect
2723   // to linker options inserted by things like #pragma comment().
2724   SmallVector<llvm::MDNode *, 16> MetadataArgs;
2725   Visited.clear();
2726   for (Module *M : LinkModules)
2727     if (Visited.insert(M).second)
2728       addLinkOptionsPostorder(*this, M, MetadataArgs, Visited);
2729   std::reverse(MetadataArgs.begin(), MetadataArgs.end());
2730   LinkerOptionsMetadata.append(MetadataArgs.begin(), MetadataArgs.end());
2731 
2732   // Add the linker options metadata flag.
2733   auto *NMD = getModule().getOrInsertNamedMetadata("llvm.linker.options");
2734   for (auto *MD : LinkerOptionsMetadata)
2735     NMD->addOperand(MD);
2736 }
2737 
2738 void CodeGenModule::EmitDeferred() {
2739   // Emit deferred declare target declarations.
2740   if (getLangOpts().OpenMP && !getLangOpts().OpenMPSimd)
2741     getOpenMPRuntime().emitDeferredTargetDecls();
2742 
2743   // Emit code for any potentially referenced deferred decls.  Since a
2744   // previously unused static decl may become used during the generation of code
2745   // for a static function, iterate until no changes are made.
2746 
2747   if (!DeferredVTables.empty()) {
2748     EmitDeferredVTables();
2749 
2750     // Emitting a vtable doesn't directly cause more vtables to
2751     // become deferred, although it can cause functions to be
2752     // emitted that then need those vtables.
2753     assert(DeferredVTables.empty());
2754   }
2755 
2756   // Emit CUDA/HIP static device variables referenced by host code only.
2757   // Note we should not clear CUDADeviceVarODRUsedByHost since it is still
2758   // needed for further handling.
2759   if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice)
2760     llvm::append_range(DeferredDeclsToEmit,
2761                        getContext().CUDADeviceVarODRUsedByHost);
2762 
2763   // Stop if we're out of both deferred vtables and deferred declarations.
2764   if (DeferredDeclsToEmit.empty())
2765     return;
2766 
2767   // Grab the list of decls to emit. If EmitGlobalDefinition schedules more
2768   // work, it will not interfere with this.
2769   std::vector<GlobalDecl> CurDeclsToEmit;
2770   CurDeclsToEmit.swap(DeferredDeclsToEmit);
2771 
2772   for (GlobalDecl &D : CurDeclsToEmit) {
2773     // We should call GetAddrOfGlobal with IsForDefinition set to true in order
2774     // to get GlobalValue with exactly the type we need, not something that
2775     // might had been created for another decl with the same mangled name but
2776     // different type.
2777     llvm::GlobalValue *GV = dyn_cast<llvm::GlobalValue>(
2778         GetAddrOfGlobal(D, ForDefinition));
2779 
2780     // In case of different address spaces, we may still get a cast, even with
2781     // IsForDefinition equal to true. Query mangled names table to get
2782     // GlobalValue.
2783     if (!GV)
2784       GV = GetGlobalValue(getMangledName(D));
2785 
2786     // Make sure GetGlobalValue returned non-null.
2787     assert(GV);
2788 
2789     // Check to see if we've already emitted this.  This is necessary
2790     // for a couple of reasons: first, decls can end up in the
2791     // deferred-decls queue multiple times, and second, decls can end
2792     // up with definitions in unusual ways (e.g. by an extern inline
2793     // function acquiring a strong function redefinition).  Just
2794     // ignore these cases.
2795     if (!GV->isDeclaration())
2796       continue;
2797 
2798     // If this is OpenMP, check if it is legal to emit this global normally.
2799     if (LangOpts.OpenMP && OpenMPRuntime && OpenMPRuntime->emitTargetGlobal(D))
2800       continue;
2801 
2802     // Otherwise, emit the definition and move on to the next one.
2803     EmitGlobalDefinition(D, GV);
2804 
2805     // If we found out that we need to emit more decls, do that recursively.
2806     // This has the advantage that the decls are emitted in a DFS and related
2807     // ones are close together, which is convenient for testing.
2808     if (!DeferredVTables.empty() || !DeferredDeclsToEmit.empty()) {
2809       EmitDeferred();
2810       assert(DeferredVTables.empty() && DeferredDeclsToEmit.empty());
2811     }
2812   }
2813 }
2814 
2815 void CodeGenModule::EmitVTablesOpportunistically() {
2816   // Try to emit external vtables as available_externally if they have emitted
2817   // all inlined virtual functions.  It runs after EmitDeferred() and therefore
2818   // is not allowed to create new references to things that need to be emitted
2819   // lazily. Note that it also uses fact that we eagerly emitting RTTI.
2820 
2821   assert((OpportunisticVTables.empty() || shouldOpportunisticallyEmitVTables())
2822          && "Only emit opportunistic vtables with optimizations");
2823 
2824   for (const CXXRecordDecl *RD : OpportunisticVTables) {
2825     assert(getVTables().isVTableExternal(RD) &&
2826            "This queue should only contain external vtables");
2827     if (getCXXABI().canSpeculativelyEmitVTable(RD))
2828       VTables.GenerateClassData(RD);
2829   }
2830   OpportunisticVTables.clear();
2831 }
2832 
2833 void CodeGenModule::EmitGlobalAnnotations() {
2834   if (Annotations.empty())
2835     return;
2836 
2837   // Create a new global variable for the ConstantStruct in the Module.
2838   llvm::Constant *Array = llvm::ConstantArray::get(llvm::ArrayType::get(
2839     Annotations[0]->getType(), Annotations.size()), Annotations);
2840   auto *gv = new llvm::GlobalVariable(getModule(), Array->getType(), false,
2841                                       llvm::GlobalValue::AppendingLinkage,
2842                                       Array, "llvm.global.annotations");
2843   gv->setSection(AnnotationSection);
2844 }
2845 
2846 llvm::Constant *CodeGenModule::EmitAnnotationString(StringRef Str) {
2847   llvm::Constant *&AStr = AnnotationStrings[Str];
2848   if (AStr)
2849     return AStr;
2850 
2851   // Not found yet, create a new global.
2852   llvm::Constant *s = llvm::ConstantDataArray::getString(getLLVMContext(), Str);
2853   auto *gv = new llvm::GlobalVariable(
2854       getModule(), s->getType(), true, llvm::GlobalValue::PrivateLinkage, s,
2855       ".str", nullptr, llvm::GlobalValue::NotThreadLocal,
2856       ConstGlobalsPtrTy->getAddressSpace());
2857   gv->setSection(AnnotationSection);
2858   gv->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
2859   AStr = gv;
2860   return gv;
2861 }
2862 
2863 llvm::Constant *CodeGenModule::EmitAnnotationUnit(SourceLocation Loc) {
2864   SourceManager &SM = getContext().getSourceManager();
2865   PresumedLoc PLoc = SM.getPresumedLoc(Loc);
2866   if (PLoc.isValid())
2867     return EmitAnnotationString(PLoc.getFilename());
2868   return EmitAnnotationString(SM.getBufferName(Loc));
2869 }
2870 
2871 llvm::Constant *CodeGenModule::EmitAnnotationLineNo(SourceLocation L) {
2872   SourceManager &SM = getContext().getSourceManager();
2873   PresumedLoc PLoc = SM.getPresumedLoc(L);
2874   unsigned LineNo = PLoc.isValid() ? PLoc.getLine() :
2875     SM.getExpansionLineNumber(L);
2876   return llvm::ConstantInt::get(Int32Ty, LineNo);
2877 }
2878 
2879 llvm::Constant *CodeGenModule::EmitAnnotationArgs(const AnnotateAttr *Attr) {
2880   ArrayRef<Expr *> Exprs = {Attr->args_begin(), Attr->args_size()};
2881   if (Exprs.empty())
2882     return llvm::ConstantPointerNull::get(ConstGlobalsPtrTy);
2883 
2884   llvm::FoldingSetNodeID ID;
2885   for (Expr *E : Exprs) {
2886     ID.Add(cast<clang::ConstantExpr>(E)->getAPValueResult());
2887   }
2888   llvm::Constant *&Lookup = AnnotationArgs[ID.ComputeHash()];
2889   if (Lookup)
2890     return Lookup;
2891 
2892   llvm::SmallVector<llvm::Constant *, 4> LLVMArgs;
2893   LLVMArgs.reserve(Exprs.size());
2894   ConstantEmitter ConstEmiter(*this);
2895   llvm::transform(Exprs, std::back_inserter(LLVMArgs), [&](const Expr *E) {
2896     const auto *CE = cast<clang::ConstantExpr>(E);
2897     return ConstEmiter.emitAbstract(CE->getBeginLoc(), CE->getAPValueResult(),
2898                                     CE->getType());
2899   });
2900   auto *Struct = llvm::ConstantStruct::getAnon(LLVMArgs);
2901   auto *GV = new llvm::GlobalVariable(getModule(), Struct->getType(), true,
2902                                       llvm::GlobalValue::PrivateLinkage, Struct,
2903                                       ".args");
2904   GV->setSection(AnnotationSection);
2905   GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
2906   auto *Bitcasted = llvm::ConstantExpr::getBitCast(GV, GlobalsInt8PtrTy);
2907 
2908   Lookup = Bitcasted;
2909   return Bitcasted;
2910 }
2911 
2912 llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV,
2913                                                 const AnnotateAttr *AA,
2914                                                 SourceLocation L) {
2915   // Get the globals for file name, annotation, and the line number.
2916   llvm::Constant *AnnoGV = EmitAnnotationString(AA->getAnnotation()),
2917                  *UnitGV = EmitAnnotationUnit(L),
2918                  *LineNoCst = EmitAnnotationLineNo(L),
2919                  *Args = EmitAnnotationArgs(AA);
2920 
2921   llvm::Constant *GVInGlobalsAS = GV;
2922   if (GV->getAddressSpace() !=
2923       getDataLayout().getDefaultGlobalsAddressSpace()) {
2924     GVInGlobalsAS = llvm::ConstantExpr::getAddrSpaceCast(
2925         GV, GV->getValueType()->getPointerTo(
2926                 getDataLayout().getDefaultGlobalsAddressSpace()));
2927   }
2928 
2929   // Create the ConstantStruct for the global annotation.
2930   llvm::Constant *Fields[] = {
2931       llvm::ConstantExpr::getBitCast(GVInGlobalsAS, GlobalsInt8PtrTy),
2932       llvm::ConstantExpr::getBitCast(AnnoGV, ConstGlobalsPtrTy),
2933       llvm::ConstantExpr::getBitCast(UnitGV, ConstGlobalsPtrTy),
2934       LineNoCst,
2935       Args,
2936   };
2937   return llvm::ConstantStruct::getAnon(Fields);
2938 }
2939 
2940 void CodeGenModule::AddGlobalAnnotations(const ValueDecl *D,
2941                                          llvm::GlobalValue *GV) {
2942   assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute");
2943   // Get the struct elements for these annotations.
2944   for (const auto *I : D->specific_attrs<AnnotateAttr>())
2945     Annotations.push_back(EmitAnnotateAttr(GV, I, D->getLocation()));
2946 }
2947 
2948 bool CodeGenModule::isInNoSanitizeList(SanitizerMask Kind, llvm::Function *Fn,
2949                                        SourceLocation Loc) const {
2950   const auto &NoSanitizeL = getContext().getNoSanitizeList();
2951   // NoSanitize by function name.
2952   if (NoSanitizeL.containsFunction(Kind, Fn->getName()))
2953     return true;
2954   // NoSanitize by location. Check "mainfile" prefix.
2955   auto &SM = Context.getSourceManager();
2956   const FileEntry &MainFile = *SM.getFileEntryForID(SM.getMainFileID());
2957   if (NoSanitizeL.containsMainFile(Kind, MainFile.getName()))
2958     return true;
2959 
2960   // Check "src" prefix.
2961   if (Loc.isValid())
2962     return NoSanitizeL.containsLocation(Kind, Loc);
2963   // If location is unknown, this may be a compiler-generated function. Assume
2964   // it's located in the main file.
2965   return NoSanitizeL.containsFile(Kind, MainFile.getName());
2966 }
2967 
2968 bool CodeGenModule::isInNoSanitizeList(SanitizerMask Kind,
2969                                        llvm::GlobalVariable *GV,
2970                                        SourceLocation Loc, QualType Ty,
2971                                        StringRef Category) const {
2972   const auto &NoSanitizeL = getContext().getNoSanitizeList();
2973   if (NoSanitizeL.containsGlobal(Kind, GV->getName(), Category))
2974     return true;
2975   auto &SM = Context.getSourceManager();
2976   if (NoSanitizeL.containsMainFile(
2977           Kind, SM.getFileEntryForID(SM.getMainFileID())->getName(), Category))
2978     return true;
2979   if (NoSanitizeL.containsLocation(Kind, Loc, Category))
2980     return true;
2981 
2982   // Check global type.
2983   if (!Ty.isNull()) {
2984     // Drill down the array types: if global variable of a fixed type is
2985     // not sanitized, we also don't instrument arrays of them.
2986     while (auto AT = dyn_cast<ArrayType>(Ty.getTypePtr()))
2987       Ty = AT->getElementType();
2988     Ty = Ty.getCanonicalType().getUnqualifiedType();
2989     // Only record types (classes, structs etc.) are ignored.
2990     if (Ty->isRecordType()) {
2991       std::string TypeStr = Ty.getAsString(getContext().getPrintingPolicy());
2992       if (NoSanitizeL.containsType(Kind, TypeStr, Category))
2993         return true;
2994     }
2995   }
2996   return false;
2997 }
2998 
2999 bool CodeGenModule::imbueXRayAttrs(llvm::Function *Fn, SourceLocation Loc,
3000                                    StringRef Category) const {
3001   const auto &XRayFilter = getContext().getXRayFilter();
3002   using ImbueAttr = XRayFunctionFilter::ImbueAttribute;
3003   auto Attr = ImbueAttr::NONE;
3004   if (Loc.isValid())
3005     Attr = XRayFilter.shouldImbueLocation(Loc, Category);
3006   if (Attr == ImbueAttr::NONE)
3007     Attr = XRayFilter.shouldImbueFunction(Fn->getName());
3008   switch (Attr) {
3009   case ImbueAttr::NONE:
3010     return false;
3011   case ImbueAttr::ALWAYS:
3012     Fn->addFnAttr("function-instrument", "xray-always");
3013     break;
3014   case ImbueAttr::ALWAYS_ARG1:
3015     Fn->addFnAttr("function-instrument", "xray-always");
3016     Fn->addFnAttr("xray-log-args", "1");
3017     break;
3018   case ImbueAttr::NEVER:
3019     Fn->addFnAttr("function-instrument", "xray-never");
3020     break;
3021   }
3022   return true;
3023 }
3024 
3025 ProfileList::ExclusionType
3026 CodeGenModule::isFunctionBlockedByProfileList(llvm::Function *Fn,
3027                                               SourceLocation Loc) const {
3028   const auto &ProfileList = getContext().getProfileList();
3029   // If the profile list is empty, then instrument everything.
3030   if (ProfileList.isEmpty())
3031     return ProfileList::Allow;
3032   CodeGenOptions::ProfileInstrKind Kind = getCodeGenOpts().getProfileInstr();
3033   // First, check the function name.
3034   if (auto V = ProfileList.isFunctionExcluded(Fn->getName(), Kind))
3035     return *V;
3036   // Next, check the source location.
3037   if (Loc.isValid())
3038     if (auto V = ProfileList.isLocationExcluded(Loc, Kind))
3039       return *V;
3040   // If location is unknown, this may be a compiler-generated function. Assume
3041   // it's located in the main file.
3042   auto &SM = Context.getSourceManager();
3043   if (const auto *MainFile = SM.getFileEntryForID(SM.getMainFileID()))
3044     if (auto V = ProfileList.isFileExcluded(MainFile->getName(), Kind))
3045       return *V;
3046   return ProfileList.getDefault(Kind);
3047 }
3048 
3049 ProfileList::ExclusionType
3050 CodeGenModule::isFunctionBlockedFromProfileInstr(llvm::Function *Fn,
3051                                                  SourceLocation Loc) const {
3052   auto V = isFunctionBlockedByProfileList(Fn, Loc);
3053   if (V != ProfileList::Allow)
3054     return V;
3055 
3056   auto NumGroups = getCodeGenOpts().ProfileTotalFunctionGroups;
3057   if (NumGroups > 1) {
3058     auto Group = llvm::crc32(arrayRefFromStringRef(Fn->getName())) % NumGroups;
3059     if (Group != getCodeGenOpts().ProfileSelectedFunctionGroup)
3060       return ProfileList::Skip;
3061   }
3062   return ProfileList::Allow;
3063 }
3064 
3065 bool CodeGenModule::MustBeEmitted(const ValueDecl *Global) {
3066   // Never defer when EmitAllDecls is specified.
3067   if (LangOpts.EmitAllDecls)
3068     return true;
3069 
3070   if (CodeGenOpts.KeepStaticConsts) {
3071     const auto *VD = dyn_cast<VarDecl>(Global);
3072     if (VD && VD->getType().isConstQualified() &&
3073         VD->getStorageDuration() == SD_Static)
3074       return true;
3075   }
3076 
3077   return getContext().DeclMustBeEmitted(Global);
3078 }
3079 
3080 bool CodeGenModule::MayBeEmittedEagerly(const ValueDecl *Global) {
3081   // In OpenMP 5.0 variables and function may be marked as
3082   // device_type(host/nohost) and we should not emit them eagerly unless we sure
3083   // that they must be emitted on the host/device. To be sure we need to have
3084   // seen a declare target with an explicit mentioning of the function, we know
3085   // we have if the level of the declare target attribute is -1. Note that we
3086   // check somewhere else if we should emit this at all.
3087   if (LangOpts.OpenMP >= 50 && !LangOpts.OpenMPSimd) {
3088     std::optional<OMPDeclareTargetDeclAttr *> ActiveAttr =
3089         OMPDeclareTargetDeclAttr::getActiveAttr(Global);
3090     if (!ActiveAttr || (*ActiveAttr)->getLevel() != (unsigned)-1)
3091       return false;
3092   }
3093 
3094   if (const auto *FD = dyn_cast<FunctionDecl>(Global)) {
3095     if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
3096       // Implicit template instantiations may change linkage if they are later
3097       // explicitly instantiated, so they should not be emitted eagerly.
3098       return false;
3099   }
3100   if (const auto *VD = dyn_cast<VarDecl>(Global)) {
3101     if (Context.getInlineVariableDefinitionKind(VD) ==
3102         ASTContext::InlineVariableDefinitionKind::WeakUnknown)
3103       // A definition of an inline constexpr static data member may change
3104       // linkage later if it's redeclared outside the class.
3105       return false;
3106     if (CXX20ModuleInits && VD->getOwningModule() &&
3107         !VD->getOwningModule()->isModuleMapModule()) {
3108       // For CXX20, module-owned initializers need to be deferred, since it is
3109       // not known at this point if they will be run for the current module or
3110       // as part of the initializer for an imported one.
3111       return false;
3112     }
3113   }
3114   // If OpenMP is enabled and threadprivates must be generated like TLS, delay
3115   // codegen for global variables, because they may be marked as threadprivate.
3116   if (LangOpts.OpenMP && LangOpts.OpenMPUseTLS &&
3117       getContext().getTargetInfo().isTLSSupported() && isa<VarDecl>(Global) &&
3118       !isTypeConstant(Global->getType(), false) &&
3119       !OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(Global))
3120     return false;
3121 
3122   return true;
3123 }
3124 
3125 ConstantAddress CodeGenModule::GetAddrOfMSGuidDecl(const MSGuidDecl *GD) {
3126   StringRef Name = getMangledName(GD);
3127 
3128   // The UUID descriptor should be pointer aligned.
3129   CharUnits Alignment = CharUnits::fromQuantity(PointerAlignInBytes);
3130 
3131   // Look for an existing global.
3132   if (llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name))
3133     return ConstantAddress(GV, GV->getValueType(), Alignment);
3134 
3135   ConstantEmitter Emitter(*this);
3136   llvm::Constant *Init;
3137 
3138   APValue &V = GD->getAsAPValue();
3139   if (!V.isAbsent()) {
3140     // If possible, emit the APValue version of the initializer. In particular,
3141     // this gets the type of the constant right.
3142     Init = Emitter.emitForInitializer(
3143         GD->getAsAPValue(), GD->getType().getAddressSpace(), GD->getType());
3144   } else {
3145     // As a fallback, directly construct the constant.
3146     // FIXME: This may get padding wrong under esoteric struct layout rules.
3147     // MSVC appears to create a complete type 'struct __s_GUID' that it
3148     // presumably uses to represent these constants.
3149     MSGuidDecl::Parts Parts = GD->getParts();
3150     llvm::Constant *Fields[4] = {
3151         llvm::ConstantInt::get(Int32Ty, Parts.Part1),
3152         llvm::ConstantInt::get(Int16Ty, Parts.Part2),
3153         llvm::ConstantInt::get(Int16Ty, Parts.Part3),
3154         llvm::ConstantDataArray::getRaw(
3155             StringRef(reinterpret_cast<char *>(Parts.Part4And5), 8), 8,
3156             Int8Ty)};
3157     Init = llvm::ConstantStruct::getAnon(Fields);
3158   }
3159 
3160   auto *GV = new llvm::GlobalVariable(
3161       getModule(), Init->getType(),
3162       /*isConstant=*/true, llvm::GlobalValue::LinkOnceODRLinkage, Init, Name);
3163   if (supportsCOMDAT())
3164     GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
3165   setDSOLocal(GV);
3166 
3167   if (!V.isAbsent()) {
3168     Emitter.finalize(GV);
3169     return ConstantAddress(GV, GV->getValueType(), Alignment);
3170   }
3171 
3172   llvm::Type *Ty = getTypes().ConvertTypeForMem(GD->getType());
3173   llvm::Constant *Addr = llvm::ConstantExpr::getBitCast(
3174       GV, Ty->getPointerTo(GV->getAddressSpace()));
3175   return ConstantAddress(Addr, Ty, Alignment);
3176 }
3177 
3178 ConstantAddress CodeGenModule::GetAddrOfUnnamedGlobalConstantDecl(
3179     const UnnamedGlobalConstantDecl *GCD) {
3180   CharUnits Alignment = getContext().getTypeAlignInChars(GCD->getType());
3181 
3182   llvm::GlobalVariable **Entry = nullptr;
3183   Entry = &UnnamedGlobalConstantDeclMap[GCD];
3184   if (*Entry)
3185     return ConstantAddress(*Entry, (*Entry)->getValueType(), Alignment);
3186 
3187   ConstantEmitter Emitter(*this);
3188   llvm::Constant *Init;
3189 
3190   const APValue &V = GCD->getValue();
3191 
3192   assert(!V.isAbsent());
3193   Init = Emitter.emitForInitializer(V, GCD->getType().getAddressSpace(),
3194                                     GCD->getType());
3195 
3196   auto *GV = new llvm::GlobalVariable(getModule(), Init->getType(),
3197                                       /*isConstant=*/true,
3198                                       llvm::GlobalValue::PrivateLinkage, Init,
3199                                       ".constant");
3200   GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
3201   GV->setAlignment(Alignment.getAsAlign());
3202 
3203   Emitter.finalize(GV);
3204 
3205   *Entry = GV;
3206   return ConstantAddress(GV, GV->getValueType(), Alignment);
3207 }
3208 
3209 ConstantAddress CodeGenModule::GetAddrOfTemplateParamObject(
3210     const TemplateParamObjectDecl *TPO) {
3211   StringRef Name = getMangledName(TPO);
3212   CharUnits Alignment = getNaturalTypeAlignment(TPO->getType());
3213 
3214   if (llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name))
3215     return ConstantAddress(GV, GV->getValueType(), Alignment);
3216 
3217   ConstantEmitter Emitter(*this);
3218   llvm::Constant *Init = Emitter.emitForInitializer(
3219         TPO->getValue(), TPO->getType().getAddressSpace(), TPO->getType());
3220 
3221   if (!Init) {
3222     ErrorUnsupported(TPO, "template parameter object");
3223     return ConstantAddress::invalid();
3224   }
3225 
3226   auto *GV = new llvm::GlobalVariable(
3227       getModule(), Init->getType(),
3228       /*isConstant=*/true, llvm::GlobalValue::LinkOnceODRLinkage, Init, Name);
3229   if (supportsCOMDAT())
3230     GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
3231   Emitter.finalize(GV);
3232 
3233   return ConstantAddress(GV, GV->getValueType(), Alignment);
3234 }
3235 
3236 ConstantAddress CodeGenModule::GetWeakRefReference(const ValueDecl *VD) {
3237   const AliasAttr *AA = VD->getAttr<AliasAttr>();
3238   assert(AA && "No alias?");
3239 
3240   CharUnits Alignment = getContext().getDeclAlign(VD);
3241   llvm::Type *DeclTy = getTypes().ConvertTypeForMem(VD->getType());
3242 
3243   // See if there is already something with the target's name in the module.
3244   llvm::GlobalValue *Entry = GetGlobalValue(AA->getAliasee());
3245   if (Entry) {
3246     unsigned AS = getTypes().getTargetAddressSpace(VD->getType());
3247     auto Ptr = llvm::ConstantExpr::getBitCast(Entry, DeclTy->getPointerTo(AS));
3248     return ConstantAddress(Ptr, DeclTy, Alignment);
3249   }
3250 
3251   llvm::Constant *Aliasee;
3252   if (isa<llvm::FunctionType>(DeclTy))
3253     Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy,
3254                                       GlobalDecl(cast<FunctionDecl>(VD)),
3255                                       /*ForVTable=*/false);
3256   else
3257     Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(), DeclTy, LangAS::Default,
3258                                     nullptr);
3259 
3260   auto *F = cast<llvm::GlobalValue>(Aliasee);
3261   F->setLinkage(llvm::Function::ExternalWeakLinkage);
3262   WeakRefReferences.insert(F);
3263 
3264   return ConstantAddress(Aliasee, DeclTy, Alignment);
3265 }
3266 
3267 void CodeGenModule::EmitGlobal(GlobalDecl GD) {
3268   const auto *Global = cast<ValueDecl>(GD.getDecl());
3269 
3270   // Weak references don't produce any output by themselves.
3271   if (Global->hasAttr<WeakRefAttr>())
3272     return;
3273 
3274   // If this is an alias definition (which otherwise looks like a declaration)
3275   // emit it now.
3276   if (Global->hasAttr<AliasAttr>())
3277     return EmitAliasDefinition(GD);
3278 
3279   // IFunc like an alias whose value is resolved at runtime by calling resolver.
3280   if (Global->hasAttr<IFuncAttr>())
3281     return emitIFuncDefinition(GD);
3282 
3283   // If this is a cpu_dispatch multiversion function, emit the resolver.
3284   if (Global->hasAttr<CPUDispatchAttr>())
3285     return emitCPUDispatchDefinition(GD);
3286 
3287   // If this is CUDA, be selective about which declarations we emit.
3288   if (LangOpts.CUDA) {
3289     if (LangOpts.CUDAIsDevice) {
3290       if (!Global->hasAttr<CUDADeviceAttr>() &&
3291           !Global->hasAttr<CUDAGlobalAttr>() &&
3292           !Global->hasAttr<CUDAConstantAttr>() &&
3293           !Global->hasAttr<CUDASharedAttr>() &&
3294           !Global->getType()->isCUDADeviceBuiltinSurfaceType() &&
3295           !Global->getType()->isCUDADeviceBuiltinTextureType())
3296         return;
3297     } else {
3298       // We need to emit host-side 'shadows' for all global
3299       // device-side variables because the CUDA runtime needs their
3300       // size and host-side address in order to provide access to
3301       // their device-side incarnations.
3302 
3303       // So device-only functions are the only things we skip.
3304       if (isa<FunctionDecl>(Global) && !Global->hasAttr<CUDAHostAttr>() &&
3305           Global->hasAttr<CUDADeviceAttr>())
3306         return;
3307 
3308       assert((isa<FunctionDecl>(Global) || isa<VarDecl>(Global)) &&
3309              "Expected Variable or Function");
3310     }
3311   }
3312 
3313   if (LangOpts.OpenMP) {
3314     // If this is OpenMP, check if it is legal to emit this global normally.
3315     if (OpenMPRuntime && OpenMPRuntime->emitTargetGlobal(GD))
3316       return;
3317     if (auto *DRD = dyn_cast<OMPDeclareReductionDecl>(Global)) {
3318       if (MustBeEmitted(Global))
3319         EmitOMPDeclareReduction(DRD);
3320       return;
3321     }
3322     if (auto *DMD = dyn_cast<OMPDeclareMapperDecl>(Global)) {
3323       if (MustBeEmitted(Global))
3324         EmitOMPDeclareMapper(DMD);
3325       return;
3326     }
3327   }
3328 
3329   // Ignore declarations, they will be emitted on their first use.
3330   if (const auto *FD = dyn_cast<FunctionDecl>(Global)) {
3331     // Forward declarations are emitted lazily on first use.
3332     if (!FD->doesThisDeclarationHaveABody()) {
3333       if (!FD->doesDeclarationForceExternallyVisibleDefinition())
3334         return;
3335 
3336       StringRef MangledName = getMangledName(GD);
3337 
3338       // Compute the function info and LLVM type.
3339       const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
3340       llvm::Type *Ty = getTypes().GetFunctionType(FI);
3341 
3342       GetOrCreateLLVMFunction(MangledName, Ty, GD, /*ForVTable=*/false,
3343                               /*DontDefer=*/false);
3344       return;
3345     }
3346   } else {
3347     const auto *VD = cast<VarDecl>(Global);
3348     assert(VD->isFileVarDecl() && "Cannot emit local var decl as global.");
3349     if (VD->isThisDeclarationADefinition() != VarDecl::Definition &&
3350         !Context.isMSStaticDataMemberInlineDefinition(VD)) {
3351       if (LangOpts.OpenMP) {
3352         // Emit declaration of the must-be-emitted declare target variable.
3353         if (std::optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
3354                 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD)) {
3355           bool UnifiedMemoryEnabled =
3356               getOpenMPRuntime().hasRequiresUnifiedSharedMemory();
3357           if ((*Res == OMPDeclareTargetDeclAttr::MT_To ||
3358                *Res == OMPDeclareTargetDeclAttr::MT_Enter) &&
3359               !UnifiedMemoryEnabled) {
3360             (void)GetAddrOfGlobalVar(VD);
3361           } else {
3362             assert(((*Res == OMPDeclareTargetDeclAttr::MT_Link) ||
3363                     ((*Res == OMPDeclareTargetDeclAttr::MT_To ||
3364                       *Res == OMPDeclareTargetDeclAttr::MT_Enter) &&
3365                      UnifiedMemoryEnabled)) &&
3366                    "Link clause or to clause with unified memory expected.");
3367             (void)getOpenMPRuntime().getAddrOfDeclareTargetVar(VD);
3368           }
3369 
3370           return;
3371         }
3372       }
3373       // If this declaration may have caused an inline variable definition to
3374       // change linkage, make sure that it's emitted.
3375       if (Context.getInlineVariableDefinitionKind(VD) ==
3376           ASTContext::InlineVariableDefinitionKind::Strong)
3377         GetAddrOfGlobalVar(VD);
3378       return;
3379     }
3380   }
3381 
3382   // Defer code generation to first use when possible, e.g. if this is an inline
3383   // function. If the global must always be emitted, do it eagerly if possible
3384   // to benefit from cache locality.
3385   if (MustBeEmitted(Global) && MayBeEmittedEagerly(Global)) {
3386     // Emit the definition if it can't be deferred.
3387     EmitGlobalDefinition(GD);
3388     return;
3389   }
3390 
3391   // If we're deferring emission of a C++ variable with an
3392   // initializer, remember the order in which it appeared in the file.
3393   if (getLangOpts().CPlusPlus && isa<VarDecl>(Global) &&
3394       cast<VarDecl>(Global)->hasInit()) {
3395     DelayedCXXInitPosition[Global] = CXXGlobalInits.size();
3396     CXXGlobalInits.push_back(nullptr);
3397   }
3398 
3399   StringRef MangledName = getMangledName(GD);
3400   if (GetGlobalValue(MangledName) != nullptr) {
3401     // The value has already been used and should therefore be emitted.
3402     addDeferredDeclToEmit(GD);
3403   } else if (MustBeEmitted(Global)) {
3404     // The value must be emitted, but cannot be emitted eagerly.
3405     assert(!MayBeEmittedEagerly(Global));
3406     addDeferredDeclToEmit(GD);
3407     EmittedDeferredDecls[MangledName] = GD;
3408   } else {
3409     // Otherwise, remember that we saw a deferred decl with this name.  The
3410     // first use of the mangled name will cause it to move into
3411     // DeferredDeclsToEmit.
3412     DeferredDecls[MangledName] = GD;
3413   }
3414 }
3415 
3416 // Check if T is a class type with a destructor that's not dllimport.
3417 static bool HasNonDllImportDtor(QualType T) {
3418   if (const auto *RT = T->getBaseElementTypeUnsafe()->getAs<RecordType>())
3419     if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl()))
3420       if (RD->getDestructor() && !RD->getDestructor()->hasAttr<DLLImportAttr>())
3421         return true;
3422 
3423   return false;
3424 }
3425 
3426 namespace {
3427   struct FunctionIsDirectlyRecursive
3428       : public ConstStmtVisitor<FunctionIsDirectlyRecursive, bool> {
3429     const StringRef Name;
3430     const Builtin::Context &BI;
3431     FunctionIsDirectlyRecursive(StringRef N, const Builtin::Context &C)
3432         : Name(N), BI(C) {}
3433 
3434     bool VisitCallExpr(const CallExpr *E) {
3435       const FunctionDecl *FD = E->getDirectCallee();
3436       if (!FD)
3437         return false;
3438       AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>();
3439       if (Attr && Name == Attr->getLabel())
3440         return true;
3441       unsigned BuiltinID = FD->getBuiltinID();
3442       if (!BuiltinID || !BI.isLibFunction(BuiltinID))
3443         return false;
3444       StringRef BuiltinName = BI.getName(BuiltinID);
3445       if (BuiltinName.startswith("__builtin_") &&
3446           Name == BuiltinName.slice(strlen("__builtin_"), StringRef::npos)) {
3447         return true;
3448       }
3449       return false;
3450     }
3451 
3452     bool VisitStmt(const Stmt *S) {
3453       for (const Stmt *Child : S->children())
3454         if (Child && this->Visit(Child))
3455           return true;
3456       return false;
3457     }
3458   };
3459 
3460   // Make sure we're not referencing non-imported vars or functions.
3461   struct DLLImportFunctionVisitor
3462       : public RecursiveASTVisitor<DLLImportFunctionVisitor> {
3463     bool SafeToInline = true;
3464 
3465     bool shouldVisitImplicitCode() const { return true; }
3466 
3467     bool VisitVarDecl(VarDecl *VD) {
3468       if (VD->getTLSKind()) {
3469         // A thread-local variable cannot be imported.
3470         SafeToInline = false;
3471         return SafeToInline;
3472       }
3473 
3474       // A variable definition might imply a destructor call.
3475       if (VD->isThisDeclarationADefinition())
3476         SafeToInline = !HasNonDllImportDtor(VD->getType());
3477 
3478       return SafeToInline;
3479     }
3480 
3481     bool VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
3482       if (const auto *D = E->getTemporary()->getDestructor())
3483         SafeToInline = D->hasAttr<DLLImportAttr>();
3484       return SafeToInline;
3485     }
3486 
3487     bool VisitDeclRefExpr(DeclRefExpr *E) {
3488       ValueDecl *VD = E->getDecl();
3489       if (isa<FunctionDecl>(VD))
3490         SafeToInline = VD->hasAttr<DLLImportAttr>();
3491       else if (VarDecl *V = dyn_cast<VarDecl>(VD))
3492         SafeToInline = !V->hasGlobalStorage() || V->hasAttr<DLLImportAttr>();
3493       return SafeToInline;
3494     }
3495 
3496     bool VisitCXXConstructExpr(CXXConstructExpr *E) {
3497       SafeToInline = E->getConstructor()->hasAttr<DLLImportAttr>();
3498       return SafeToInline;
3499     }
3500 
3501     bool VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
3502       CXXMethodDecl *M = E->getMethodDecl();
3503       if (!M) {
3504         // Call through a pointer to member function. This is safe to inline.
3505         SafeToInline = true;
3506       } else {
3507         SafeToInline = M->hasAttr<DLLImportAttr>();
3508       }
3509       return SafeToInline;
3510     }
3511 
3512     bool VisitCXXDeleteExpr(CXXDeleteExpr *E) {
3513       SafeToInline = E->getOperatorDelete()->hasAttr<DLLImportAttr>();
3514       return SafeToInline;
3515     }
3516 
3517     bool VisitCXXNewExpr(CXXNewExpr *E) {
3518       SafeToInline = E->getOperatorNew()->hasAttr<DLLImportAttr>();
3519       return SafeToInline;
3520     }
3521   };
3522 }
3523 
3524 // isTriviallyRecursive - Check if this function calls another
3525 // decl that, because of the asm attribute or the other decl being a builtin,
3526 // ends up pointing to itself.
3527 bool
3528 CodeGenModule::isTriviallyRecursive(const FunctionDecl *FD) {
3529   StringRef Name;
3530   if (getCXXABI().getMangleContext().shouldMangleDeclName(FD)) {
3531     // asm labels are a special kind of mangling we have to support.
3532     AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>();
3533     if (!Attr)
3534       return false;
3535     Name = Attr->getLabel();
3536   } else {
3537     Name = FD->getName();
3538   }
3539 
3540   FunctionIsDirectlyRecursive Walker(Name, Context.BuiltinInfo);
3541   const Stmt *Body = FD->getBody();
3542   return Body ? Walker.Visit(Body) : false;
3543 }
3544 
3545 bool CodeGenModule::shouldEmitFunction(GlobalDecl GD) {
3546   if (getFunctionLinkage(GD) != llvm::Function::AvailableExternallyLinkage)
3547     return true;
3548   const auto *F = cast<FunctionDecl>(GD.getDecl());
3549   if (CodeGenOpts.OptimizationLevel == 0 && !F->hasAttr<AlwaysInlineAttr>())
3550     return false;
3551 
3552   if (F->hasAttr<DLLImportAttr>() && !F->hasAttr<AlwaysInlineAttr>()) {
3553     // Check whether it would be safe to inline this dllimport function.
3554     DLLImportFunctionVisitor Visitor;
3555     Visitor.TraverseFunctionDecl(const_cast<FunctionDecl*>(F));
3556     if (!Visitor.SafeToInline)
3557       return false;
3558 
3559     if (const CXXDestructorDecl *Dtor = dyn_cast<CXXDestructorDecl>(F)) {
3560       // Implicit destructor invocations aren't captured in the AST, so the
3561       // check above can't see them. Check for them manually here.
3562       for (const Decl *Member : Dtor->getParent()->decls())
3563         if (isa<FieldDecl>(Member))
3564           if (HasNonDllImportDtor(cast<FieldDecl>(Member)->getType()))
3565             return false;
3566       for (const CXXBaseSpecifier &B : Dtor->getParent()->bases())
3567         if (HasNonDllImportDtor(B.getType()))
3568           return false;
3569     }
3570   }
3571 
3572   // Inline builtins declaration must be emitted. They often are fortified
3573   // functions.
3574   if (F->isInlineBuiltinDeclaration())
3575     return true;
3576 
3577   // PR9614. Avoid cases where the source code is lying to us. An available
3578   // externally function should have an equivalent function somewhere else,
3579   // but a function that calls itself through asm label/`__builtin_` trickery is
3580   // clearly not equivalent to the real implementation.
3581   // This happens in glibc's btowc and in some configure checks.
3582   return !isTriviallyRecursive(F);
3583 }
3584 
3585 bool CodeGenModule::shouldOpportunisticallyEmitVTables() {
3586   return CodeGenOpts.OptimizationLevel > 0;
3587 }
3588 
3589 void CodeGenModule::EmitMultiVersionFunctionDefinition(GlobalDecl GD,
3590                                                        llvm::GlobalValue *GV) {
3591   const auto *FD = cast<FunctionDecl>(GD.getDecl());
3592 
3593   if (FD->isCPUSpecificMultiVersion()) {
3594     auto *Spec = FD->getAttr<CPUSpecificAttr>();
3595     for (unsigned I = 0; I < Spec->cpus_size(); ++I)
3596       EmitGlobalFunctionDefinition(GD.getWithMultiVersionIndex(I), nullptr);
3597   } else if (FD->isTargetClonesMultiVersion()) {
3598     auto *Clone = FD->getAttr<TargetClonesAttr>();
3599     for (unsigned I = 0; I < Clone->featuresStrs_size(); ++I)
3600       if (Clone->isFirstOfVersion(I))
3601         EmitGlobalFunctionDefinition(GD.getWithMultiVersionIndex(I), nullptr);
3602     // Ensure that the resolver function is also emitted.
3603     GetOrCreateMultiVersionResolver(GD);
3604   } else
3605     EmitGlobalFunctionDefinition(GD, GV);
3606 }
3607 
3608 void CodeGenModule::EmitGlobalDefinition(GlobalDecl GD, llvm::GlobalValue *GV) {
3609   const auto *D = cast<ValueDecl>(GD.getDecl());
3610 
3611   PrettyStackTraceDecl CrashInfo(const_cast<ValueDecl *>(D), D->getLocation(),
3612                                  Context.getSourceManager(),
3613                                  "Generating code for declaration");
3614 
3615   if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
3616     // At -O0, don't generate IR for functions with available_externally
3617     // linkage.
3618     if (!shouldEmitFunction(GD))
3619       return;
3620 
3621     llvm::TimeTraceScope TimeScope("CodeGen Function", [&]() {
3622       std::string Name;
3623       llvm::raw_string_ostream OS(Name);
3624       FD->getNameForDiagnostic(OS, getContext().getPrintingPolicy(),
3625                                /*Qualified=*/true);
3626       return Name;
3627     });
3628 
3629     if (const auto *Method = dyn_cast<CXXMethodDecl>(D)) {
3630       // Make sure to emit the definition(s) before we emit the thunks.
3631       // This is necessary for the generation of certain thunks.
3632       if (isa<CXXConstructorDecl>(Method) || isa<CXXDestructorDecl>(Method))
3633         ABI->emitCXXStructor(GD);
3634       else if (FD->isMultiVersion())
3635         EmitMultiVersionFunctionDefinition(GD, GV);
3636       else
3637         EmitGlobalFunctionDefinition(GD, GV);
3638 
3639       if (Method->isVirtual())
3640         getVTables().EmitThunks(GD);
3641 
3642       return;
3643     }
3644 
3645     if (FD->isMultiVersion())
3646       return EmitMultiVersionFunctionDefinition(GD, GV);
3647     return EmitGlobalFunctionDefinition(GD, GV);
3648   }
3649 
3650   if (const auto *VD = dyn_cast<VarDecl>(D))
3651     return EmitGlobalVarDefinition(VD, !VD->hasDefinition());
3652 
3653   llvm_unreachable("Invalid argument to EmitGlobalDefinition()");
3654 }
3655 
3656 static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old,
3657                                                       llvm::Function *NewFn);
3658 
3659 static unsigned
3660 TargetMVPriority(const TargetInfo &TI,
3661                  const CodeGenFunction::MultiVersionResolverOption &RO) {
3662   unsigned Priority = 0;
3663   unsigned NumFeatures = 0;
3664   for (StringRef Feat : RO.Conditions.Features) {
3665     Priority = std::max(Priority, TI.multiVersionSortPriority(Feat));
3666     NumFeatures++;
3667   }
3668 
3669   if (!RO.Conditions.Architecture.empty())
3670     Priority = std::max(
3671         Priority, TI.multiVersionSortPriority(RO.Conditions.Architecture));
3672 
3673   Priority += TI.multiVersionFeatureCost() * NumFeatures;
3674 
3675   return Priority;
3676 }
3677 
3678 // Multiversion functions should be at most 'WeakODRLinkage' so that a different
3679 // TU can forward declare the function without causing problems.  Particularly
3680 // in the cases of CPUDispatch, this causes issues. This also makes sure we
3681 // work with internal linkage functions, so that the same function name can be
3682 // used with internal linkage in multiple TUs.
3683 llvm::GlobalValue::LinkageTypes getMultiversionLinkage(CodeGenModule &CGM,
3684                                                        GlobalDecl GD) {
3685   const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
3686   if (FD->getFormalLinkage() == InternalLinkage)
3687     return llvm::GlobalValue::InternalLinkage;
3688   return llvm::GlobalValue::WeakODRLinkage;
3689 }
3690 
3691 void CodeGenModule::emitMultiVersionFunctions() {
3692   std::vector<GlobalDecl> MVFuncsToEmit;
3693   MultiVersionFuncs.swap(MVFuncsToEmit);
3694   for (GlobalDecl GD : MVFuncsToEmit) {
3695     const auto *FD = cast<FunctionDecl>(GD.getDecl());
3696     assert(FD && "Expected a FunctionDecl");
3697 
3698     SmallVector<CodeGenFunction::MultiVersionResolverOption, 10> Options;
3699     if (FD->isTargetMultiVersion()) {
3700       getContext().forEachMultiversionedFunctionVersion(
3701           FD, [this, &GD, &Options](const FunctionDecl *CurFD) {
3702             GlobalDecl CurGD{
3703                 (CurFD->isDefined() ? CurFD->getDefinition() : CurFD)};
3704             StringRef MangledName = getMangledName(CurGD);
3705             llvm::Constant *Func = GetGlobalValue(MangledName);
3706             if (!Func) {
3707               if (CurFD->isDefined()) {
3708                 EmitGlobalFunctionDefinition(CurGD, nullptr);
3709                 Func = GetGlobalValue(MangledName);
3710               } else {
3711                 const CGFunctionInfo &FI =
3712                     getTypes().arrangeGlobalDeclaration(GD);
3713                 llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
3714                 Func = GetAddrOfFunction(CurGD, Ty, /*ForVTable=*/false,
3715                                          /*DontDefer=*/false, ForDefinition);
3716               }
3717               assert(Func && "This should have just been created");
3718             }
3719             if (CurFD->getMultiVersionKind() == MultiVersionKind::Target) {
3720               const auto *TA = CurFD->getAttr<TargetAttr>();
3721               llvm::SmallVector<StringRef, 8> Feats;
3722               TA->getAddedFeatures(Feats);
3723               Options.emplace_back(cast<llvm::Function>(Func),
3724                                    TA->getArchitecture(), Feats);
3725             } else {
3726               const auto *TVA = CurFD->getAttr<TargetVersionAttr>();
3727               llvm::SmallVector<StringRef, 8> Feats;
3728               TVA->getFeatures(Feats);
3729               Options.emplace_back(cast<llvm::Function>(Func),
3730                                    /*Architecture*/ "", Feats);
3731             }
3732           });
3733     } else if (FD->isTargetClonesMultiVersion()) {
3734       const auto *TC = FD->getAttr<TargetClonesAttr>();
3735       for (unsigned VersionIndex = 0; VersionIndex < TC->featuresStrs_size();
3736            ++VersionIndex) {
3737         if (!TC->isFirstOfVersion(VersionIndex))
3738           continue;
3739         GlobalDecl CurGD{(FD->isDefined() ? FD->getDefinition() : FD),
3740                          VersionIndex};
3741         StringRef Version = TC->getFeatureStr(VersionIndex);
3742         StringRef MangledName = getMangledName(CurGD);
3743         llvm::Constant *Func = GetGlobalValue(MangledName);
3744         if (!Func) {
3745           if (FD->isDefined()) {
3746             EmitGlobalFunctionDefinition(CurGD, nullptr);
3747             Func = GetGlobalValue(MangledName);
3748           } else {
3749             const CGFunctionInfo &FI =
3750                 getTypes().arrangeGlobalDeclaration(CurGD);
3751             llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
3752             Func = GetAddrOfFunction(CurGD, Ty, /*ForVTable=*/false,
3753                                      /*DontDefer=*/false, ForDefinition);
3754           }
3755           assert(Func && "This should have just been created");
3756         }
3757 
3758         StringRef Architecture;
3759         llvm::SmallVector<StringRef, 1> Feature;
3760 
3761         if (getTarget().getTriple().isAArch64()) {
3762           if (Version != "default") {
3763             llvm::SmallVector<StringRef, 8> VerFeats;
3764             Version.split(VerFeats, "+");
3765             for (auto &CurFeat : VerFeats)
3766               Feature.push_back(CurFeat.trim());
3767           }
3768         } else {
3769           if (Version.startswith("arch="))
3770             Architecture = Version.drop_front(sizeof("arch=") - 1);
3771           else if (Version != "default")
3772             Feature.push_back(Version);
3773         }
3774 
3775         Options.emplace_back(cast<llvm::Function>(Func), Architecture, Feature);
3776       }
3777     } else {
3778       assert(0 && "Expected a target or target_clones multiversion function");
3779       continue;
3780     }
3781 
3782     llvm::Constant *ResolverConstant = GetOrCreateMultiVersionResolver(GD);
3783     if (auto *IFunc = dyn_cast<llvm::GlobalIFunc>(ResolverConstant))
3784       ResolverConstant = IFunc->getResolver();
3785     llvm::Function *ResolverFunc = cast<llvm::Function>(ResolverConstant);
3786 
3787     ResolverFunc->setLinkage(getMultiversionLinkage(*this, GD));
3788 
3789     if (supportsCOMDAT())
3790       ResolverFunc->setComdat(
3791           getModule().getOrInsertComdat(ResolverFunc->getName()));
3792 
3793     const TargetInfo &TI = getTarget();
3794     llvm::stable_sort(
3795         Options, [&TI](const CodeGenFunction::MultiVersionResolverOption &LHS,
3796                        const CodeGenFunction::MultiVersionResolverOption &RHS) {
3797           return TargetMVPriority(TI, LHS) > TargetMVPriority(TI, RHS);
3798         });
3799     CodeGenFunction CGF(*this);
3800     CGF.EmitMultiVersionResolver(ResolverFunc, Options);
3801   }
3802 
3803   // Ensure that any additions to the deferred decls list caused by emitting a
3804   // variant are emitted.  This can happen when the variant itself is inline and
3805   // calls a function without linkage.
3806   if (!MVFuncsToEmit.empty())
3807     EmitDeferred();
3808 
3809   // Ensure that any additions to the multiversion funcs list from either the
3810   // deferred decls or the multiversion functions themselves are emitted.
3811   if (!MultiVersionFuncs.empty())
3812     emitMultiVersionFunctions();
3813 }
3814 
3815 void CodeGenModule::emitCPUDispatchDefinition(GlobalDecl GD) {
3816   const auto *FD = cast<FunctionDecl>(GD.getDecl());
3817   assert(FD && "Not a FunctionDecl?");
3818   assert(FD->isCPUDispatchMultiVersion() && "Not a multiversion function?");
3819   const auto *DD = FD->getAttr<CPUDispatchAttr>();
3820   assert(DD && "Not a cpu_dispatch Function?");
3821 
3822   const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
3823   llvm::FunctionType *DeclTy = getTypes().GetFunctionType(FI);
3824 
3825   StringRef ResolverName = getMangledName(GD);
3826   UpdateMultiVersionNames(GD, FD, ResolverName);
3827 
3828   llvm::Type *ResolverType;
3829   GlobalDecl ResolverGD;
3830   if (getTarget().supportsIFunc()) {
3831     ResolverType = llvm::FunctionType::get(
3832         llvm::PointerType::get(DeclTy,
3833                                getTypes().getTargetAddressSpace(FD->getType())),
3834         false);
3835   }
3836   else {
3837     ResolverType = DeclTy;
3838     ResolverGD = GD;
3839   }
3840 
3841   auto *ResolverFunc = cast<llvm::Function>(GetOrCreateLLVMFunction(
3842       ResolverName, ResolverType, ResolverGD, /*ForVTable=*/false));
3843   ResolverFunc->setLinkage(getMultiversionLinkage(*this, GD));
3844   if (supportsCOMDAT())
3845     ResolverFunc->setComdat(
3846         getModule().getOrInsertComdat(ResolverFunc->getName()));
3847 
3848   SmallVector<CodeGenFunction::MultiVersionResolverOption, 10> Options;
3849   const TargetInfo &Target = getTarget();
3850   unsigned Index = 0;
3851   for (const IdentifierInfo *II : DD->cpus()) {
3852     // Get the name of the target function so we can look it up/create it.
3853     std::string MangledName = getMangledNameImpl(*this, GD, FD, true) +
3854                               getCPUSpecificMangling(*this, II->getName());
3855 
3856     llvm::Constant *Func = GetGlobalValue(MangledName);
3857 
3858     if (!Func) {
3859       GlobalDecl ExistingDecl = Manglings.lookup(MangledName);
3860       if (ExistingDecl.getDecl() &&
3861           ExistingDecl.getDecl()->getAsFunction()->isDefined()) {
3862         EmitGlobalFunctionDefinition(ExistingDecl, nullptr);
3863         Func = GetGlobalValue(MangledName);
3864       } else {
3865         if (!ExistingDecl.getDecl())
3866           ExistingDecl = GD.getWithMultiVersionIndex(Index);
3867 
3868       Func = GetOrCreateLLVMFunction(
3869           MangledName, DeclTy, ExistingDecl,
3870           /*ForVTable=*/false, /*DontDefer=*/true,
3871           /*IsThunk=*/false, llvm::AttributeList(), ForDefinition);
3872       }
3873     }
3874 
3875     llvm::SmallVector<StringRef, 32> Features;
3876     Target.getCPUSpecificCPUDispatchFeatures(II->getName(), Features);
3877     llvm::transform(Features, Features.begin(),
3878                     [](StringRef Str) { return Str.substr(1); });
3879     llvm::erase_if(Features, [&Target](StringRef Feat) {
3880       return !Target.validateCpuSupports(Feat);
3881     });
3882     Options.emplace_back(cast<llvm::Function>(Func), StringRef{}, Features);
3883     ++Index;
3884   }
3885 
3886   llvm::stable_sort(
3887       Options, [](const CodeGenFunction::MultiVersionResolverOption &LHS,
3888                   const CodeGenFunction::MultiVersionResolverOption &RHS) {
3889         return llvm::X86::getCpuSupportsMask(LHS.Conditions.Features) >
3890                llvm::X86::getCpuSupportsMask(RHS.Conditions.Features);
3891       });
3892 
3893   // If the list contains multiple 'default' versions, such as when it contains
3894   // 'pentium' and 'generic', don't emit the call to the generic one (since we
3895   // always run on at least a 'pentium'). We do this by deleting the 'least
3896   // advanced' (read, lowest mangling letter).
3897   while (Options.size() > 1 &&
3898          llvm::X86::getCpuSupportsMask(
3899              (Options.end() - 2)->Conditions.Features) == 0) {
3900     StringRef LHSName = (Options.end() - 2)->Function->getName();
3901     StringRef RHSName = (Options.end() - 1)->Function->getName();
3902     if (LHSName.compare(RHSName) < 0)
3903       Options.erase(Options.end() - 2);
3904     else
3905       Options.erase(Options.end() - 1);
3906   }
3907 
3908   CodeGenFunction CGF(*this);
3909   CGF.EmitMultiVersionResolver(ResolverFunc, Options);
3910 
3911   if (getTarget().supportsIFunc()) {
3912     llvm::GlobalValue::LinkageTypes Linkage = getMultiversionLinkage(*this, GD);
3913     auto *IFunc = cast<llvm::GlobalValue>(GetOrCreateMultiVersionResolver(GD));
3914 
3915     // Fix up function declarations that were created for cpu_specific before
3916     // cpu_dispatch was known
3917     if (!isa<llvm::GlobalIFunc>(IFunc)) {
3918       assert(cast<llvm::Function>(IFunc)->isDeclaration());
3919       auto *GI = llvm::GlobalIFunc::create(DeclTy, 0, Linkage, "", ResolverFunc,
3920                                            &getModule());
3921       GI->takeName(IFunc);
3922       IFunc->replaceAllUsesWith(GI);
3923       IFunc->eraseFromParent();
3924       IFunc = GI;
3925     }
3926 
3927     std::string AliasName = getMangledNameImpl(
3928         *this, GD, FD, /*OmitMultiVersionMangling=*/true);
3929     llvm::Constant *AliasFunc = GetGlobalValue(AliasName);
3930     if (!AliasFunc) {
3931       auto *GA = llvm::GlobalAlias::create(DeclTy, 0, Linkage, AliasName, IFunc,
3932                                            &getModule());
3933       SetCommonAttributes(GD, GA);
3934     }
3935   }
3936 }
3937 
3938 /// If a dispatcher for the specified mangled name is not in the module, create
3939 /// and return an llvm Function with the specified type.
3940 llvm::Constant *CodeGenModule::GetOrCreateMultiVersionResolver(GlobalDecl GD) {
3941   const auto *FD = cast<FunctionDecl>(GD.getDecl());
3942   assert(FD && "Not a FunctionDecl?");
3943 
3944   std::string MangledName =
3945       getMangledNameImpl(*this, GD, FD, /*OmitMultiVersionMangling=*/true);
3946 
3947   // Holds the name of the resolver, in ifunc mode this is the ifunc (which has
3948   // a separate resolver).
3949   std::string ResolverName = MangledName;
3950   if (getTarget().supportsIFunc())
3951     ResolverName += ".ifunc";
3952   else if (FD->isTargetMultiVersion())
3953     ResolverName += ".resolver";
3954 
3955   // If the resolver has already been created, just return it.
3956   if (llvm::GlobalValue *ResolverGV = GetGlobalValue(ResolverName))
3957     return ResolverGV;
3958 
3959   const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
3960   llvm::FunctionType *DeclTy = getTypes().GetFunctionType(FI);
3961 
3962   // The resolver needs to be created. For target and target_clones, defer
3963   // creation until the end of the TU.
3964   if (FD->isTargetMultiVersion() || FD->isTargetClonesMultiVersion())
3965     MultiVersionFuncs.push_back(GD);
3966 
3967   // For cpu_specific, don't create an ifunc yet because we don't know if the
3968   // cpu_dispatch will be emitted in this translation unit.
3969   if (getTarget().supportsIFunc() && !FD->isCPUSpecificMultiVersion()) {
3970     llvm::Type *ResolverType = llvm::FunctionType::get(
3971         llvm::PointerType::get(DeclTy,
3972                                getTypes().getTargetAddressSpace(FD->getType())),
3973         false);
3974     llvm::Constant *Resolver = GetOrCreateLLVMFunction(
3975         MangledName + ".resolver", ResolverType, GlobalDecl{},
3976         /*ForVTable=*/false);
3977     llvm::GlobalIFunc *GIF =
3978         llvm::GlobalIFunc::create(DeclTy, 0, getMultiversionLinkage(*this, GD),
3979                                   "", Resolver, &getModule());
3980     GIF->setName(ResolverName);
3981     SetCommonAttributes(FD, GIF);
3982 
3983     return GIF;
3984   }
3985 
3986   llvm::Constant *Resolver = GetOrCreateLLVMFunction(
3987       ResolverName, DeclTy, GlobalDecl{}, /*ForVTable=*/false);
3988   assert(isa<llvm::GlobalValue>(Resolver) &&
3989          "Resolver should be created for the first time");
3990   SetCommonAttributes(FD, cast<llvm::GlobalValue>(Resolver));
3991   return Resolver;
3992 }
3993 
3994 /// GetOrCreateLLVMFunction - If the specified mangled name is not in the
3995 /// module, create and return an llvm Function with the specified type. If there
3996 /// is something in the module with the specified name, return it potentially
3997 /// bitcasted to the right type.
3998 ///
3999 /// If D is non-null, it specifies a decl that correspond to this.  This is used
4000 /// to set the attributes on the function when it is first created.
4001 llvm::Constant *CodeGenModule::GetOrCreateLLVMFunction(
4002     StringRef MangledName, llvm::Type *Ty, GlobalDecl GD, bool ForVTable,
4003     bool DontDefer, bool IsThunk, llvm::AttributeList ExtraAttrs,
4004     ForDefinition_t IsForDefinition) {
4005   const Decl *D = GD.getDecl();
4006 
4007   // Any attempts to use a MultiVersion function should result in retrieving
4008   // the iFunc instead. Name Mangling will handle the rest of the changes.
4009   if (const FunctionDecl *FD = cast_or_null<FunctionDecl>(D)) {
4010     // For the device mark the function as one that should be emitted.
4011     if (getLangOpts().OpenMPIsDevice && OpenMPRuntime &&
4012         !OpenMPRuntime->markAsGlobalTarget(GD) && FD->isDefined() &&
4013         !DontDefer && !IsForDefinition) {
4014       if (const FunctionDecl *FDDef = FD->getDefinition()) {
4015         GlobalDecl GDDef;
4016         if (const auto *CD = dyn_cast<CXXConstructorDecl>(FDDef))
4017           GDDef = GlobalDecl(CD, GD.getCtorType());
4018         else if (const auto *DD = dyn_cast<CXXDestructorDecl>(FDDef))
4019           GDDef = GlobalDecl(DD, GD.getDtorType());
4020         else
4021           GDDef = GlobalDecl(FDDef);
4022         EmitGlobal(GDDef);
4023       }
4024     }
4025 
4026     if (FD->isMultiVersion()) {
4027       UpdateMultiVersionNames(GD, FD, MangledName);
4028       if (!IsForDefinition)
4029         return GetOrCreateMultiVersionResolver(GD);
4030     }
4031   }
4032 
4033   // Lookup the entry, lazily creating it if necessary.
4034   llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
4035   if (Entry) {
4036     if (WeakRefReferences.erase(Entry)) {
4037       const FunctionDecl *FD = cast_or_null<FunctionDecl>(D);
4038       if (FD && !FD->hasAttr<WeakAttr>())
4039         Entry->setLinkage(llvm::Function::ExternalLinkage);
4040     }
4041 
4042     // Handle dropped DLL attributes.
4043     if (D && !D->hasAttr<DLLImportAttr>() && !D->hasAttr<DLLExportAttr>() &&
4044         !shouldMapVisibilityToDLLExport(cast_or_null<NamedDecl>(D))) {
4045       Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
4046       setDSOLocal(Entry);
4047     }
4048 
4049     // If there are two attempts to define the same mangled name, issue an
4050     // error.
4051     if (IsForDefinition && !Entry->isDeclaration()) {
4052       GlobalDecl OtherGD;
4053       // Check that GD is not yet in DiagnosedConflictingDefinitions is required
4054       // to make sure that we issue an error only once.
4055       if (lookupRepresentativeDecl(MangledName, OtherGD) &&
4056           (GD.getCanonicalDecl().getDecl() !=
4057            OtherGD.getCanonicalDecl().getDecl()) &&
4058           DiagnosedConflictingDefinitions.insert(GD).second) {
4059         getDiags().Report(D->getLocation(), diag::err_duplicate_mangled_name)
4060             << MangledName;
4061         getDiags().Report(OtherGD.getDecl()->getLocation(),
4062                           diag::note_previous_definition);
4063       }
4064     }
4065 
4066     if ((isa<llvm::Function>(Entry) || isa<llvm::GlobalAlias>(Entry)) &&
4067         (Entry->getValueType() == Ty)) {
4068       return Entry;
4069     }
4070 
4071     // Make sure the result is of the correct type.
4072     // (If function is requested for a definition, we always need to create a new
4073     // function, not just return a bitcast.)
4074     if (!IsForDefinition)
4075       return llvm::ConstantExpr::getBitCast(
4076           Entry, Ty->getPointerTo(Entry->getAddressSpace()));
4077   }
4078 
4079   // This function doesn't have a complete type (for example, the return
4080   // type is an incomplete struct). Use a fake type instead, and make
4081   // sure not to try to set attributes.
4082   bool IsIncompleteFunction = false;
4083 
4084   llvm::FunctionType *FTy;
4085   if (isa<llvm::FunctionType>(Ty)) {
4086     FTy = cast<llvm::FunctionType>(Ty);
4087   } else {
4088     FTy = llvm::FunctionType::get(VoidTy, false);
4089     IsIncompleteFunction = true;
4090   }
4091 
4092   llvm::Function *F =
4093       llvm::Function::Create(FTy, llvm::Function::ExternalLinkage,
4094                              Entry ? StringRef() : MangledName, &getModule());
4095 
4096   // If we already created a function with the same mangled name (but different
4097   // type) before, take its name and add it to the list of functions to be
4098   // replaced with F at the end of CodeGen.
4099   //
4100   // This happens if there is a prototype for a function (e.g. "int f()") and
4101   // then a definition of a different type (e.g. "int f(int x)").
4102   if (Entry) {
4103     F->takeName(Entry);
4104 
4105     // This might be an implementation of a function without a prototype, in
4106     // which case, try to do special replacement of calls which match the new
4107     // prototype.  The really key thing here is that we also potentially drop
4108     // arguments from the call site so as to make a direct call, which makes the
4109     // inliner happier and suppresses a number of optimizer warnings (!) about
4110     // dropping arguments.
4111     if (!Entry->use_empty()) {
4112       ReplaceUsesOfNonProtoTypeWithRealFunction(Entry, F);
4113       Entry->removeDeadConstantUsers();
4114     }
4115 
4116     llvm::Constant *BC = llvm::ConstantExpr::getBitCast(
4117         F, Entry->getValueType()->getPointerTo(Entry->getAddressSpace()));
4118     addGlobalValReplacement(Entry, BC);
4119   }
4120 
4121   assert(F->getName() == MangledName && "name was uniqued!");
4122   if (D)
4123     SetFunctionAttributes(GD, F, IsIncompleteFunction, IsThunk);
4124   if (ExtraAttrs.hasFnAttrs()) {
4125     llvm::AttrBuilder B(F->getContext(), ExtraAttrs.getFnAttrs());
4126     F->addFnAttrs(B);
4127   }
4128 
4129   if (!DontDefer) {
4130     // All MSVC dtors other than the base dtor are linkonce_odr and delegate to
4131     // each other bottoming out with the base dtor.  Therefore we emit non-base
4132     // dtors on usage, even if there is no dtor definition in the TU.
4133     if (isa_and_nonnull<CXXDestructorDecl>(D) &&
4134         getCXXABI().useThunkForDtorVariant(cast<CXXDestructorDecl>(D),
4135                                            GD.getDtorType()))
4136       addDeferredDeclToEmit(GD);
4137 
4138     // This is the first use or definition of a mangled name.  If there is a
4139     // deferred decl with this name, remember that we need to emit it at the end
4140     // of the file.
4141     auto DDI = DeferredDecls.find(MangledName);
4142     if (DDI != DeferredDecls.end()) {
4143       // Move the potentially referenced deferred decl to the
4144       // DeferredDeclsToEmit list, and remove it from DeferredDecls (since we
4145       // don't need it anymore).
4146       addDeferredDeclToEmit(DDI->second);
4147       EmittedDeferredDecls[DDI->first] = DDI->second;
4148       DeferredDecls.erase(DDI);
4149 
4150       // Otherwise, there are cases we have to worry about where we're
4151       // using a declaration for which we must emit a definition but where
4152       // we might not find a top-level definition:
4153       //   - member functions defined inline in their classes
4154       //   - friend functions defined inline in some class
4155       //   - special member functions with implicit definitions
4156       // If we ever change our AST traversal to walk into class methods,
4157       // this will be unnecessary.
4158       //
4159       // We also don't emit a definition for a function if it's going to be an
4160       // entry in a vtable, unless it's already marked as used.
4161     } else if (getLangOpts().CPlusPlus && D) {
4162       // Look for a declaration that's lexically in a record.
4163       for (const auto *FD = cast<FunctionDecl>(D)->getMostRecentDecl(); FD;
4164            FD = FD->getPreviousDecl()) {
4165         if (isa<CXXRecordDecl>(FD->getLexicalDeclContext())) {
4166           if (FD->doesThisDeclarationHaveABody()) {
4167             addDeferredDeclToEmit(GD.getWithDecl(FD));
4168             break;
4169           }
4170         }
4171       }
4172     }
4173   }
4174 
4175   // Make sure the result is of the requested type.
4176   if (!IsIncompleteFunction) {
4177     assert(F->getFunctionType() == Ty);
4178     return F;
4179   }
4180 
4181   return llvm::ConstantExpr::getBitCast(F,
4182                                         Ty->getPointerTo(F->getAddressSpace()));
4183 }
4184 
4185 /// GetAddrOfFunction - Return the address of the given function.  If Ty is
4186 /// non-null, then this function will use the specified type if it has to
4187 /// create it (this occurs when we see a definition of the function).
4188 llvm::Constant *CodeGenModule::GetAddrOfFunction(GlobalDecl GD,
4189                                                  llvm::Type *Ty,
4190                                                  bool ForVTable,
4191                                                  bool DontDefer,
4192                                               ForDefinition_t IsForDefinition) {
4193   assert(!cast<FunctionDecl>(GD.getDecl())->isConsteval() &&
4194          "consteval function should never be emitted");
4195   // If there was no specific requested type, just convert it now.
4196   if (!Ty) {
4197     const auto *FD = cast<FunctionDecl>(GD.getDecl());
4198     Ty = getTypes().ConvertType(FD->getType());
4199   }
4200 
4201   // Devirtualized destructor calls may come through here instead of via
4202   // getAddrOfCXXStructor. Make sure we use the MS ABI base destructor instead
4203   // of the complete destructor when necessary.
4204   if (const auto *DD = dyn_cast<CXXDestructorDecl>(GD.getDecl())) {
4205     if (getTarget().getCXXABI().isMicrosoft() &&
4206         GD.getDtorType() == Dtor_Complete &&
4207         DD->getParent()->getNumVBases() == 0)
4208       GD = GlobalDecl(DD, Dtor_Base);
4209   }
4210 
4211   StringRef MangledName = getMangledName(GD);
4212   auto *F = GetOrCreateLLVMFunction(MangledName, Ty, GD, ForVTable, DontDefer,
4213                                     /*IsThunk=*/false, llvm::AttributeList(),
4214                                     IsForDefinition);
4215   // Returns kernel handle for HIP kernel stub function.
4216   if (LangOpts.CUDA && !LangOpts.CUDAIsDevice &&
4217       cast<FunctionDecl>(GD.getDecl())->hasAttr<CUDAGlobalAttr>()) {
4218     auto *Handle = getCUDARuntime().getKernelHandle(
4219         cast<llvm::Function>(F->stripPointerCasts()), GD);
4220     if (IsForDefinition)
4221       return F;
4222     return llvm::ConstantExpr::getBitCast(Handle, Ty->getPointerTo());
4223   }
4224   return F;
4225 }
4226 
4227 llvm::Constant *CodeGenModule::GetFunctionStart(const ValueDecl *Decl) {
4228   llvm::GlobalValue *F =
4229       cast<llvm::GlobalValue>(GetAddrOfFunction(Decl)->stripPointerCasts());
4230 
4231   return llvm::ConstantExpr::getBitCast(
4232       llvm::NoCFIValue::get(F),
4233       llvm::Type::getInt8PtrTy(VMContext, F->getAddressSpace()));
4234 }
4235 
4236 static const FunctionDecl *
4237 GetRuntimeFunctionDecl(ASTContext &C, StringRef Name) {
4238   TranslationUnitDecl *TUDecl = C.getTranslationUnitDecl();
4239   DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl);
4240 
4241   IdentifierInfo &CII = C.Idents.get(Name);
4242   for (const auto *Result : DC->lookup(&CII))
4243     if (const auto *FD = dyn_cast<FunctionDecl>(Result))
4244       return FD;
4245 
4246   if (!C.getLangOpts().CPlusPlus)
4247     return nullptr;
4248 
4249   // Demangle the premangled name from getTerminateFn()
4250   IdentifierInfo &CXXII =
4251       (Name == "_ZSt9terminatev" || Name == "?terminate@@YAXXZ")
4252           ? C.Idents.get("terminate")
4253           : C.Idents.get(Name);
4254 
4255   for (const auto &N : {"__cxxabiv1", "std"}) {
4256     IdentifierInfo &NS = C.Idents.get(N);
4257     for (const auto *Result : DC->lookup(&NS)) {
4258       const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(Result);
4259       if (auto *LSD = dyn_cast<LinkageSpecDecl>(Result))
4260         for (const auto *Result : LSD->lookup(&NS))
4261           if ((ND = dyn_cast<NamespaceDecl>(Result)))
4262             break;
4263 
4264       if (ND)
4265         for (const auto *Result : ND->lookup(&CXXII))
4266           if (const auto *FD = dyn_cast<FunctionDecl>(Result))
4267             return FD;
4268     }
4269   }
4270 
4271   return nullptr;
4272 }
4273 
4274 /// CreateRuntimeFunction - Create a new runtime function with the specified
4275 /// type and name.
4276 llvm::FunctionCallee
4277 CodeGenModule::CreateRuntimeFunction(llvm::FunctionType *FTy, StringRef Name,
4278                                      llvm::AttributeList ExtraAttrs, bool Local,
4279                                      bool AssumeConvergent) {
4280   if (AssumeConvergent) {
4281     ExtraAttrs =
4282         ExtraAttrs.addFnAttribute(VMContext, llvm::Attribute::Convergent);
4283   }
4284 
4285   llvm::Constant *C =
4286       GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(), /*ForVTable=*/false,
4287                               /*DontDefer=*/false, /*IsThunk=*/false,
4288                               ExtraAttrs);
4289 
4290   if (auto *F = dyn_cast<llvm::Function>(C)) {
4291     if (F->empty()) {
4292       F->setCallingConv(getRuntimeCC());
4293 
4294       // In Windows Itanium environments, try to mark runtime functions
4295       // dllimport. For Mingw and MSVC, don't. We don't really know if the user
4296       // will link their standard library statically or dynamically. Marking
4297       // functions imported when they are not imported can cause linker errors
4298       // and warnings.
4299       if (!Local && getTriple().isWindowsItaniumEnvironment() &&
4300           !getCodeGenOpts().LTOVisibilityPublicStd) {
4301         const FunctionDecl *FD = GetRuntimeFunctionDecl(Context, Name);
4302         if (!FD || FD->hasAttr<DLLImportAttr>()) {
4303           F->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
4304           F->setLinkage(llvm::GlobalValue::ExternalLinkage);
4305         }
4306       }
4307       setDSOLocal(F);
4308     }
4309   }
4310 
4311   return {FTy, C};
4312 }
4313 
4314 /// isTypeConstant - Determine whether an object of this type can be emitted
4315 /// as a constant.
4316 ///
4317 /// If ExcludeCtor is true, the duration when the object's constructor runs
4318 /// will not be considered. The caller will need to verify that the object is
4319 /// not written to during its construction.
4320 bool CodeGenModule::isTypeConstant(QualType Ty, bool ExcludeCtor) {
4321   if (!Ty.isConstant(Context) && !Ty->isReferenceType())
4322     return false;
4323 
4324   if (Context.getLangOpts().CPlusPlus) {
4325     if (const CXXRecordDecl *Record
4326           = Context.getBaseElementType(Ty)->getAsCXXRecordDecl())
4327       return ExcludeCtor && !Record->hasMutableFields() &&
4328              Record->hasTrivialDestructor();
4329   }
4330 
4331   return true;
4332 }
4333 
4334 /// GetOrCreateLLVMGlobal - If the specified mangled name is not in the module,
4335 /// create and return an llvm GlobalVariable with the specified type and address
4336 /// space. If there is something in the module with the specified name, return
4337 /// it potentially bitcasted to the right type.
4338 ///
4339 /// If D is non-null, it specifies a decl that correspond to this.  This is used
4340 /// to set the attributes on the global when it is first created.
4341 ///
4342 /// If IsForDefinition is true, it is guaranteed that an actual global with
4343 /// type Ty will be returned, not conversion of a variable with the same
4344 /// mangled name but some other type.
4345 llvm::Constant *
4346 CodeGenModule::GetOrCreateLLVMGlobal(StringRef MangledName, llvm::Type *Ty,
4347                                      LangAS AddrSpace, const VarDecl *D,
4348                                      ForDefinition_t IsForDefinition) {
4349   // Lookup the entry, lazily creating it if necessary.
4350   llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
4351   unsigned TargetAS = getContext().getTargetAddressSpace(AddrSpace);
4352   if (Entry) {
4353     if (WeakRefReferences.erase(Entry)) {
4354       if (D && !D->hasAttr<WeakAttr>())
4355         Entry->setLinkage(llvm::Function::ExternalLinkage);
4356     }
4357 
4358     // Handle dropped DLL attributes.
4359     if (D && !D->hasAttr<DLLImportAttr>() && !D->hasAttr<DLLExportAttr>() &&
4360         !shouldMapVisibilityToDLLExport(D))
4361       Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
4362 
4363     if (LangOpts.OpenMP && !LangOpts.OpenMPSimd && D)
4364       getOpenMPRuntime().registerTargetGlobalVariable(D, Entry);
4365 
4366     if (Entry->getValueType() == Ty && Entry->getAddressSpace() == TargetAS)
4367       return Entry;
4368 
4369     // If there are two attempts to define the same mangled name, issue an
4370     // error.
4371     if (IsForDefinition && !Entry->isDeclaration()) {
4372       GlobalDecl OtherGD;
4373       const VarDecl *OtherD;
4374 
4375       // Check that D is not yet in DiagnosedConflictingDefinitions is required
4376       // to make sure that we issue an error only once.
4377       if (D && lookupRepresentativeDecl(MangledName, OtherGD) &&
4378           (D->getCanonicalDecl() != OtherGD.getCanonicalDecl().getDecl()) &&
4379           (OtherD = dyn_cast<VarDecl>(OtherGD.getDecl())) &&
4380           OtherD->hasInit() &&
4381           DiagnosedConflictingDefinitions.insert(D).second) {
4382         getDiags().Report(D->getLocation(), diag::err_duplicate_mangled_name)
4383             << MangledName;
4384         getDiags().Report(OtherGD.getDecl()->getLocation(),
4385                           diag::note_previous_definition);
4386       }
4387     }
4388 
4389     // Make sure the result is of the correct type.
4390     if (Entry->getType()->getAddressSpace() != TargetAS) {
4391       return llvm::ConstantExpr::getAddrSpaceCast(Entry,
4392                                                   Ty->getPointerTo(TargetAS));
4393     }
4394 
4395     // (If global is requested for a definition, we always need to create a new
4396     // global, not just return a bitcast.)
4397     if (!IsForDefinition)
4398       return llvm::ConstantExpr::getBitCast(Entry, Ty->getPointerTo(TargetAS));
4399   }
4400 
4401   auto DAddrSpace = GetGlobalVarAddressSpace(D);
4402 
4403   auto *GV = new llvm::GlobalVariable(
4404       getModule(), Ty, false, llvm::GlobalValue::ExternalLinkage, nullptr,
4405       MangledName, nullptr, llvm::GlobalVariable::NotThreadLocal,
4406       getContext().getTargetAddressSpace(DAddrSpace));
4407 
4408   // If we already created a global with the same mangled name (but different
4409   // type) before, take its name and remove it from its parent.
4410   if (Entry) {
4411     GV->takeName(Entry);
4412 
4413     if (!Entry->use_empty()) {
4414       llvm::Constant *NewPtrForOldDecl =
4415           llvm::ConstantExpr::getBitCast(GV, Entry->getType());
4416       Entry->replaceAllUsesWith(NewPtrForOldDecl);
4417     }
4418 
4419     Entry->eraseFromParent();
4420   }
4421 
4422   // This is the first use or definition of a mangled name.  If there is a
4423   // deferred decl with this name, remember that we need to emit it at the end
4424   // of the file.
4425   auto DDI = DeferredDecls.find(MangledName);
4426   if (DDI != DeferredDecls.end()) {
4427     // Move the potentially referenced deferred decl to the DeferredDeclsToEmit
4428     // list, and remove it from DeferredDecls (since we don't need it anymore).
4429     addDeferredDeclToEmit(DDI->second);
4430     EmittedDeferredDecls[DDI->first] = DDI->second;
4431     DeferredDecls.erase(DDI);
4432   }
4433 
4434   // Handle things which are present even on external declarations.
4435   if (D) {
4436     if (LangOpts.OpenMP && !LangOpts.OpenMPSimd)
4437       getOpenMPRuntime().registerTargetGlobalVariable(D, GV);
4438 
4439     // FIXME: This code is overly simple and should be merged with other global
4440     // handling.
4441     GV->setConstant(isTypeConstant(D->getType(), false));
4442 
4443     GV->setAlignment(getContext().getDeclAlign(D).getAsAlign());
4444 
4445     setLinkageForGV(GV, D);
4446 
4447     if (D->getTLSKind()) {
4448       if (D->getTLSKind() == VarDecl::TLS_Dynamic)
4449         CXXThreadLocals.push_back(D);
4450       setTLSMode(GV, *D);
4451     }
4452 
4453     setGVProperties(GV, D);
4454 
4455     // If required by the ABI, treat declarations of static data members with
4456     // inline initializers as definitions.
4457     if (getContext().isMSStaticDataMemberInlineDefinition(D)) {
4458       EmitGlobalVarDefinition(D);
4459     }
4460 
4461     // Emit section information for extern variables.
4462     if (D->hasExternalStorage()) {
4463       if (const SectionAttr *SA = D->getAttr<SectionAttr>())
4464         GV->setSection(SA->getName());
4465     }
4466 
4467     // Handle XCore specific ABI requirements.
4468     if (getTriple().getArch() == llvm::Triple::xcore &&
4469         D->getLanguageLinkage() == CLanguageLinkage &&
4470         D->getType().isConstant(Context) &&
4471         isExternallyVisible(D->getLinkageAndVisibility().getLinkage()))
4472       GV->setSection(".cp.rodata");
4473 
4474     // Check if we a have a const declaration with an initializer, we may be
4475     // able to emit it as available_externally to expose it's value to the
4476     // optimizer.
4477     if (Context.getLangOpts().CPlusPlus && GV->hasExternalLinkage() &&
4478         D->getType().isConstQualified() && !GV->hasInitializer() &&
4479         !D->hasDefinition() && D->hasInit() && !D->hasAttr<DLLImportAttr>()) {
4480       const auto *Record =
4481           Context.getBaseElementType(D->getType())->getAsCXXRecordDecl();
4482       bool HasMutableFields = Record && Record->hasMutableFields();
4483       if (!HasMutableFields) {
4484         const VarDecl *InitDecl;
4485         const Expr *InitExpr = D->getAnyInitializer(InitDecl);
4486         if (InitExpr) {
4487           ConstantEmitter emitter(*this);
4488           llvm::Constant *Init = emitter.tryEmitForInitializer(*InitDecl);
4489           if (Init) {
4490             auto *InitType = Init->getType();
4491             if (GV->getValueType() != InitType) {
4492               // The type of the initializer does not match the definition.
4493               // This happens when an initializer has a different type from
4494               // the type of the global (because of padding at the end of a
4495               // structure for instance).
4496               GV->setName(StringRef());
4497               // Make a new global with the correct type, this is now guaranteed
4498               // to work.
4499               auto *NewGV = cast<llvm::GlobalVariable>(
4500                   GetAddrOfGlobalVar(D, InitType, IsForDefinition)
4501                       ->stripPointerCasts());
4502 
4503               // Erase the old global, since it is no longer used.
4504               GV->eraseFromParent();
4505               GV = NewGV;
4506             } else {
4507               GV->setInitializer(Init);
4508               GV->setConstant(true);
4509               GV->setLinkage(llvm::GlobalValue::AvailableExternallyLinkage);
4510             }
4511             emitter.finalize(GV);
4512           }
4513         }
4514       }
4515     }
4516   }
4517 
4518   if (GV->isDeclaration()) {
4519     getTargetCodeGenInfo().setTargetAttributes(D, GV, *this);
4520     // External HIP managed variables needed to be recorded for transformation
4521     // in both device and host compilations.
4522     if (getLangOpts().CUDA && D && D->hasAttr<HIPManagedAttr>() &&
4523         D->hasExternalStorage())
4524       getCUDARuntime().handleVarRegistration(D, *GV);
4525   }
4526 
4527   if (D)
4528     SanitizerMD->reportGlobal(GV, *D);
4529 
4530   LangAS ExpectedAS =
4531       D ? D->getType().getAddressSpace()
4532         : (LangOpts.OpenCL ? LangAS::opencl_global : LangAS::Default);
4533   assert(getContext().getTargetAddressSpace(ExpectedAS) == TargetAS);
4534   if (DAddrSpace != ExpectedAS) {
4535     return getTargetCodeGenInfo().performAddrSpaceCast(
4536         *this, GV, DAddrSpace, ExpectedAS, Ty->getPointerTo(TargetAS));
4537   }
4538 
4539   return GV;
4540 }
4541 
4542 llvm::Constant *
4543 CodeGenModule::GetAddrOfGlobal(GlobalDecl GD, ForDefinition_t IsForDefinition) {
4544   const Decl *D = GD.getDecl();
4545 
4546   if (isa<CXXConstructorDecl>(D) || isa<CXXDestructorDecl>(D))
4547     return getAddrOfCXXStructor(GD, /*FnInfo=*/nullptr, /*FnType=*/nullptr,
4548                                 /*DontDefer=*/false, IsForDefinition);
4549 
4550   if (isa<CXXMethodDecl>(D)) {
4551     auto FInfo =
4552         &getTypes().arrangeCXXMethodDeclaration(cast<CXXMethodDecl>(D));
4553     auto Ty = getTypes().GetFunctionType(*FInfo);
4554     return GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, /*DontDefer=*/false,
4555                              IsForDefinition);
4556   }
4557 
4558   if (isa<FunctionDecl>(D)) {
4559     const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
4560     llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
4561     return GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, /*DontDefer=*/false,
4562                              IsForDefinition);
4563   }
4564 
4565   return GetAddrOfGlobalVar(cast<VarDecl>(D), /*Ty=*/nullptr, IsForDefinition);
4566 }
4567 
4568 llvm::GlobalVariable *CodeGenModule::CreateOrReplaceCXXRuntimeVariable(
4569     StringRef Name, llvm::Type *Ty, llvm::GlobalValue::LinkageTypes Linkage,
4570     llvm::Align Alignment) {
4571   llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name);
4572   llvm::GlobalVariable *OldGV = nullptr;
4573 
4574   if (GV) {
4575     // Check if the variable has the right type.
4576     if (GV->getValueType() == Ty)
4577       return GV;
4578 
4579     // Because C++ name mangling, the only way we can end up with an already
4580     // existing global with the same name is if it has been declared extern "C".
4581     assert(GV->isDeclaration() && "Declaration has wrong type!");
4582     OldGV = GV;
4583   }
4584 
4585   // Create a new variable.
4586   GV = new llvm::GlobalVariable(getModule(), Ty, /*isConstant=*/true,
4587                                 Linkage, nullptr, Name);
4588 
4589   if (OldGV) {
4590     // Replace occurrences of the old variable if needed.
4591     GV->takeName(OldGV);
4592 
4593     if (!OldGV->use_empty()) {
4594       llvm::Constant *NewPtrForOldDecl =
4595       llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
4596       OldGV->replaceAllUsesWith(NewPtrForOldDecl);
4597     }
4598 
4599     OldGV->eraseFromParent();
4600   }
4601 
4602   if (supportsCOMDAT() && GV->isWeakForLinker() &&
4603       !GV->hasAvailableExternallyLinkage())
4604     GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
4605 
4606   GV->setAlignment(Alignment);
4607 
4608   return GV;
4609 }
4610 
4611 /// GetAddrOfGlobalVar - Return the llvm::Constant for the address of the
4612 /// given global variable.  If Ty is non-null and if the global doesn't exist,
4613 /// then it will be created with the specified type instead of whatever the
4614 /// normal requested type would be. If IsForDefinition is true, it is guaranteed
4615 /// that an actual global with type Ty will be returned, not conversion of a
4616 /// variable with the same mangled name but some other type.
4617 llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D,
4618                                                   llvm::Type *Ty,
4619                                            ForDefinition_t IsForDefinition) {
4620   assert(D->hasGlobalStorage() && "Not a global variable");
4621   QualType ASTTy = D->getType();
4622   if (!Ty)
4623     Ty = getTypes().ConvertTypeForMem(ASTTy);
4624 
4625   StringRef MangledName = getMangledName(D);
4626   return GetOrCreateLLVMGlobal(MangledName, Ty, ASTTy.getAddressSpace(), D,
4627                                IsForDefinition);
4628 }
4629 
4630 /// CreateRuntimeVariable - Create a new runtime global variable with the
4631 /// specified type and name.
4632 llvm::Constant *
4633 CodeGenModule::CreateRuntimeVariable(llvm::Type *Ty,
4634                                      StringRef Name) {
4635   LangAS AddrSpace = getContext().getLangOpts().OpenCL ? LangAS::opencl_global
4636                                                        : LangAS::Default;
4637   auto *Ret = GetOrCreateLLVMGlobal(Name, Ty, AddrSpace, nullptr);
4638   setDSOLocal(cast<llvm::GlobalValue>(Ret->stripPointerCasts()));
4639   return Ret;
4640 }
4641 
4642 void CodeGenModule::EmitTentativeDefinition(const VarDecl *D) {
4643   assert(!D->getInit() && "Cannot emit definite definitions here!");
4644 
4645   StringRef MangledName = getMangledName(D);
4646   llvm::GlobalValue *GV = GetGlobalValue(MangledName);
4647 
4648   // We already have a definition, not declaration, with the same mangled name.
4649   // Emitting of declaration is not required (and actually overwrites emitted
4650   // definition).
4651   if (GV && !GV->isDeclaration())
4652     return;
4653 
4654   // If we have not seen a reference to this variable yet, place it into the
4655   // deferred declarations table to be emitted if needed later.
4656   if (!MustBeEmitted(D) && !GV) {
4657       DeferredDecls[MangledName] = D;
4658       return;
4659   }
4660 
4661   // The tentative definition is the only definition.
4662   EmitGlobalVarDefinition(D);
4663 }
4664 
4665 void CodeGenModule::EmitExternalDeclaration(const VarDecl *D) {
4666   EmitExternalVarDeclaration(D);
4667 }
4668 
4669 CharUnits CodeGenModule::GetTargetTypeStoreSize(llvm::Type *Ty) const {
4670   return Context.toCharUnitsFromBits(
4671       getDataLayout().getTypeStoreSizeInBits(Ty));
4672 }
4673 
4674 LangAS CodeGenModule::GetGlobalVarAddressSpace(const VarDecl *D) {
4675   if (LangOpts.OpenCL) {
4676     LangAS AS = D ? D->getType().getAddressSpace() : LangAS::opencl_global;
4677     assert(AS == LangAS::opencl_global ||
4678            AS == LangAS::opencl_global_device ||
4679            AS == LangAS::opencl_global_host ||
4680            AS == LangAS::opencl_constant ||
4681            AS == LangAS::opencl_local ||
4682            AS >= LangAS::FirstTargetAddressSpace);
4683     return AS;
4684   }
4685 
4686   if (LangOpts.SYCLIsDevice &&
4687       (!D || D->getType().getAddressSpace() == LangAS::Default))
4688     return LangAS::sycl_global;
4689 
4690   if (LangOpts.CUDA && LangOpts.CUDAIsDevice) {
4691     if (D) {
4692       if (D->hasAttr<CUDAConstantAttr>())
4693         return LangAS::cuda_constant;
4694       if (D->hasAttr<CUDASharedAttr>())
4695         return LangAS::cuda_shared;
4696       if (D->hasAttr<CUDADeviceAttr>())
4697         return LangAS::cuda_device;
4698       if (D->getType().isConstQualified())
4699         return LangAS::cuda_constant;
4700     }
4701     return LangAS::cuda_device;
4702   }
4703 
4704   if (LangOpts.OpenMP) {
4705     LangAS AS;
4706     if (OpenMPRuntime->hasAllocateAttributeForGlobalVar(D, AS))
4707       return AS;
4708   }
4709   return getTargetCodeGenInfo().getGlobalVarAddressSpace(*this, D);
4710 }
4711 
4712 LangAS CodeGenModule::GetGlobalConstantAddressSpace() const {
4713   // OpenCL v1.2 s6.5.3: a string literal is in the constant address space.
4714   if (LangOpts.OpenCL)
4715     return LangAS::opencl_constant;
4716   if (LangOpts.SYCLIsDevice)
4717     return LangAS::sycl_global;
4718   if (LangOpts.HIP && LangOpts.CUDAIsDevice && getTriple().isSPIRV())
4719     // For HIPSPV map literals to cuda_device (maps to CrossWorkGroup in SPIR-V)
4720     // instead of default AS (maps to Generic in SPIR-V). Otherwise, we end up
4721     // with OpVariable instructions with Generic storage class which is not
4722     // allowed (SPIR-V V1.6 s3.42.8). Also, mapping literals to SPIR-V
4723     // UniformConstant storage class is not viable as pointers to it may not be
4724     // casted to Generic pointers which are used to model HIP's "flat" pointers.
4725     return LangAS::cuda_device;
4726   if (auto AS = getTarget().getConstantAddressSpace())
4727     return *AS;
4728   return LangAS::Default;
4729 }
4730 
4731 // In address space agnostic languages, string literals are in default address
4732 // space in AST. However, certain targets (e.g. amdgcn) request them to be
4733 // emitted in constant address space in LLVM IR. To be consistent with other
4734 // parts of AST, string literal global variables in constant address space
4735 // need to be casted to default address space before being put into address
4736 // map and referenced by other part of CodeGen.
4737 // In OpenCL, string literals are in constant address space in AST, therefore
4738 // they should not be casted to default address space.
4739 static llvm::Constant *
4740 castStringLiteralToDefaultAddressSpace(CodeGenModule &CGM,
4741                                        llvm::GlobalVariable *GV) {
4742   llvm::Constant *Cast = GV;
4743   if (!CGM.getLangOpts().OpenCL) {
4744     auto AS = CGM.GetGlobalConstantAddressSpace();
4745     if (AS != LangAS::Default)
4746       Cast = CGM.getTargetCodeGenInfo().performAddrSpaceCast(
4747           CGM, GV, AS, LangAS::Default,
4748           GV->getValueType()->getPointerTo(
4749               CGM.getContext().getTargetAddressSpace(LangAS::Default)));
4750   }
4751   return Cast;
4752 }
4753 
4754 template<typename SomeDecl>
4755 void CodeGenModule::MaybeHandleStaticInExternC(const SomeDecl *D,
4756                                                llvm::GlobalValue *GV) {
4757   if (!getLangOpts().CPlusPlus)
4758     return;
4759 
4760   // Must have 'used' attribute, or else inline assembly can't rely on
4761   // the name existing.
4762   if (!D->template hasAttr<UsedAttr>())
4763     return;
4764 
4765   // Must have internal linkage and an ordinary name.
4766   if (!D->getIdentifier() || D->getFormalLinkage() != InternalLinkage)
4767     return;
4768 
4769   // Must be in an extern "C" context. Entities declared directly within
4770   // a record are not extern "C" even if the record is in such a context.
4771   const SomeDecl *First = D->getFirstDecl();
4772   if (First->getDeclContext()->isRecord() || !First->isInExternCContext())
4773     return;
4774 
4775   // OK, this is an internal linkage entity inside an extern "C" linkage
4776   // specification. Make a note of that so we can give it the "expected"
4777   // mangled name if nothing else is using that name.
4778   std::pair<StaticExternCMap::iterator, bool> R =
4779       StaticExternCValues.insert(std::make_pair(D->getIdentifier(), GV));
4780 
4781   // If we have multiple internal linkage entities with the same name
4782   // in extern "C" regions, none of them gets that name.
4783   if (!R.second)
4784     R.first->second = nullptr;
4785 }
4786 
4787 static bool shouldBeInCOMDAT(CodeGenModule &CGM, const Decl &D) {
4788   if (!CGM.supportsCOMDAT())
4789     return false;
4790 
4791   if (D.hasAttr<SelectAnyAttr>())
4792     return true;
4793 
4794   GVALinkage Linkage;
4795   if (auto *VD = dyn_cast<VarDecl>(&D))
4796     Linkage = CGM.getContext().GetGVALinkageForVariable(VD);
4797   else
4798     Linkage = CGM.getContext().GetGVALinkageForFunction(cast<FunctionDecl>(&D));
4799 
4800   switch (Linkage) {
4801   case GVA_Internal:
4802   case GVA_AvailableExternally:
4803   case GVA_StrongExternal:
4804     return false;
4805   case GVA_DiscardableODR:
4806   case GVA_StrongODR:
4807     return true;
4808   }
4809   llvm_unreachable("No such linkage");
4810 }
4811 
4812 void CodeGenModule::maybeSetTrivialComdat(const Decl &D,
4813                                           llvm::GlobalObject &GO) {
4814   if (!shouldBeInCOMDAT(*this, D))
4815     return;
4816   GO.setComdat(TheModule.getOrInsertComdat(GO.getName()));
4817 }
4818 
4819 /// Pass IsTentative as true if you want to create a tentative definition.
4820 void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D,
4821                                             bool IsTentative) {
4822   // OpenCL global variables of sampler type are translated to function calls,
4823   // therefore no need to be translated.
4824   QualType ASTTy = D->getType();
4825   if (getLangOpts().OpenCL && ASTTy->isSamplerT())
4826     return;
4827 
4828   // If this is OpenMP device, check if it is legal to emit this global
4829   // normally.
4830   if (LangOpts.OpenMPIsDevice && OpenMPRuntime &&
4831       OpenMPRuntime->emitTargetGlobalVariable(D))
4832     return;
4833 
4834   llvm::TrackingVH<llvm::Constant> Init;
4835   bool NeedsGlobalCtor = false;
4836   // Whether the definition of the variable is available externally.
4837   // If yes, we shouldn't emit the GloablCtor and GlobalDtor for the variable
4838   // since this is the job for its original source.
4839   bool IsDefinitionAvailableExternally =
4840       getContext().GetGVALinkageForVariable(D) == GVA_AvailableExternally;
4841   bool NeedsGlobalDtor =
4842       !IsDefinitionAvailableExternally &&
4843       D->needsDestruction(getContext()) == QualType::DK_cxx_destructor;
4844 
4845   const VarDecl *InitDecl;
4846   const Expr *InitExpr = D->getAnyInitializer(InitDecl);
4847 
4848   std::optional<ConstantEmitter> emitter;
4849 
4850   // CUDA E.2.4.1 "__shared__ variables cannot have an initialization
4851   // as part of their declaration."  Sema has already checked for
4852   // error cases, so we just need to set Init to UndefValue.
4853   bool IsCUDASharedVar =
4854       getLangOpts().CUDAIsDevice && D->hasAttr<CUDASharedAttr>();
4855   // Shadows of initialized device-side global variables are also left
4856   // undefined.
4857   // Managed Variables should be initialized on both host side and device side.
4858   bool IsCUDAShadowVar =
4859       !getLangOpts().CUDAIsDevice && !D->hasAttr<HIPManagedAttr>() &&
4860       (D->hasAttr<CUDAConstantAttr>() || D->hasAttr<CUDADeviceAttr>() ||
4861        D->hasAttr<CUDASharedAttr>());
4862   bool IsCUDADeviceShadowVar =
4863       getLangOpts().CUDAIsDevice && !D->hasAttr<HIPManagedAttr>() &&
4864       (D->getType()->isCUDADeviceBuiltinSurfaceType() ||
4865        D->getType()->isCUDADeviceBuiltinTextureType());
4866   if (getLangOpts().CUDA &&
4867       (IsCUDASharedVar || IsCUDAShadowVar || IsCUDADeviceShadowVar))
4868     Init = llvm::UndefValue::get(getTypes().ConvertTypeForMem(ASTTy));
4869   else if (D->hasAttr<LoaderUninitializedAttr>())
4870     Init = llvm::UndefValue::get(getTypes().ConvertTypeForMem(ASTTy));
4871   else if (!InitExpr) {
4872     // This is a tentative definition; tentative definitions are
4873     // implicitly initialized with { 0 }.
4874     //
4875     // Note that tentative definitions are only emitted at the end of
4876     // a translation unit, so they should never have incomplete
4877     // type. In addition, EmitTentativeDefinition makes sure that we
4878     // never attempt to emit a tentative definition if a real one
4879     // exists. A use may still exists, however, so we still may need
4880     // to do a RAUW.
4881     assert(!ASTTy->isIncompleteType() && "Unexpected incomplete type");
4882     Init = EmitNullConstant(D->getType());
4883   } else {
4884     initializedGlobalDecl = GlobalDecl(D);
4885     emitter.emplace(*this);
4886     llvm::Constant *Initializer = emitter->tryEmitForInitializer(*InitDecl);
4887     if (!Initializer) {
4888       QualType T = InitExpr->getType();
4889       if (D->getType()->isReferenceType())
4890         T = D->getType();
4891 
4892       if (getLangOpts().CPlusPlus) {
4893         if (InitDecl->hasFlexibleArrayInit(getContext()))
4894           ErrorUnsupported(D, "flexible array initializer");
4895         Init = EmitNullConstant(T);
4896 
4897         if (!IsDefinitionAvailableExternally)
4898           NeedsGlobalCtor = true;
4899       } else {
4900         ErrorUnsupported(D, "static initializer");
4901         Init = llvm::UndefValue::get(getTypes().ConvertType(T));
4902       }
4903     } else {
4904       Init = Initializer;
4905       // We don't need an initializer, so remove the entry for the delayed
4906       // initializer position (just in case this entry was delayed) if we
4907       // also don't need to register a destructor.
4908       if (getLangOpts().CPlusPlus && !NeedsGlobalDtor)
4909         DelayedCXXInitPosition.erase(D);
4910 
4911 #ifndef NDEBUG
4912       CharUnits VarSize = getContext().getTypeSizeInChars(ASTTy) +
4913                           InitDecl->getFlexibleArrayInitChars(getContext());
4914       CharUnits CstSize = CharUnits::fromQuantity(
4915           getDataLayout().getTypeAllocSize(Init->getType()));
4916       assert(VarSize == CstSize && "Emitted constant has unexpected size");
4917 #endif
4918     }
4919   }
4920 
4921   llvm::Type* InitType = Init->getType();
4922   llvm::Constant *Entry =
4923       GetAddrOfGlobalVar(D, InitType, ForDefinition_t(!IsTentative));
4924 
4925   // Strip off pointer casts if we got them.
4926   Entry = Entry->stripPointerCasts();
4927 
4928   // Entry is now either a Function or GlobalVariable.
4929   auto *GV = dyn_cast<llvm::GlobalVariable>(Entry);
4930 
4931   // We have a definition after a declaration with the wrong type.
4932   // We must make a new GlobalVariable* and update everything that used OldGV
4933   // (a declaration or tentative definition) with the new GlobalVariable*
4934   // (which will be a definition).
4935   //
4936   // This happens if there is a prototype for a global (e.g.
4937   // "extern int x[];") and then a definition of a different type (e.g.
4938   // "int x[10];"). This also happens when an initializer has a different type
4939   // from the type of the global (this happens with unions).
4940   if (!GV || GV->getValueType() != InitType ||
4941       GV->getType()->getAddressSpace() !=
4942           getContext().getTargetAddressSpace(GetGlobalVarAddressSpace(D))) {
4943 
4944     // Move the old entry aside so that we'll create a new one.
4945     Entry->setName(StringRef());
4946 
4947     // Make a new global with the correct type, this is now guaranteed to work.
4948     GV = cast<llvm::GlobalVariable>(
4949         GetAddrOfGlobalVar(D, InitType, ForDefinition_t(!IsTentative))
4950             ->stripPointerCasts());
4951 
4952     // Replace all uses of the old global with the new global
4953     llvm::Constant *NewPtrForOldDecl =
4954         llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(GV,
4955                                                              Entry->getType());
4956     Entry->replaceAllUsesWith(NewPtrForOldDecl);
4957 
4958     // Erase the old global, since it is no longer used.
4959     cast<llvm::GlobalValue>(Entry)->eraseFromParent();
4960   }
4961 
4962   MaybeHandleStaticInExternC(D, GV);
4963 
4964   if (D->hasAttr<AnnotateAttr>())
4965     AddGlobalAnnotations(D, GV);
4966 
4967   // Set the llvm linkage type as appropriate.
4968   llvm::GlobalValue::LinkageTypes Linkage =
4969       getLLVMLinkageVarDefinition(D, GV->isConstant());
4970 
4971   // CUDA B.2.1 "The __device__ qualifier declares a variable that resides on
4972   // the device. [...]"
4973   // CUDA B.2.2 "The __constant__ qualifier, optionally used together with
4974   // __device__, declares a variable that: [...]
4975   // Is accessible from all the threads within the grid and from the host
4976   // through the runtime library (cudaGetSymbolAddress() / cudaGetSymbolSize()
4977   // / cudaMemcpyToSymbol() / cudaMemcpyFromSymbol())."
4978   if (GV && LangOpts.CUDA) {
4979     if (LangOpts.CUDAIsDevice) {
4980       if (Linkage != llvm::GlobalValue::InternalLinkage &&
4981           (D->hasAttr<CUDADeviceAttr>() || D->hasAttr<CUDAConstantAttr>() ||
4982            D->getType()->isCUDADeviceBuiltinSurfaceType() ||
4983            D->getType()->isCUDADeviceBuiltinTextureType()))
4984         GV->setExternallyInitialized(true);
4985     } else {
4986       getCUDARuntime().internalizeDeviceSideVar(D, Linkage);
4987     }
4988     getCUDARuntime().handleVarRegistration(D, *GV);
4989   }
4990 
4991   GV->setInitializer(Init);
4992   if (emitter)
4993     emitter->finalize(GV);
4994 
4995   // If it is safe to mark the global 'constant', do so now.
4996   GV->setConstant(!NeedsGlobalCtor && !NeedsGlobalDtor &&
4997                   isTypeConstant(D->getType(), true));
4998 
4999   // If it is in a read-only section, mark it 'constant'.
5000   if (const SectionAttr *SA = D->getAttr<SectionAttr>()) {
5001     const ASTContext::SectionInfo &SI = Context.SectionInfos[SA->getName()];
5002     if ((SI.SectionFlags & ASTContext::PSF_Write) == 0)
5003       GV->setConstant(true);
5004   }
5005 
5006   CharUnits AlignVal = getContext().getDeclAlign(D);
5007   // Check for alignment specifed in an 'omp allocate' directive.
5008   if (std::optional<CharUnits> AlignValFromAllocate =
5009           getOMPAllocateAlignment(D))
5010     AlignVal = *AlignValFromAllocate;
5011   GV->setAlignment(AlignVal.getAsAlign());
5012 
5013   // On Darwin, unlike other Itanium C++ ABI platforms, the thread-wrapper
5014   // function is only defined alongside the variable, not also alongside
5015   // callers. Normally, all accesses to a thread_local go through the
5016   // thread-wrapper in order to ensure initialization has occurred, underlying
5017   // variable will never be used other than the thread-wrapper, so it can be
5018   // converted to internal linkage.
5019   //
5020   // However, if the variable has the 'constinit' attribute, it _can_ be
5021   // referenced directly, without calling the thread-wrapper, so the linkage
5022   // must not be changed.
5023   //
5024   // Additionally, if the variable isn't plain external linkage, e.g. if it's
5025   // weak or linkonce, the de-duplication semantics are important to preserve,
5026   // so we don't change the linkage.
5027   if (D->getTLSKind() == VarDecl::TLS_Dynamic &&
5028       Linkage == llvm::GlobalValue::ExternalLinkage &&
5029       Context.getTargetInfo().getTriple().isOSDarwin() &&
5030       !D->hasAttr<ConstInitAttr>())
5031     Linkage = llvm::GlobalValue::InternalLinkage;
5032 
5033   GV->setLinkage(Linkage);
5034   if (D->hasAttr<DLLImportAttr>())
5035     GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
5036   else if (D->hasAttr<DLLExportAttr>())
5037     GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass);
5038   else
5039     GV->setDLLStorageClass(llvm::GlobalVariable::DefaultStorageClass);
5040 
5041   if (Linkage == llvm::GlobalVariable::CommonLinkage) {
5042     // common vars aren't constant even if declared const.
5043     GV->setConstant(false);
5044     // Tentative definition of global variables may be initialized with
5045     // non-zero null pointers. In this case they should have weak linkage
5046     // since common linkage must have zero initializer and must not have
5047     // explicit section therefore cannot have non-zero initial value.
5048     if (!GV->getInitializer()->isNullValue())
5049       GV->setLinkage(llvm::GlobalVariable::WeakAnyLinkage);
5050   }
5051 
5052   setNonAliasAttributes(D, GV);
5053 
5054   if (D->getTLSKind() && !GV->isThreadLocal()) {
5055     if (D->getTLSKind() == VarDecl::TLS_Dynamic)
5056       CXXThreadLocals.push_back(D);
5057     setTLSMode(GV, *D);
5058   }
5059 
5060   maybeSetTrivialComdat(*D, *GV);
5061 
5062   // Emit the initializer function if necessary.
5063   if (NeedsGlobalCtor || NeedsGlobalDtor)
5064     EmitCXXGlobalVarDeclInitFunc(D, GV, NeedsGlobalCtor);
5065 
5066   SanitizerMD->reportGlobal(GV, *D, NeedsGlobalCtor);
5067 
5068   // Emit global variable debug information.
5069   if (CGDebugInfo *DI = getModuleDebugInfo())
5070     if (getCodeGenOpts().hasReducedDebugInfo())
5071       DI->EmitGlobalVariable(GV, D);
5072 }
5073 
5074 void CodeGenModule::EmitExternalVarDeclaration(const VarDecl *D) {
5075   if (CGDebugInfo *DI = getModuleDebugInfo())
5076     if (getCodeGenOpts().hasReducedDebugInfo()) {
5077       QualType ASTTy = D->getType();
5078       llvm::Type *Ty = getTypes().ConvertTypeForMem(D->getType());
5079       llvm::Constant *GV =
5080           GetOrCreateLLVMGlobal(D->getName(), Ty, ASTTy.getAddressSpace(), D);
5081       DI->EmitExternalVariable(
5082           cast<llvm::GlobalVariable>(GV->stripPointerCasts()), D);
5083     }
5084 }
5085 
5086 static bool isVarDeclStrongDefinition(const ASTContext &Context,
5087                                       CodeGenModule &CGM, const VarDecl *D,
5088                                       bool NoCommon) {
5089   // Don't give variables common linkage if -fno-common was specified unless it
5090   // was overridden by a NoCommon attribute.
5091   if ((NoCommon || D->hasAttr<NoCommonAttr>()) && !D->hasAttr<CommonAttr>())
5092     return true;
5093 
5094   // C11 6.9.2/2:
5095   //   A declaration of an identifier for an object that has file scope without
5096   //   an initializer, and without a storage-class specifier or with the
5097   //   storage-class specifier static, constitutes a tentative definition.
5098   if (D->getInit() || D->hasExternalStorage())
5099     return true;
5100 
5101   // A variable cannot be both common and exist in a section.
5102   if (D->hasAttr<SectionAttr>())
5103     return true;
5104 
5105   // A variable cannot be both common and exist in a section.
5106   // We don't try to determine which is the right section in the front-end.
5107   // If no specialized section name is applicable, it will resort to default.
5108   if (D->hasAttr<PragmaClangBSSSectionAttr>() ||
5109       D->hasAttr<PragmaClangDataSectionAttr>() ||
5110       D->hasAttr<PragmaClangRelroSectionAttr>() ||
5111       D->hasAttr<PragmaClangRodataSectionAttr>())
5112     return true;
5113 
5114   // Thread local vars aren't considered common linkage.
5115   if (D->getTLSKind())
5116     return true;
5117 
5118   // Tentative definitions marked with WeakImportAttr are true definitions.
5119   if (D->hasAttr<WeakImportAttr>())
5120     return true;
5121 
5122   // A variable cannot be both common and exist in a comdat.
5123   if (shouldBeInCOMDAT(CGM, *D))
5124     return true;
5125 
5126   // Declarations with a required alignment do not have common linkage in MSVC
5127   // mode.
5128   if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
5129     if (D->hasAttr<AlignedAttr>())
5130       return true;
5131     QualType VarType = D->getType();
5132     if (Context.isAlignmentRequired(VarType))
5133       return true;
5134 
5135     if (const auto *RT = VarType->getAs<RecordType>()) {
5136       const RecordDecl *RD = RT->getDecl();
5137       for (const FieldDecl *FD : RD->fields()) {
5138         if (FD->isBitField())
5139           continue;
5140         if (FD->hasAttr<AlignedAttr>())
5141           return true;
5142         if (Context.isAlignmentRequired(FD->getType()))
5143           return true;
5144       }
5145     }
5146   }
5147 
5148   // Microsoft's link.exe doesn't support alignments greater than 32 bytes for
5149   // common symbols, so symbols with greater alignment requirements cannot be
5150   // common.
5151   // Other COFF linkers (ld.bfd and LLD) support arbitrary power-of-two
5152   // alignments for common symbols via the aligncomm directive, so this
5153   // restriction only applies to MSVC environments.
5154   if (Context.getTargetInfo().getTriple().isKnownWindowsMSVCEnvironment() &&
5155       Context.getTypeAlignIfKnown(D->getType()) >
5156           Context.toBits(CharUnits::fromQuantity(32)))
5157     return true;
5158 
5159   return false;
5160 }
5161 
5162 llvm::GlobalValue::LinkageTypes CodeGenModule::getLLVMLinkageForDeclarator(
5163     const DeclaratorDecl *D, GVALinkage Linkage, bool IsConstantVariable) {
5164   if (Linkage == GVA_Internal)
5165     return llvm::Function::InternalLinkage;
5166 
5167   if (D->hasAttr<WeakAttr>())
5168     return llvm::GlobalVariable::WeakAnyLinkage;
5169 
5170   if (const auto *FD = D->getAsFunction())
5171     if (FD->isMultiVersion() && Linkage == GVA_AvailableExternally)
5172       return llvm::GlobalVariable::LinkOnceAnyLinkage;
5173 
5174   // We are guaranteed to have a strong definition somewhere else,
5175   // so we can use available_externally linkage.
5176   if (Linkage == GVA_AvailableExternally)
5177     return llvm::GlobalValue::AvailableExternallyLinkage;
5178 
5179   // Note that Apple's kernel linker doesn't support symbol
5180   // coalescing, so we need to avoid linkonce and weak linkages there.
5181   // Normally, this means we just map to internal, but for explicit
5182   // instantiations we'll map to external.
5183 
5184   // In C++, the compiler has to emit a definition in every translation unit
5185   // that references the function.  We should use linkonce_odr because
5186   // a) if all references in this translation unit are optimized away, we
5187   // don't need to codegen it.  b) if the function persists, it needs to be
5188   // merged with other definitions. c) C++ has the ODR, so we know the
5189   // definition is dependable.
5190   if (Linkage == GVA_DiscardableODR)
5191     return !Context.getLangOpts().AppleKext ? llvm::Function::LinkOnceODRLinkage
5192                                             : llvm::Function::InternalLinkage;
5193 
5194   // An explicit instantiation of a template has weak linkage, since
5195   // explicit instantiations can occur in multiple translation units
5196   // and must all be equivalent. However, we are not allowed to
5197   // throw away these explicit instantiations.
5198   //
5199   // CUDA/HIP: For -fno-gpu-rdc case, device code is limited to one TU,
5200   // so say that CUDA templates are either external (for kernels) or internal.
5201   // This lets llvm perform aggressive inter-procedural optimizations. For
5202   // -fgpu-rdc case, device function calls across multiple TU's are allowed,
5203   // therefore we need to follow the normal linkage paradigm.
5204   if (Linkage == GVA_StrongODR) {
5205     if (getLangOpts().AppleKext)
5206       return llvm::Function::ExternalLinkage;
5207     if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice &&
5208         !getLangOpts().GPURelocatableDeviceCode)
5209       return D->hasAttr<CUDAGlobalAttr>() ? llvm::Function::ExternalLinkage
5210                                           : llvm::Function::InternalLinkage;
5211     return llvm::Function::WeakODRLinkage;
5212   }
5213 
5214   // C++ doesn't have tentative definitions and thus cannot have common
5215   // linkage.
5216   if (!getLangOpts().CPlusPlus && isa<VarDecl>(D) &&
5217       !isVarDeclStrongDefinition(Context, *this, cast<VarDecl>(D),
5218                                  CodeGenOpts.NoCommon))
5219     return llvm::GlobalVariable::CommonLinkage;
5220 
5221   // selectany symbols are externally visible, so use weak instead of
5222   // linkonce.  MSVC optimizes away references to const selectany globals, so
5223   // all definitions should be the same and ODR linkage should be used.
5224   // http://msdn.microsoft.com/en-us/library/5tkz6s71.aspx
5225   if (D->hasAttr<SelectAnyAttr>())
5226     return llvm::GlobalVariable::WeakODRLinkage;
5227 
5228   // Otherwise, we have strong external linkage.
5229   assert(Linkage == GVA_StrongExternal);
5230   return llvm::GlobalVariable::ExternalLinkage;
5231 }
5232 
5233 llvm::GlobalValue::LinkageTypes CodeGenModule::getLLVMLinkageVarDefinition(
5234     const VarDecl *VD, bool IsConstant) {
5235   GVALinkage Linkage = getContext().GetGVALinkageForVariable(VD);
5236   return getLLVMLinkageForDeclarator(VD, Linkage, IsConstant);
5237 }
5238 
5239 /// Replace the uses of a function that was declared with a non-proto type.
5240 /// We want to silently drop extra arguments from call sites
5241 static void replaceUsesOfNonProtoConstant(llvm::Constant *old,
5242                                           llvm::Function *newFn) {
5243   // Fast path.
5244   if (old->use_empty()) return;
5245 
5246   llvm::Type *newRetTy = newFn->getReturnType();
5247   SmallVector<llvm::Value*, 4> newArgs;
5248 
5249   for (llvm::Value::use_iterator ui = old->use_begin(), ue = old->use_end();
5250          ui != ue; ) {
5251     llvm::Value::use_iterator use = ui++; // Increment before the use is erased.
5252     llvm::User *user = use->getUser();
5253 
5254     // Recognize and replace uses of bitcasts.  Most calls to
5255     // unprototyped functions will use bitcasts.
5256     if (auto *bitcast = dyn_cast<llvm::ConstantExpr>(user)) {
5257       if (bitcast->getOpcode() == llvm::Instruction::BitCast)
5258         replaceUsesOfNonProtoConstant(bitcast, newFn);
5259       continue;
5260     }
5261 
5262     // Recognize calls to the function.
5263     llvm::CallBase *callSite = dyn_cast<llvm::CallBase>(user);
5264     if (!callSite) continue;
5265     if (!callSite->isCallee(&*use))
5266       continue;
5267 
5268     // If the return types don't match exactly, then we can't
5269     // transform this call unless it's dead.
5270     if (callSite->getType() != newRetTy && !callSite->use_empty())
5271       continue;
5272 
5273     // Get the call site's attribute list.
5274     SmallVector<llvm::AttributeSet, 8> newArgAttrs;
5275     llvm::AttributeList oldAttrs = callSite->getAttributes();
5276 
5277     // If the function was passed too few arguments, don't transform.
5278     unsigned newNumArgs = newFn->arg_size();
5279     if (callSite->arg_size() < newNumArgs)
5280       continue;
5281 
5282     // If extra arguments were passed, we silently drop them.
5283     // If any of the types mismatch, we don't transform.
5284     unsigned argNo = 0;
5285     bool dontTransform = false;
5286     for (llvm::Argument &A : newFn->args()) {
5287       if (callSite->getArgOperand(argNo)->getType() != A.getType()) {
5288         dontTransform = true;
5289         break;
5290       }
5291 
5292       // Add any parameter attributes.
5293       newArgAttrs.push_back(oldAttrs.getParamAttrs(argNo));
5294       argNo++;
5295     }
5296     if (dontTransform)
5297       continue;
5298 
5299     // Okay, we can transform this.  Create the new call instruction and copy
5300     // over the required information.
5301     newArgs.append(callSite->arg_begin(), callSite->arg_begin() + argNo);
5302 
5303     // Copy over any operand bundles.
5304     SmallVector<llvm::OperandBundleDef, 1> newBundles;
5305     callSite->getOperandBundlesAsDefs(newBundles);
5306 
5307     llvm::CallBase *newCall;
5308     if (isa<llvm::CallInst>(callSite)) {
5309       newCall =
5310           llvm::CallInst::Create(newFn, newArgs, newBundles, "", callSite);
5311     } else {
5312       auto *oldInvoke = cast<llvm::InvokeInst>(callSite);
5313       newCall = llvm::InvokeInst::Create(newFn, oldInvoke->getNormalDest(),
5314                                          oldInvoke->getUnwindDest(), newArgs,
5315                                          newBundles, "", callSite);
5316     }
5317     newArgs.clear(); // for the next iteration
5318 
5319     if (!newCall->getType()->isVoidTy())
5320       newCall->takeName(callSite);
5321     newCall->setAttributes(
5322         llvm::AttributeList::get(newFn->getContext(), oldAttrs.getFnAttrs(),
5323                                  oldAttrs.getRetAttrs(), newArgAttrs));
5324     newCall->setCallingConv(callSite->getCallingConv());
5325 
5326     // Finally, remove the old call, replacing any uses with the new one.
5327     if (!callSite->use_empty())
5328       callSite->replaceAllUsesWith(newCall);
5329 
5330     // Copy debug location attached to CI.
5331     if (callSite->getDebugLoc())
5332       newCall->setDebugLoc(callSite->getDebugLoc());
5333 
5334     callSite->eraseFromParent();
5335   }
5336 }
5337 
5338 /// ReplaceUsesOfNonProtoTypeWithRealFunction - This function is called when we
5339 /// implement a function with no prototype, e.g. "int foo() {}".  If there are
5340 /// existing call uses of the old function in the module, this adjusts them to
5341 /// call the new function directly.
5342 ///
5343 /// This is not just a cleanup: the always_inline pass requires direct calls to
5344 /// functions to be able to inline them.  If there is a bitcast in the way, it
5345 /// won't inline them.  Instcombine normally deletes these calls, but it isn't
5346 /// run at -O0.
5347 static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old,
5348                                                       llvm::Function *NewFn) {
5349   // If we're redefining a global as a function, don't transform it.
5350   if (!isa<llvm::Function>(Old)) return;
5351 
5352   replaceUsesOfNonProtoConstant(Old, NewFn);
5353 }
5354 
5355 void CodeGenModule::HandleCXXStaticMemberVarInstantiation(VarDecl *VD) {
5356   auto DK = VD->isThisDeclarationADefinition();
5357   if (DK == VarDecl::Definition && VD->hasAttr<DLLImportAttr>())
5358     return;
5359 
5360   TemplateSpecializationKind TSK = VD->getTemplateSpecializationKind();
5361   // If we have a definition, this might be a deferred decl. If the
5362   // instantiation is explicit, make sure we emit it at the end.
5363   if (VD->getDefinition() && TSK == TSK_ExplicitInstantiationDefinition)
5364     GetAddrOfGlobalVar(VD);
5365 
5366   EmitTopLevelDecl(VD);
5367 }
5368 
5369 void CodeGenModule::EmitGlobalFunctionDefinition(GlobalDecl GD,
5370                                                  llvm::GlobalValue *GV) {
5371   const auto *D = cast<FunctionDecl>(GD.getDecl());
5372 
5373   // Compute the function info and LLVM type.
5374   const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
5375   llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
5376 
5377   // Get or create the prototype for the function.
5378   if (!GV || (GV->getValueType() != Ty))
5379     GV = cast<llvm::GlobalValue>(GetAddrOfFunction(GD, Ty, /*ForVTable=*/false,
5380                                                    /*DontDefer=*/true,
5381                                                    ForDefinition));
5382 
5383   // Already emitted.
5384   if (!GV->isDeclaration())
5385     return;
5386 
5387   // We need to set linkage and visibility on the function before
5388   // generating code for it because various parts of IR generation
5389   // want to propagate this information down (e.g. to local static
5390   // declarations).
5391   auto *Fn = cast<llvm::Function>(GV);
5392   setFunctionLinkage(GD, Fn);
5393 
5394   // FIXME: this is redundant with part of setFunctionDefinitionAttributes
5395   setGVProperties(Fn, GD);
5396 
5397   MaybeHandleStaticInExternC(D, Fn);
5398 
5399   maybeSetTrivialComdat(*D, *Fn);
5400 
5401   // Set CodeGen attributes that represent floating point environment.
5402   setLLVMFunctionFEnvAttributes(D, Fn);
5403 
5404   CodeGenFunction(*this).GenerateCode(GD, Fn, FI);
5405 
5406   setNonAliasAttributes(GD, Fn);
5407   SetLLVMFunctionAttributesForDefinition(D, Fn);
5408 
5409   if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>())
5410     AddGlobalCtor(Fn, CA->getPriority());
5411   if (const DestructorAttr *DA = D->getAttr<DestructorAttr>())
5412     AddGlobalDtor(Fn, DA->getPriority(), true);
5413   if (D->hasAttr<AnnotateAttr>())
5414     AddGlobalAnnotations(D, Fn);
5415 }
5416 
5417 void CodeGenModule::EmitAliasDefinition(GlobalDecl GD) {
5418   const auto *D = cast<ValueDecl>(GD.getDecl());
5419   const AliasAttr *AA = D->getAttr<AliasAttr>();
5420   assert(AA && "Not an alias?");
5421 
5422   StringRef MangledName = getMangledName(GD);
5423 
5424   if (AA->getAliasee() == MangledName) {
5425     Diags.Report(AA->getLocation(), diag::err_cyclic_alias) << 0;
5426     return;
5427   }
5428 
5429   // If there is a definition in the module, then it wins over the alias.
5430   // This is dubious, but allow it to be safe.  Just ignore the alias.
5431   llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
5432   if (Entry && !Entry->isDeclaration())
5433     return;
5434 
5435   Aliases.push_back(GD);
5436 
5437   llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType());
5438 
5439   // Create a reference to the named value.  This ensures that it is emitted
5440   // if a deferred decl.
5441   llvm::Constant *Aliasee;
5442   llvm::GlobalValue::LinkageTypes LT;
5443   if (isa<llvm::FunctionType>(DeclTy)) {
5444     Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GD,
5445                                       /*ForVTable=*/false);
5446     LT = getFunctionLinkage(GD);
5447   } else {
5448     Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(), DeclTy, LangAS::Default,
5449                                     /*D=*/nullptr);
5450     if (const auto *VD = dyn_cast<VarDecl>(GD.getDecl()))
5451       LT = getLLVMLinkageVarDefinition(VD, D->getType().isConstQualified());
5452     else
5453       LT = getFunctionLinkage(GD);
5454   }
5455 
5456   // Create the new alias itself, but don't set a name yet.
5457   unsigned AS = Aliasee->getType()->getPointerAddressSpace();
5458   auto *GA =
5459       llvm::GlobalAlias::create(DeclTy, AS, LT, "", Aliasee, &getModule());
5460 
5461   if (Entry) {
5462     if (GA->getAliasee() == Entry) {
5463       Diags.Report(AA->getLocation(), diag::err_cyclic_alias) << 0;
5464       return;
5465     }
5466 
5467     assert(Entry->isDeclaration());
5468 
5469     // If there is a declaration in the module, then we had an extern followed
5470     // by the alias, as in:
5471     //   extern int test6();
5472     //   ...
5473     //   int test6() __attribute__((alias("test7")));
5474     //
5475     // Remove it and replace uses of it with the alias.
5476     GA->takeName(Entry);
5477 
5478     Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GA,
5479                                                           Entry->getType()));
5480     Entry->eraseFromParent();
5481   } else {
5482     GA->setName(MangledName);
5483   }
5484 
5485   // Set attributes which are particular to an alias; this is a
5486   // specialization of the attributes which may be set on a global
5487   // variable/function.
5488   if (D->hasAttr<WeakAttr>() || D->hasAttr<WeakRefAttr>() ||
5489       D->isWeakImported()) {
5490     GA->setLinkage(llvm::Function::WeakAnyLinkage);
5491   }
5492 
5493   if (const auto *VD = dyn_cast<VarDecl>(D))
5494     if (VD->getTLSKind())
5495       setTLSMode(GA, *VD);
5496 
5497   SetCommonAttributes(GD, GA);
5498 
5499   // Emit global alias debug information.
5500   if (isa<VarDecl>(D))
5501     if (CGDebugInfo *DI = getModuleDebugInfo())
5502       DI->EmitGlobalAlias(cast<llvm::GlobalValue>(GA->getAliasee()->stripPointerCasts()), GD);
5503 }
5504 
5505 void CodeGenModule::emitIFuncDefinition(GlobalDecl GD) {
5506   const auto *D = cast<ValueDecl>(GD.getDecl());
5507   const IFuncAttr *IFA = D->getAttr<IFuncAttr>();
5508   assert(IFA && "Not an ifunc?");
5509 
5510   StringRef MangledName = getMangledName(GD);
5511 
5512   if (IFA->getResolver() == MangledName) {
5513     Diags.Report(IFA->getLocation(), diag::err_cyclic_alias) << 1;
5514     return;
5515   }
5516 
5517   // Report an error if some definition overrides ifunc.
5518   llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
5519   if (Entry && !Entry->isDeclaration()) {
5520     GlobalDecl OtherGD;
5521     if (lookupRepresentativeDecl(MangledName, OtherGD) &&
5522         DiagnosedConflictingDefinitions.insert(GD).second) {
5523       Diags.Report(D->getLocation(), diag::err_duplicate_mangled_name)
5524           << MangledName;
5525       Diags.Report(OtherGD.getDecl()->getLocation(),
5526                    diag::note_previous_definition);
5527     }
5528     return;
5529   }
5530 
5531   Aliases.push_back(GD);
5532 
5533   llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType());
5534   llvm::Type *ResolverTy = llvm::GlobalIFunc::getResolverFunctionType(DeclTy);
5535   llvm::Constant *Resolver =
5536       GetOrCreateLLVMFunction(IFA->getResolver(), ResolverTy, {},
5537                               /*ForVTable=*/false);
5538   llvm::GlobalIFunc *GIF =
5539       llvm::GlobalIFunc::create(DeclTy, 0, llvm::Function::ExternalLinkage,
5540                                 "", Resolver, &getModule());
5541   if (Entry) {
5542     if (GIF->getResolver() == Entry) {
5543       Diags.Report(IFA->getLocation(), diag::err_cyclic_alias) << 1;
5544       return;
5545     }
5546     assert(Entry->isDeclaration());
5547 
5548     // If there is a declaration in the module, then we had an extern followed
5549     // by the ifunc, as in:
5550     //   extern int test();
5551     //   ...
5552     //   int test() __attribute__((ifunc("resolver")));
5553     //
5554     // Remove it and replace uses of it with the ifunc.
5555     GIF->takeName(Entry);
5556 
5557     Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GIF,
5558                                                           Entry->getType()));
5559     Entry->eraseFromParent();
5560   } else
5561     GIF->setName(MangledName);
5562 
5563   SetCommonAttributes(GD, GIF);
5564 }
5565 
5566 llvm::Function *CodeGenModule::getIntrinsic(unsigned IID,
5567                                             ArrayRef<llvm::Type*> Tys) {
5568   return llvm::Intrinsic::getDeclaration(&getModule(), (llvm::Intrinsic::ID)IID,
5569                                          Tys);
5570 }
5571 
5572 static llvm::StringMapEntry<llvm::GlobalVariable *> &
5573 GetConstantCFStringEntry(llvm::StringMap<llvm::GlobalVariable *> &Map,
5574                          const StringLiteral *Literal, bool TargetIsLSB,
5575                          bool &IsUTF16, unsigned &StringLength) {
5576   StringRef String = Literal->getString();
5577   unsigned NumBytes = String.size();
5578 
5579   // Check for simple case.
5580   if (!Literal->containsNonAsciiOrNull()) {
5581     StringLength = NumBytes;
5582     return *Map.insert(std::make_pair(String, nullptr)).first;
5583   }
5584 
5585   // Otherwise, convert the UTF8 literals into a string of shorts.
5586   IsUTF16 = true;
5587 
5588   SmallVector<llvm::UTF16, 128> ToBuf(NumBytes + 1); // +1 for ending nulls.
5589   const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data();
5590   llvm::UTF16 *ToPtr = &ToBuf[0];
5591 
5592   (void)llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr,
5593                                  ToPtr + NumBytes, llvm::strictConversion);
5594 
5595   // ConvertUTF8toUTF16 returns the length in ToPtr.
5596   StringLength = ToPtr - &ToBuf[0];
5597 
5598   // Add an explicit null.
5599   *ToPtr = 0;
5600   return *Map.insert(std::make_pair(
5601                          StringRef(reinterpret_cast<const char *>(ToBuf.data()),
5602                                    (StringLength + 1) * 2),
5603                          nullptr)).first;
5604 }
5605 
5606 ConstantAddress
5607 CodeGenModule::GetAddrOfConstantCFString(const StringLiteral *Literal) {
5608   unsigned StringLength = 0;
5609   bool isUTF16 = false;
5610   llvm::StringMapEntry<llvm::GlobalVariable *> &Entry =
5611       GetConstantCFStringEntry(CFConstantStringMap, Literal,
5612                                getDataLayout().isLittleEndian(), isUTF16,
5613                                StringLength);
5614 
5615   if (auto *C = Entry.second)
5616     return ConstantAddress(
5617         C, C->getValueType(), CharUnits::fromQuantity(C->getAlignment()));
5618 
5619   llvm::Constant *Zero = llvm::Constant::getNullValue(Int32Ty);
5620   llvm::Constant *Zeros[] = { Zero, Zero };
5621 
5622   const ASTContext &Context = getContext();
5623   const llvm::Triple &Triple = getTriple();
5624 
5625   const auto CFRuntime = getLangOpts().CFRuntime;
5626   const bool IsSwiftABI =
5627       static_cast<unsigned>(CFRuntime) >=
5628       static_cast<unsigned>(LangOptions::CoreFoundationABI::Swift);
5629   const bool IsSwift4_1 = CFRuntime == LangOptions::CoreFoundationABI::Swift4_1;
5630 
5631   // If we don't already have it, get __CFConstantStringClassReference.
5632   if (!CFConstantStringClassRef) {
5633     const char *CFConstantStringClassName = "__CFConstantStringClassReference";
5634     llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
5635     Ty = llvm::ArrayType::get(Ty, 0);
5636 
5637     switch (CFRuntime) {
5638     default: break;
5639     case LangOptions::CoreFoundationABI::Swift: [[fallthrough]];
5640     case LangOptions::CoreFoundationABI::Swift5_0:
5641       CFConstantStringClassName =
5642           Triple.isOSDarwin() ? "$s15SwiftFoundation19_NSCFConstantStringCN"
5643                               : "$s10Foundation19_NSCFConstantStringCN";
5644       Ty = IntPtrTy;
5645       break;
5646     case LangOptions::CoreFoundationABI::Swift4_2:
5647       CFConstantStringClassName =
5648           Triple.isOSDarwin() ? "$S15SwiftFoundation19_NSCFConstantStringCN"
5649                               : "$S10Foundation19_NSCFConstantStringCN";
5650       Ty = IntPtrTy;
5651       break;
5652     case LangOptions::CoreFoundationABI::Swift4_1:
5653       CFConstantStringClassName =
5654           Triple.isOSDarwin() ? "__T015SwiftFoundation19_NSCFConstantStringCN"
5655                               : "__T010Foundation19_NSCFConstantStringCN";
5656       Ty = IntPtrTy;
5657       break;
5658     }
5659 
5660     llvm::Constant *C = CreateRuntimeVariable(Ty, CFConstantStringClassName);
5661 
5662     if (Triple.isOSBinFormatELF() || Triple.isOSBinFormatCOFF()) {
5663       llvm::GlobalValue *GV = nullptr;
5664 
5665       if ((GV = dyn_cast<llvm::GlobalValue>(C))) {
5666         IdentifierInfo &II = Context.Idents.get(GV->getName());
5667         TranslationUnitDecl *TUDecl = Context.getTranslationUnitDecl();
5668         DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl);
5669 
5670         const VarDecl *VD = nullptr;
5671         for (const auto *Result : DC->lookup(&II))
5672           if ((VD = dyn_cast<VarDecl>(Result)))
5673             break;
5674 
5675         if (Triple.isOSBinFormatELF()) {
5676           if (!VD)
5677             GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
5678         } else {
5679           GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
5680           if (!VD || !VD->hasAttr<DLLExportAttr>())
5681             GV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
5682           else
5683             GV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
5684         }
5685 
5686         setDSOLocal(GV);
5687       }
5688     }
5689 
5690     // Decay array -> ptr
5691     CFConstantStringClassRef =
5692         IsSwiftABI ? llvm::ConstantExpr::getPtrToInt(C, Ty)
5693                    : llvm::ConstantExpr::getGetElementPtr(Ty, C, Zeros);
5694   }
5695 
5696   QualType CFTy = Context.getCFConstantStringType();
5697 
5698   auto *STy = cast<llvm::StructType>(getTypes().ConvertType(CFTy));
5699 
5700   ConstantInitBuilder Builder(*this);
5701   auto Fields = Builder.beginStruct(STy);
5702 
5703   // Class pointer.
5704   Fields.add(cast<llvm::Constant>(CFConstantStringClassRef));
5705 
5706   // Flags.
5707   if (IsSwiftABI) {
5708     Fields.addInt(IntPtrTy, IsSwift4_1 ? 0x05 : 0x01);
5709     Fields.addInt(Int64Ty, isUTF16 ? 0x07d0 : 0x07c8);
5710   } else {
5711     Fields.addInt(IntTy, isUTF16 ? 0x07d0 : 0x07C8);
5712   }
5713 
5714   // String pointer.
5715   llvm::Constant *C = nullptr;
5716   if (isUTF16) {
5717     auto Arr = llvm::ArrayRef(
5718         reinterpret_cast<uint16_t *>(const_cast<char *>(Entry.first().data())),
5719         Entry.first().size() / 2);
5720     C = llvm::ConstantDataArray::get(VMContext, Arr);
5721   } else {
5722     C = llvm::ConstantDataArray::getString(VMContext, Entry.first());
5723   }
5724 
5725   // Note: -fwritable-strings doesn't make the backing store strings of
5726   // CFStrings writable. (See <rdar://problem/10657500>)
5727   auto *GV =
5728       new llvm::GlobalVariable(getModule(), C->getType(), /*isConstant=*/true,
5729                                llvm::GlobalValue::PrivateLinkage, C, ".str");
5730   GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
5731   // Don't enforce the target's minimum global alignment, since the only use
5732   // of the string is via this class initializer.
5733   CharUnits Align = isUTF16 ? Context.getTypeAlignInChars(Context.ShortTy)
5734                             : Context.getTypeAlignInChars(Context.CharTy);
5735   GV->setAlignment(Align.getAsAlign());
5736 
5737   // FIXME: We set the section explicitly to avoid a bug in ld64 224.1.
5738   // Without it LLVM can merge the string with a non unnamed_addr one during
5739   // LTO.  Doing that changes the section it ends in, which surprises ld64.
5740   if (Triple.isOSBinFormatMachO())
5741     GV->setSection(isUTF16 ? "__TEXT,__ustring"
5742                            : "__TEXT,__cstring,cstring_literals");
5743   // Make sure the literal ends up in .rodata to allow for safe ICF and for
5744   // the static linker to adjust permissions to read-only later on.
5745   else if (Triple.isOSBinFormatELF())
5746     GV->setSection(".rodata");
5747 
5748   // String.
5749   llvm::Constant *Str =
5750       llvm::ConstantExpr::getGetElementPtr(GV->getValueType(), GV, Zeros);
5751 
5752   if (isUTF16)
5753     // Cast the UTF16 string to the correct type.
5754     Str = llvm::ConstantExpr::getBitCast(Str, Int8PtrTy);
5755   Fields.add(Str);
5756 
5757   // String length.
5758   llvm::IntegerType *LengthTy =
5759       llvm::IntegerType::get(getModule().getContext(),
5760                              Context.getTargetInfo().getLongWidth());
5761   if (IsSwiftABI) {
5762     if (CFRuntime == LangOptions::CoreFoundationABI::Swift4_1 ||
5763         CFRuntime == LangOptions::CoreFoundationABI::Swift4_2)
5764       LengthTy = Int32Ty;
5765     else
5766       LengthTy = IntPtrTy;
5767   }
5768   Fields.addInt(LengthTy, StringLength);
5769 
5770   // Swift ABI requires 8-byte alignment to ensure that the _Atomic(uint64_t) is
5771   // properly aligned on 32-bit platforms.
5772   CharUnits Alignment =
5773       IsSwiftABI ? Context.toCharUnitsFromBits(64) : getPointerAlign();
5774 
5775   // The struct.
5776   GV = Fields.finishAndCreateGlobal("_unnamed_cfstring_", Alignment,
5777                                     /*isConstant=*/false,
5778                                     llvm::GlobalVariable::PrivateLinkage);
5779   GV->addAttribute("objc_arc_inert");
5780   switch (Triple.getObjectFormat()) {
5781   case llvm::Triple::UnknownObjectFormat:
5782     llvm_unreachable("unknown file format");
5783   case llvm::Triple::DXContainer:
5784   case llvm::Triple::GOFF:
5785   case llvm::Triple::SPIRV:
5786   case llvm::Triple::XCOFF:
5787     llvm_unreachable("unimplemented");
5788   case llvm::Triple::COFF:
5789   case llvm::Triple::ELF:
5790   case llvm::Triple::Wasm:
5791     GV->setSection("cfstring");
5792     break;
5793   case llvm::Triple::MachO:
5794     GV->setSection("__DATA,__cfstring");
5795     break;
5796   }
5797   Entry.second = GV;
5798 
5799   return ConstantAddress(GV, GV->getValueType(), Alignment);
5800 }
5801 
5802 bool CodeGenModule::getExpressionLocationsEnabled() const {
5803   return !CodeGenOpts.EmitCodeView || CodeGenOpts.DebugColumnInfo;
5804 }
5805 
5806 QualType CodeGenModule::getObjCFastEnumerationStateType() {
5807   if (ObjCFastEnumerationStateType.isNull()) {
5808     RecordDecl *D = Context.buildImplicitRecord("__objcFastEnumerationState");
5809     D->startDefinition();
5810 
5811     QualType FieldTypes[] = {
5812       Context.UnsignedLongTy,
5813       Context.getPointerType(Context.getObjCIdType()),
5814       Context.getPointerType(Context.UnsignedLongTy),
5815       Context.getConstantArrayType(Context.UnsignedLongTy,
5816                            llvm::APInt(32, 5), nullptr, ArrayType::Normal, 0)
5817     };
5818 
5819     for (size_t i = 0; i < 4; ++i) {
5820       FieldDecl *Field = FieldDecl::Create(Context,
5821                                            D,
5822                                            SourceLocation(),
5823                                            SourceLocation(), nullptr,
5824                                            FieldTypes[i], /*TInfo=*/nullptr,
5825                                            /*BitWidth=*/nullptr,
5826                                            /*Mutable=*/false,
5827                                            ICIS_NoInit);
5828       Field->setAccess(AS_public);
5829       D->addDecl(Field);
5830     }
5831 
5832     D->completeDefinition();
5833     ObjCFastEnumerationStateType = Context.getTagDeclType(D);
5834   }
5835 
5836   return ObjCFastEnumerationStateType;
5837 }
5838 
5839 llvm::Constant *
5840 CodeGenModule::GetConstantArrayFromStringLiteral(const StringLiteral *E) {
5841   assert(!E->getType()->isPointerType() && "Strings are always arrays");
5842 
5843   // Don't emit it as the address of the string, emit the string data itself
5844   // as an inline array.
5845   if (E->getCharByteWidth() == 1) {
5846     SmallString<64> Str(E->getString());
5847 
5848     // Resize the string to the right size, which is indicated by its type.
5849     const ConstantArrayType *CAT = Context.getAsConstantArrayType(E->getType());
5850     Str.resize(CAT->getSize().getZExtValue());
5851     return llvm::ConstantDataArray::getString(VMContext, Str, false);
5852   }
5853 
5854   auto *AType = cast<llvm::ArrayType>(getTypes().ConvertType(E->getType()));
5855   llvm::Type *ElemTy = AType->getElementType();
5856   unsigned NumElements = AType->getNumElements();
5857 
5858   // Wide strings have either 2-byte or 4-byte elements.
5859   if (ElemTy->getPrimitiveSizeInBits() == 16) {
5860     SmallVector<uint16_t, 32> Elements;
5861     Elements.reserve(NumElements);
5862 
5863     for(unsigned i = 0, e = E->getLength(); i != e; ++i)
5864       Elements.push_back(E->getCodeUnit(i));
5865     Elements.resize(NumElements);
5866     return llvm::ConstantDataArray::get(VMContext, Elements);
5867   }
5868 
5869   assert(ElemTy->getPrimitiveSizeInBits() == 32);
5870   SmallVector<uint32_t, 32> Elements;
5871   Elements.reserve(NumElements);
5872 
5873   for(unsigned i = 0, e = E->getLength(); i != e; ++i)
5874     Elements.push_back(E->getCodeUnit(i));
5875   Elements.resize(NumElements);
5876   return llvm::ConstantDataArray::get(VMContext, Elements);
5877 }
5878 
5879 static llvm::GlobalVariable *
5880 GenerateStringLiteral(llvm::Constant *C, llvm::GlobalValue::LinkageTypes LT,
5881                       CodeGenModule &CGM, StringRef GlobalName,
5882                       CharUnits Alignment) {
5883   unsigned AddrSpace = CGM.getContext().getTargetAddressSpace(
5884       CGM.GetGlobalConstantAddressSpace());
5885 
5886   llvm::Module &M = CGM.getModule();
5887   // Create a global variable for this string
5888   auto *GV = new llvm::GlobalVariable(
5889       M, C->getType(), !CGM.getLangOpts().WritableStrings, LT, C, GlobalName,
5890       nullptr, llvm::GlobalVariable::NotThreadLocal, AddrSpace);
5891   GV->setAlignment(Alignment.getAsAlign());
5892   GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
5893   if (GV->isWeakForLinker()) {
5894     assert(CGM.supportsCOMDAT() && "Only COFF uses weak string literals");
5895     GV->setComdat(M.getOrInsertComdat(GV->getName()));
5896   }
5897   CGM.setDSOLocal(GV);
5898 
5899   return GV;
5900 }
5901 
5902 /// GetAddrOfConstantStringFromLiteral - Return a pointer to a
5903 /// constant array for the given string literal.
5904 ConstantAddress
5905 CodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S,
5906                                                   StringRef Name) {
5907   CharUnits Alignment = getContext().getAlignOfGlobalVarInChars(S->getType());
5908 
5909   llvm::Constant *C = GetConstantArrayFromStringLiteral(S);
5910   llvm::GlobalVariable **Entry = nullptr;
5911   if (!LangOpts.WritableStrings) {
5912     Entry = &ConstantStringMap[C];
5913     if (auto GV = *Entry) {
5914       if (uint64_t(Alignment.getQuantity()) > GV->getAlignment())
5915         GV->setAlignment(Alignment.getAsAlign());
5916       return ConstantAddress(castStringLiteralToDefaultAddressSpace(*this, GV),
5917                              GV->getValueType(), Alignment);
5918     }
5919   }
5920 
5921   SmallString<256> MangledNameBuffer;
5922   StringRef GlobalVariableName;
5923   llvm::GlobalValue::LinkageTypes LT;
5924 
5925   // Mangle the string literal if that's how the ABI merges duplicate strings.
5926   // Don't do it if they are writable, since we don't want writes in one TU to
5927   // affect strings in another.
5928   if (getCXXABI().getMangleContext().shouldMangleStringLiteral(S) &&
5929       !LangOpts.WritableStrings) {
5930     llvm::raw_svector_ostream Out(MangledNameBuffer);
5931     getCXXABI().getMangleContext().mangleStringLiteral(S, Out);
5932     LT = llvm::GlobalValue::LinkOnceODRLinkage;
5933     GlobalVariableName = MangledNameBuffer;
5934   } else {
5935     LT = llvm::GlobalValue::PrivateLinkage;
5936     GlobalVariableName = Name;
5937   }
5938 
5939   auto GV = GenerateStringLiteral(C, LT, *this, GlobalVariableName, Alignment);
5940 
5941   CGDebugInfo *DI = getModuleDebugInfo();
5942   if (DI && getCodeGenOpts().hasReducedDebugInfo())
5943     DI->AddStringLiteralDebugInfo(GV, S);
5944 
5945   if (Entry)
5946     *Entry = GV;
5947 
5948   SanitizerMD->reportGlobal(GV, S->getStrTokenLoc(0), "<string literal>");
5949 
5950   return ConstantAddress(castStringLiteralToDefaultAddressSpace(*this, GV),
5951                          GV->getValueType(), Alignment);
5952 }
5953 
5954 /// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant
5955 /// array for the given ObjCEncodeExpr node.
5956 ConstantAddress
5957 CodeGenModule::GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *E) {
5958   std::string Str;
5959   getContext().getObjCEncodingForType(E->getEncodedType(), Str);
5960 
5961   return GetAddrOfConstantCString(Str);
5962 }
5963 
5964 /// GetAddrOfConstantCString - Returns a pointer to a character array containing
5965 /// the literal and a terminating '\0' character.
5966 /// The result has pointer to array type.
5967 ConstantAddress CodeGenModule::GetAddrOfConstantCString(
5968     const std::string &Str, const char *GlobalName) {
5969   StringRef StrWithNull(Str.c_str(), Str.size() + 1);
5970   CharUnits Alignment =
5971     getContext().getAlignOfGlobalVarInChars(getContext().CharTy);
5972 
5973   llvm::Constant *C =
5974       llvm::ConstantDataArray::getString(getLLVMContext(), StrWithNull, false);
5975 
5976   // Don't share any string literals if strings aren't constant.
5977   llvm::GlobalVariable **Entry = nullptr;
5978   if (!LangOpts.WritableStrings) {
5979     Entry = &ConstantStringMap[C];
5980     if (auto GV = *Entry) {
5981       if (uint64_t(Alignment.getQuantity()) > GV->getAlignment())
5982         GV->setAlignment(Alignment.getAsAlign());
5983       return ConstantAddress(castStringLiteralToDefaultAddressSpace(*this, GV),
5984                              GV->getValueType(), Alignment);
5985     }
5986   }
5987 
5988   // Get the default prefix if a name wasn't specified.
5989   if (!GlobalName)
5990     GlobalName = ".str";
5991   // Create a global variable for this.
5992   auto GV = GenerateStringLiteral(C, llvm::GlobalValue::PrivateLinkage, *this,
5993                                   GlobalName, Alignment);
5994   if (Entry)
5995     *Entry = GV;
5996 
5997   return ConstantAddress(castStringLiteralToDefaultAddressSpace(*this, GV),
5998                          GV->getValueType(), Alignment);
5999 }
6000 
6001 ConstantAddress CodeGenModule::GetAddrOfGlobalTemporary(
6002     const MaterializeTemporaryExpr *E, const Expr *Init) {
6003   assert((E->getStorageDuration() == SD_Static ||
6004           E->getStorageDuration() == SD_Thread) && "not a global temporary");
6005   const auto *VD = cast<VarDecl>(E->getExtendingDecl());
6006 
6007   // If we're not materializing a subobject of the temporary, keep the
6008   // cv-qualifiers from the type of the MaterializeTemporaryExpr.
6009   QualType MaterializedType = Init->getType();
6010   if (Init == E->getSubExpr())
6011     MaterializedType = E->getType();
6012 
6013   CharUnits Align = getContext().getTypeAlignInChars(MaterializedType);
6014 
6015   auto InsertResult = MaterializedGlobalTemporaryMap.insert({E, nullptr});
6016   if (!InsertResult.second) {
6017     // We've seen this before: either we already created it or we're in the
6018     // process of doing so.
6019     if (!InsertResult.first->second) {
6020       // We recursively re-entered this function, probably during emission of
6021       // the initializer. Create a placeholder. We'll clean this up in the
6022       // outer call, at the end of this function.
6023       llvm::Type *Type = getTypes().ConvertTypeForMem(MaterializedType);
6024       InsertResult.first->second = new llvm::GlobalVariable(
6025           getModule(), Type, false, llvm::GlobalVariable::InternalLinkage,
6026           nullptr);
6027     }
6028     return ConstantAddress(InsertResult.first->second,
6029                            llvm::cast<llvm::GlobalVariable>(
6030                                InsertResult.first->second->stripPointerCasts())
6031                                ->getValueType(),
6032                            Align);
6033   }
6034 
6035   // FIXME: If an externally-visible declaration extends multiple temporaries,
6036   // we need to give each temporary the same name in every translation unit (and
6037   // we also need to make the temporaries externally-visible).
6038   SmallString<256> Name;
6039   llvm::raw_svector_ostream Out(Name);
6040   getCXXABI().getMangleContext().mangleReferenceTemporary(
6041       VD, E->getManglingNumber(), Out);
6042 
6043   APValue *Value = nullptr;
6044   if (E->getStorageDuration() == SD_Static && VD && VD->evaluateValue()) {
6045     // If the initializer of the extending declaration is a constant
6046     // initializer, we should have a cached constant initializer for this
6047     // temporary. Note that this might have a different value from the value
6048     // computed by evaluating the initializer if the surrounding constant
6049     // expression modifies the temporary.
6050     Value = E->getOrCreateValue(false);
6051   }
6052 
6053   // Try evaluating it now, it might have a constant initializer.
6054   Expr::EvalResult EvalResult;
6055   if (!Value && Init->EvaluateAsRValue(EvalResult, getContext()) &&
6056       !EvalResult.hasSideEffects())
6057     Value = &EvalResult.Val;
6058 
6059   LangAS AddrSpace =
6060       VD ? GetGlobalVarAddressSpace(VD) : MaterializedType.getAddressSpace();
6061 
6062   std::optional<ConstantEmitter> emitter;
6063   llvm::Constant *InitialValue = nullptr;
6064   bool Constant = false;
6065   llvm::Type *Type;
6066   if (Value) {
6067     // The temporary has a constant initializer, use it.
6068     emitter.emplace(*this);
6069     InitialValue = emitter->emitForInitializer(*Value, AddrSpace,
6070                                                MaterializedType);
6071     Constant = isTypeConstant(MaterializedType, /*ExcludeCtor*/Value);
6072     Type = InitialValue->getType();
6073   } else {
6074     // No initializer, the initialization will be provided when we
6075     // initialize the declaration which performed lifetime extension.
6076     Type = getTypes().ConvertTypeForMem(MaterializedType);
6077   }
6078 
6079   // Create a global variable for this lifetime-extended temporary.
6080   llvm::GlobalValue::LinkageTypes Linkage =
6081       getLLVMLinkageVarDefinition(VD, Constant);
6082   if (Linkage == llvm::GlobalVariable::ExternalLinkage) {
6083     const VarDecl *InitVD;
6084     if (VD->isStaticDataMember() && VD->getAnyInitializer(InitVD) &&
6085         isa<CXXRecordDecl>(InitVD->getLexicalDeclContext())) {
6086       // Temporaries defined inside a class get linkonce_odr linkage because the
6087       // class can be defined in multiple translation units.
6088       Linkage = llvm::GlobalVariable::LinkOnceODRLinkage;
6089     } else {
6090       // There is no need for this temporary to have external linkage if the
6091       // VarDecl has external linkage.
6092       Linkage = llvm::GlobalVariable::InternalLinkage;
6093     }
6094   }
6095   auto TargetAS = getContext().getTargetAddressSpace(AddrSpace);
6096   auto *GV = new llvm::GlobalVariable(
6097       getModule(), Type, Constant, Linkage, InitialValue, Name.c_str(),
6098       /*InsertBefore=*/nullptr, llvm::GlobalVariable::NotThreadLocal, TargetAS);
6099   if (emitter) emitter->finalize(GV);
6100   // Don't assign dllimport or dllexport to local linkage globals.
6101   if (!llvm::GlobalValue::isLocalLinkage(Linkage)) {
6102     setGVProperties(GV, VD);
6103     if (GV->getDLLStorageClass() == llvm::GlobalVariable::DLLExportStorageClass)
6104       // The reference temporary should never be dllexport.
6105       GV->setDLLStorageClass(llvm::GlobalVariable::DefaultStorageClass);
6106   }
6107   GV->setAlignment(Align.getAsAlign());
6108   if (supportsCOMDAT() && GV->isWeakForLinker())
6109     GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
6110   if (VD->getTLSKind())
6111     setTLSMode(GV, *VD);
6112   llvm::Constant *CV = GV;
6113   if (AddrSpace != LangAS::Default)
6114     CV = getTargetCodeGenInfo().performAddrSpaceCast(
6115         *this, GV, AddrSpace, LangAS::Default,
6116         Type->getPointerTo(
6117             getContext().getTargetAddressSpace(LangAS::Default)));
6118 
6119   // Update the map with the new temporary. If we created a placeholder above,
6120   // replace it with the new global now.
6121   llvm::Constant *&Entry = MaterializedGlobalTemporaryMap[E];
6122   if (Entry) {
6123     Entry->replaceAllUsesWith(
6124         llvm::ConstantExpr::getBitCast(CV, Entry->getType()));
6125     llvm::cast<llvm::GlobalVariable>(Entry)->eraseFromParent();
6126   }
6127   Entry = CV;
6128 
6129   return ConstantAddress(CV, Type, Align);
6130 }
6131 
6132 /// EmitObjCPropertyImplementations - Emit information for synthesized
6133 /// properties for an implementation.
6134 void CodeGenModule::EmitObjCPropertyImplementations(const
6135                                                     ObjCImplementationDecl *D) {
6136   for (const auto *PID : D->property_impls()) {
6137     // Dynamic is just for type-checking.
6138     if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
6139       ObjCPropertyDecl *PD = PID->getPropertyDecl();
6140 
6141       // Determine which methods need to be implemented, some may have
6142       // been overridden. Note that ::isPropertyAccessor is not the method
6143       // we want, that just indicates if the decl came from a
6144       // property. What we want to know is if the method is defined in
6145       // this implementation.
6146       auto *Getter = PID->getGetterMethodDecl();
6147       if (!Getter || Getter->isSynthesizedAccessorStub())
6148         CodeGenFunction(*this).GenerateObjCGetter(
6149             const_cast<ObjCImplementationDecl *>(D), PID);
6150       auto *Setter = PID->getSetterMethodDecl();
6151       if (!PD->isReadOnly() && (!Setter || Setter->isSynthesizedAccessorStub()))
6152         CodeGenFunction(*this).GenerateObjCSetter(
6153                                  const_cast<ObjCImplementationDecl *>(D), PID);
6154     }
6155   }
6156 }
6157 
6158 static bool needsDestructMethod(ObjCImplementationDecl *impl) {
6159   const ObjCInterfaceDecl *iface = impl->getClassInterface();
6160   for (const ObjCIvarDecl *ivar = iface->all_declared_ivar_begin();
6161        ivar; ivar = ivar->getNextIvar())
6162     if (ivar->getType().isDestructedType())
6163       return true;
6164 
6165   return false;
6166 }
6167 
6168 static bool AllTrivialInitializers(CodeGenModule &CGM,
6169                                    ObjCImplementationDecl *D) {
6170   CodeGenFunction CGF(CGM);
6171   for (ObjCImplementationDecl::init_iterator B = D->init_begin(),
6172        E = D->init_end(); B != E; ++B) {
6173     CXXCtorInitializer *CtorInitExp = *B;
6174     Expr *Init = CtorInitExp->getInit();
6175     if (!CGF.isTrivialInitializer(Init))
6176       return false;
6177   }
6178   return true;
6179 }
6180 
6181 /// EmitObjCIvarInitializations - Emit information for ivar initialization
6182 /// for an implementation.
6183 void CodeGenModule::EmitObjCIvarInitializations(ObjCImplementationDecl *D) {
6184   // We might need a .cxx_destruct even if we don't have any ivar initializers.
6185   if (needsDestructMethod(D)) {
6186     IdentifierInfo *II = &getContext().Idents.get(".cxx_destruct");
6187     Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
6188     ObjCMethodDecl *DTORMethod = ObjCMethodDecl::Create(
6189         getContext(), D->getLocation(), D->getLocation(), cxxSelector,
6190         getContext().VoidTy, nullptr, D,
6191         /*isInstance=*/true, /*isVariadic=*/false,
6192         /*isPropertyAccessor=*/true, /*isSynthesizedAccessorStub=*/false,
6193         /*isImplicitlyDeclared=*/true,
6194         /*isDefined=*/false, ObjCMethodDecl::Required);
6195     D->addInstanceMethod(DTORMethod);
6196     CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, DTORMethod, false);
6197     D->setHasDestructors(true);
6198   }
6199 
6200   // If the implementation doesn't have any ivar initializers, we don't need
6201   // a .cxx_construct.
6202   if (D->getNumIvarInitializers() == 0 ||
6203       AllTrivialInitializers(*this, D))
6204     return;
6205 
6206   IdentifierInfo *II = &getContext().Idents.get(".cxx_construct");
6207   Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
6208   // The constructor returns 'self'.
6209   ObjCMethodDecl *CTORMethod = ObjCMethodDecl::Create(
6210       getContext(), D->getLocation(), D->getLocation(), cxxSelector,
6211       getContext().getObjCIdType(), nullptr, D, /*isInstance=*/true,
6212       /*isVariadic=*/false,
6213       /*isPropertyAccessor=*/true, /*isSynthesizedAccessorStub=*/false,
6214       /*isImplicitlyDeclared=*/true,
6215       /*isDefined=*/false, ObjCMethodDecl::Required);
6216   D->addInstanceMethod(CTORMethod);
6217   CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, CTORMethod, true);
6218   D->setHasNonZeroConstructors(true);
6219 }
6220 
6221 // EmitLinkageSpec - Emit all declarations in a linkage spec.
6222 void CodeGenModule::EmitLinkageSpec(const LinkageSpecDecl *LSD) {
6223   if (LSD->getLanguage() != LinkageSpecDecl::lang_c &&
6224       LSD->getLanguage() != LinkageSpecDecl::lang_cxx) {
6225     ErrorUnsupported(LSD, "linkage spec");
6226     return;
6227   }
6228 
6229   EmitDeclContext(LSD);
6230 }
6231 
6232 void CodeGenModule::EmitTopLevelStmt(const TopLevelStmtDecl *D) {
6233   std::unique_ptr<CodeGenFunction> &CurCGF =
6234       GlobalTopLevelStmtBlockInFlight.first;
6235 
6236   // We emitted a top-level stmt but after it there is initialization.
6237   // Stop squashing the top-level stmts into a single function.
6238   if (CurCGF && CXXGlobalInits.back() != CurCGF->CurFn) {
6239     CurCGF->FinishFunction(D->getEndLoc());
6240     CurCGF = nullptr;
6241   }
6242 
6243   if (!CurCGF) {
6244     // void __stmts__N(void)
6245     // FIXME: Ask the ABI name mangler to pick a name.
6246     std::string Name = "__stmts__" + llvm::utostr(CXXGlobalInits.size());
6247     FunctionArgList Args;
6248     QualType RetTy = getContext().VoidTy;
6249     const CGFunctionInfo &FnInfo =
6250         getTypes().arrangeBuiltinFunctionDeclaration(RetTy, Args);
6251     llvm::FunctionType *FnTy = getTypes().GetFunctionType(FnInfo);
6252     llvm::Function *Fn = llvm::Function::Create(
6253         FnTy, llvm::GlobalValue::InternalLinkage, Name, &getModule());
6254 
6255     CurCGF.reset(new CodeGenFunction(*this));
6256     GlobalTopLevelStmtBlockInFlight.second = D;
6257     CurCGF->StartFunction(GlobalDecl(), RetTy, Fn, FnInfo, Args,
6258                           D->getBeginLoc(), D->getBeginLoc());
6259     CXXGlobalInits.push_back(Fn);
6260   }
6261 
6262   CurCGF->EmitStmt(D->getStmt());
6263 }
6264 
6265 void CodeGenModule::EmitDeclContext(const DeclContext *DC) {
6266   for (auto *I : DC->decls()) {
6267     // Unlike other DeclContexts, the contents of an ObjCImplDecl at TU scope
6268     // are themselves considered "top-level", so EmitTopLevelDecl on an
6269     // ObjCImplDecl does not recursively visit them. We need to do that in
6270     // case they're nested inside another construct (LinkageSpecDecl /
6271     // ExportDecl) that does stop them from being considered "top-level".
6272     if (auto *OID = dyn_cast<ObjCImplDecl>(I)) {
6273       for (auto *M : OID->methods())
6274         EmitTopLevelDecl(M);
6275     }
6276 
6277     EmitTopLevelDecl(I);
6278   }
6279 }
6280 
6281 /// EmitTopLevelDecl - Emit code for a single top level declaration.
6282 void CodeGenModule::EmitTopLevelDecl(Decl *D) {
6283   // Ignore dependent declarations.
6284   if (D->isTemplated())
6285     return;
6286 
6287   // Consteval function shouldn't be emitted.
6288   if (auto *FD = dyn_cast<FunctionDecl>(D))
6289     if (FD->isConsteval())
6290       return;
6291 
6292   switch (D->getKind()) {
6293   case Decl::CXXConversion:
6294   case Decl::CXXMethod:
6295   case Decl::Function:
6296     EmitGlobal(cast<FunctionDecl>(D));
6297     // Always provide some coverage mapping
6298     // even for the functions that aren't emitted.
6299     AddDeferredUnusedCoverageMapping(D);
6300     break;
6301 
6302   case Decl::CXXDeductionGuide:
6303     // Function-like, but does not result in code emission.
6304     break;
6305 
6306   case Decl::Var:
6307   case Decl::Decomposition:
6308   case Decl::VarTemplateSpecialization:
6309     EmitGlobal(cast<VarDecl>(D));
6310     if (auto *DD = dyn_cast<DecompositionDecl>(D))
6311       for (auto *B : DD->bindings())
6312         if (auto *HD = B->getHoldingVar())
6313           EmitGlobal(HD);
6314     break;
6315 
6316   // Indirect fields from global anonymous structs and unions can be
6317   // ignored; only the actual variable requires IR gen support.
6318   case Decl::IndirectField:
6319     break;
6320 
6321   // C++ Decls
6322   case Decl::Namespace:
6323     EmitDeclContext(cast<NamespaceDecl>(D));
6324     break;
6325   case Decl::ClassTemplateSpecialization: {
6326     const auto *Spec = cast<ClassTemplateSpecializationDecl>(D);
6327     if (CGDebugInfo *DI = getModuleDebugInfo())
6328       if (Spec->getSpecializationKind() ==
6329               TSK_ExplicitInstantiationDefinition &&
6330           Spec->hasDefinition())
6331         DI->completeTemplateDefinition(*Spec);
6332   } [[fallthrough]];
6333   case Decl::CXXRecord: {
6334     CXXRecordDecl *CRD = cast<CXXRecordDecl>(D);
6335     if (CGDebugInfo *DI = getModuleDebugInfo()) {
6336       if (CRD->hasDefinition())
6337         DI->EmitAndRetainType(getContext().getRecordType(cast<RecordDecl>(D)));
6338       if (auto *ES = D->getASTContext().getExternalSource())
6339         if (ES->hasExternalDefinitions(D) == ExternalASTSource::EK_Never)
6340           DI->completeUnusedClass(*CRD);
6341     }
6342     // Emit any static data members, they may be definitions.
6343     for (auto *I : CRD->decls())
6344       if (isa<VarDecl>(I) || isa<CXXRecordDecl>(I))
6345         EmitTopLevelDecl(I);
6346     break;
6347   }
6348     // No code generation needed.
6349   case Decl::UsingShadow:
6350   case Decl::ClassTemplate:
6351   case Decl::VarTemplate:
6352   case Decl::Concept:
6353   case Decl::VarTemplatePartialSpecialization:
6354   case Decl::FunctionTemplate:
6355   case Decl::TypeAliasTemplate:
6356   case Decl::Block:
6357   case Decl::Empty:
6358   case Decl::Binding:
6359     break;
6360   case Decl::Using:          // using X; [C++]
6361     if (CGDebugInfo *DI = getModuleDebugInfo())
6362         DI->EmitUsingDecl(cast<UsingDecl>(*D));
6363     break;
6364   case Decl::UsingEnum: // using enum X; [C++]
6365     if (CGDebugInfo *DI = getModuleDebugInfo())
6366       DI->EmitUsingEnumDecl(cast<UsingEnumDecl>(*D));
6367     break;
6368   case Decl::NamespaceAlias:
6369     if (CGDebugInfo *DI = getModuleDebugInfo())
6370         DI->EmitNamespaceAlias(cast<NamespaceAliasDecl>(*D));
6371     break;
6372   case Decl::UsingDirective: // using namespace X; [C++]
6373     if (CGDebugInfo *DI = getModuleDebugInfo())
6374       DI->EmitUsingDirective(cast<UsingDirectiveDecl>(*D));
6375     break;
6376   case Decl::CXXConstructor:
6377     getCXXABI().EmitCXXConstructors(cast<CXXConstructorDecl>(D));
6378     break;
6379   case Decl::CXXDestructor:
6380     getCXXABI().EmitCXXDestructors(cast<CXXDestructorDecl>(D));
6381     break;
6382 
6383   case Decl::StaticAssert:
6384     // Nothing to do.
6385     break;
6386 
6387   // Objective-C Decls
6388 
6389   // Forward declarations, no (immediate) code generation.
6390   case Decl::ObjCInterface:
6391   case Decl::ObjCCategory:
6392     break;
6393 
6394   case Decl::ObjCProtocol: {
6395     auto *Proto = cast<ObjCProtocolDecl>(D);
6396     if (Proto->isThisDeclarationADefinition())
6397       ObjCRuntime->GenerateProtocol(Proto);
6398     break;
6399   }
6400 
6401   case Decl::ObjCCategoryImpl:
6402     // Categories have properties but don't support synthesize so we
6403     // can ignore them here.
6404     ObjCRuntime->GenerateCategory(cast<ObjCCategoryImplDecl>(D));
6405     break;
6406 
6407   case Decl::ObjCImplementation: {
6408     auto *OMD = cast<ObjCImplementationDecl>(D);
6409     EmitObjCPropertyImplementations(OMD);
6410     EmitObjCIvarInitializations(OMD);
6411     ObjCRuntime->GenerateClass(OMD);
6412     // Emit global variable debug information.
6413     if (CGDebugInfo *DI = getModuleDebugInfo())
6414       if (getCodeGenOpts().hasReducedDebugInfo())
6415         DI->getOrCreateInterfaceType(getContext().getObjCInterfaceType(
6416             OMD->getClassInterface()), OMD->getLocation());
6417     break;
6418   }
6419   case Decl::ObjCMethod: {
6420     auto *OMD = cast<ObjCMethodDecl>(D);
6421     // If this is not a prototype, emit the body.
6422     if (OMD->getBody())
6423       CodeGenFunction(*this).GenerateObjCMethod(OMD);
6424     break;
6425   }
6426   case Decl::ObjCCompatibleAlias:
6427     ObjCRuntime->RegisterAlias(cast<ObjCCompatibleAliasDecl>(D));
6428     break;
6429 
6430   case Decl::PragmaComment: {
6431     const auto *PCD = cast<PragmaCommentDecl>(D);
6432     switch (PCD->getCommentKind()) {
6433     case PCK_Unknown:
6434       llvm_unreachable("unexpected pragma comment kind");
6435     case PCK_Linker:
6436       AppendLinkerOptions(PCD->getArg());
6437       break;
6438     case PCK_Lib:
6439         AddDependentLib(PCD->getArg());
6440       break;
6441     case PCK_Compiler:
6442     case PCK_ExeStr:
6443     case PCK_User:
6444       break; // We ignore all of these.
6445     }
6446     break;
6447   }
6448 
6449   case Decl::PragmaDetectMismatch: {
6450     const auto *PDMD = cast<PragmaDetectMismatchDecl>(D);
6451     AddDetectMismatch(PDMD->getName(), PDMD->getValue());
6452     break;
6453   }
6454 
6455   case Decl::LinkageSpec:
6456     EmitLinkageSpec(cast<LinkageSpecDecl>(D));
6457     break;
6458 
6459   case Decl::FileScopeAsm: {
6460     // File-scope asm is ignored during device-side CUDA compilation.
6461     if (LangOpts.CUDA && LangOpts.CUDAIsDevice)
6462       break;
6463     // File-scope asm is ignored during device-side OpenMP compilation.
6464     if (LangOpts.OpenMPIsDevice)
6465       break;
6466     // File-scope asm is ignored during device-side SYCL compilation.
6467     if (LangOpts.SYCLIsDevice)
6468       break;
6469     auto *AD = cast<FileScopeAsmDecl>(D);
6470     getModule().appendModuleInlineAsm(AD->getAsmString()->getString());
6471     break;
6472   }
6473 
6474   case Decl::TopLevelStmt:
6475     EmitTopLevelStmt(cast<TopLevelStmtDecl>(D));
6476     break;
6477 
6478   case Decl::Import: {
6479     auto *Import = cast<ImportDecl>(D);
6480 
6481     // If we've already imported this module, we're done.
6482     if (!ImportedModules.insert(Import->getImportedModule()))
6483       break;
6484 
6485     // Emit debug information for direct imports.
6486     if (!Import->getImportedOwningModule()) {
6487       if (CGDebugInfo *DI = getModuleDebugInfo())
6488         DI->EmitImportDecl(*Import);
6489     }
6490 
6491     // For C++ standard modules we are done - we will call the module
6492     // initializer for imported modules, and that will likewise call those for
6493     // any imports it has.
6494     if (CXX20ModuleInits && Import->getImportedOwningModule() &&
6495         !Import->getImportedOwningModule()->isModuleMapModule())
6496       break;
6497 
6498     // For clang C++ module map modules the initializers for sub-modules are
6499     // emitted here.
6500 
6501     // Find all of the submodules and emit the module initializers.
6502     llvm::SmallPtrSet<clang::Module *, 16> Visited;
6503     SmallVector<clang::Module *, 16> Stack;
6504     Visited.insert(Import->getImportedModule());
6505     Stack.push_back(Import->getImportedModule());
6506 
6507     while (!Stack.empty()) {
6508       clang::Module *Mod = Stack.pop_back_val();
6509       if (!EmittedModuleInitializers.insert(Mod).second)
6510         continue;
6511 
6512       for (auto *D : Context.getModuleInitializers(Mod))
6513         EmitTopLevelDecl(D);
6514 
6515       // Visit the submodules of this module.
6516       for (clang::Module::submodule_iterator Sub = Mod->submodule_begin(),
6517                                              SubEnd = Mod->submodule_end();
6518            Sub != SubEnd; ++Sub) {
6519         // Skip explicit children; they need to be explicitly imported to emit
6520         // the initializers.
6521         if ((*Sub)->IsExplicit)
6522           continue;
6523 
6524         if (Visited.insert(*Sub).second)
6525           Stack.push_back(*Sub);
6526       }
6527     }
6528     break;
6529   }
6530 
6531   case Decl::Export:
6532     EmitDeclContext(cast<ExportDecl>(D));
6533     break;
6534 
6535   case Decl::OMPThreadPrivate:
6536     EmitOMPThreadPrivateDecl(cast<OMPThreadPrivateDecl>(D));
6537     break;
6538 
6539   case Decl::OMPAllocate:
6540     EmitOMPAllocateDecl(cast<OMPAllocateDecl>(D));
6541     break;
6542 
6543   case Decl::OMPDeclareReduction:
6544     EmitOMPDeclareReduction(cast<OMPDeclareReductionDecl>(D));
6545     break;
6546 
6547   case Decl::OMPDeclareMapper:
6548     EmitOMPDeclareMapper(cast<OMPDeclareMapperDecl>(D));
6549     break;
6550 
6551   case Decl::OMPRequires:
6552     EmitOMPRequiresDecl(cast<OMPRequiresDecl>(D));
6553     break;
6554 
6555   case Decl::Typedef:
6556   case Decl::TypeAlias: // using foo = bar; [C++11]
6557     if (CGDebugInfo *DI = getModuleDebugInfo())
6558       DI->EmitAndRetainType(
6559           getContext().getTypedefType(cast<TypedefNameDecl>(D)));
6560     break;
6561 
6562   case Decl::Record:
6563     if (CGDebugInfo *DI = getModuleDebugInfo())
6564       if (cast<RecordDecl>(D)->getDefinition())
6565         DI->EmitAndRetainType(getContext().getRecordType(cast<RecordDecl>(D)));
6566     break;
6567 
6568   case Decl::Enum:
6569     if (CGDebugInfo *DI = getModuleDebugInfo())
6570       if (cast<EnumDecl>(D)->getDefinition())
6571         DI->EmitAndRetainType(getContext().getEnumType(cast<EnumDecl>(D)));
6572     break;
6573 
6574   case Decl::HLSLBuffer:
6575     getHLSLRuntime().addBuffer(cast<HLSLBufferDecl>(D));
6576     break;
6577 
6578   default:
6579     // Make sure we handled everything we should, every other kind is a
6580     // non-top-level decl.  FIXME: Would be nice to have an isTopLevelDeclKind
6581     // function. Need to recode Decl::Kind to do that easily.
6582     assert(isa<TypeDecl>(D) && "Unsupported decl kind");
6583     break;
6584   }
6585 }
6586 
6587 void CodeGenModule::AddDeferredUnusedCoverageMapping(Decl *D) {
6588   // Do we need to generate coverage mapping?
6589   if (!CodeGenOpts.CoverageMapping)
6590     return;
6591   switch (D->getKind()) {
6592   case Decl::CXXConversion:
6593   case Decl::CXXMethod:
6594   case Decl::Function:
6595   case Decl::ObjCMethod:
6596   case Decl::CXXConstructor:
6597   case Decl::CXXDestructor: {
6598     if (!cast<FunctionDecl>(D)->doesThisDeclarationHaveABody())
6599       break;
6600     SourceManager &SM = getContext().getSourceManager();
6601     if (LimitedCoverage && SM.getMainFileID() != SM.getFileID(D->getBeginLoc()))
6602       break;
6603     auto I = DeferredEmptyCoverageMappingDecls.find(D);
6604     if (I == DeferredEmptyCoverageMappingDecls.end())
6605       DeferredEmptyCoverageMappingDecls[D] = true;
6606     break;
6607   }
6608   default:
6609     break;
6610   };
6611 }
6612 
6613 void CodeGenModule::ClearUnusedCoverageMapping(const Decl *D) {
6614   // Do we need to generate coverage mapping?
6615   if (!CodeGenOpts.CoverageMapping)
6616     return;
6617   if (const auto *Fn = dyn_cast<FunctionDecl>(D)) {
6618     if (Fn->isTemplateInstantiation())
6619       ClearUnusedCoverageMapping(Fn->getTemplateInstantiationPattern());
6620   }
6621   auto I = DeferredEmptyCoverageMappingDecls.find(D);
6622   if (I == DeferredEmptyCoverageMappingDecls.end())
6623     DeferredEmptyCoverageMappingDecls[D] = false;
6624   else
6625     I->second = false;
6626 }
6627 
6628 void CodeGenModule::EmitDeferredUnusedCoverageMappings() {
6629   // We call takeVector() here to avoid use-after-free.
6630   // FIXME: DeferredEmptyCoverageMappingDecls is getting mutated because
6631   // we deserialize function bodies to emit coverage info for them, and that
6632   // deserializes more declarations. How should we handle that case?
6633   for (const auto &Entry : DeferredEmptyCoverageMappingDecls.takeVector()) {
6634     if (!Entry.second)
6635       continue;
6636     const Decl *D = Entry.first;
6637     switch (D->getKind()) {
6638     case Decl::CXXConversion:
6639     case Decl::CXXMethod:
6640     case Decl::Function:
6641     case Decl::ObjCMethod: {
6642       CodeGenPGO PGO(*this);
6643       GlobalDecl GD(cast<FunctionDecl>(D));
6644       PGO.emitEmptyCounterMapping(D, getMangledName(GD),
6645                                   getFunctionLinkage(GD));
6646       break;
6647     }
6648     case Decl::CXXConstructor: {
6649       CodeGenPGO PGO(*this);
6650       GlobalDecl GD(cast<CXXConstructorDecl>(D), Ctor_Base);
6651       PGO.emitEmptyCounterMapping(D, getMangledName(GD),
6652                                   getFunctionLinkage(GD));
6653       break;
6654     }
6655     case Decl::CXXDestructor: {
6656       CodeGenPGO PGO(*this);
6657       GlobalDecl GD(cast<CXXDestructorDecl>(D), Dtor_Base);
6658       PGO.emitEmptyCounterMapping(D, getMangledName(GD),
6659                                   getFunctionLinkage(GD));
6660       break;
6661     }
6662     default:
6663       break;
6664     };
6665   }
6666 }
6667 
6668 void CodeGenModule::EmitMainVoidAlias() {
6669   // In order to transition away from "__original_main" gracefully, emit an
6670   // alias for "main" in the no-argument case so that libc can detect when
6671   // new-style no-argument main is in used.
6672   if (llvm::Function *F = getModule().getFunction("main")) {
6673     if (!F->isDeclaration() && F->arg_size() == 0 && !F->isVarArg() &&
6674         F->getReturnType()->isIntegerTy(Context.getTargetInfo().getIntWidth())) {
6675       auto *GA = llvm::GlobalAlias::create("__main_void", F);
6676       GA->setVisibility(llvm::GlobalValue::HiddenVisibility);
6677     }
6678   }
6679 }
6680 
6681 /// Turns the given pointer into a constant.
6682 static llvm::Constant *GetPointerConstant(llvm::LLVMContext &Context,
6683                                           const void *Ptr) {
6684   uintptr_t PtrInt = reinterpret_cast<uintptr_t>(Ptr);
6685   llvm::Type *i64 = llvm::Type::getInt64Ty(Context);
6686   return llvm::ConstantInt::get(i64, PtrInt);
6687 }
6688 
6689 static void EmitGlobalDeclMetadata(CodeGenModule &CGM,
6690                                    llvm::NamedMDNode *&GlobalMetadata,
6691                                    GlobalDecl D,
6692                                    llvm::GlobalValue *Addr) {
6693   if (!GlobalMetadata)
6694     GlobalMetadata =
6695       CGM.getModule().getOrInsertNamedMetadata("clang.global.decl.ptrs");
6696 
6697   // TODO: should we report variant information for ctors/dtors?
6698   llvm::Metadata *Ops[] = {llvm::ConstantAsMetadata::get(Addr),
6699                            llvm::ConstantAsMetadata::get(GetPointerConstant(
6700                                CGM.getLLVMContext(), D.getDecl()))};
6701   GlobalMetadata->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops));
6702 }
6703 
6704 bool CodeGenModule::CheckAndReplaceExternCIFuncs(llvm::GlobalValue *Elem,
6705                                                  llvm::GlobalValue *CppFunc) {
6706   // Store the list of ifuncs we need to replace uses in.
6707   llvm::SmallVector<llvm::GlobalIFunc *> IFuncs;
6708   // List of ConstantExprs that we should be able to delete when we're done
6709   // here.
6710   llvm::SmallVector<llvm::ConstantExpr *> CEs;
6711 
6712   // It isn't valid to replace the extern-C ifuncs if all we find is itself!
6713   if (Elem == CppFunc)
6714     return false;
6715 
6716   // First make sure that all users of this are ifuncs (or ifuncs via a
6717   // bitcast), and collect the list of ifuncs and CEs so we can work on them
6718   // later.
6719   for (llvm::User *User : Elem->users()) {
6720     // Users can either be a bitcast ConstExpr that is used by the ifuncs, OR an
6721     // ifunc directly. In any other case, just give up, as we don't know what we
6722     // could break by changing those.
6723     if (auto *ConstExpr = dyn_cast<llvm::ConstantExpr>(User)) {
6724       if (ConstExpr->getOpcode() != llvm::Instruction::BitCast)
6725         return false;
6726 
6727       for (llvm::User *CEUser : ConstExpr->users()) {
6728         if (auto *IFunc = dyn_cast<llvm::GlobalIFunc>(CEUser)) {
6729           IFuncs.push_back(IFunc);
6730         } else {
6731           return false;
6732         }
6733       }
6734       CEs.push_back(ConstExpr);
6735     } else if (auto *IFunc = dyn_cast<llvm::GlobalIFunc>(User)) {
6736       IFuncs.push_back(IFunc);
6737     } else {
6738       // This user is one we don't know how to handle, so fail redirection. This
6739       // will result in an ifunc retaining a resolver name that will ultimately
6740       // fail to be resolved to a defined function.
6741       return false;
6742     }
6743   }
6744 
6745   // Now we know this is a valid case where we can do this alias replacement, we
6746   // need to remove all of the references to Elem (and the bitcasts!) so we can
6747   // delete it.
6748   for (llvm::GlobalIFunc *IFunc : IFuncs)
6749     IFunc->setResolver(nullptr);
6750   for (llvm::ConstantExpr *ConstExpr : CEs)
6751     ConstExpr->destroyConstant();
6752 
6753   // We should now be out of uses for the 'old' version of this function, so we
6754   // can erase it as well.
6755   Elem->eraseFromParent();
6756 
6757   for (llvm::GlobalIFunc *IFunc : IFuncs) {
6758     // The type of the resolver is always just a function-type that returns the
6759     // type of the IFunc, so create that here. If the type of the actual
6760     // resolver doesn't match, it just gets bitcast to the right thing.
6761     auto *ResolverTy =
6762         llvm::FunctionType::get(IFunc->getType(), /*isVarArg*/ false);
6763     llvm::Constant *Resolver = GetOrCreateLLVMFunction(
6764         CppFunc->getName(), ResolverTy, {}, /*ForVTable*/ false);
6765     IFunc->setResolver(Resolver);
6766   }
6767   return true;
6768 }
6769 
6770 /// For each function which is declared within an extern "C" region and marked
6771 /// as 'used', but has internal linkage, create an alias from the unmangled
6772 /// name to the mangled name if possible. People expect to be able to refer
6773 /// to such functions with an unmangled name from inline assembly within the
6774 /// same translation unit.
6775 void CodeGenModule::EmitStaticExternCAliases() {
6776   if (!getTargetCodeGenInfo().shouldEmitStaticExternCAliases())
6777     return;
6778   for (auto &I : StaticExternCValues) {
6779     IdentifierInfo *Name = I.first;
6780     llvm::GlobalValue *Val = I.second;
6781 
6782     // If Val is null, that implies there were multiple declarations that each
6783     // had a claim to the unmangled name. In this case, generation of the alias
6784     // is suppressed. See CodeGenModule::MaybeHandleStaticInExternC.
6785     if (!Val)
6786       break;
6787 
6788     llvm::GlobalValue *ExistingElem =
6789         getModule().getNamedValue(Name->getName());
6790 
6791     // If there is either not something already by this name, or we were able to
6792     // replace all uses from IFuncs, create the alias.
6793     if (!ExistingElem || CheckAndReplaceExternCIFuncs(ExistingElem, Val))
6794       addCompilerUsedGlobal(llvm::GlobalAlias::create(Name->getName(), Val));
6795   }
6796 }
6797 
6798 bool CodeGenModule::lookupRepresentativeDecl(StringRef MangledName,
6799                                              GlobalDecl &Result) const {
6800   auto Res = Manglings.find(MangledName);
6801   if (Res == Manglings.end())
6802     return false;
6803   Result = Res->getValue();
6804   return true;
6805 }
6806 
6807 /// Emits metadata nodes associating all the global values in the
6808 /// current module with the Decls they came from.  This is useful for
6809 /// projects using IR gen as a subroutine.
6810 ///
6811 /// Since there's currently no way to associate an MDNode directly
6812 /// with an llvm::GlobalValue, we create a global named metadata
6813 /// with the name 'clang.global.decl.ptrs'.
6814 void CodeGenModule::EmitDeclMetadata() {
6815   llvm::NamedMDNode *GlobalMetadata = nullptr;
6816 
6817   for (auto &I : MangledDeclNames) {
6818     llvm::GlobalValue *Addr = getModule().getNamedValue(I.second);
6819     // Some mangled names don't necessarily have an associated GlobalValue
6820     // in this module, e.g. if we mangled it for DebugInfo.
6821     if (Addr)
6822       EmitGlobalDeclMetadata(*this, GlobalMetadata, I.first, Addr);
6823   }
6824 }
6825 
6826 /// Emits metadata nodes for all the local variables in the current
6827 /// function.
6828 void CodeGenFunction::EmitDeclMetadata() {
6829   if (LocalDeclMap.empty()) return;
6830 
6831   llvm::LLVMContext &Context = getLLVMContext();
6832 
6833   // Find the unique metadata ID for this name.
6834   unsigned DeclPtrKind = Context.getMDKindID("clang.decl.ptr");
6835 
6836   llvm::NamedMDNode *GlobalMetadata = nullptr;
6837 
6838   for (auto &I : LocalDeclMap) {
6839     const Decl *D = I.first;
6840     llvm::Value *Addr = I.second.getPointer();
6841     if (auto *Alloca = dyn_cast<llvm::AllocaInst>(Addr)) {
6842       llvm::Value *DAddr = GetPointerConstant(getLLVMContext(), D);
6843       Alloca->setMetadata(
6844           DeclPtrKind, llvm::MDNode::get(
6845                            Context, llvm::ValueAsMetadata::getConstant(DAddr)));
6846     } else if (auto *GV = dyn_cast<llvm::GlobalValue>(Addr)) {
6847       GlobalDecl GD = GlobalDecl(cast<VarDecl>(D));
6848       EmitGlobalDeclMetadata(CGM, GlobalMetadata, GD, GV);
6849     }
6850   }
6851 }
6852 
6853 void CodeGenModule::EmitVersionIdentMetadata() {
6854   llvm::NamedMDNode *IdentMetadata =
6855     TheModule.getOrInsertNamedMetadata("llvm.ident");
6856   std::string Version = getClangFullVersion();
6857   llvm::LLVMContext &Ctx = TheModule.getContext();
6858 
6859   llvm::Metadata *IdentNode[] = {llvm::MDString::get(Ctx, Version)};
6860   IdentMetadata->addOperand(llvm::MDNode::get(Ctx, IdentNode));
6861 }
6862 
6863 void CodeGenModule::EmitCommandLineMetadata() {
6864   llvm::NamedMDNode *CommandLineMetadata =
6865     TheModule.getOrInsertNamedMetadata("llvm.commandline");
6866   std::string CommandLine = getCodeGenOpts().RecordCommandLine;
6867   llvm::LLVMContext &Ctx = TheModule.getContext();
6868 
6869   llvm::Metadata *CommandLineNode[] = {llvm::MDString::get(Ctx, CommandLine)};
6870   CommandLineMetadata->addOperand(llvm::MDNode::get(Ctx, CommandLineNode));
6871 }
6872 
6873 void CodeGenModule::EmitCoverageFile() {
6874   if (getCodeGenOpts().CoverageDataFile.empty() &&
6875       getCodeGenOpts().CoverageNotesFile.empty())
6876     return;
6877 
6878   llvm::NamedMDNode *CUNode = TheModule.getNamedMetadata("llvm.dbg.cu");
6879   if (!CUNode)
6880     return;
6881 
6882   llvm::NamedMDNode *GCov = TheModule.getOrInsertNamedMetadata("llvm.gcov");
6883   llvm::LLVMContext &Ctx = TheModule.getContext();
6884   auto *CoverageDataFile =
6885       llvm::MDString::get(Ctx, getCodeGenOpts().CoverageDataFile);
6886   auto *CoverageNotesFile =
6887       llvm::MDString::get(Ctx, getCodeGenOpts().CoverageNotesFile);
6888   for (int i = 0, e = CUNode->getNumOperands(); i != e; ++i) {
6889     llvm::MDNode *CU = CUNode->getOperand(i);
6890     llvm::Metadata *Elts[] = {CoverageNotesFile, CoverageDataFile, CU};
6891     GCov->addOperand(llvm::MDNode::get(Ctx, Elts));
6892   }
6893 }
6894 
6895 llvm::Constant *CodeGenModule::GetAddrOfRTTIDescriptor(QualType Ty,
6896                                                        bool ForEH) {
6897   // Return a bogus pointer if RTTI is disabled, unless it's for EH.
6898   // FIXME: should we even be calling this method if RTTI is disabled
6899   // and it's not for EH?
6900   if ((!ForEH && !getLangOpts().RTTI) || getLangOpts().CUDAIsDevice ||
6901       (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice &&
6902        getTriple().isNVPTX()))
6903     return llvm::Constant::getNullValue(Int8PtrTy);
6904 
6905   if (ForEH && Ty->isObjCObjectPointerType() &&
6906       LangOpts.ObjCRuntime.isGNUFamily())
6907     return ObjCRuntime->GetEHType(Ty);
6908 
6909   return getCXXABI().getAddrOfRTTIDescriptor(Ty);
6910 }
6911 
6912 void CodeGenModule::EmitOMPThreadPrivateDecl(const OMPThreadPrivateDecl *D) {
6913   // Do not emit threadprivates in simd-only mode.
6914   if (LangOpts.OpenMP && LangOpts.OpenMPSimd)
6915     return;
6916   for (auto RefExpr : D->varlists()) {
6917     auto *VD = cast<VarDecl>(cast<DeclRefExpr>(RefExpr)->getDecl());
6918     bool PerformInit =
6919         VD->getAnyInitializer() &&
6920         !VD->getAnyInitializer()->isConstantInitializer(getContext(),
6921                                                         /*ForRef=*/false);
6922 
6923     Address Addr(GetAddrOfGlobalVar(VD),
6924                  getTypes().ConvertTypeForMem(VD->getType()),
6925                  getContext().getDeclAlign(VD));
6926     if (auto InitFunction = getOpenMPRuntime().emitThreadPrivateVarDefinition(
6927             VD, Addr, RefExpr->getBeginLoc(), PerformInit))
6928       CXXGlobalInits.push_back(InitFunction);
6929   }
6930 }
6931 
6932 llvm::Metadata *
6933 CodeGenModule::CreateMetadataIdentifierImpl(QualType T, MetadataTypeMap &Map,
6934                                             StringRef Suffix) {
6935   if (auto *FnType = T->getAs<FunctionProtoType>())
6936     T = getContext().getFunctionType(
6937         FnType->getReturnType(), FnType->getParamTypes(),
6938         FnType->getExtProtoInfo().withExceptionSpec(EST_None));
6939 
6940   llvm::Metadata *&InternalId = Map[T.getCanonicalType()];
6941   if (InternalId)
6942     return InternalId;
6943 
6944   if (isExternallyVisible(T->getLinkage())) {
6945     std::string OutName;
6946     llvm::raw_string_ostream Out(OutName);
6947     getCXXABI().getMangleContext().mangleTypeName(T, Out);
6948     Out << Suffix;
6949 
6950     InternalId = llvm::MDString::get(getLLVMContext(), Out.str());
6951   } else {
6952     InternalId = llvm::MDNode::getDistinct(getLLVMContext(),
6953                                            llvm::ArrayRef<llvm::Metadata *>());
6954   }
6955 
6956   return InternalId;
6957 }
6958 
6959 llvm::Metadata *CodeGenModule::CreateMetadataIdentifierForType(QualType T) {
6960   return CreateMetadataIdentifierImpl(T, MetadataIdMap, "");
6961 }
6962 
6963 llvm::Metadata *
6964 CodeGenModule::CreateMetadataIdentifierForVirtualMemPtrType(QualType T) {
6965   return CreateMetadataIdentifierImpl(T, VirtualMetadataIdMap, ".virtual");
6966 }
6967 
6968 // Generalize pointer types to a void pointer with the qualifiers of the
6969 // originally pointed-to type, e.g. 'const char *' and 'char * const *'
6970 // generalize to 'const void *' while 'char *' and 'const char **' generalize to
6971 // 'void *'.
6972 static QualType GeneralizeType(ASTContext &Ctx, QualType Ty) {
6973   if (!Ty->isPointerType())
6974     return Ty;
6975 
6976   return Ctx.getPointerType(
6977       QualType(Ctx.VoidTy).withCVRQualifiers(
6978           Ty->getPointeeType().getCVRQualifiers()));
6979 }
6980 
6981 // Apply type generalization to a FunctionType's return and argument types
6982 static QualType GeneralizeFunctionType(ASTContext &Ctx, QualType Ty) {
6983   if (auto *FnType = Ty->getAs<FunctionProtoType>()) {
6984     SmallVector<QualType, 8> GeneralizedParams;
6985     for (auto &Param : FnType->param_types())
6986       GeneralizedParams.push_back(GeneralizeType(Ctx, Param));
6987 
6988     return Ctx.getFunctionType(
6989         GeneralizeType(Ctx, FnType->getReturnType()),
6990         GeneralizedParams, FnType->getExtProtoInfo());
6991   }
6992 
6993   if (auto *FnType = Ty->getAs<FunctionNoProtoType>())
6994     return Ctx.getFunctionNoProtoType(
6995         GeneralizeType(Ctx, FnType->getReturnType()));
6996 
6997   llvm_unreachable("Encountered unknown FunctionType");
6998 }
6999 
7000 llvm::Metadata *CodeGenModule::CreateMetadataIdentifierGeneralized(QualType T) {
7001   return CreateMetadataIdentifierImpl(GeneralizeFunctionType(getContext(), T),
7002                                       GeneralizedMetadataIdMap, ".generalized");
7003 }
7004 
7005 /// Returns whether this module needs the "all-vtables" type identifier.
7006 bool CodeGenModule::NeedAllVtablesTypeId() const {
7007   // Returns true if at least one of vtable-based CFI checkers is enabled and
7008   // is not in the trapping mode.
7009   return ((LangOpts.Sanitize.has(SanitizerKind::CFIVCall) &&
7010            !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIVCall)) ||
7011           (LangOpts.Sanitize.has(SanitizerKind::CFINVCall) &&
7012            !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFINVCall)) ||
7013           (LangOpts.Sanitize.has(SanitizerKind::CFIDerivedCast) &&
7014            !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIDerivedCast)) ||
7015           (LangOpts.Sanitize.has(SanitizerKind::CFIUnrelatedCast) &&
7016            !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIUnrelatedCast)));
7017 }
7018 
7019 void CodeGenModule::AddVTableTypeMetadata(llvm::GlobalVariable *VTable,
7020                                           CharUnits Offset,
7021                                           const CXXRecordDecl *RD) {
7022   llvm::Metadata *MD =
7023       CreateMetadataIdentifierForType(QualType(RD->getTypeForDecl(), 0));
7024   VTable->addTypeMetadata(Offset.getQuantity(), MD);
7025 
7026   if (CodeGenOpts.SanitizeCfiCrossDso)
7027     if (auto CrossDsoTypeId = CreateCrossDsoCfiTypeId(MD))
7028       VTable->addTypeMetadata(Offset.getQuantity(),
7029                               llvm::ConstantAsMetadata::get(CrossDsoTypeId));
7030 
7031   if (NeedAllVtablesTypeId()) {
7032     llvm::Metadata *MD = llvm::MDString::get(getLLVMContext(), "all-vtables");
7033     VTable->addTypeMetadata(Offset.getQuantity(), MD);
7034   }
7035 }
7036 
7037 llvm::SanitizerStatReport &CodeGenModule::getSanStats() {
7038   if (!SanStats)
7039     SanStats = std::make_unique<llvm::SanitizerStatReport>(&getModule());
7040 
7041   return *SanStats;
7042 }
7043 
7044 llvm::Value *
7045 CodeGenModule::createOpenCLIntToSamplerConversion(const Expr *E,
7046                                                   CodeGenFunction &CGF) {
7047   llvm::Constant *C = ConstantEmitter(CGF).emitAbstract(E, E->getType());
7048   auto *SamplerT = getOpenCLRuntime().getSamplerType(E->getType().getTypePtr());
7049   auto *FTy = llvm::FunctionType::get(SamplerT, {C->getType()}, false);
7050   auto *Call = CGF.EmitRuntimeCall(
7051       CreateRuntimeFunction(FTy, "__translate_sampler_initializer"), {C});
7052   return Call;
7053 }
7054 
7055 CharUnits CodeGenModule::getNaturalPointeeTypeAlignment(
7056     QualType T, LValueBaseInfo *BaseInfo, TBAAAccessInfo *TBAAInfo) {
7057   return getNaturalTypeAlignment(T->getPointeeType(), BaseInfo, TBAAInfo,
7058                                  /* forPointeeType= */ true);
7059 }
7060 
7061 CharUnits CodeGenModule::getNaturalTypeAlignment(QualType T,
7062                                                  LValueBaseInfo *BaseInfo,
7063                                                  TBAAAccessInfo *TBAAInfo,
7064                                                  bool forPointeeType) {
7065   if (TBAAInfo)
7066     *TBAAInfo = getTBAAAccessInfo(T);
7067 
7068   // FIXME: This duplicates logic in ASTContext::getTypeAlignIfKnown. But
7069   // that doesn't return the information we need to compute BaseInfo.
7070 
7071   // Honor alignment typedef attributes even on incomplete types.
7072   // We also honor them straight for C++ class types, even as pointees;
7073   // there's an expressivity gap here.
7074   if (auto TT = T->getAs<TypedefType>()) {
7075     if (auto Align = TT->getDecl()->getMaxAlignment()) {
7076       if (BaseInfo)
7077         *BaseInfo = LValueBaseInfo(AlignmentSource::AttributedType);
7078       return getContext().toCharUnitsFromBits(Align);
7079     }
7080   }
7081 
7082   bool AlignForArray = T->isArrayType();
7083 
7084   // Analyze the base element type, so we don't get confused by incomplete
7085   // array types.
7086   T = getContext().getBaseElementType(T);
7087 
7088   if (T->isIncompleteType()) {
7089     // We could try to replicate the logic from
7090     // ASTContext::getTypeAlignIfKnown, but nothing uses the alignment if the
7091     // type is incomplete, so it's impossible to test. We could try to reuse
7092     // getTypeAlignIfKnown, but that doesn't return the information we need
7093     // to set BaseInfo.  So just ignore the possibility that the alignment is
7094     // greater than one.
7095     if (BaseInfo)
7096       *BaseInfo = LValueBaseInfo(AlignmentSource::Type);
7097     return CharUnits::One();
7098   }
7099 
7100   if (BaseInfo)
7101     *BaseInfo = LValueBaseInfo(AlignmentSource::Type);
7102 
7103   CharUnits Alignment;
7104   const CXXRecordDecl *RD;
7105   if (T.getQualifiers().hasUnaligned()) {
7106     Alignment = CharUnits::One();
7107   } else if (forPointeeType && !AlignForArray &&
7108              (RD = T->getAsCXXRecordDecl())) {
7109     // For C++ class pointees, we don't know whether we're pointing at a
7110     // base or a complete object, so we generally need to use the
7111     // non-virtual alignment.
7112     Alignment = getClassPointerAlignment(RD);
7113   } else {
7114     Alignment = getContext().getTypeAlignInChars(T);
7115   }
7116 
7117   // Cap to the global maximum type alignment unless the alignment
7118   // was somehow explicit on the type.
7119   if (unsigned MaxAlign = getLangOpts().MaxTypeAlign) {
7120     if (Alignment.getQuantity() > MaxAlign &&
7121         !getContext().isAlignmentRequired(T))
7122       Alignment = CharUnits::fromQuantity(MaxAlign);
7123   }
7124   return Alignment;
7125 }
7126 
7127 bool CodeGenModule::stopAutoInit() {
7128   unsigned StopAfter = getContext().getLangOpts().TrivialAutoVarInitStopAfter;
7129   if (StopAfter) {
7130     // This number is positive only when -ftrivial-auto-var-init-stop-after=* is
7131     // used
7132     if (NumAutoVarInit >= StopAfter) {
7133       return true;
7134     }
7135     if (!NumAutoVarInit) {
7136       unsigned DiagID = getDiags().getCustomDiagID(
7137           DiagnosticsEngine::Warning,
7138           "-ftrivial-auto-var-init-stop-after=%0 has been enabled to limit the "
7139           "number of times ftrivial-auto-var-init=%1 gets applied.");
7140       getDiags().Report(DiagID)
7141           << StopAfter
7142           << (getContext().getLangOpts().getTrivialAutoVarInit() ==
7143                       LangOptions::TrivialAutoVarInitKind::Zero
7144                   ? "zero"
7145                   : "pattern");
7146     }
7147     ++NumAutoVarInit;
7148   }
7149   return false;
7150 }
7151 
7152 void CodeGenModule::printPostfixForExternalizedDecl(llvm::raw_ostream &OS,
7153                                                     const Decl *D) const {
7154   // ptxas does not allow '.' in symbol names. On the other hand, HIP prefers
7155   // postfix beginning with '.' since the symbol name can be demangled.
7156   if (LangOpts.HIP)
7157     OS << (isa<VarDecl>(D) ? ".static." : ".intern.");
7158   else
7159     OS << (isa<VarDecl>(D) ? "__static__" : "__intern__");
7160 
7161   // If the CUID is not specified we try to generate a unique postfix.
7162   if (getLangOpts().CUID.empty()) {
7163     SourceManager &SM = getContext().getSourceManager();
7164     PresumedLoc PLoc = SM.getPresumedLoc(D->getLocation());
7165     assert(PLoc.isValid() && "Source location is expected to be valid.");
7166 
7167     // Get the hash of the user defined macros.
7168     llvm::MD5 Hash;
7169     llvm::MD5::MD5Result Result;
7170     for (const auto &Arg : PreprocessorOpts.Macros)
7171       Hash.update(Arg.first);
7172     Hash.final(Result);
7173 
7174     // Get the UniqueID for the file containing the decl.
7175     llvm::sys::fs::UniqueID ID;
7176     if (auto EC = llvm::sys::fs::getUniqueID(PLoc.getFilename(), ID)) {
7177       PLoc = SM.getPresumedLoc(D->getLocation(), /*UseLineDirectives=*/false);
7178       assert(PLoc.isValid() && "Source location is expected to be valid.");
7179       if (auto EC = llvm::sys::fs::getUniqueID(PLoc.getFilename(), ID))
7180         SM.getDiagnostics().Report(diag::err_cannot_open_file)
7181             << PLoc.getFilename() << EC.message();
7182     }
7183     OS << llvm::format("%x", ID.getFile()) << llvm::format("%x", ID.getDevice())
7184        << "_" << llvm::utohexstr(Result.low(), /*LowerCase=*/true, /*Width=*/8);
7185   } else {
7186     OS << getContext().getCUIDHash();
7187   }
7188 }
7189 
7190 void CodeGenModule::moveLazyEmissionStates(CodeGenModule *NewBuilder) {
7191   assert(DeferredDeclsToEmit.empty() &&
7192          "Should have emitted all decls deferred to emit.");
7193   assert(NewBuilder->DeferredDecls.empty() &&
7194          "Newly created module should not have deferred decls");
7195   NewBuilder->DeferredDecls = std::move(DeferredDecls);
7196 
7197   assert(NewBuilder->DeferredVTables.empty() &&
7198          "Newly created module should not have deferred vtables");
7199   NewBuilder->DeferredVTables = std::move(DeferredVTables);
7200 
7201   assert(NewBuilder->MangledDeclNames.empty() &&
7202          "Newly created module should not have mangled decl names");
7203   assert(NewBuilder->Manglings.empty() &&
7204          "Newly created module should not have manglings");
7205   NewBuilder->Manglings = std::move(Manglings);
7206 
7207   assert(WeakRefReferences.empty() && "Not all WeakRefRefs have been applied");
7208   NewBuilder->WeakRefReferences = std::move(WeakRefReferences);
7209 
7210   NewBuilder->TBAA = std::move(TBAA);
7211 
7212   assert(NewBuilder->EmittedDeferredDecls.empty() &&
7213          "Still have (unmerged) EmittedDeferredDecls deferred decls");
7214 
7215   NewBuilder->EmittedDeferredDecls = std::move(EmittedDeferredDecls);
7216 
7217   NewBuilder->ABI->MangleCtx = std::move(ABI->MangleCtx);
7218 }
7219