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