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