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