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