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