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