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