xref: /llvm-project/clang/lib/CodeGen/CodeGenModule.cpp (revision 74b56e02bda09ae735c6aeca583a2078375f2da1)
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 const GlobalDecl CodeGenModule::getMangledNameDecl(StringRef Name) {
1506   auto it = MangledDeclNames.begin();
1507   while (it != MangledDeclNames.end()) {
1508     if (it->second == Name)
1509       return it->first;
1510     it++;
1511   }
1512   return GlobalDecl();
1513 }
1514 
1515 llvm::GlobalValue *CodeGenModule::GetGlobalValue(StringRef Name) {
1516   return getModule().getNamedValue(Name);
1517 }
1518 
1519 /// AddGlobalCtor - Add a function to the list that will be called before
1520 /// main() runs.
1521 void CodeGenModule::AddGlobalCtor(llvm::Function *Ctor, int Priority,
1522                                   llvm::Constant *AssociatedData) {
1523   // FIXME: Type coercion of void()* types.
1524   GlobalCtors.push_back(Structor(Priority, Ctor, AssociatedData));
1525 }
1526 
1527 /// AddGlobalDtor - Add a function to the list that will be called
1528 /// when the module is unloaded.
1529 void CodeGenModule::AddGlobalDtor(llvm::Function *Dtor, int Priority,
1530                                   bool IsDtorAttrFunc) {
1531   if (CodeGenOpts.RegisterGlobalDtorsWithAtExit &&
1532       (!getContext().getTargetInfo().getTriple().isOSAIX() || IsDtorAttrFunc)) {
1533     DtorsUsingAtExit[Priority].push_back(Dtor);
1534     return;
1535   }
1536 
1537   // FIXME: Type coercion of void()* types.
1538   GlobalDtors.push_back(Structor(Priority, Dtor, nullptr));
1539 }
1540 
1541 void CodeGenModule::EmitCtorList(CtorList &Fns, const char *GlobalName) {
1542   if (Fns.empty()) return;
1543 
1544   // Ctor function type is void()*.
1545   llvm::FunctionType* CtorFTy = llvm::FunctionType::get(VoidTy, false);
1546   llvm::Type *CtorPFTy = llvm::PointerType::get(CtorFTy,
1547       TheModule.getDataLayout().getProgramAddressSpace());
1548 
1549   // Get the type of a ctor entry, { i32, void ()*, i8* }.
1550   llvm::StructType *CtorStructTy = llvm::StructType::get(
1551       Int32Ty, CtorPFTy, VoidPtrTy);
1552 
1553   // Construct the constructor and destructor arrays.
1554   ConstantInitBuilder builder(*this);
1555   auto ctors = builder.beginArray(CtorStructTy);
1556   for (const auto &I : Fns) {
1557     auto ctor = ctors.beginStruct(CtorStructTy);
1558     ctor.addInt(Int32Ty, I.Priority);
1559     ctor.add(llvm::ConstantExpr::getBitCast(I.Initializer, CtorPFTy));
1560     if (I.AssociatedData)
1561       ctor.add(llvm::ConstantExpr::getBitCast(I.AssociatedData, VoidPtrTy));
1562     else
1563       ctor.addNullPointer(VoidPtrTy);
1564     ctor.finishAndAddTo(ctors);
1565   }
1566 
1567   auto list =
1568     ctors.finishAndCreateGlobal(GlobalName, getPointerAlign(),
1569                                 /*constant*/ false,
1570                                 llvm::GlobalValue::AppendingLinkage);
1571 
1572   // The LTO linker doesn't seem to like it when we set an alignment
1573   // on appending variables.  Take it off as a workaround.
1574   list->setAlignment(llvm::None);
1575 
1576   Fns.clear();
1577 }
1578 
1579 llvm::GlobalValue::LinkageTypes
1580 CodeGenModule::getFunctionLinkage(GlobalDecl GD) {
1581   const auto *D = cast<FunctionDecl>(GD.getDecl());
1582 
1583   GVALinkage Linkage = getContext().GetGVALinkageForFunction(D);
1584 
1585   if (const auto *Dtor = dyn_cast<CXXDestructorDecl>(D))
1586     return getCXXABI().getCXXDestructorLinkage(Linkage, Dtor, GD.getDtorType());
1587 
1588   if (isa<CXXConstructorDecl>(D) &&
1589       cast<CXXConstructorDecl>(D)->isInheritingConstructor() &&
1590       Context.getTargetInfo().getCXXABI().isMicrosoft()) {
1591     // Our approach to inheriting constructors is fundamentally different from
1592     // that used by the MS ABI, so keep our inheriting constructor thunks
1593     // internal rather than trying to pick an unambiguous mangling for them.
1594     return llvm::GlobalValue::InternalLinkage;
1595   }
1596 
1597   return getLLVMLinkageForDeclarator(D, Linkage, /*IsConstantVariable=*/false);
1598 }
1599 
1600 llvm::ConstantInt *CodeGenModule::CreateCrossDsoCfiTypeId(llvm::Metadata *MD) {
1601   llvm::MDString *MDS = dyn_cast<llvm::MDString>(MD);
1602   if (!MDS) return nullptr;
1603 
1604   return llvm::ConstantInt::get(Int64Ty, llvm::MD5Hash(MDS->getString()));
1605 }
1606 
1607 void CodeGenModule::SetLLVMFunctionAttributes(GlobalDecl GD,
1608                                               const CGFunctionInfo &Info,
1609                                               llvm::Function *F, bool IsThunk) {
1610   unsigned CallingConv;
1611   llvm::AttributeList PAL;
1612   ConstructAttributeList(F->getName(), Info, GD, PAL, CallingConv,
1613                          /*AttrOnCallSite=*/false, IsThunk);
1614   F->setAttributes(PAL);
1615   F->setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv));
1616 }
1617 
1618 static void removeImageAccessQualifier(std::string& TyName) {
1619   std::string ReadOnlyQual("__read_only");
1620   std::string::size_type ReadOnlyPos = TyName.find(ReadOnlyQual);
1621   if (ReadOnlyPos != std::string::npos)
1622     // "+ 1" for the space after access qualifier.
1623     TyName.erase(ReadOnlyPos, ReadOnlyQual.size() + 1);
1624   else {
1625     std::string WriteOnlyQual("__write_only");
1626     std::string::size_type WriteOnlyPos = TyName.find(WriteOnlyQual);
1627     if (WriteOnlyPos != std::string::npos)
1628       TyName.erase(WriteOnlyPos, WriteOnlyQual.size() + 1);
1629     else {
1630       std::string ReadWriteQual("__read_write");
1631       std::string::size_type ReadWritePos = TyName.find(ReadWriteQual);
1632       if (ReadWritePos != std::string::npos)
1633         TyName.erase(ReadWritePos, ReadWriteQual.size() + 1);
1634     }
1635   }
1636 }
1637 
1638 // Returns the address space id that should be produced to the
1639 // kernel_arg_addr_space metadata. This is always fixed to the ids
1640 // as specified in the SPIR 2.0 specification in order to differentiate
1641 // for example in clGetKernelArgInfo() implementation between the address
1642 // spaces with targets without unique mapping to the OpenCL address spaces
1643 // (basically all single AS CPUs).
1644 static unsigned ArgInfoAddressSpace(LangAS AS) {
1645   switch (AS) {
1646   case LangAS::opencl_global:
1647     return 1;
1648   case LangAS::opencl_constant:
1649     return 2;
1650   case LangAS::opencl_local:
1651     return 3;
1652   case LangAS::opencl_generic:
1653     return 4; // Not in SPIR 2.0 specs.
1654   case LangAS::opencl_global_device:
1655     return 5;
1656   case LangAS::opencl_global_host:
1657     return 6;
1658   default:
1659     return 0; // Assume private.
1660   }
1661 }
1662 
1663 void CodeGenModule::GenOpenCLArgMetadata(llvm::Function *Fn,
1664                                          const FunctionDecl *FD,
1665                                          CodeGenFunction *CGF) {
1666   assert(((FD && CGF) || (!FD && !CGF)) &&
1667          "Incorrect use - FD and CGF should either be both null or not!");
1668   // Create MDNodes that represent the kernel arg metadata.
1669   // Each MDNode is a list in the form of "key", N number of values which is
1670   // the same number of values as their are kernel arguments.
1671 
1672   const PrintingPolicy &Policy = Context.getPrintingPolicy();
1673 
1674   // MDNode for the kernel argument address space qualifiers.
1675   SmallVector<llvm::Metadata *, 8> addressQuals;
1676 
1677   // MDNode for the kernel argument access qualifiers (images only).
1678   SmallVector<llvm::Metadata *, 8> accessQuals;
1679 
1680   // MDNode for the kernel argument type names.
1681   SmallVector<llvm::Metadata *, 8> argTypeNames;
1682 
1683   // MDNode for the kernel argument base type names.
1684   SmallVector<llvm::Metadata *, 8> argBaseTypeNames;
1685 
1686   // MDNode for the kernel argument type qualifiers.
1687   SmallVector<llvm::Metadata *, 8> argTypeQuals;
1688 
1689   // MDNode for the kernel argument names.
1690   SmallVector<llvm::Metadata *, 8> argNames;
1691 
1692   if (FD && CGF)
1693     for (unsigned i = 0, e = FD->getNumParams(); i != e; ++i) {
1694       const ParmVarDecl *parm = FD->getParamDecl(i);
1695       QualType ty = parm->getType();
1696       std::string typeQuals;
1697 
1698       // Get image and pipe access qualifier:
1699       if (ty->isImageType() || ty->isPipeType()) {
1700         const Decl *PDecl = parm;
1701         if (auto *TD = dyn_cast<TypedefType>(ty))
1702           PDecl = TD->getDecl();
1703         const OpenCLAccessAttr *A = PDecl->getAttr<OpenCLAccessAttr>();
1704         if (A && A->isWriteOnly())
1705           accessQuals.push_back(llvm::MDString::get(VMContext, "write_only"));
1706         else if (A && A->isReadWrite())
1707           accessQuals.push_back(llvm::MDString::get(VMContext, "read_write"));
1708         else
1709           accessQuals.push_back(llvm::MDString::get(VMContext, "read_only"));
1710       } else
1711         accessQuals.push_back(llvm::MDString::get(VMContext, "none"));
1712 
1713       // Get argument name.
1714       argNames.push_back(llvm::MDString::get(VMContext, parm->getName()));
1715 
1716       auto getTypeSpelling = [&](QualType Ty) {
1717         auto typeName = Ty.getUnqualifiedType().getAsString(Policy);
1718 
1719         if (Ty.isCanonical()) {
1720           StringRef typeNameRef = typeName;
1721           // Turn "unsigned type" to "utype"
1722           if (typeNameRef.consume_front("unsigned "))
1723             return std::string("u") + typeNameRef.str();
1724           if (typeNameRef.consume_front("signed "))
1725             return typeNameRef.str();
1726         }
1727 
1728         return typeName;
1729       };
1730 
1731       if (ty->isPointerType()) {
1732         QualType pointeeTy = ty->getPointeeType();
1733 
1734         // Get address qualifier.
1735         addressQuals.push_back(
1736             llvm::ConstantAsMetadata::get(CGF->Builder.getInt32(
1737                 ArgInfoAddressSpace(pointeeTy.getAddressSpace()))));
1738 
1739         // Get argument type name.
1740         std::string typeName = getTypeSpelling(pointeeTy) + "*";
1741         std::string baseTypeName =
1742             getTypeSpelling(pointeeTy.getCanonicalType()) + "*";
1743         argTypeNames.push_back(llvm::MDString::get(VMContext, typeName));
1744         argBaseTypeNames.push_back(
1745             llvm::MDString::get(VMContext, baseTypeName));
1746 
1747         // Get argument type qualifiers:
1748         if (ty.isRestrictQualified())
1749           typeQuals = "restrict";
1750         if (pointeeTy.isConstQualified() ||
1751             (pointeeTy.getAddressSpace() == LangAS::opencl_constant))
1752           typeQuals += typeQuals.empty() ? "const" : " const";
1753         if (pointeeTy.isVolatileQualified())
1754           typeQuals += typeQuals.empty() ? "volatile" : " volatile";
1755       } else {
1756         uint32_t AddrSpc = 0;
1757         bool isPipe = ty->isPipeType();
1758         if (ty->isImageType() || isPipe)
1759           AddrSpc = ArgInfoAddressSpace(LangAS::opencl_global);
1760 
1761         addressQuals.push_back(
1762             llvm::ConstantAsMetadata::get(CGF->Builder.getInt32(AddrSpc)));
1763 
1764         // Get argument type name.
1765         ty = isPipe ? ty->castAs<PipeType>()->getElementType() : ty;
1766         std::string typeName = getTypeSpelling(ty);
1767         std::string baseTypeName = getTypeSpelling(ty.getCanonicalType());
1768 
1769         // Remove access qualifiers on images
1770         // (as they are inseparable from type in clang implementation,
1771         // but OpenCL spec provides a special query to get access qualifier
1772         // via clGetKernelArgInfo with CL_KERNEL_ARG_ACCESS_QUALIFIER):
1773         if (ty->isImageType()) {
1774           removeImageAccessQualifier(typeName);
1775           removeImageAccessQualifier(baseTypeName);
1776         }
1777 
1778         argTypeNames.push_back(llvm::MDString::get(VMContext, typeName));
1779         argBaseTypeNames.push_back(
1780             llvm::MDString::get(VMContext, baseTypeName));
1781 
1782         if (isPipe)
1783           typeQuals = "pipe";
1784       }
1785       argTypeQuals.push_back(llvm::MDString::get(VMContext, typeQuals));
1786     }
1787 
1788   Fn->setMetadata("kernel_arg_addr_space",
1789                   llvm::MDNode::get(VMContext, addressQuals));
1790   Fn->setMetadata("kernel_arg_access_qual",
1791                   llvm::MDNode::get(VMContext, accessQuals));
1792   Fn->setMetadata("kernel_arg_type",
1793                   llvm::MDNode::get(VMContext, argTypeNames));
1794   Fn->setMetadata("kernel_arg_base_type",
1795                   llvm::MDNode::get(VMContext, argBaseTypeNames));
1796   Fn->setMetadata("kernel_arg_type_qual",
1797                   llvm::MDNode::get(VMContext, argTypeQuals));
1798   if (getCodeGenOpts().EmitOpenCLArgMetadata)
1799     Fn->setMetadata("kernel_arg_name",
1800                     llvm::MDNode::get(VMContext, argNames));
1801 }
1802 
1803 /// Determines whether the language options require us to model
1804 /// unwind exceptions.  We treat -fexceptions as mandating this
1805 /// except under the fragile ObjC ABI with only ObjC exceptions
1806 /// enabled.  This means, for example, that C with -fexceptions
1807 /// enables this.
1808 static bool hasUnwindExceptions(const LangOptions &LangOpts) {
1809   // If exceptions are completely disabled, obviously this is false.
1810   if (!LangOpts.Exceptions) return false;
1811 
1812   // If C++ exceptions are enabled, this is true.
1813   if (LangOpts.CXXExceptions) return true;
1814 
1815   // If ObjC exceptions are enabled, this depends on the ABI.
1816   if (LangOpts.ObjCExceptions) {
1817     return LangOpts.ObjCRuntime.hasUnwindExceptions();
1818   }
1819 
1820   return true;
1821 }
1822 
1823 static bool requiresMemberFunctionPointerTypeMetadata(CodeGenModule &CGM,
1824                                                       const CXXMethodDecl *MD) {
1825   // Check that the type metadata can ever actually be used by a call.
1826   if (!CGM.getCodeGenOpts().LTOUnit ||
1827       !CGM.HasHiddenLTOVisibility(MD->getParent()))
1828     return false;
1829 
1830   // Only functions whose address can be taken with a member function pointer
1831   // need this sort of type metadata.
1832   return !MD->isStatic() && !MD->isVirtual() && !isa<CXXConstructorDecl>(MD) &&
1833          !isa<CXXDestructorDecl>(MD);
1834 }
1835 
1836 std::vector<const CXXRecordDecl *>
1837 CodeGenModule::getMostBaseClasses(const CXXRecordDecl *RD) {
1838   llvm::SetVector<const CXXRecordDecl *> MostBases;
1839 
1840   std::function<void (const CXXRecordDecl *)> CollectMostBases;
1841   CollectMostBases = [&](const CXXRecordDecl *RD) {
1842     if (RD->getNumBases() == 0)
1843       MostBases.insert(RD);
1844     for (const CXXBaseSpecifier &B : RD->bases())
1845       CollectMostBases(B.getType()->getAsCXXRecordDecl());
1846   };
1847   CollectMostBases(RD);
1848   return MostBases.takeVector();
1849 }
1850 
1851 void CodeGenModule::SetLLVMFunctionAttributesForDefinition(const Decl *D,
1852                                                            llvm::Function *F) {
1853   llvm::AttrBuilder B(F->getContext());
1854 
1855   if (CodeGenOpts.UnwindTables)
1856     B.addUWTableAttr(llvm::UWTableKind(CodeGenOpts.UnwindTables));
1857 
1858   if (CodeGenOpts.StackClashProtector)
1859     B.addAttribute("probe-stack", "inline-asm");
1860 
1861   if (!hasUnwindExceptions(LangOpts))
1862     B.addAttribute(llvm::Attribute::NoUnwind);
1863 
1864   if (!D || !D->hasAttr<NoStackProtectorAttr>()) {
1865     if (LangOpts.getStackProtector() == LangOptions::SSPOn)
1866       B.addAttribute(llvm::Attribute::StackProtect);
1867     else if (LangOpts.getStackProtector() == LangOptions::SSPStrong)
1868       B.addAttribute(llvm::Attribute::StackProtectStrong);
1869     else if (LangOpts.getStackProtector() == LangOptions::SSPReq)
1870       B.addAttribute(llvm::Attribute::StackProtectReq);
1871   }
1872 
1873   if (!D) {
1874     // If we don't have a declaration to control inlining, the function isn't
1875     // explicitly marked as alwaysinline for semantic reasons, and inlining is
1876     // disabled, mark the function as noinline.
1877     if (!F->hasFnAttribute(llvm::Attribute::AlwaysInline) &&
1878         CodeGenOpts.getInlining() == CodeGenOptions::OnlyAlwaysInlining)
1879       B.addAttribute(llvm::Attribute::NoInline);
1880 
1881     F->addFnAttrs(B);
1882     return;
1883   }
1884 
1885   // Track whether we need to add the optnone LLVM attribute,
1886   // starting with the default for this optimization level.
1887   bool ShouldAddOptNone =
1888       !CodeGenOpts.DisableO0ImplyOptNone && CodeGenOpts.OptimizationLevel == 0;
1889   // We can't add optnone in the following cases, it won't pass the verifier.
1890   ShouldAddOptNone &= !D->hasAttr<MinSizeAttr>();
1891   ShouldAddOptNone &= !D->hasAttr<AlwaysInlineAttr>();
1892 
1893   // Add optnone, but do so only if the function isn't always_inline.
1894   if ((ShouldAddOptNone || D->hasAttr<OptimizeNoneAttr>()) &&
1895       !F->hasFnAttribute(llvm::Attribute::AlwaysInline)) {
1896     B.addAttribute(llvm::Attribute::OptimizeNone);
1897 
1898     // OptimizeNone implies noinline; we should not be inlining such functions.
1899     B.addAttribute(llvm::Attribute::NoInline);
1900 
1901     // We still need to handle naked functions even though optnone subsumes
1902     // much of their semantics.
1903     if (D->hasAttr<NakedAttr>())
1904       B.addAttribute(llvm::Attribute::Naked);
1905 
1906     // OptimizeNone wins over OptimizeForSize and MinSize.
1907     F->removeFnAttr(llvm::Attribute::OptimizeForSize);
1908     F->removeFnAttr(llvm::Attribute::MinSize);
1909   } else if (D->hasAttr<NakedAttr>()) {
1910     // Naked implies noinline: we should not be inlining such functions.
1911     B.addAttribute(llvm::Attribute::Naked);
1912     B.addAttribute(llvm::Attribute::NoInline);
1913   } else if (D->hasAttr<NoDuplicateAttr>()) {
1914     B.addAttribute(llvm::Attribute::NoDuplicate);
1915   } else if (D->hasAttr<NoInlineAttr>() && !F->hasFnAttribute(llvm::Attribute::AlwaysInline)) {
1916     // Add noinline if the function isn't always_inline.
1917     B.addAttribute(llvm::Attribute::NoInline);
1918   } else if (D->hasAttr<AlwaysInlineAttr>() &&
1919              !F->hasFnAttribute(llvm::Attribute::NoInline)) {
1920     // (noinline wins over always_inline, and we can't specify both in IR)
1921     B.addAttribute(llvm::Attribute::AlwaysInline);
1922   } else if (CodeGenOpts.getInlining() == CodeGenOptions::OnlyAlwaysInlining) {
1923     // If we're not inlining, then force everything that isn't always_inline to
1924     // carry an explicit noinline attribute.
1925     if (!F->hasFnAttribute(llvm::Attribute::AlwaysInline))
1926       B.addAttribute(llvm::Attribute::NoInline);
1927   } else {
1928     // Otherwise, propagate the inline hint attribute and potentially use its
1929     // absence to mark things as noinline.
1930     if (auto *FD = dyn_cast<FunctionDecl>(D)) {
1931       // Search function and template pattern redeclarations for inline.
1932       auto CheckForInline = [](const FunctionDecl *FD) {
1933         auto CheckRedeclForInline = [](const FunctionDecl *Redecl) {
1934           return Redecl->isInlineSpecified();
1935         };
1936         if (any_of(FD->redecls(), CheckRedeclForInline))
1937           return true;
1938         const FunctionDecl *Pattern = FD->getTemplateInstantiationPattern();
1939         if (!Pattern)
1940           return false;
1941         return any_of(Pattern->redecls(), CheckRedeclForInline);
1942       };
1943       if (CheckForInline(FD)) {
1944         B.addAttribute(llvm::Attribute::InlineHint);
1945       } else if (CodeGenOpts.getInlining() ==
1946                      CodeGenOptions::OnlyHintInlining &&
1947                  !FD->isInlined() &&
1948                  !F->hasFnAttribute(llvm::Attribute::AlwaysInline)) {
1949         B.addAttribute(llvm::Attribute::NoInline);
1950       }
1951     }
1952   }
1953 
1954   // Add other optimization related attributes if we are optimizing this
1955   // function.
1956   if (!D->hasAttr<OptimizeNoneAttr>()) {
1957     if (D->hasAttr<ColdAttr>()) {
1958       if (!ShouldAddOptNone)
1959         B.addAttribute(llvm::Attribute::OptimizeForSize);
1960       B.addAttribute(llvm::Attribute::Cold);
1961     }
1962     if (D->hasAttr<HotAttr>())
1963       B.addAttribute(llvm::Attribute::Hot);
1964     if (D->hasAttr<MinSizeAttr>())
1965       B.addAttribute(llvm::Attribute::MinSize);
1966   }
1967 
1968   F->addFnAttrs(B);
1969 
1970   unsigned alignment = D->getMaxAlignment() / Context.getCharWidth();
1971   if (alignment)
1972     F->setAlignment(llvm::Align(alignment));
1973 
1974   if (!D->hasAttr<AlignedAttr>())
1975     if (LangOpts.FunctionAlignment)
1976       F->setAlignment(llvm::Align(1ull << LangOpts.FunctionAlignment));
1977 
1978   // Some C++ ABIs require 2-byte alignment for member functions, in order to
1979   // reserve a bit for differentiating between virtual and non-virtual member
1980   // functions. If the current target's C++ ABI requires this and this is a
1981   // member function, set its alignment accordingly.
1982   if (getTarget().getCXXABI().areMemberFunctionsAligned()) {
1983     if (F->getAlignment() < 2 && isa<CXXMethodDecl>(D))
1984       F->setAlignment(llvm::Align(2));
1985   }
1986 
1987   // In the cross-dso CFI mode with canonical jump tables, we want !type
1988   // attributes on definitions only.
1989   if (CodeGenOpts.SanitizeCfiCrossDso &&
1990       CodeGenOpts.SanitizeCfiCanonicalJumpTables) {
1991     if (auto *FD = dyn_cast<FunctionDecl>(D)) {
1992       // Skip available_externally functions. They won't be codegen'ed in the
1993       // current module anyway.
1994       if (getContext().GetGVALinkageForFunction(FD) != GVA_AvailableExternally)
1995         CreateFunctionTypeMetadataForIcall(FD, F);
1996     }
1997   }
1998 
1999   // Emit type metadata on member functions for member function pointer checks.
2000   // These are only ever necessary on definitions; we're guaranteed that the
2001   // definition will be present in the LTO unit as a result of LTO visibility.
2002   auto *MD = dyn_cast<CXXMethodDecl>(D);
2003   if (MD && requiresMemberFunctionPointerTypeMetadata(*this, MD)) {
2004     for (const CXXRecordDecl *Base : getMostBaseClasses(MD->getParent())) {
2005       llvm::Metadata *Id =
2006           CreateMetadataIdentifierForType(Context.getMemberPointerType(
2007               MD->getType(), Context.getRecordType(Base).getTypePtr()));
2008       F->addTypeMetadata(0, Id);
2009     }
2010   }
2011 }
2012 
2013 void CodeGenModule::setLLVMFunctionFEnvAttributes(const FunctionDecl *D,
2014                                                   llvm::Function *F) {
2015   if (D->hasAttr<StrictFPAttr>()) {
2016     llvm::AttrBuilder FuncAttrs(F->getContext());
2017     FuncAttrs.addAttribute("strictfp");
2018     F->addFnAttrs(FuncAttrs);
2019   }
2020 }
2021 
2022 void CodeGenModule::SetCommonAttributes(GlobalDecl GD, llvm::GlobalValue *GV) {
2023   const Decl *D = GD.getDecl();
2024   if (isa_and_nonnull<NamedDecl>(D))
2025     setGVProperties(GV, GD);
2026   else
2027     GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
2028 
2029   if (D && D->hasAttr<UsedAttr>())
2030     addUsedOrCompilerUsedGlobal(GV);
2031 
2032   if (CodeGenOpts.KeepStaticConsts && D && isa<VarDecl>(D)) {
2033     const auto *VD = cast<VarDecl>(D);
2034     if (VD->getType().isConstQualified() &&
2035         VD->getStorageDuration() == SD_Static)
2036       addUsedOrCompilerUsedGlobal(GV);
2037   }
2038 }
2039 
2040 bool CodeGenModule::GetCPUAndFeaturesAttributes(GlobalDecl GD,
2041                                                 llvm::AttrBuilder &Attrs) {
2042   // Add target-cpu and target-features attributes to functions. If
2043   // we have a decl for the function and it has a target attribute then
2044   // parse that and add it to the feature set.
2045   StringRef TargetCPU = getTarget().getTargetOpts().CPU;
2046   StringRef TuneCPU = getTarget().getTargetOpts().TuneCPU;
2047   std::vector<std::string> Features;
2048   const auto *FD = dyn_cast_or_null<FunctionDecl>(GD.getDecl());
2049   FD = FD ? FD->getMostRecentDecl() : FD;
2050   const auto *TD = FD ? FD->getAttr<TargetAttr>() : nullptr;
2051   const auto *SD = FD ? FD->getAttr<CPUSpecificAttr>() : nullptr;
2052   const auto *TC = FD ? FD->getAttr<TargetClonesAttr>() : nullptr;
2053   bool AddedAttr = false;
2054   if (TD || SD || TC) {
2055     llvm::StringMap<bool> FeatureMap;
2056     getContext().getFunctionFeatureMap(FeatureMap, GD);
2057 
2058     // Produce the canonical string for this set of features.
2059     for (const llvm::StringMap<bool>::value_type &Entry : FeatureMap)
2060       Features.push_back((Entry.getValue() ? "+" : "-") + Entry.getKey().str());
2061 
2062     // Now add the target-cpu and target-features to the function.
2063     // While we populated the feature map above, we still need to
2064     // get and parse the target attribute so we can get the cpu for
2065     // the function.
2066     if (TD) {
2067       ParsedTargetAttr ParsedAttr = TD->parse();
2068       if (!ParsedAttr.Architecture.empty() &&
2069           getTarget().isValidCPUName(ParsedAttr.Architecture)) {
2070         TargetCPU = ParsedAttr.Architecture;
2071         TuneCPU = ""; // Clear the tune CPU.
2072       }
2073       if (!ParsedAttr.Tune.empty() &&
2074           getTarget().isValidCPUName(ParsedAttr.Tune))
2075         TuneCPU = ParsedAttr.Tune;
2076     }
2077 
2078     if (SD) {
2079       // Apply the given CPU name as the 'tune-cpu' so that the optimizer can
2080       // favor this processor.
2081       TuneCPU = getTarget().getCPUSpecificTuneName(
2082           SD->getCPUName(GD.getMultiVersionIndex())->getName());
2083     }
2084   } else {
2085     // Otherwise just add the existing target cpu and target features to the
2086     // function.
2087     Features = getTarget().getTargetOpts().Features;
2088   }
2089 
2090   if (!TargetCPU.empty()) {
2091     Attrs.addAttribute("target-cpu", TargetCPU);
2092     AddedAttr = true;
2093   }
2094   if (!TuneCPU.empty()) {
2095     Attrs.addAttribute("tune-cpu", TuneCPU);
2096     AddedAttr = true;
2097   }
2098   if (!Features.empty()) {
2099     llvm::sort(Features);
2100     Attrs.addAttribute("target-features", llvm::join(Features, ","));
2101     AddedAttr = true;
2102   }
2103 
2104   return AddedAttr;
2105 }
2106 
2107 void CodeGenModule::setNonAliasAttributes(GlobalDecl GD,
2108                                           llvm::GlobalObject *GO) {
2109   const Decl *D = GD.getDecl();
2110   SetCommonAttributes(GD, GO);
2111 
2112   if (D) {
2113     if (auto *GV = dyn_cast<llvm::GlobalVariable>(GO)) {
2114       if (D->hasAttr<RetainAttr>())
2115         addUsedGlobal(GV);
2116       if (auto *SA = D->getAttr<PragmaClangBSSSectionAttr>())
2117         GV->addAttribute("bss-section", SA->getName());
2118       if (auto *SA = D->getAttr<PragmaClangDataSectionAttr>())
2119         GV->addAttribute("data-section", SA->getName());
2120       if (auto *SA = D->getAttr<PragmaClangRodataSectionAttr>())
2121         GV->addAttribute("rodata-section", SA->getName());
2122       if (auto *SA = D->getAttr<PragmaClangRelroSectionAttr>())
2123         GV->addAttribute("relro-section", SA->getName());
2124     }
2125 
2126     if (auto *F = dyn_cast<llvm::Function>(GO)) {
2127       if (D->hasAttr<RetainAttr>())
2128         addUsedGlobal(F);
2129       if (auto *SA = D->getAttr<PragmaClangTextSectionAttr>())
2130         if (!D->getAttr<SectionAttr>())
2131           F->addFnAttr("implicit-section-name", SA->getName());
2132 
2133       llvm::AttrBuilder Attrs(F->getContext());
2134       if (GetCPUAndFeaturesAttributes(GD, Attrs)) {
2135         // We know that GetCPUAndFeaturesAttributes will always have the
2136         // newest set, since it has the newest possible FunctionDecl, so the
2137         // new ones should replace the old.
2138         llvm::AttributeMask RemoveAttrs;
2139         RemoveAttrs.addAttribute("target-cpu");
2140         RemoveAttrs.addAttribute("target-features");
2141         RemoveAttrs.addAttribute("tune-cpu");
2142         F->removeFnAttrs(RemoveAttrs);
2143         F->addFnAttrs(Attrs);
2144       }
2145     }
2146 
2147     if (const auto *CSA = D->getAttr<CodeSegAttr>())
2148       GO->setSection(CSA->getName());
2149     else if (const auto *SA = D->getAttr<SectionAttr>())
2150       GO->setSection(SA->getName());
2151   }
2152 
2153   getTargetCodeGenInfo().setTargetAttributes(D, GO, *this);
2154 }
2155 
2156 void CodeGenModule::SetInternalFunctionAttributes(GlobalDecl GD,
2157                                                   llvm::Function *F,
2158                                                   const CGFunctionInfo &FI) {
2159   const Decl *D = GD.getDecl();
2160   SetLLVMFunctionAttributes(GD, FI, F, /*IsThunk=*/false);
2161   SetLLVMFunctionAttributesForDefinition(D, F);
2162 
2163   F->setLinkage(llvm::Function::InternalLinkage);
2164 
2165   setNonAliasAttributes(GD, F);
2166 }
2167 
2168 static void setLinkageForGV(llvm::GlobalValue *GV, const NamedDecl *ND) {
2169   // Set linkage and visibility in case we never see a definition.
2170   LinkageInfo LV = ND->getLinkageAndVisibility();
2171   // Don't set internal linkage on declarations.
2172   // "extern_weak" is overloaded in LLVM; we probably should have
2173   // separate linkage types for this.
2174   if (isExternallyVisible(LV.getLinkage()) &&
2175       (ND->hasAttr<WeakAttr>() || ND->isWeakImported()))
2176     GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
2177 }
2178 
2179 void CodeGenModule::CreateFunctionTypeMetadataForIcall(const FunctionDecl *FD,
2180                                                        llvm::Function *F) {
2181   // Only if we are checking indirect calls.
2182   if (!LangOpts.Sanitize.has(SanitizerKind::CFIICall))
2183     return;
2184 
2185   // Non-static class methods are handled via vtable or member function pointer
2186   // checks elsewhere.
2187   if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
2188     return;
2189 
2190   llvm::Metadata *MD = CreateMetadataIdentifierForType(FD->getType());
2191   F->addTypeMetadata(0, MD);
2192   F->addTypeMetadata(0, CreateMetadataIdentifierGeneralized(FD->getType()));
2193 
2194   // Emit a hash-based bit set entry for cross-DSO calls.
2195   if (CodeGenOpts.SanitizeCfiCrossDso)
2196     if (auto CrossDsoTypeId = CreateCrossDsoCfiTypeId(MD))
2197       F->addTypeMetadata(0, llvm::ConstantAsMetadata::get(CrossDsoTypeId));
2198 }
2199 
2200 void CodeGenModule::SetFunctionAttributes(GlobalDecl GD, llvm::Function *F,
2201                                           bool IsIncompleteFunction,
2202                                           bool IsThunk) {
2203 
2204   if (llvm::Intrinsic::ID IID = F->getIntrinsicID()) {
2205     // If this is an intrinsic function, set the function's attributes
2206     // to the intrinsic's attributes.
2207     F->setAttributes(llvm::Intrinsic::getAttributes(getLLVMContext(), IID));
2208     return;
2209   }
2210 
2211   const auto *FD = cast<FunctionDecl>(GD.getDecl());
2212 
2213   if (!IsIncompleteFunction)
2214     SetLLVMFunctionAttributes(GD, getTypes().arrangeGlobalDeclaration(GD), F,
2215                               IsThunk);
2216 
2217   // Add the Returned attribute for "this", except for iOS 5 and earlier
2218   // where substantial code, including the libstdc++ dylib, was compiled with
2219   // GCC and does not actually return "this".
2220   if (!IsThunk && getCXXABI().HasThisReturn(GD) &&
2221       !(getTriple().isiOS() && getTriple().isOSVersionLT(6))) {
2222     assert(!F->arg_empty() &&
2223            F->arg_begin()->getType()
2224              ->canLosslesslyBitCastTo(F->getReturnType()) &&
2225            "unexpected this return");
2226     F->addParamAttr(0, llvm::Attribute::Returned);
2227   }
2228 
2229   // Only a few attributes are set on declarations; these may later be
2230   // overridden by a definition.
2231 
2232   setLinkageForGV(F, FD);
2233   setGVProperties(F, FD);
2234 
2235   // Setup target-specific attributes.
2236   if (!IsIncompleteFunction && F->isDeclaration())
2237     getTargetCodeGenInfo().setTargetAttributes(FD, F, *this);
2238 
2239   if (const auto *CSA = FD->getAttr<CodeSegAttr>())
2240     F->setSection(CSA->getName());
2241   else if (const auto *SA = FD->getAttr<SectionAttr>())
2242      F->setSection(SA->getName());
2243 
2244   if (const auto *EA = FD->getAttr<ErrorAttr>()) {
2245     if (EA->isError())
2246       F->addFnAttr("dontcall-error", EA->getUserDiagnostic());
2247     else if (EA->isWarning())
2248       F->addFnAttr("dontcall-warn", EA->getUserDiagnostic());
2249   }
2250 
2251   // If we plan on emitting this inline builtin, we can't treat it as a builtin.
2252   if (FD->isInlineBuiltinDeclaration()) {
2253     const FunctionDecl *FDBody;
2254     bool HasBody = FD->hasBody(FDBody);
2255     (void)HasBody;
2256     assert(HasBody && "Inline builtin declarations should always have an "
2257                       "available body!");
2258     if (shouldEmitFunction(FDBody))
2259       F->addFnAttr(llvm::Attribute::NoBuiltin);
2260   }
2261 
2262   if (FD->isReplaceableGlobalAllocationFunction()) {
2263     // A replaceable global allocation function does not act like a builtin by
2264     // default, only if it is invoked by a new-expression or delete-expression.
2265     F->addFnAttr(llvm::Attribute::NoBuiltin);
2266   }
2267 
2268   if (isa<CXXConstructorDecl>(FD) || isa<CXXDestructorDecl>(FD))
2269     F->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
2270   else if (const auto *MD = dyn_cast<CXXMethodDecl>(FD))
2271     if (MD->isVirtual())
2272       F->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
2273 
2274   // Don't emit entries for function declarations in the cross-DSO mode. This
2275   // is handled with better precision by the receiving DSO. But if jump tables
2276   // are non-canonical then we need type metadata in order to produce the local
2277   // jump table.
2278   if (!CodeGenOpts.SanitizeCfiCrossDso ||
2279       !CodeGenOpts.SanitizeCfiCanonicalJumpTables)
2280     CreateFunctionTypeMetadataForIcall(FD, F);
2281 
2282   if (getLangOpts().OpenMP && FD->hasAttr<OMPDeclareSimdDeclAttr>())
2283     getOpenMPRuntime().emitDeclareSimdFunction(FD, F);
2284 
2285   if (const auto *CB = FD->getAttr<CallbackAttr>()) {
2286     // Annotate the callback behavior as metadata:
2287     //  - The callback callee (as argument number).
2288     //  - The callback payloads (as argument numbers).
2289     llvm::LLVMContext &Ctx = F->getContext();
2290     llvm::MDBuilder MDB(Ctx);
2291 
2292     // The payload indices are all but the first one in the encoding. The first
2293     // identifies the callback callee.
2294     int CalleeIdx = *CB->encoding_begin();
2295     ArrayRef<int> PayloadIndices(CB->encoding_begin() + 1, CB->encoding_end());
2296     F->addMetadata(llvm::LLVMContext::MD_callback,
2297                    *llvm::MDNode::get(Ctx, {MDB.createCallbackEncoding(
2298                                                CalleeIdx, PayloadIndices,
2299                                                /* VarArgsArePassed */ false)}));
2300   }
2301 }
2302 
2303 void CodeGenModule::addUsedGlobal(llvm::GlobalValue *GV) {
2304   assert((isa<llvm::Function>(GV) || !GV->isDeclaration()) &&
2305          "Only globals with definition can force usage.");
2306   LLVMUsed.emplace_back(GV);
2307 }
2308 
2309 void CodeGenModule::addCompilerUsedGlobal(llvm::GlobalValue *GV) {
2310   assert(!GV->isDeclaration() &&
2311          "Only globals with definition can force usage.");
2312   LLVMCompilerUsed.emplace_back(GV);
2313 }
2314 
2315 void CodeGenModule::addUsedOrCompilerUsedGlobal(llvm::GlobalValue *GV) {
2316   assert((isa<llvm::Function>(GV) || !GV->isDeclaration()) &&
2317          "Only globals with definition can force usage.");
2318   if (getTriple().isOSBinFormatELF())
2319     LLVMCompilerUsed.emplace_back(GV);
2320   else
2321     LLVMUsed.emplace_back(GV);
2322 }
2323 
2324 static void emitUsed(CodeGenModule &CGM, StringRef Name,
2325                      std::vector<llvm::WeakTrackingVH> &List) {
2326   // Don't create llvm.used if there is no need.
2327   if (List.empty())
2328     return;
2329 
2330   // Convert List to what ConstantArray needs.
2331   SmallVector<llvm::Constant*, 8> UsedArray;
2332   UsedArray.resize(List.size());
2333   for (unsigned i = 0, e = List.size(); i != e; ++i) {
2334     UsedArray[i] =
2335         llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
2336             cast<llvm::Constant>(&*List[i]), CGM.Int8PtrTy);
2337   }
2338 
2339   if (UsedArray.empty())
2340     return;
2341   llvm::ArrayType *ATy = llvm::ArrayType::get(CGM.Int8PtrTy, UsedArray.size());
2342 
2343   auto *GV = new llvm::GlobalVariable(
2344       CGM.getModule(), ATy, false, llvm::GlobalValue::AppendingLinkage,
2345       llvm::ConstantArray::get(ATy, UsedArray), Name);
2346 
2347   GV->setSection("llvm.metadata");
2348 }
2349 
2350 void CodeGenModule::emitLLVMUsed() {
2351   emitUsed(*this, "llvm.used", LLVMUsed);
2352   emitUsed(*this, "llvm.compiler.used", LLVMCompilerUsed);
2353 }
2354 
2355 void CodeGenModule::AppendLinkerOptions(StringRef Opts) {
2356   auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opts);
2357   LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
2358 }
2359 
2360 void CodeGenModule::AddDetectMismatch(StringRef Name, StringRef Value) {
2361   llvm::SmallString<32> Opt;
2362   getTargetCodeGenInfo().getDetectMismatchOption(Name, Value, Opt);
2363   if (Opt.empty())
2364     return;
2365   auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opt);
2366   LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
2367 }
2368 
2369 void CodeGenModule::AddDependentLib(StringRef Lib) {
2370   auto &C = getLLVMContext();
2371   if (getTarget().getTriple().isOSBinFormatELF()) {
2372       ELFDependentLibraries.push_back(
2373         llvm::MDNode::get(C, llvm::MDString::get(C, Lib)));
2374     return;
2375   }
2376 
2377   llvm::SmallString<24> Opt;
2378   getTargetCodeGenInfo().getDependentLibraryOption(Lib, Opt);
2379   auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opt);
2380   LinkerOptionsMetadata.push_back(llvm::MDNode::get(C, MDOpts));
2381 }
2382 
2383 /// Add link options implied by the given module, including modules
2384 /// it depends on, using a postorder walk.
2385 static void addLinkOptionsPostorder(CodeGenModule &CGM, Module *Mod,
2386                                     SmallVectorImpl<llvm::MDNode *> &Metadata,
2387                                     llvm::SmallPtrSet<Module *, 16> &Visited) {
2388   // Import this module's parent.
2389   if (Mod->Parent && Visited.insert(Mod->Parent).second) {
2390     addLinkOptionsPostorder(CGM, Mod->Parent, Metadata, Visited);
2391   }
2392 
2393   // Import this module's dependencies.
2394   for (Module *Import : llvm::reverse(Mod->Imports)) {
2395     if (Visited.insert(Import).second)
2396       addLinkOptionsPostorder(CGM, Import, Metadata, Visited);
2397   }
2398 
2399   // Add linker options to link against the libraries/frameworks
2400   // described by this module.
2401   llvm::LLVMContext &Context = CGM.getLLVMContext();
2402   bool IsELF = CGM.getTarget().getTriple().isOSBinFormatELF();
2403 
2404   // For modules that use export_as for linking, use that module
2405   // name instead.
2406   if (Mod->UseExportAsModuleLinkName)
2407     return;
2408 
2409   for (const Module::LinkLibrary &LL : llvm::reverse(Mod->LinkLibraries)) {
2410     // Link against a framework.  Frameworks are currently Darwin only, so we
2411     // don't to ask TargetCodeGenInfo for the spelling of the linker option.
2412     if (LL.IsFramework) {
2413       llvm::Metadata *Args[2] = {llvm::MDString::get(Context, "-framework"),
2414                                  llvm::MDString::get(Context, LL.Library)};
2415 
2416       Metadata.push_back(llvm::MDNode::get(Context, Args));
2417       continue;
2418     }
2419 
2420     // Link against a library.
2421     if (IsELF) {
2422       llvm::Metadata *Args[2] = {
2423           llvm::MDString::get(Context, "lib"),
2424           llvm::MDString::get(Context, LL.Library),
2425       };
2426       Metadata.push_back(llvm::MDNode::get(Context, Args));
2427     } else {
2428       llvm::SmallString<24> Opt;
2429       CGM.getTargetCodeGenInfo().getDependentLibraryOption(LL.Library, Opt);
2430       auto *OptString = llvm::MDString::get(Context, Opt);
2431       Metadata.push_back(llvm::MDNode::get(Context, OptString));
2432     }
2433   }
2434 }
2435 
2436 void CodeGenModule::EmitModuleLinkOptions() {
2437   // Collect the set of all of the modules we want to visit to emit link
2438   // options, which is essentially the imported modules and all of their
2439   // non-explicit child modules.
2440   llvm::SetVector<clang::Module *> LinkModules;
2441   llvm::SmallPtrSet<clang::Module *, 16> Visited;
2442   SmallVector<clang::Module *, 16> Stack;
2443 
2444   // Seed the stack with imported modules.
2445   for (Module *M : ImportedModules) {
2446     // Do not add any link flags when an implementation TU of a module imports
2447     // a header of that same module.
2448     if (M->getTopLevelModuleName() == getLangOpts().CurrentModule &&
2449         !getLangOpts().isCompilingModule())
2450       continue;
2451     if (Visited.insert(M).second)
2452       Stack.push_back(M);
2453   }
2454 
2455   // Find all of the modules to import, making a little effort to prune
2456   // non-leaf modules.
2457   while (!Stack.empty()) {
2458     clang::Module *Mod = Stack.pop_back_val();
2459 
2460     bool AnyChildren = false;
2461 
2462     // Visit the submodules of this module.
2463     for (const auto &SM : Mod->submodules()) {
2464       // Skip explicit children; they need to be explicitly imported to be
2465       // linked against.
2466       if (SM->IsExplicit)
2467         continue;
2468 
2469       if (Visited.insert(SM).second) {
2470         Stack.push_back(SM);
2471         AnyChildren = true;
2472       }
2473     }
2474 
2475     // We didn't find any children, so add this module to the list of
2476     // modules to link against.
2477     if (!AnyChildren) {
2478       LinkModules.insert(Mod);
2479     }
2480   }
2481 
2482   // Add link options for all of the imported modules in reverse topological
2483   // order.  We don't do anything to try to order import link flags with respect
2484   // to linker options inserted by things like #pragma comment().
2485   SmallVector<llvm::MDNode *, 16> MetadataArgs;
2486   Visited.clear();
2487   for (Module *M : LinkModules)
2488     if (Visited.insert(M).second)
2489       addLinkOptionsPostorder(*this, M, MetadataArgs, Visited);
2490   std::reverse(MetadataArgs.begin(), MetadataArgs.end());
2491   LinkerOptionsMetadata.append(MetadataArgs.begin(), MetadataArgs.end());
2492 
2493   // Add the linker options metadata flag.
2494   auto *NMD = getModule().getOrInsertNamedMetadata("llvm.linker.options");
2495   for (auto *MD : LinkerOptionsMetadata)
2496     NMD->addOperand(MD);
2497 }
2498 
2499 void CodeGenModule::EmitDeferred() {
2500   // Emit deferred declare target declarations.
2501   if (getLangOpts().OpenMP && !getLangOpts().OpenMPSimd)
2502     getOpenMPRuntime().emitDeferredTargetDecls();
2503 
2504   // Emit code for any potentially referenced deferred decls.  Since a
2505   // previously unused static decl may become used during the generation of code
2506   // for a static function, iterate until no changes are made.
2507 
2508   if (!DeferredVTables.empty()) {
2509     EmitDeferredVTables();
2510 
2511     // Emitting a vtable doesn't directly cause more vtables to
2512     // become deferred, although it can cause functions to be
2513     // emitted that then need those vtables.
2514     assert(DeferredVTables.empty());
2515   }
2516 
2517   // Emit CUDA/HIP static device variables referenced by host code only.
2518   // Note we should not clear CUDADeviceVarODRUsedByHost since it is still
2519   // needed for further handling.
2520   if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice)
2521     llvm::append_range(DeferredDeclsToEmit,
2522                        getContext().CUDADeviceVarODRUsedByHost);
2523 
2524   // Stop if we're out of both deferred vtables and deferred declarations.
2525   if (DeferredDeclsToEmit.empty())
2526     return;
2527 
2528   // Grab the list of decls to emit. If EmitGlobalDefinition schedules more
2529   // work, it will not interfere with this.
2530   std::vector<GlobalDecl> CurDeclsToEmit;
2531   CurDeclsToEmit.swap(DeferredDeclsToEmit);
2532 
2533   for (GlobalDecl &D : CurDeclsToEmit) {
2534     // We should call GetAddrOfGlobal with IsForDefinition set to true in order
2535     // to get GlobalValue with exactly the type we need, not something that
2536     // might had been created for another decl with the same mangled name but
2537     // different type.
2538     llvm::GlobalValue *GV = dyn_cast<llvm::GlobalValue>(
2539         GetAddrOfGlobal(D, ForDefinition));
2540 
2541     // In case of different address spaces, we may still get a cast, even with
2542     // IsForDefinition equal to true. Query mangled names table to get
2543     // GlobalValue.
2544     if (!GV)
2545       GV = GetGlobalValue(getMangledName(D));
2546 
2547     // Make sure GetGlobalValue returned non-null.
2548     assert(GV);
2549 
2550     // Check to see if we've already emitted this.  This is necessary
2551     // for a couple of reasons: first, decls can end up in the
2552     // deferred-decls queue multiple times, and second, decls can end
2553     // up with definitions in unusual ways (e.g. by an extern inline
2554     // function acquiring a strong function redefinition).  Just
2555     // ignore these cases.
2556     if (!GV->isDeclaration())
2557       continue;
2558 
2559     // If this is OpenMP, check if it is legal to emit this global normally.
2560     if (LangOpts.OpenMP && OpenMPRuntime && OpenMPRuntime->emitTargetGlobal(D))
2561       continue;
2562 
2563     // Otherwise, emit the definition and move on to the next one.
2564     EmitGlobalDefinition(D, GV);
2565 
2566     // If we found out that we need to emit more decls, do that recursively.
2567     // This has the advantage that the decls are emitted in a DFS and related
2568     // ones are close together, which is convenient for testing.
2569     if (!DeferredVTables.empty() || !DeferredDeclsToEmit.empty()) {
2570       EmitDeferred();
2571       assert(DeferredVTables.empty() && DeferredDeclsToEmit.empty());
2572     }
2573   }
2574 }
2575 
2576 void CodeGenModule::EmitVTablesOpportunistically() {
2577   // Try to emit external vtables as available_externally if they have emitted
2578   // all inlined virtual functions.  It runs after EmitDeferred() and therefore
2579   // is not allowed to create new references to things that need to be emitted
2580   // lazily. Note that it also uses fact that we eagerly emitting RTTI.
2581 
2582   assert((OpportunisticVTables.empty() || shouldOpportunisticallyEmitVTables())
2583          && "Only emit opportunistic vtables with optimizations");
2584 
2585   for (const CXXRecordDecl *RD : OpportunisticVTables) {
2586     assert(getVTables().isVTableExternal(RD) &&
2587            "This queue should only contain external vtables");
2588     if (getCXXABI().canSpeculativelyEmitVTable(RD))
2589       VTables.GenerateClassData(RD);
2590   }
2591   OpportunisticVTables.clear();
2592 }
2593 
2594 void CodeGenModule::EmitGlobalAnnotations() {
2595   if (Annotations.empty())
2596     return;
2597 
2598   // Create a new global variable for the ConstantStruct in the Module.
2599   llvm::Constant *Array = llvm::ConstantArray::get(llvm::ArrayType::get(
2600     Annotations[0]->getType(), Annotations.size()), Annotations);
2601   auto *gv = new llvm::GlobalVariable(getModule(), Array->getType(), false,
2602                                       llvm::GlobalValue::AppendingLinkage,
2603                                       Array, "llvm.global.annotations");
2604   gv->setSection(AnnotationSection);
2605 }
2606 
2607 llvm::Constant *CodeGenModule::EmitAnnotationString(StringRef Str) {
2608   llvm::Constant *&AStr = AnnotationStrings[Str];
2609   if (AStr)
2610     return AStr;
2611 
2612   // Not found yet, create a new global.
2613   llvm::Constant *s = llvm::ConstantDataArray::getString(getLLVMContext(), Str);
2614   auto *gv =
2615       new llvm::GlobalVariable(getModule(), s->getType(), true,
2616                                llvm::GlobalValue::PrivateLinkage, s, ".str");
2617   gv->setSection(AnnotationSection);
2618   gv->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
2619   AStr = gv;
2620   return gv;
2621 }
2622 
2623 llvm::Constant *CodeGenModule::EmitAnnotationUnit(SourceLocation Loc) {
2624   SourceManager &SM = getContext().getSourceManager();
2625   PresumedLoc PLoc = SM.getPresumedLoc(Loc);
2626   if (PLoc.isValid())
2627     return EmitAnnotationString(PLoc.getFilename());
2628   return EmitAnnotationString(SM.getBufferName(Loc));
2629 }
2630 
2631 llvm::Constant *CodeGenModule::EmitAnnotationLineNo(SourceLocation L) {
2632   SourceManager &SM = getContext().getSourceManager();
2633   PresumedLoc PLoc = SM.getPresumedLoc(L);
2634   unsigned LineNo = PLoc.isValid() ? PLoc.getLine() :
2635     SM.getExpansionLineNumber(L);
2636   return llvm::ConstantInt::get(Int32Ty, LineNo);
2637 }
2638 
2639 llvm::Constant *CodeGenModule::EmitAnnotationArgs(const AnnotateAttr *Attr) {
2640   ArrayRef<Expr *> Exprs = {Attr->args_begin(), Attr->args_size()};
2641   if (Exprs.empty())
2642     return llvm::ConstantPointerNull::get(GlobalsInt8PtrTy);
2643 
2644   llvm::FoldingSetNodeID ID;
2645   for (Expr *E : Exprs) {
2646     ID.Add(cast<clang::ConstantExpr>(E)->getAPValueResult());
2647   }
2648   llvm::Constant *&Lookup = AnnotationArgs[ID.ComputeHash()];
2649   if (Lookup)
2650     return Lookup;
2651 
2652   llvm::SmallVector<llvm::Constant *, 4> LLVMArgs;
2653   LLVMArgs.reserve(Exprs.size());
2654   ConstantEmitter ConstEmiter(*this);
2655   llvm::transform(Exprs, std::back_inserter(LLVMArgs), [&](const Expr *E) {
2656     const auto *CE = cast<clang::ConstantExpr>(E);
2657     return ConstEmiter.emitAbstract(CE->getBeginLoc(), CE->getAPValueResult(),
2658                                     CE->getType());
2659   });
2660   auto *Struct = llvm::ConstantStruct::getAnon(LLVMArgs);
2661   auto *GV = new llvm::GlobalVariable(getModule(), Struct->getType(), true,
2662                                       llvm::GlobalValue::PrivateLinkage, Struct,
2663                                       ".args");
2664   GV->setSection(AnnotationSection);
2665   GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
2666   auto *Bitcasted = llvm::ConstantExpr::getBitCast(GV, GlobalsInt8PtrTy);
2667 
2668   Lookup = Bitcasted;
2669   return Bitcasted;
2670 }
2671 
2672 llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV,
2673                                                 const AnnotateAttr *AA,
2674                                                 SourceLocation L) {
2675   // Get the globals for file name, annotation, and the line number.
2676   llvm::Constant *AnnoGV = EmitAnnotationString(AA->getAnnotation()),
2677                  *UnitGV = EmitAnnotationUnit(L),
2678                  *LineNoCst = EmitAnnotationLineNo(L),
2679                  *Args = EmitAnnotationArgs(AA);
2680 
2681   llvm::Constant *GVInGlobalsAS = GV;
2682   if (GV->getAddressSpace() !=
2683       getDataLayout().getDefaultGlobalsAddressSpace()) {
2684     GVInGlobalsAS = llvm::ConstantExpr::getAddrSpaceCast(
2685         GV, GV->getValueType()->getPointerTo(
2686                 getDataLayout().getDefaultGlobalsAddressSpace()));
2687   }
2688 
2689   // Create the ConstantStruct for the global annotation.
2690   llvm::Constant *Fields[] = {
2691       llvm::ConstantExpr::getBitCast(GVInGlobalsAS, GlobalsInt8PtrTy),
2692       llvm::ConstantExpr::getBitCast(AnnoGV, GlobalsInt8PtrTy),
2693       llvm::ConstantExpr::getBitCast(UnitGV, GlobalsInt8PtrTy),
2694       LineNoCst,
2695       Args,
2696   };
2697   return llvm::ConstantStruct::getAnon(Fields);
2698 }
2699 
2700 void CodeGenModule::AddGlobalAnnotations(const ValueDecl *D,
2701                                          llvm::GlobalValue *GV) {
2702   assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute");
2703   // Get the struct elements for these annotations.
2704   for (const auto *I : D->specific_attrs<AnnotateAttr>())
2705     Annotations.push_back(EmitAnnotateAttr(GV, I, D->getLocation()));
2706 }
2707 
2708 bool CodeGenModule::isInNoSanitizeList(SanitizerMask Kind, llvm::Function *Fn,
2709                                        SourceLocation Loc) const {
2710   const auto &NoSanitizeL = getContext().getNoSanitizeList();
2711   // NoSanitize by function name.
2712   if (NoSanitizeL.containsFunction(Kind, Fn->getName()))
2713     return true;
2714   // NoSanitize by location.
2715   if (Loc.isValid())
2716     return NoSanitizeL.containsLocation(Kind, Loc);
2717   // If location is unknown, this may be a compiler-generated function. Assume
2718   // it's located in the main file.
2719   auto &SM = Context.getSourceManager();
2720   if (const auto *MainFile = SM.getFileEntryForID(SM.getMainFileID())) {
2721     return NoSanitizeL.containsFile(Kind, MainFile->getName());
2722   }
2723   return false;
2724 }
2725 
2726 bool CodeGenModule::isInNoSanitizeList(llvm::GlobalVariable *GV,
2727                                        SourceLocation Loc, QualType Ty,
2728                                        StringRef Category) const {
2729   // For now globals can be ignored only in ASan and KASan.
2730   const SanitizerMask EnabledAsanMask =
2731       LangOpts.Sanitize.Mask &
2732       (SanitizerKind::Address | SanitizerKind::KernelAddress |
2733        SanitizerKind::HWAddress | SanitizerKind::KernelHWAddress |
2734        SanitizerKind::MemTag);
2735   if (!EnabledAsanMask)
2736     return false;
2737   const auto &NoSanitizeL = getContext().getNoSanitizeList();
2738   if (NoSanitizeL.containsGlobal(EnabledAsanMask, GV->getName(), Category))
2739     return true;
2740   if (NoSanitizeL.containsLocation(EnabledAsanMask, Loc, Category))
2741     return true;
2742   // Check global type.
2743   if (!Ty.isNull()) {
2744     // Drill down the array types: if global variable of a fixed type is
2745     // not sanitized, we also don't instrument arrays of them.
2746     while (auto AT = dyn_cast<ArrayType>(Ty.getTypePtr()))
2747       Ty = AT->getElementType();
2748     Ty = Ty.getCanonicalType().getUnqualifiedType();
2749     // Only record types (classes, structs etc.) are ignored.
2750     if (Ty->isRecordType()) {
2751       std::string TypeStr = Ty.getAsString(getContext().getPrintingPolicy());
2752       if (NoSanitizeL.containsType(EnabledAsanMask, TypeStr, Category))
2753         return true;
2754     }
2755   }
2756   return false;
2757 }
2758 
2759 bool CodeGenModule::imbueXRayAttrs(llvm::Function *Fn, SourceLocation Loc,
2760                                    StringRef Category) const {
2761   const auto &XRayFilter = getContext().getXRayFilter();
2762   using ImbueAttr = XRayFunctionFilter::ImbueAttribute;
2763   auto Attr = ImbueAttr::NONE;
2764   if (Loc.isValid())
2765     Attr = XRayFilter.shouldImbueLocation(Loc, Category);
2766   if (Attr == ImbueAttr::NONE)
2767     Attr = XRayFilter.shouldImbueFunction(Fn->getName());
2768   switch (Attr) {
2769   case ImbueAttr::NONE:
2770     return false;
2771   case ImbueAttr::ALWAYS:
2772     Fn->addFnAttr("function-instrument", "xray-always");
2773     break;
2774   case ImbueAttr::ALWAYS_ARG1:
2775     Fn->addFnAttr("function-instrument", "xray-always");
2776     Fn->addFnAttr("xray-log-args", "1");
2777     break;
2778   case ImbueAttr::NEVER:
2779     Fn->addFnAttr("function-instrument", "xray-never");
2780     break;
2781   }
2782   return true;
2783 }
2784 
2785 bool CodeGenModule::isProfileInstrExcluded(llvm::Function *Fn,
2786                                            SourceLocation Loc) const {
2787   const auto &ProfileList = getContext().getProfileList();
2788   // If the profile list is empty, then instrument everything.
2789   if (ProfileList.isEmpty())
2790     return false;
2791   CodeGenOptions::ProfileInstrKind Kind = getCodeGenOpts().getProfileInstr();
2792   // First, check the function name.
2793   Optional<bool> V = ProfileList.isFunctionExcluded(Fn->getName(), Kind);
2794   if (V.hasValue())
2795     return *V;
2796   // Next, check the source location.
2797   if (Loc.isValid()) {
2798     Optional<bool> V = ProfileList.isLocationExcluded(Loc, Kind);
2799     if (V.hasValue())
2800       return *V;
2801   }
2802   // If location is unknown, this may be a compiler-generated function. Assume
2803   // it's located in the main file.
2804   auto &SM = Context.getSourceManager();
2805   if (const auto *MainFile = SM.getFileEntryForID(SM.getMainFileID())) {
2806     Optional<bool> V = ProfileList.isFileExcluded(MainFile->getName(), Kind);
2807     if (V.hasValue())
2808       return *V;
2809   }
2810   return ProfileList.getDefault();
2811 }
2812 
2813 bool CodeGenModule::MustBeEmitted(const ValueDecl *Global) {
2814   // Never defer when EmitAllDecls is specified.
2815   if (LangOpts.EmitAllDecls)
2816     return true;
2817 
2818   if (CodeGenOpts.KeepStaticConsts) {
2819     const auto *VD = dyn_cast<VarDecl>(Global);
2820     if (VD && VD->getType().isConstQualified() &&
2821         VD->getStorageDuration() == SD_Static)
2822       return true;
2823   }
2824 
2825   return getContext().DeclMustBeEmitted(Global);
2826 }
2827 
2828 bool CodeGenModule::MayBeEmittedEagerly(const ValueDecl *Global) {
2829   // In OpenMP 5.0 variables and function may be marked as
2830   // device_type(host/nohost) and we should not emit them eagerly unless we sure
2831   // that they must be emitted on the host/device. To be sure we need to have
2832   // seen a declare target with an explicit mentioning of the function, we know
2833   // we have if the level of the declare target attribute is -1. Note that we
2834   // check somewhere else if we should emit this at all.
2835   if (LangOpts.OpenMP >= 50 && !LangOpts.OpenMPSimd) {
2836     llvm::Optional<OMPDeclareTargetDeclAttr *> ActiveAttr =
2837         OMPDeclareTargetDeclAttr::getActiveAttr(Global);
2838     if (!ActiveAttr || (*ActiveAttr)->getLevel() != (unsigned)-1)
2839       return false;
2840   }
2841 
2842   if (const auto *FD = dyn_cast<FunctionDecl>(Global)) {
2843     if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
2844       // Implicit template instantiations may change linkage if they are later
2845       // explicitly instantiated, so they should not be emitted eagerly.
2846       return false;
2847   }
2848   if (const auto *VD = dyn_cast<VarDecl>(Global))
2849     if (Context.getInlineVariableDefinitionKind(VD) ==
2850         ASTContext::InlineVariableDefinitionKind::WeakUnknown)
2851       // A definition of an inline constexpr static data member may change
2852       // linkage later if it's redeclared outside the class.
2853       return false;
2854   // If OpenMP is enabled and threadprivates must be generated like TLS, delay
2855   // codegen for global variables, because they may be marked as threadprivate.
2856   if (LangOpts.OpenMP && LangOpts.OpenMPUseTLS &&
2857       getContext().getTargetInfo().isTLSSupported() && isa<VarDecl>(Global) &&
2858       !isTypeConstant(Global->getType(), false) &&
2859       !OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(Global))
2860     return false;
2861 
2862   return true;
2863 }
2864 
2865 ConstantAddress CodeGenModule::GetAddrOfMSGuidDecl(const MSGuidDecl *GD) {
2866   StringRef Name = getMangledName(GD);
2867 
2868   // The UUID descriptor should be pointer aligned.
2869   CharUnits Alignment = CharUnits::fromQuantity(PointerAlignInBytes);
2870 
2871   // Look for an existing global.
2872   if (llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name))
2873     return ConstantAddress(GV, GV->getValueType(), Alignment);
2874 
2875   ConstantEmitter Emitter(*this);
2876   llvm::Constant *Init;
2877 
2878   APValue &V = GD->getAsAPValue();
2879   if (!V.isAbsent()) {
2880     // If possible, emit the APValue version of the initializer. In particular,
2881     // this gets the type of the constant right.
2882     Init = Emitter.emitForInitializer(
2883         GD->getAsAPValue(), GD->getType().getAddressSpace(), GD->getType());
2884   } else {
2885     // As a fallback, directly construct the constant.
2886     // FIXME: This may get padding wrong under esoteric struct layout rules.
2887     // MSVC appears to create a complete type 'struct __s_GUID' that it
2888     // presumably uses to represent these constants.
2889     MSGuidDecl::Parts Parts = GD->getParts();
2890     llvm::Constant *Fields[4] = {
2891         llvm::ConstantInt::get(Int32Ty, Parts.Part1),
2892         llvm::ConstantInt::get(Int16Ty, Parts.Part2),
2893         llvm::ConstantInt::get(Int16Ty, Parts.Part3),
2894         llvm::ConstantDataArray::getRaw(
2895             StringRef(reinterpret_cast<char *>(Parts.Part4And5), 8), 8,
2896             Int8Ty)};
2897     Init = llvm::ConstantStruct::getAnon(Fields);
2898   }
2899 
2900   auto *GV = new llvm::GlobalVariable(
2901       getModule(), Init->getType(),
2902       /*isConstant=*/true, llvm::GlobalValue::LinkOnceODRLinkage, Init, Name);
2903   if (supportsCOMDAT())
2904     GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
2905   setDSOLocal(GV);
2906 
2907   if (!V.isAbsent()) {
2908     Emitter.finalize(GV);
2909     return ConstantAddress(GV, GV->getValueType(), Alignment);
2910   }
2911 
2912   llvm::Type *Ty = getTypes().ConvertTypeForMem(GD->getType());
2913   llvm::Constant *Addr = llvm::ConstantExpr::getBitCast(
2914       GV, Ty->getPointerTo(GV->getAddressSpace()));
2915   return ConstantAddress(Addr, Ty, Alignment);
2916 }
2917 
2918 ConstantAddress CodeGenModule::GetAddrOfUnnamedGlobalConstantDecl(
2919     const UnnamedGlobalConstantDecl *GCD) {
2920   CharUnits Alignment = getContext().getTypeAlignInChars(GCD->getType());
2921 
2922   llvm::GlobalVariable **Entry = nullptr;
2923   Entry = &UnnamedGlobalConstantDeclMap[GCD];
2924   if (*Entry)
2925     return ConstantAddress(*Entry, (*Entry)->getValueType(), Alignment);
2926 
2927   ConstantEmitter Emitter(*this);
2928   llvm::Constant *Init;
2929 
2930   const APValue &V = GCD->getValue();
2931 
2932   assert(!V.isAbsent());
2933   Init = Emitter.emitForInitializer(V, GCD->getType().getAddressSpace(),
2934                                     GCD->getType());
2935 
2936   auto *GV = new llvm::GlobalVariable(getModule(), Init->getType(),
2937                                       /*isConstant=*/true,
2938                                       llvm::GlobalValue::PrivateLinkage, Init,
2939                                       ".constant");
2940   GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
2941   GV->setAlignment(Alignment.getAsAlign());
2942 
2943   Emitter.finalize(GV);
2944 
2945   *Entry = GV;
2946   return ConstantAddress(GV, GV->getValueType(), Alignment);
2947 }
2948 
2949 ConstantAddress CodeGenModule::GetAddrOfTemplateParamObject(
2950     const TemplateParamObjectDecl *TPO) {
2951   StringRef Name = getMangledName(TPO);
2952   CharUnits Alignment = getNaturalTypeAlignment(TPO->getType());
2953 
2954   if (llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name))
2955     return ConstantAddress(GV, GV->getValueType(), Alignment);
2956 
2957   ConstantEmitter Emitter(*this);
2958   llvm::Constant *Init = Emitter.emitForInitializer(
2959         TPO->getValue(), TPO->getType().getAddressSpace(), TPO->getType());
2960 
2961   if (!Init) {
2962     ErrorUnsupported(TPO, "template parameter object");
2963     return ConstantAddress::invalid();
2964   }
2965 
2966   auto *GV = new llvm::GlobalVariable(
2967       getModule(), Init->getType(),
2968       /*isConstant=*/true, llvm::GlobalValue::LinkOnceODRLinkage, Init, Name);
2969   if (supportsCOMDAT())
2970     GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
2971   Emitter.finalize(GV);
2972 
2973   return ConstantAddress(GV, GV->getValueType(), Alignment);
2974 }
2975 
2976 ConstantAddress CodeGenModule::GetWeakRefReference(const ValueDecl *VD) {
2977   const AliasAttr *AA = VD->getAttr<AliasAttr>();
2978   assert(AA && "No alias?");
2979 
2980   CharUnits Alignment = getContext().getDeclAlign(VD);
2981   llvm::Type *DeclTy = getTypes().ConvertTypeForMem(VD->getType());
2982 
2983   // See if there is already something with the target's name in the module.
2984   llvm::GlobalValue *Entry = GetGlobalValue(AA->getAliasee());
2985   if (Entry) {
2986     unsigned AS = getContext().getTargetAddressSpace(VD->getType());
2987     auto Ptr = llvm::ConstantExpr::getBitCast(Entry, DeclTy->getPointerTo(AS));
2988     return ConstantAddress(Ptr, DeclTy, Alignment);
2989   }
2990 
2991   llvm::Constant *Aliasee;
2992   if (isa<llvm::FunctionType>(DeclTy))
2993     Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy,
2994                                       GlobalDecl(cast<FunctionDecl>(VD)),
2995                                       /*ForVTable=*/false);
2996   else
2997     Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(), DeclTy, LangAS::Default,
2998                                     nullptr);
2999 
3000   auto *F = cast<llvm::GlobalValue>(Aliasee);
3001   F->setLinkage(llvm::Function::ExternalWeakLinkage);
3002   WeakRefReferences.insert(F);
3003 
3004   return ConstantAddress(Aliasee, DeclTy, Alignment);
3005 }
3006 
3007 void CodeGenModule::EmitGlobal(GlobalDecl GD) {
3008   const auto *Global = cast<ValueDecl>(GD.getDecl());
3009 
3010   // Weak references don't produce any output by themselves.
3011   if (Global->hasAttr<WeakRefAttr>())
3012     return;
3013 
3014   // If this is an alias definition (which otherwise looks like a declaration)
3015   // emit it now.
3016   if (Global->hasAttr<AliasAttr>())
3017     return EmitAliasDefinition(GD);
3018 
3019   // IFunc like an alias whose value is resolved at runtime by calling resolver.
3020   if (Global->hasAttr<IFuncAttr>())
3021     return emitIFuncDefinition(GD);
3022 
3023   // If this is a cpu_dispatch multiversion function, emit the resolver.
3024   if (Global->hasAttr<CPUDispatchAttr>())
3025     return emitCPUDispatchDefinition(GD);
3026 
3027   // If this is CUDA, be selective about which declarations we emit.
3028   if (LangOpts.CUDA) {
3029     if (LangOpts.CUDAIsDevice) {
3030       if (!Global->hasAttr<CUDADeviceAttr>() &&
3031           !Global->hasAttr<CUDAGlobalAttr>() &&
3032           !Global->hasAttr<CUDAConstantAttr>() &&
3033           !Global->hasAttr<CUDASharedAttr>() &&
3034           !Global->getType()->isCUDADeviceBuiltinSurfaceType() &&
3035           !Global->getType()->isCUDADeviceBuiltinTextureType())
3036         return;
3037     } else {
3038       // We need to emit host-side 'shadows' for all global
3039       // device-side variables because the CUDA runtime needs their
3040       // size and host-side address in order to provide access to
3041       // their device-side incarnations.
3042 
3043       // So device-only functions are the only things we skip.
3044       if (isa<FunctionDecl>(Global) && !Global->hasAttr<CUDAHostAttr>() &&
3045           Global->hasAttr<CUDADeviceAttr>())
3046         return;
3047 
3048       assert((isa<FunctionDecl>(Global) || isa<VarDecl>(Global)) &&
3049              "Expected Variable or Function");
3050     }
3051   }
3052 
3053   if (LangOpts.OpenMP) {
3054     // If this is OpenMP, check if it is legal to emit this global normally.
3055     if (OpenMPRuntime && OpenMPRuntime->emitTargetGlobal(GD))
3056       return;
3057     if (auto *DRD = dyn_cast<OMPDeclareReductionDecl>(Global)) {
3058       if (MustBeEmitted(Global))
3059         EmitOMPDeclareReduction(DRD);
3060       return;
3061     } else if (auto *DMD = dyn_cast<OMPDeclareMapperDecl>(Global)) {
3062       if (MustBeEmitted(Global))
3063         EmitOMPDeclareMapper(DMD);
3064       return;
3065     }
3066   }
3067 
3068   // Ignore declarations, they will be emitted on their first use.
3069   if (const auto *FD = dyn_cast<FunctionDecl>(Global)) {
3070     // Forward declarations are emitted lazily on first use.
3071     if (!FD->doesThisDeclarationHaveABody()) {
3072       if (!FD->doesDeclarationForceExternallyVisibleDefinition())
3073         return;
3074 
3075       StringRef MangledName = getMangledName(GD);
3076 
3077       // Compute the function info and LLVM type.
3078       const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
3079       llvm::Type *Ty = getTypes().GetFunctionType(FI);
3080 
3081       GetOrCreateLLVMFunction(MangledName, Ty, GD, /*ForVTable=*/false,
3082                               /*DontDefer=*/false);
3083       return;
3084     }
3085   } else {
3086     const auto *VD = cast<VarDecl>(Global);
3087     assert(VD->isFileVarDecl() && "Cannot emit local var decl as global.");
3088     if (VD->isThisDeclarationADefinition() != VarDecl::Definition &&
3089         !Context.isMSStaticDataMemberInlineDefinition(VD)) {
3090       if (LangOpts.OpenMP) {
3091         // Emit declaration of the must-be-emitted declare target variable.
3092         if (llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
3093                 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD)) {
3094           bool UnifiedMemoryEnabled =
3095               getOpenMPRuntime().hasRequiresUnifiedSharedMemory();
3096           if (*Res == OMPDeclareTargetDeclAttr::MT_To &&
3097               !UnifiedMemoryEnabled) {
3098             (void)GetAddrOfGlobalVar(VD);
3099           } else {
3100             assert(((*Res == OMPDeclareTargetDeclAttr::MT_Link) ||
3101                     (*Res == OMPDeclareTargetDeclAttr::MT_To &&
3102                      UnifiedMemoryEnabled)) &&
3103                    "Link clause or to clause with unified memory expected.");
3104             (void)getOpenMPRuntime().getAddrOfDeclareTargetVar(VD);
3105           }
3106 
3107           return;
3108         }
3109       }
3110       // If this declaration may have caused an inline variable definition to
3111       // change linkage, make sure that it's emitted.
3112       if (Context.getInlineVariableDefinitionKind(VD) ==
3113           ASTContext::InlineVariableDefinitionKind::Strong)
3114         GetAddrOfGlobalVar(VD);
3115       return;
3116     }
3117   }
3118 
3119   // Defer code generation to first use when possible, e.g. if this is an inline
3120   // function. If the global must always be emitted, do it eagerly if possible
3121   // to benefit from cache locality.
3122   if (MustBeEmitted(Global) && MayBeEmittedEagerly(Global)) {
3123     // Emit the definition if it can't be deferred.
3124     EmitGlobalDefinition(GD);
3125     return;
3126   }
3127 
3128   // If we're deferring emission of a C++ variable with an
3129   // initializer, remember the order in which it appeared in the file.
3130   if (getLangOpts().CPlusPlus && isa<VarDecl>(Global) &&
3131       cast<VarDecl>(Global)->hasInit()) {
3132     DelayedCXXInitPosition[Global] = CXXGlobalInits.size();
3133     CXXGlobalInits.push_back(nullptr);
3134   }
3135 
3136   StringRef MangledName = getMangledName(GD);
3137   if (GetGlobalValue(MangledName) != nullptr) {
3138     // The value has already been used and should therefore be emitted.
3139     addDeferredDeclToEmit(GD);
3140   } else if (MustBeEmitted(Global)) {
3141     // The value must be emitted, but cannot be emitted eagerly.
3142     assert(!MayBeEmittedEagerly(Global));
3143     addDeferredDeclToEmit(GD);
3144   } else {
3145     // Otherwise, remember that we saw a deferred decl with this name.  The
3146     // first use of the mangled name will cause it to move into
3147     // DeferredDeclsToEmit.
3148     DeferredDecls[MangledName] = GD;
3149   }
3150 }
3151 
3152 // Check if T is a class type with a destructor that's not dllimport.
3153 static bool HasNonDllImportDtor(QualType T) {
3154   if (const auto *RT = T->getBaseElementTypeUnsafe()->getAs<RecordType>())
3155     if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl()))
3156       if (RD->getDestructor() && !RD->getDestructor()->hasAttr<DLLImportAttr>())
3157         return true;
3158 
3159   return false;
3160 }
3161 
3162 namespace {
3163   struct FunctionIsDirectlyRecursive
3164       : public ConstStmtVisitor<FunctionIsDirectlyRecursive, bool> {
3165     const StringRef Name;
3166     const Builtin::Context &BI;
3167     FunctionIsDirectlyRecursive(StringRef N, const Builtin::Context &C)
3168         : Name(N), BI(C) {}
3169 
3170     bool VisitCallExpr(const CallExpr *E) {
3171       const FunctionDecl *FD = E->getDirectCallee();
3172       if (!FD)
3173         return false;
3174       AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>();
3175       if (Attr && Name == Attr->getLabel())
3176         return true;
3177       unsigned BuiltinID = FD->getBuiltinID();
3178       if (!BuiltinID || !BI.isLibFunction(BuiltinID))
3179         return false;
3180       StringRef BuiltinName = BI.getName(BuiltinID);
3181       if (BuiltinName.startswith("__builtin_") &&
3182           Name == BuiltinName.slice(strlen("__builtin_"), StringRef::npos)) {
3183         return true;
3184       }
3185       return false;
3186     }
3187 
3188     bool VisitStmt(const Stmt *S) {
3189       for (const Stmt *Child : S->children())
3190         if (Child && this->Visit(Child))
3191           return true;
3192       return false;
3193     }
3194   };
3195 
3196   // Make sure we're not referencing non-imported vars or functions.
3197   struct DLLImportFunctionVisitor
3198       : public RecursiveASTVisitor<DLLImportFunctionVisitor> {
3199     bool SafeToInline = true;
3200 
3201     bool shouldVisitImplicitCode() const { return true; }
3202 
3203     bool VisitVarDecl(VarDecl *VD) {
3204       if (VD->getTLSKind()) {
3205         // A thread-local variable cannot be imported.
3206         SafeToInline = false;
3207         return SafeToInline;
3208       }
3209 
3210       // A variable definition might imply a destructor call.
3211       if (VD->isThisDeclarationADefinition())
3212         SafeToInline = !HasNonDllImportDtor(VD->getType());
3213 
3214       return SafeToInline;
3215     }
3216 
3217     bool VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
3218       if (const auto *D = E->getTemporary()->getDestructor())
3219         SafeToInline = D->hasAttr<DLLImportAttr>();
3220       return SafeToInline;
3221     }
3222 
3223     bool VisitDeclRefExpr(DeclRefExpr *E) {
3224       ValueDecl *VD = E->getDecl();
3225       if (isa<FunctionDecl>(VD))
3226         SafeToInline = VD->hasAttr<DLLImportAttr>();
3227       else if (VarDecl *V = dyn_cast<VarDecl>(VD))
3228         SafeToInline = !V->hasGlobalStorage() || V->hasAttr<DLLImportAttr>();
3229       return SafeToInline;
3230     }
3231 
3232     bool VisitCXXConstructExpr(CXXConstructExpr *E) {
3233       SafeToInline = E->getConstructor()->hasAttr<DLLImportAttr>();
3234       return SafeToInline;
3235     }
3236 
3237     bool VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
3238       CXXMethodDecl *M = E->getMethodDecl();
3239       if (!M) {
3240         // Call through a pointer to member function. This is safe to inline.
3241         SafeToInline = true;
3242       } else {
3243         SafeToInline = M->hasAttr<DLLImportAttr>();
3244       }
3245       return SafeToInline;
3246     }
3247 
3248     bool VisitCXXDeleteExpr(CXXDeleteExpr *E) {
3249       SafeToInline = E->getOperatorDelete()->hasAttr<DLLImportAttr>();
3250       return SafeToInline;
3251     }
3252 
3253     bool VisitCXXNewExpr(CXXNewExpr *E) {
3254       SafeToInline = E->getOperatorNew()->hasAttr<DLLImportAttr>();
3255       return SafeToInline;
3256     }
3257   };
3258 }
3259 
3260 // isTriviallyRecursive - Check if this function calls another
3261 // decl that, because of the asm attribute or the other decl being a builtin,
3262 // ends up pointing to itself.
3263 bool
3264 CodeGenModule::isTriviallyRecursive(const FunctionDecl *FD) {
3265   StringRef Name;
3266   if (getCXXABI().getMangleContext().shouldMangleDeclName(FD)) {
3267     // asm labels are a special kind of mangling we have to support.
3268     AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>();
3269     if (!Attr)
3270       return false;
3271     Name = Attr->getLabel();
3272   } else {
3273     Name = FD->getName();
3274   }
3275 
3276   FunctionIsDirectlyRecursive Walker(Name, Context.BuiltinInfo);
3277   const Stmt *Body = FD->getBody();
3278   return Body ? Walker.Visit(Body) : false;
3279 }
3280 
3281 bool CodeGenModule::shouldEmitFunction(GlobalDecl GD) {
3282   if (getFunctionLinkage(GD) != llvm::Function::AvailableExternallyLinkage)
3283     return true;
3284   const auto *F = cast<FunctionDecl>(GD.getDecl());
3285   if (CodeGenOpts.OptimizationLevel == 0 && !F->hasAttr<AlwaysInlineAttr>())
3286     return false;
3287 
3288   if (F->hasAttr<DLLImportAttr>() && !F->hasAttr<AlwaysInlineAttr>()) {
3289     // Check whether it would be safe to inline this dllimport function.
3290     DLLImportFunctionVisitor Visitor;
3291     Visitor.TraverseFunctionDecl(const_cast<FunctionDecl*>(F));
3292     if (!Visitor.SafeToInline)
3293       return false;
3294 
3295     if (const CXXDestructorDecl *Dtor = dyn_cast<CXXDestructorDecl>(F)) {
3296       // Implicit destructor invocations aren't captured in the AST, so the
3297       // check above can't see them. Check for them manually here.
3298       for (const Decl *Member : Dtor->getParent()->decls())
3299         if (isa<FieldDecl>(Member))
3300           if (HasNonDllImportDtor(cast<FieldDecl>(Member)->getType()))
3301             return false;
3302       for (const CXXBaseSpecifier &B : Dtor->getParent()->bases())
3303         if (HasNonDllImportDtor(B.getType()))
3304           return false;
3305     }
3306   }
3307 
3308   // Inline builtins declaration must be emitted. They often are fortified
3309   // functions.
3310   if (F->isInlineBuiltinDeclaration())
3311     return true;
3312 
3313   // PR9614. Avoid cases where the source code is lying to us. An available
3314   // externally function should have an equivalent function somewhere else,
3315   // but a function that calls itself through asm label/`__builtin_` trickery is
3316   // clearly not equivalent to the real implementation.
3317   // This happens in glibc's btowc and in some configure checks.
3318   return !isTriviallyRecursive(F);
3319 }
3320 
3321 bool CodeGenModule::shouldOpportunisticallyEmitVTables() {
3322   return CodeGenOpts.OptimizationLevel > 0;
3323 }
3324 
3325 void CodeGenModule::EmitMultiVersionFunctionDefinition(GlobalDecl GD,
3326                                                        llvm::GlobalValue *GV) {
3327   const auto *FD = cast<FunctionDecl>(GD.getDecl());
3328 
3329   if (FD->isCPUSpecificMultiVersion()) {
3330     auto *Spec = FD->getAttr<CPUSpecificAttr>();
3331     for (unsigned I = 0; I < Spec->cpus_size(); ++I)
3332       EmitGlobalFunctionDefinition(GD.getWithMultiVersionIndex(I), nullptr);
3333   } else if (FD->isTargetClonesMultiVersion()) {
3334     auto *Clone = FD->getAttr<TargetClonesAttr>();
3335     for (unsigned I = 0; I < Clone->featuresStrs_size(); ++I)
3336       if (Clone->isFirstOfVersion(I))
3337         EmitGlobalFunctionDefinition(GD.getWithMultiVersionIndex(I), nullptr);
3338     // Ensure that the resolver function is also emitted.
3339     GetOrCreateMultiVersionResolver(GD);
3340   } else
3341     EmitGlobalFunctionDefinition(GD, GV);
3342 }
3343 
3344 void CodeGenModule::EmitGlobalDefinition(GlobalDecl GD, llvm::GlobalValue *GV) {
3345   const auto *D = cast<ValueDecl>(GD.getDecl());
3346 
3347   PrettyStackTraceDecl CrashInfo(const_cast<ValueDecl *>(D), D->getLocation(),
3348                                  Context.getSourceManager(),
3349                                  "Generating code for declaration");
3350 
3351   if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
3352     // At -O0, don't generate IR for functions with available_externally
3353     // linkage.
3354     if (!shouldEmitFunction(GD))
3355       return;
3356 
3357     llvm::TimeTraceScope TimeScope("CodeGen Function", [&]() {
3358       std::string Name;
3359       llvm::raw_string_ostream OS(Name);
3360       FD->getNameForDiagnostic(OS, getContext().getPrintingPolicy(),
3361                                /*Qualified=*/true);
3362       return Name;
3363     });
3364 
3365     if (const auto *Method = dyn_cast<CXXMethodDecl>(D)) {
3366       // Make sure to emit the definition(s) before we emit the thunks.
3367       // This is necessary for the generation of certain thunks.
3368       if (isa<CXXConstructorDecl>(Method) || isa<CXXDestructorDecl>(Method))
3369         ABI->emitCXXStructor(GD);
3370       else if (FD->isMultiVersion())
3371         EmitMultiVersionFunctionDefinition(GD, GV);
3372       else
3373         EmitGlobalFunctionDefinition(GD, GV);
3374 
3375       if (Method->isVirtual())
3376         getVTables().EmitThunks(GD);
3377 
3378       return;
3379     }
3380 
3381     if (FD->isMultiVersion())
3382       return EmitMultiVersionFunctionDefinition(GD, GV);
3383     return EmitGlobalFunctionDefinition(GD, GV);
3384   }
3385 
3386   if (const auto *VD = dyn_cast<VarDecl>(D))
3387     return EmitGlobalVarDefinition(VD, !VD->hasDefinition());
3388 
3389   llvm_unreachable("Invalid argument to EmitGlobalDefinition()");
3390 }
3391 
3392 static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old,
3393                                                       llvm::Function *NewFn);
3394 
3395 static unsigned
3396 TargetMVPriority(const TargetInfo &TI,
3397                  const CodeGenFunction::MultiVersionResolverOption &RO) {
3398   unsigned Priority = 0;
3399   for (StringRef Feat : RO.Conditions.Features)
3400     Priority = std::max(Priority, TI.multiVersionSortPriority(Feat));
3401 
3402   if (!RO.Conditions.Architecture.empty())
3403     Priority = std::max(
3404         Priority, TI.multiVersionSortPriority(RO.Conditions.Architecture));
3405   return Priority;
3406 }
3407 
3408 // Multiversion functions should be at most 'WeakODRLinkage' so that a different
3409 // TU can forward declare the function without causing problems.  Particularly
3410 // in the cases of CPUDispatch, this causes issues. This also makes sure we
3411 // work with internal linkage functions, so that the same function name can be
3412 // used with internal linkage in multiple TUs.
3413 llvm::GlobalValue::LinkageTypes getMultiversionLinkage(CodeGenModule &CGM,
3414                                                        GlobalDecl GD) {
3415   const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
3416   if (FD->getFormalLinkage() == InternalLinkage)
3417     return llvm::GlobalValue::InternalLinkage;
3418   return llvm::GlobalValue::WeakODRLinkage;
3419 }
3420 
3421 void CodeGenModule::emitMultiVersionFunctions() {
3422   std::vector<GlobalDecl> MVFuncsToEmit;
3423   MultiVersionFuncs.swap(MVFuncsToEmit);
3424   for (GlobalDecl GD : MVFuncsToEmit) {
3425     const auto *FD = cast<FunctionDecl>(GD.getDecl());
3426     assert(FD && "Expected a FunctionDecl");
3427 
3428     SmallVector<CodeGenFunction::MultiVersionResolverOption, 10> Options;
3429     if (FD->isTargetMultiVersion()) {
3430       getContext().forEachMultiversionedFunctionVersion(
3431           FD, [this, &GD, &Options](const FunctionDecl *CurFD) {
3432             GlobalDecl CurGD{
3433                 (CurFD->isDefined() ? CurFD->getDefinition() : CurFD)};
3434             StringRef MangledName = getMangledName(CurGD);
3435             llvm::Constant *Func = GetGlobalValue(MangledName);
3436             if (!Func) {
3437               if (CurFD->isDefined()) {
3438                 EmitGlobalFunctionDefinition(CurGD, nullptr);
3439                 Func = GetGlobalValue(MangledName);
3440               } else {
3441                 const CGFunctionInfo &FI =
3442                     getTypes().arrangeGlobalDeclaration(GD);
3443                 llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
3444                 Func = GetAddrOfFunction(CurGD, Ty, /*ForVTable=*/false,
3445                                          /*DontDefer=*/false, ForDefinition);
3446               }
3447               assert(Func && "This should have just been created");
3448             }
3449 
3450             const auto *TA = CurFD->getAttr<TargetAttr>();
3451             llvm::SmallVector<StringRef, 8> Feats;
3452             TA->getAddedFeatures(Feats);
3453 
3454             Options.emplace_back(cast<llvm::Function>(Func),
3455                                  TA->getArchitecture(), Feats);
3456           });
3457     } else if (FD->isTargetClonesMultiVersion()) {
3458       const auto *TC = FD->getAttr<TargetClonesAttr>();
3459       for (unsigned VersionIndex = 0; VersionIndex < TC->featuresStrs_size();
3460            ++VersionIndex) {
3461         if (!TC->isFirstOfVersion(VersionIndex))
3462           continue;
3463         GlobalDecl CurGD{(FD->isDefined() ? FD->getDefinition() : FD),
3464                          VersionIndex};
3465         StringRef Version = TC->getFeatureStr(VersionIndex);
3466         StringRef MangledName = getMangledName(CurGD);
3467         llvm::Constant *Func = GetGlobalValue(MangledName);
3468         if (!Func) {
3469           if (FD->isDefined()) {
3470             EmitGlobalFunctionDefinition(CurGD, nullptr);
3471             Func = GetGlobalValue(MangledName);
3472           } else {
3473             const CGFunctionInfo &FI =
3474                 getTypes().arrangeGlobalDeclaration(CurGD);
3475             llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
3476             Func = GetAddrOfFunction(CurGD, Ty, /*ForVTable=*/false,
3477                                      /*DontDefer=*/false, ForDefinition);
3478           }
3479           assert(Func && "This should have just been created");
3480         }
3481 
3482         StringRef Architecture;
3483         llvm::SmallVector<StringRef, 1> Feature;
3484 
3485         if (Version.startswith("arch="))
3486           Architecture = Version.drop_front(sizeof("arch=") - 1);
3487         else if (Version != "default")
3488           Feature.push_back(Version);
3489 
3490         Options.emplace_back(cast<llvm::Function>(Func), Architecture, Feature);
3491       }
3492     } else {
3493       assert(0 && "Expected a target or target_clones multiversion function");
3494       continue;
3495     }
3496 
3497     llvm::Constant *ResolverConstant = GetOrCreateMultiVersionResolver(GD);
3498     if (auto *IFunc = dyn_cast<llvm::GlobalIFunc>(ResolverConstant))
3499       ResolverConstant = IFunc->getResolver();
3500     llvm::Function *ResolverFunc = cast<llvm::Function>(ResolverConstant);
3501 
3502     ResolverFunc->setLinkage(getMultiversionLinkage(*this, GD));
3503 
3504     if (supportsCOMDAT())
3505       ResolverFunc->setComdat(
3506           getModule().getOrInsertComdat(ResolverFunc->getName()));
3507 
3508     const TargetInfo &TI = getTarget();
3509     llvm::stable_sort(
3510         Options, [&TI](const CodeGenFunction::MultiVersionResolverOption &LHS,
3511                        const CodeGenFunction::MultiVersionResolverOption &RHS) {
3512           return TargetMVPriority(TI, LHS) > TargetMVPriority(TI, RHS);
3513         });
3514     CodeGenFunction CGF(*this);
3515     CGF.EmitMultiVersionResolver(ResolverFunc, Options);
3516   }
3517 
3518   // Ensure that any additions to the deferred decls list caused by emitting a
3519   // variant are emitted.  This can happen when the variant itself is inline and
3520   // calls a function without linkage.
3521   if (!MVFuncsToEmit.empty())
3522     EmitDeferred();
3523 
3524   // Ensure that any additions to the multiversion funcs list from either the
3525   // deferred decls or the multiversion functions themselves are emitted.
3526   if (!MultiVersionFuncs.empty())
3527     emitMultiVersionFunctions();
3528 }
3529 
3530 void CodeGenModule::emitCPUDispatchDefinition(GlobalDecl GD) {
3531   const auto *FD = cast<FunctionDecl>(GD.getDecl());
3532   assert(FD && "Not a FunctionDecl?");
3533   assert(FD->isCPUDispatchMultiVersion() && "Not a multiversion function?");
3534   const auto *DD = FD->getAttr<CPUDispatchAttr>();
3535   assert(DD && "Not a cpu_dispatch Function?");
3536 
3537   const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
3538   llvm::FunctionType *DeclTy = getTypes().GetFunctionType(FI);
3539 
3540   StringRef ResolverName = getMangledName(GD);
3541   UpdateMultiVersionNames(GD, FD, ResolverName);
3542 
3543   llvm::Type *ResolverType;
3544   GlobalDecl ResolverGD;
3545   if (getTarget().supportsIFunc()) {
3546     ResolverType = llvm::FunctionType::get(
3547         llvm::PointerType::get(DeclTy,
3548                                Context.getTargetAddressSpace(FD->getType())),
3549         false);
3550   }
3551   else {
3552     ResolverType = DeclTy;
3553     ResolverGD = GD;
3554   }
3555 
3556   auto *ResolverFunc = cast<llvm::Function>(GetOrCreateLLVMFunction(
3557       ResolverName, ResolverType, ResolverGD, /*ForVTable=*/false));
3558   ResolverFunc->setLinkage(getMultiversionLinkage(*this, GD));
3559   if (supportsCOMDAT())
3560     ResolverFunc->setComdat(
3561         getModule().getOrInsertComdat(ResolverFunc->getName()));
3562 
3563   SmallVector<CodeGenFunction::MultiVersionResolverOption, 10> Options;
3564   const TargetInfo &Target = getTarget();
3565   unsigned Index = 0;
3566   for (const IdentifierInfo *II : DD->cpus()) {
3567     // Get the name of the target function so we can look it up/create it.
3568     std::string MangledName = getMangledNameImpl(*this, GD, FD, true) +
3569                               getCPUSpecificMangling(*this, II->getName());
3570 
3571     llvm::Constant *Func = GetGlobalValue(MangledName);
3572 
3573     if (!Func) {
3574       GlobalDecl ExistingDecl = Manglings.lookup(MangledName);
3575       if (ExistingDecl.getDecl() &&
3576           ExistingDecl.getDecl()->getAsFunction()->isDefined()) {
3577         EmitGlobalFunctionDefinition(ExistingDecl, nullptr);
3578         Func = GetGlobalValue(MangledName);
3579       } else {
3580         if (!ExistingDecl.getDecl())
3581           ExistingDecl = GD.getWithMultiVersionIndex(Index);
3582 
3583       Func = GetOrCreateLLVMFunction(
3584           MangledName, DeclTy, ExistingDecl,
3585           /*ForVTable=*/false, /*DontDefer=*/true,
3586           /*IsThunk=*/false, llvm::AttributeList(), ForDefinition);
3587       }
3588     }
3589 
3590     llvm::SmallVector<StringRef, 32> Features;
3591     Target.getCPUSpecificCPUDispatchFeatures(II->getName(), Features);
3592     llvm::transform(Features, Features.begin(),
3593                     [](StringRef Str) { return Str.substr(1); });
3594     llvm::erase_if(Features, [&Target](StringRef Feat) {
3595       return !Target.validateCpuSupports(Feat);
3596     });
3597     Options.emplace_back(cast<llvm::Function>(Func), StringRef{}, Features);
3598     ++Index;
3599   }
3600 
3601   llvm::stable_sort(
3602       Options, [](const CodeGenFunction::MultiVersionResolverOption &LHS,
3603                   const CodeGenFunction::MultiVersionResolverOption &RHS) {
3604         return llvm::X86::getCpuSupportsMask(LHS.Conditions.Features) >
3605                llvm::X86::getCpuSupportsMask(RHS.Conditions.Features);
3606       });
3607 
3608   // If the list contains multiple 'default' versions, such as when it contains
3609   // 'pentium' and 'generic', don't emit the call to the generic one (since we
3610   // always run on at least a 'pentium'). We do this by deleting the 'least
3611   // advanced' (read, lowest mangling letter).
3612   while (Options.size() > 1 &&
3613          llvm::X86::getCpuSupportsMask(
3614              (Options.end() - 2)->Conditions.Features) == 0) {
3615     StringRef LHSName = (Options.end() - 2)->Function->getName();
3616     StringRef RHSName = (Options.end() - 1)->Function->getName();
3617     if (LHSName.compare(RHSName) < 0)
3618       Options.erase(Options.end() - 2);
3619     else
3620       Options.erase(Options.end() - 1);
3621   }
3622 
3623   CodeGenFunction CGF(*this);
3624   CGF.EmitMultiVersionResolver(ResolverFunc, Options);
3625 
3626   if (getTarget().supportsIFunc()) {
3627     llvm::GlobalValue::LinkageTypes Linkage = getMultiversionLinkage(*this, GD);
3628     auto *IFunc = cast<llvm::GlobalValue>(GetOrCreateMultiVersionResolver(GD));
3629 
3630     // Fix up function declarations that were created for cpu_specific before
3631     // cpu_dispatch was known
3632     if (!dyn_cast<llvm::GlobalIFunc>(IFunc)) {
3633       assert(cast<llvm::Function>(IFunc)->isDeclaration());
3634       auto *GI = llvm::GlobalIFunc::create(DeclTy, 0, Linkage, "", ResolverFunc,
3635                                            &getModule());
3636       GI->takeName(IFunc);
3637       IFunc->replaceAllUsesWith(GI);
3638       IFunc->eraseFromParent();
3639       IFunc = GI;
3640     }
3641 
3642     std::string AliasName = getMangledNameImpl(
3643         *this, GD, FD, /*OmitMultiVersionMangling=*/true);
3644     llvm::Constant *AliasFunc = GetGlobalValue(AliasName);
3645     if (!AliasFunc) {
3646       auto *GA = llvm::GlobalAlias::create(DeclTy, 0, Linkage, AliasName, IFunc,
3647                                            &getModule());
3648       SetCommonAttributes(GD, GA);
3649     }
3650   }
3651 }
3652 
3653 /// If a dispatcher for the specified mangled name is not in the module, create
3654 /// and return an llvm Function with the specified type.
3655 llvm::Constant *CodeGenModule::GetOrCreateMultiVersionResolver(GlobalDecl GD) {
3656   const auto *FD = cast<FunctionDecl>(GD.getDecl());
3657   assert(FD && "Not a FunctionDecl?");
3658 
3659   std::string MangledName =
3660       getMangledNameImpl(*this, GD, FD, /*OmitMultiVersionMangling=*/true);
3661 
3662   // Holds the name of the resolver, in ifunc mode this is the ifunc (which has
3663   // a separate resolver).
3664   std::string ResolverName = MangledName;
3665   if (getTarget().supportsIFunc())
3666     ResolverName += ".ifunc";
3667   else if (FD->isTargetMultiVersion())
3668     ResolverName += ".resolver";
3669 
3670   // If the resolver has already been created, just return it.
3671   if (llvm::GlobalValue *ResolverGV = GetGlobalValue(ResolverName))
3672     return ResolverGV;
3673 
3674   const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
3675   llvm::FunctionType *DeclTy = getTypes().GetFunctionType(FI);
3676 
3677   // The resolver needs to be created. For target and target_clones, defer
3678   // creation until the end of the TU.
3679   if (FD->isTargetMultiVersion() || FD->isTargetClonesMultiVersion())
3680     MultiVersionFuncs.push_back(GD);
3681 
3682   // For cpu_specific, don't create an ifunc yet because we don't know if the
3683   // cpu_dispatch will be emitted in this translation unit.
3684   if (getTarget().supportsIFunc() && !FD->isCPUSpecificMultiVersion()) {
3685     llvm::Type *ResolverType = llvm::FunctionType::get(
3686         llvm::PointerType::get(
3687             DeclTy, getContext().getTargetAddressSpace(FD->getType())),
3688         false);
3689     llvm::Constant *Resolver = GetOrCreateLLVMFunction(
3690         MangledName + ".resolver", ResolverType, GlobalDecl{},
3691         /*ForVTable=*/false);
3692     llvm::GlobalIFunc *GIF =
3693         llvm::GlobalIFunc::create(DeclTy, 0, getMultiversionLinkage(*this, GD),
3694                                   "", Resolver, &getModule());
3695     GIF->setName(ResolverName);
3696     SetCommonAttributes(FD, GIF);
3697 
3698     return GIF;
3699   }
3700 
3701   llvm::Constant *Resolver = GetOrCreateLLVMFunction(
3702       ResolverName, DeclTy, GlobalDecl{}, /*ForVTable=*/false);
3703   assert(isa<llvm::GlobalValue>(Resolver) &&
3704          "Resolver should be created for the first time");
3705   SetCommonAttributes(FD, cast<llvm::GlobalValue>(Resolver));
3706   return Resolver;
3707 }
3708 
3709 /// GetOrCreateLLVMFunction - If the specified mangled name is not in the
3710 /// module, create and return an llvm Function with the specified type. If there
3711 /// is something in the module with the specified name, return it potentially
3712 /// bitcasted to the right type.
3713 ///
3714 /// If D is non-null, it specifies a decl that correspond to this.  This is used
3715 /// to set the attributes on the function when it is first created.
3716 llvm::Constant *CodeGenModule::GetOrCreateLLVMFunction(
3717     StringRef MangledName, llvm::Type *Ty, GlobalDecl GD, bool ForVTable,
3718     bool DontDefer, bool IsThunk, llvm::AttributeList ExtraAttrs,
3719     ForDefinition_t IsForDefinition) {
3720   const Decl *D = GD.getDecl();
3721 
3722   // Any attempts to use a MultiVersion function should result in retrieving
3723   // the iFunc instead. Name Mangling will handle the rest of the changes.
3724   if (const FunctionDecl *FD = cast_or_null<FunctionDecl>(D)) {
3725     // For the device mark the function as one that should be emitted.
3726     if (getLangOpts().OpenMPIsDevice && OpenMPRuntime &&
3727         !OpenMPRuntime->markAsGlobalTarget(GD) && FD->isDefined() &&
3728         !DontDefer && !IsForDefinition) {
3729       if (const FunctionDecl *FDDef = FD->getDefinition()) {
3730         GlobalDecl GDDef;
3731         if (const auto *CD = dyn_cast<CXXConstructorDecl>(FDDef))
3732           GDDef = GlobalDecl(CD, GD.getCtorType());
3733         else if (const auto *DD = dyn_cast<CXXDestructorDecl>(FDDef))
3734           GDDef = GlobalDecl(DD, GD.getDtorType());
3735         else
3736           GDDef = GlobalDecl(FDDef);
3737         EmitGlobal(GDDef);
3738       }
3739     }
3740 
3741     if (FD->isMultiVersion()) {
3742       UpdateMultiVersionNames(GD, FD, MangledName);
3743       if (!IsForDefinition)
3744         return GetOrCreateMultiVersionResolver(GD);
3745     }
3746   }
3747 
3748   // Lookup the entry, lazily creating it if necessary.
3749   llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
3750   if (Entry) {
3751     if (WeakRefReferences.erase(Entry)) {
3752       const FunctionDecl *FD = cast_or_null<FunctionDecl>(D);
3753       if (FD && !FD->hasAttr<WeakAttr>())
3754         Entry->setLinkage(llvm::Function::ExternalLinkage);
3755     }
3756 
3757     // Handle dropped DLL attributes.
3758     if (D && !D->hasAttr<DLLImportAttr>() && !D->hasAttr<DLLExportAttr>()) {
3759       Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
3760       setDSOLocal(Entry);
3761     }
3762 
3763     // If there are two attempts to define the same mangled name, issue an
3764     // error.
3765     if (IsForDefinition && !Entry->isDeclaration()) {
3766       GlobalDecl OtherGD;
3767       // Check that GD is not yet in DiagnosedConflictingDefinitions is required
3768       // to make sure that we issue an error only once.
3769       if (lookupRepresentativeDecl(MangledName, OtherGD) &&
3770           (GD.getCanonicalDecl().getDecl() !=
3771            OtherGD.getCanonicalDecl().getDecl()) &&
3772           DiagnosedConflictingDefinitions.insert(GD).second) {
3773         getDiags().Report(D->getLocation(), diag::err_duplicate_mangled_name)
3774             << MangledName;
3775         getDiags().Report(OtherGD.getDecl()->getLocation(),
3776                           diag::note_previous_definition);
3777       }
3778     }
3779 
3780     if ((isa<llvm::Function>(Entry) || isa<llvm::GlobalAlias>(Entry)) &&
3781         (Entry->getValueType() == Ty)) {
3782       return Entry;
3783     }
3784 
3785     // Make sure the result is of the correct type.
3786     // (If function is requested for a definition, we always need to create a new
3787     // function, not just return a bitcast.)
3788     if (!IsForDefinition)
3789       return llvm::ConstantExpr::getBitCast(Entry, Ty->getPointerTo());
3790   }
3791 
3792   // This function doesn't have a complete type (for example, the return
3793   // type is an incomplete struct). Use a fake type instead, and make
3794   // sure not to try to set attributes.
3795   bool IsIncompleteFunction = false;
3796 
3797   llvm::FunctionType *FTy;
3798   if (isa<llvm::FunctionType>(Ty)) {
3799     FTy = cast<llvm::FunctionType>(Ty);
3800   } else {
3801     FTy = llvm::FunctionType::get(VoidTy, false);
3802     IsIncompleteFunction = true;
3803   }
3804 
3805   llvm::Function *F =
3806       llvm::Function::Create(FTy, llvm::Function::ExternalLinkage,
3807                              Entry ? StringRef() : MangledName, &getModule());
3808 
3809   // If we already created a function with the same mangled name (but different
3810   // type) before, take its name and add it to the list of functions to be
3811   // replaced with F at the end of CodeGen.
3812   //
3813   // This happens if there is a prototype for a function (e.g. "int f()") and
3814   // then a definition of a different type (e.g. "int f(int x)").
3815   if (Entry) {
3816     F->takeName(Entry);
3817 
3818     // This might be an implementation of a function without a prototype, in
3819     // which case, try to do special replacement of calls which match the new
3820     // prototype.  The really key thing here is that we also potentially drop
3821     // arguments from the call site so as to make a direct call, which makes the
3822     // inliner happier and suppresses a number of optimizer warnings (!) about
3823     // dropping arguments.
3824     if (!Entry->use_empty()) {
3825       ReplaceUsesOfNonProtoTypeWithRealFunction(Entry, F);
3826       Entry->removeDeadConstantUsers();
3827     }
3828 
3829     llvm::Constant *BC = llvm::ConstantExpr::getBitCast(
3830         F, Entry->getValueType()->getPointerTo());
3831     addGlobalValReplacement(Entry, BC);
3832   }
3833 
3834   assert(F->getName() == MangledName && "name was uniqued!");
3835   if (D)
3836     SetFunctionAttributes(GD, F, IsIncompleteFunction, IsThunk);
3837   if (ExtraAttrs.hasFnAttrs()) {
3838     llvm::AttrBuilder B(F->getContext(), ExtraAttrs.getFnAttrs());
3839     F->addFnAttrs(B);
3840   }
3841 
3842   if (!DontDefer) {
3843     // All MSVC dtors other than the base dtor are linkonce_odr and delegate to
3844     // each other bottoming out with the base dtor.  Therefore we emit non-base
3845     // dtors on usage, even if there is no dtor definition in the TU.
3846     if (D && isa<CXXDestructorDecl>(D) &&
3847         getCXXABI().useThunkForDtorVariant(cast<CXXDestructorDecl>(D),
3848                                            GD.getDtorType()))
3849       addDeferredDeclToEmit(GD);
3850 
3851     // This is the first use or definition of a mangled name.  If there is a
3852     // deferred decl with this name, remember that we need to emit it at the end
3853     // of the file.
3854     auto DDI = DeferredDecls.find(MangledName);
3855     if (DDI != DeferredDecls.end()) {
3856       // Move the potentially referenced deferred decl to the
3857       // DeferredDeclsToEmit list, and remove it from DeferredDecls (since we
3858       // don't need it anymore).
3859       addDeferredDeclToEmit(DDI->second);
3860       DeferredDecls.erase(DDI);
3861 
3862       // Otherwise, there are cases we have to worry about where we're
3863       // using a declaration for which we must emit a definition but where
3864       // we might not find a top-level definition:
3865       //   - member functions defined inline in their classes
3866       //   - friend functions defined inline in some class
3867       //   - special member functions with implicit definitions
3868       // If we ever change our AST traversal to walk into class methods,
3869       // this will be unnecessary.
3870       //
3871       // We also don't emit a definition for a function if it's going to be an
3872       // entry in a vtable, unless it's already marked as used.
3873     } else if (getLangOpts().CPlusPlus && D) {
3874       // Look for a declaration that's lexically in a record.
3875       for (const auto *FD = cast<FunctionDecl>(D)->getMostRecentDecl(); FD;
3876            FD = FD->getPreviousDecl()) {
3877         if (isa<CXXRecordDecl>(FD->getLexicalDeclContext())) {
3878           if (FD->doesThisDeclarationHaveABody()) {
3879             addDeferredDeclToEmit(GD.getWithDecl(FD));
3880             break;
3881           }
3882         }
3883       }
3884     }
3885   }
3886 
3887   // Make sure the result is of the requested type.
3888   if (!IsIncompleteFunction) {
3889     assert(F->getFunctionType() == Ty);
3890     return F;
3891   }
3892 
3893   llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
3894   return llvm::ConstantExpr::getBitCast(F, PTy);
3895 }
3896 
3897 /// GetAddrOfFunction - Return the address of the given function.  If Ty is
3898 /// non-null, then this function will use the specified type if it has to
3899 /// create it (this occurs when we see a definition of the function).
3900 llvm::Constant *CodeGenModule::GetAddrOfFunction(GlobalDecl GD,
3901                                                  llvm::Type *Ty,
3902                                                  bool ForVTable,
3903                                                  bool DontDefer,
3904                                               ForDefinition_t IsForDefinition) {
3905   assert(!cast<FunctionDecl>(GD.getDecl())->isConsteval() &&
3906          "consteval function should never be emitted");
3907   // If there was no specific requested type, just convert it now.
3908   if (!Ty) {
3909     const auto *FD = cast<FunctionDecl>(GD.getDecl());
3910     Ty = getTypes().ConvertType(FD->getType());
3911   }
3912 
3913   // Devirtualized destructor calls may come through here instead of via
3914   // getAddrOfCXXStructor. Make sure we use the MS ABI base destructor instead
3915   // of the complete destructor when necessary.
3916   if (const auto *DD = dyn_cast<CXXDestructorDecl>(GD.getDecl())) {
3917     if (getTarget().getCXXABI().isMicrosoft() &&
3918         GD.getDtorType() == Dtor_Complete &&
3919         DD->getParent()->getNumVBases() == 0)
3920       GD = GlobalDecl(DD, Dtor_Base);
3921   }
3922 
3923   StringRef MangledName = getMangledName(GD);
3924   auto *F = GetOrCreateLLVMFunction(MangledName, Ty, GD, ForVTable, DontDefer,
3925                                     /*IsThunk=*/false, llvm::AttributeList(),
3926                                     IsForDefinition);
3927   // Returns kernel handle for HIP kernel stub function.
3928   if (LangOpts.CUDA && !LangOpts.CUDAIsDevice &&
3929       cast<FunctionDecl>(GD.getDecl())->hasAttr<CUDAGlobalAttr>()) {
3930     auto *Handle = getCUDARuntime().getKernelHandle(
3931         cast<llvm::Function>(F->stripPointerCasts()), GD);
3932     if (IsForDefinition)
3933       return F;
3934     return llvm::ConstantExpr::getBitCast(Handle, Ty->getPointerTo());
3935   }
3936   return F;
3937 }
3938 
3939 llvm::Constant *CodeGenModule::GetFunctionStart(const ValueDecl *Decl) {
3940   llvm::GlobalValue *F =
3941       cast<llvm::GlobalValue>(GetAddrOfFunction(Decl)->stripPointerCasts());
3942 
3943   return llvm::ConstantExpr::getBitCast(llvm::NoCFIValue::get(F),
3944                                         llvm::Type::getInt8PtrTy(VMContext));
3945 }
3946 
3947 static const FunctionDecl *
3948 GetRuntimeFunctionDecl(ASTContext &C, StringRef Name) {
3949   TranslationUnitDecl *TUDecl = C.getTranslationUnitDecl();
3950   DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl);
3951 
3952   IdentifierInfo &CII = C.Idents.get(Name);
3953   for (const auto *Result : DC->lookup(&CII))
3954     if (const auto *FD = dyn_cast<FunctionDecl>(Result))
3955       return FD;
3956 
3957   if (!C.getLangOpts().CPlusPlus)
3958     return nullptr;
3959 
3960   // Demangle the premangled name from getTerminateFn()
3961   IdentifierInfo &CXXII =
3962       (Name == "_ZSt9terminatev" || Name == "?terminate@@YAXXZ")
3963           ? C.Idents.get("terminate")
3964           : C.Idents.get(Name);
3965 
3966   for (const auto &N : {"__cxxabiv1", "std"}) {
3967     IdentifierInfo &NS = C.Idents.get(N);
3968     for (const auto *Result : DC->lookup(&NS)) {
3969       const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(Result);
3970       if (auto *LSD = dyn_cast<LinkageSpecDecl>(Result))
3971         for (const auto *Result : LSD->lookup(&NS))
3972           if ((ND = dyn_cast<NamespaceDecl>(Result)))
3973             break;
3974 
3975       if (ND)
3976         for (const auto *Result : ND->lookup(&CXXII))
3977           if (const auto *FD = dyn_cast<FunctionDecl>(Result))
3978             return FD;
3979     }
3980   }
3981 
3982   return nullptr;
3983 }
3984 
3985 /// CreateRuntimeFunction - Create a new runtime function with the specified
3986 /// type and name.
3987 llvm::FunctionCallee
3988 CodeGenModule::CreateRuntimeFunction(llvm::FunctionType *FTy, StringRef Name,
3989                                      llvm::AttributeList ExtraAttrs, bool Local,
3990                                      bool AssumeConvergent) {
3991   if (AssumeConvergent) {
3992     ExtraAttrs =
3993         ExtraAttrs.addFnAttribute(VMContext, llvm::Attribute::Convergent);
3994   }
3995 
3996   llvm::Constant *C =
3997       GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(), /*ForVTable=*/false,
3998                               /*DontDefer=*/false, /*IsThunk=*/false,
3999                               ExtraAttrs);
4000 
4001   if (auto *F = dyn_cast<llvm::Function>(C)) {
4002     if (F->empty()) {
4003       F->setCallingConv(getRuntimeCC());
4004 
4005       // In Windows Itanium environments, try to mark runtime functions
4006       // dllimport. For Mingw and MSVC, don't. We don't really know if the user
4007       // will link their standard library statically or dynamically. Marking
4008       // functions imported when they are not imported can cause linker errors
4009       // and warnings.
4010       if (!Local && getTriple().isWindowsItaniumEnvironment() &&
4011           !getCodeGenOpts().LTOVisibilityPublicStd) {
4012         const FunctionDecl *FD = GetRuntimeFunctionDecl(Context, Name);
4013         if (!FD || FD->hasAttr<DLLImportAttr>()) {
4014           F->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
4015           F->setLinkage(llvm::GlobalValue::ExternalLinkage);
4016         }
4017       }
4018       setDSOLocal(F);
4019     }
4020   }
4021 
4022   return {FTy, C};
4023 }
4024 
4025 /// isTypeConstant - Determine whether an object of this type can be emitted
4026 /// as a constant.
4027 ///
4028 /// If ExcludeCtor is true, the duration when the object's constructor runs
4029 /// will not be considered. The caller will need to verify that the object is
4030 /// not written to during its construction.
4031 bool CodeGenModule::isTypeConstant(QualType Ty, bool ExcludeCtor) {
4032   if (!Ty.isConstant(Context) && !Ty->isReferenceType())
4033     return false;
4034 
4035   if (Context.getLangOpts().CPlusPlus) {
4036     if (const CXXRecordDecl *Record
4037           = Context.getBaseElementType(Ty)->getAsCXXRecordDecl())
4038       return ExcludeCtor && !Record->hasMutableFields() &&
4039              Record->hasTrivialDestructor();
4040   }
4041 
4042   return true;
4043 }
4044 
4045 /// GetOrCreateLLVMGlobal - If the specified mangled name is not in the module,
4046 /// create and return an llvm GlobalVariable with the specified type and address
4047 /// space. If there is something in the module with the specified name, return
4048 /// it potentially bitcasted to the right type.
4049 ///
4050 /// If D is non-null, it specifies a decl that correspond to this.  This is used
4051 /// to set the attributes on the global when it is first created.
4052 ///
4053 /// If IsForDefinition is true, it is guaranteed that an actual global with
4054 /// type Ty will be returned, not conversion of a variable with the same
4055 /// mangled name but some other type.
4056 llvm::Constant *
4057 CodeGenModule::GetOrCreateLLVMGlobal(StringRef MangledName, llvm::Type *Ty,
4058                                      LangAS AddrSpace, const VarDecl *D,
4059                                      ForDefinition_t IsForDefinition) {
4060   // Lookup the entry, lazily creating it if necessary.
4061   llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
4062   unsigned TargetAS = getContext().getTargetAddressSpace(AddrSpace);
4063   if (Entry) {
4064     if (WeakRefReferences.erase(Entry)) {
4065       if (D && !D->hasAttr<WeakAttr>())
4066         Entry->setLinkage(llvm::Function::ExternalLinkage);
4067     }
4068 
4069     // Handle dropped DLL attributes.
4070     if (D && !D->hasAttr<DLLImportAttr>() && !D->hasAttr<DLLExportAttr>())
4071       Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
4072 
4073     if (LangOpts.OpenMP && !LangOpts.OpenMPSimd && D)
4074       getOpenMPRuntime().registerTargetGlobalVariable(D, Entry);
4075 
4076     if (Entry->getValueType() == Ty && Entry->getAddressSpace() == TargetAS)
4077       return Entry;
4078 
4079     // If there are two attempts to define the same mangled name, issue an
4080     // error.
4081     if (IsForDefinition && !Entry->isDeclaration()) {
4082       GlobalDecl OtherGD;
4083       const VarDecl *OtherD;
4084 
4085       // Check that D is not yet in DiagnosedConflictingDefinitions is required
4086       // to make sure that we issue an error only once.
4087       if (D && lookupRepresentativeDecl(MangledName, OtherGD) &&
4088           (D->getCanonicalDecl() != OtherGD.getCanonicalDecl().getDecl()) &&
4089           (OtherD = dyn_cast<VarDecl>(OtherGD.getDecl())) &&
4090           OtherD->hasInit() &&
4091           DiagnosedConflictingDefinitions.insert(D).second) {
4092         getDiags().Report(D->getLocation(), diag::err_duplicate_mangled_name)
4093             << MangledName;
4094         getDiags().Report(OtherGD.getDecl()->getLocation(),
4095                           diag::note_previous_definition);
4096       }
4097     }
4098 
4099     // Make sure the result is of the correct type.
4100     if (Entry->getType()->getAddressSpace() != TargetAS) {
4101       return llvm::ConstantExpr::getAddrSpaceCast(Entry,
4102                                                   Ty->getPointerTo(TargetAS));
4103     }
4104 
4105     // (If global is requested for a definition, we always need to create a new
4106     // global, not just return a bitcast.)
4107     if (!IsForDefinition)
4108       return llvm::ConstantExpr::getBitCast(Entry, Ty->getPointerTo(TargetAS));
4109   }
4110 
4111   auto DAddrSpace = GetGlobalVarAddressSpace(D);
4112 
4113   auto *GV = new llvm::GlobalVariable(
4114       getModule(), Ty, false, llvm::GlobalValue::ExternalLinkage, nullptr,
4115       MangledName, nullptr, llvm::GlobalVariable::NotThreadLocal,
4116       getContext().getTargetAddressSpace(DAddrSpace));
4117 
4118   // If we already created a global with the same mangled name (but different
4119   // type) before, take its name and remove it from its parent.
4120   if (Entry) {
4121     GV->takeName(Entry);
4122 
4123     if (!Entry->use_empty()) {
4124       llvm::Constant *NewPtrForOldDecl =
4125           llvm::ConstantExpr::getBitCast(GV, Entry->getType());
4126       Entry->replaceAllUsesWith(NewPtrForOldDecl);
4127     }
4128 
4129     Entry->eraseFromParent();
4130   }
4131 
4132   // This is the first use or definition of a mangled name.  If there is a
4133   // deferred decl with this name, remember that we need to emit it at the end
4134   // of the file.
4135   auto DDI = DeferredDecls.find(MangledName);
4136   if (DDI != DeferredDecls.end()) {
4137     // Move the potentially referenced deferred decl to the DeferredDeclsToEmit
4138     // list, and remove it from DeferredDecls (since we don't need it anymore).
4139     addDeferredDeclToEmit(DDI->second);
4140     DeferredDecls.erase(DDI);
4141   }
4142 
4143   // Handle things which are present even on external declarations.
4144   if (D) {
4145     if (LangOpts.OpenMP && !LangOpts.OpenMPSimd)
4146       getOpenMPRuntime().registerTargetGlobalVariable(D, GV);
4147 
4148     // FIXME: This code is overly simple and should be merged with other global
4149     // handling.
4150     GV->setConstant(isTypeConstant(D->getType(), false));
4151 
4152     GV->setAlignment(getContext().getDeclAlign(D).getAsAlign());
4153 
4154     setLinkageForGV(GV, D);
4155 
4156     if (D->getTLSKind()) {
4157       if (D->getTLSKind() == VarDecl::TLS_Dynamic)
4158         CXXThreadLocals.push_back(D);
4159       setTLSMode(GV, *D);
4160     }
4161 
4162     setGVProperties(GV, D);
4163 
4164     // If required by the ABI, treat declarations of static data members with
4165     // inline initializers as definitions.
4166     if (getContext().isMSStaticDataMemberInlineDefinition(D)) {
4167       EmitGlobalVarDefinition(D);
4168     }
4169 
4170     // Emit section information for extern variables.
4171     if (D->hasExternalStorage()) {
4172       if (const SectionAttr *SA = D->getAttr<SectionAttr>())
4173         GV->setSection(SA->getName());
4174     }
4175 
4176     // Handle XCore specific ABI requirements.
4177     if (getTriple().getArch() == llvm::Triple::xcore &&
4178         D->getLanguageLinkage() == CLanguageLinkage &&
4179         D->getType().isConstant(Context) &&
4180         isExternallyVisible(D->getLinkageAndVisibility().getLinkage()))
4181       GV->setSection(".cp.rodata");
4182 
4183     // Check if we a have a const declaration with an initializer, we may be
4184     // able to emit it as available_externally to expose it's value to the
4185     // optimizer.
4186     if (Context.getLangOpts().CPlusPlus && GV->hasExternalLinkage() &&
4187         D->getType().isConstQualified() && !GV->hasInitializer() &&
4188         !D->hasDefinition() && D->hasInit() && !D->hasAttr<DLLImportAttr>()) {
4189       const auto *Record =
4190           Context.getBaseElementType(D->getType())->getAsCXXRecordDecl();
4191       bool HasMutableFields = Record && Record->hasMutableFields();
4192       if (!HasMutableFields) {
4193         const VarDecl *InitDecl;
4194         const Expr *InitExpr = D->getAnyInitializer(InitDecl);
4195         if (InitExpr) {
4196           ConstantEmitter emitter(*this);
4197           llvm::Constant *Init = emitter.tryEmitForInitializer(*InitDecl);
4198           if (Init) {
4199             auto *InitType = Init->getType();
4200             if (GV->getValueType() != InitType) {
4201               // The type of the initializer does not match the definition.
4202               // This happens when an initializer has a different type from
4203               // the type of the global (because of padding at the end of a
4204               // structure for instance).
4205               GV->setName(StringRef());
4206               // Make a new global with the correct type, this is now guaranteed
4207               // to work.
4208               auto *NewGV = cast<llvm::GlobalVariable>(
4209                   GetAddrOfGlobalVar(D, InitType, IsForDefinition)
4210                       ->stripPointerCasts());
4211 
4212               // Erase the old global, since it is no longer used.
4213               GV->eraseFromParent();
4214               GV = NewGV;
4215             } else {
4216               GV->setInitializer(Init);
4217               GV->setConstant(true);
4218               GV->setLinkage(llvm::GlobalValue::AvailableExternallyLinkage);
4219             }
4220             emitter.finalize(GV);
4221           }
4222         }
4223       }
4224     }
4225   }
4226 
4227   if (GV->isDeclaration()) {
4228     getTargetCodeGenInfo().setTargetAttributes(D, GV, *this);
4229     // External HIP managed variables needed to be recorded for transformation
4230     // in both device and host compilations.
4231     if (getLangOpts().CUDA && D && D->hasAttr<HIPManagedAttr>() &&
4232         D->hasExternalStorage())
4233       getCUDARuntime().handleVarRegistration(D, *GV);
4234   }
4235 
4236   LangAS ExpectedAS =
4237       D ? D->getType().getAddressSpace()
4238         : (LangOpts.OpenCL ? LangAS::opencl_global : LangAS::Default);
4239   assert(getContext().getTargetAddressSpace(ExpectedAS) == TargetAS);
4240   if (DAddrSpace != ExpectedAS) {
4241     return getTargetCodeGenInfo().performAddrSpaceCast(
4242         *this, GV, DAddrSpace, ExpectedAS, Ty->getPointerTo(TargetAS));
4243   }
4244 
4245   return GV;
4246 }
4247 
4248 llvm::Constant *
4249 CodeGenModule::GetAddrOfGlobal(GlobalDecl GD, ForDefinition_t IsForDefinition) {
4250   const Decl *D = GD.getDecl();
4251 
4252   if (isa<CXXConstructorDecl>(D) || isa<CXXDestructorDecl>(D))
4253     return getAddrOfCXXStructor(GD, /*FnInfo=*/nullptr, /*FnType=*/nullptr,
4254                                 /*DontDefer=*/false, IsForDefinition);
4255 
4256   if (isa<CXXMethodDecl>(D)) {
4257     auto FInfo =
4258         &getTypes().arrangeCXXMethodDeclaration(cast<CXXMethodDecl>(D));
4259     auto Ty = getTypes().GetFunctionType(*FInfo);
4260     return GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, /*DontDefer=*/false,
4261                              IsForDefinition);
4262   }
4263 
4264   if (isa<FunctionDecl>(D)) {
4265     const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
4266     llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
4267     return GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, /*DontDefer=*/false,
4268                              IsForDefinition);
4269   }
4270 
4271   return GetAddrOfGlobalVar(cast<VarDecl>(D), /*Ty=*/nullptr, IsForDefinition);
4272 }
4273 
4274 llvm::GlobalVariable *CodeGenModule::CreateOrReplaceCXXRuntimeVariable(
4275     StringRef Name, llvm::Type *Ty, llvm::GlobalValue::LinkageTypes Linkage,
4276     unsigned Alignment) {
4277   llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name);
4278   llvm::GlobalVariable *OldGV = nullptr;
4279 
4280   if (GV) {
4281     // Check if the variable has the right type.
4282     if (GV->getValueType() == Ty)
4283       return GV;
4284 
4285     // Because C++ name mangling, the only way we can end up with an already
4286     // existing global with the same name is if it has been declared extern "C".
4287     assert(GV->isDeclaration() && "Declaration has wrong type!");
4288     OldGV = GV;
4289   }
4290 
4291   // Create a new variable.
4292   GV = new llvm::GlobalVariable(getModule(), Ty, /*isConstant=*/true,
4293                                 Linkage, nullptr, Name);
4294 
4295   if (OldGV) {
4296     // Replace occurrences of the old variable if needed.
4297     GV->takeName(OldGV);
4298 
4299     if (!OldGV->use_empty()) {
4300       llvm::Constant *NewPtrForOldDecl =
4301       llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
4302       OldGV->replaceAllUsesWith(NewPtrForOldDecl);
4303     }
4304 
4305     OldGV->eraseFromParent();
4306   }
4307 
4308   if (supportsCOMDAT() && GV->isWeakForLinker() &&
4309       !GV->hasAvailableExternallyLinkage())
4310     GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
4311 
4312   GV->setAlignment(llvm::MaybeAlign(Alignment));
4313 
4314   return GV;
4315 }
4316 
4317 /// GetAddrOfGlobalVar - Return the llvm::Constant for the address of the
4318 /// given global variable.  If Ty is non-null and if the global doesn't exist,
4319 /// then it will be created with the specified type instead of whatever the
4320 /// normal requested type would be. If IsForDefinition is true, it is guaranteed
4321 /// that an actual global with type Ty will be returned, not conversion of a
4322 /// variable with the same mangled name but some other type.
4323 llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D,
4324                                                   llvm::Type *Ty,
4325                                            ForDefinition_t IsForDefinition) {
4326   assert(D->hasGlobalStorage() && "Not a global variable");
4327   QualType ASTTy = D->getType();
4328   if (!Ty)
4329     Ty = getTypes().ConvertTypeForMem(ASTTy);
4330 
4331   StringRef MangledName = getMangledName(D);
4332   return GetOrCreateLLVMGlobal(MangledName, Ty, ASTTy.getAddressSpace(), D,
4333                                IsForDefinition);
4334 }
4335 
4336 /// CreateRuntimeVariable - Create a new runtime global variable with the
4337 /// specified type and name.
4338 llvm::Constant *
4339 CodeGenModule::CreateRuntimeVariable(llvm::Type *Ty,
4340                                      StringRef Name) {
4341   LangAS AddrSpace = getContext().getLangOpts().OpenCL ? LangAS::opencl_global
4342                                                        : LangAS::Default;
4343   auto *Ret = GetOrCreateLLVMGlobal(Name, Ty, AddrSpace, nullptr);
4344   setDSOLocal(cast<llvm::GlobalValue>(Ret->stripPointerCasts()));
4345   return Ret;
4346 }
4347 
4348 void CodeGenModule::EmitTentativeDefinition(const VarDecl *D) {
4349   assert(!D->getInit() && "Cannot emit definite definitions here!");
4350 
4351   StringRef MangledName = getMangledName(D);
4352   llvm::GlobalValue *GV = GetGlobalValue(MangledName);
4353 
4354   // We already have a definition, not declaration, with the same mangled name.
4355   // Emitting of declaration is not required (and actually overwrites emitted
4356   // definition).
4357   if (GV && !GV->isDeclaration())
4358     return;
4359 
4360   // If we have not seen a reference to this variable yet, place it into the
4361   // deferred declarations table to be emitted if needed later.
4362   if (!MustBeEmitted(D) && !GV) {
4363       DeferredDecls[MangledName] = D;
4364       return;
4365   }
4366 
4367   // The tentative definition is the only definition.
4368   EmitGlobalVarDefinition(D);
4369 }
4370 
4371 void CodeGenModule::EmitExternalDeclaration(const VarDecl *D) {
4372   EmitExternalVarDeclaration(D);
4373 }
4374 
4375 CharUnits CodeGenModule::GetTargetTypeStoreSize(llvm::Type *Ty) const {
4376   return Context.toCharUnitsFromBits(
4377       getDataLayout().getTypeStoreSizeInBits(Ty));
4378 }
4379 
4380 LangAS CodeGenModule::GetGlobalVarAddressSpace(const VarDecl *D) {
4381   if (LangOpts.OpenCL) {
4382     LangAS AS = D ? D->getType().getAddressSpace() : LangAS::opencl_global;
4383     assert(AS == LangAS::opencl_global ||
4384            AS == LangAS::opencl_global_device ||
4385            AS == LangAS::opencl_global_host ||
4386            AS == LangAS::opencl_constant ||
4387            AS == LangAS::opencl_local ||
4388            AS >= LangAS::FirstTargetAddressSpace);
4389     return AS;
4390   }
4391 
4392   if (LangOpts.SYCLIsDevice &&
4393       (!D || D->getType().getAddressSpace() == LangAS::Default))
4394     return LangAS::sycl_global;
4395 
4396   if (LangOpts.CUDA && LangOpts.CUDAIsDevice) {
4397     if (D && D->hasAttr<CUDAConstantAttr>())
4398       return LangAS::cuda_constant;
4399     else if (D && D->hasAttr<CUDASharedAttr>())
4400       return LangAS::cuda_shared;
4401     else if (D && D->hasAttr<CUDADeviceAttr>())
4402       return LangAS::cuda_device;
4403     else if (D && D->getType().isConstQualified())
4404       return LangAS::cuda_constant;
4405     else
4406       return LangAS::cuda_device;
4407   }
4408 
4409   if (LangOpts.OpenMP) {
4410     LangAS AS;
4411     if (OpenMPRuntime->hasAllocateAttributeForGlobalVar(D, AS))
4412       return AS;
4413   }
4414   return getTargetCodeGenInfo().getGlobalVarAddressSpace(*this, D);
4415 }
4416 
4417 LangAS CodeGenModule::GetGlobalConstantAddressSpace() const {
4418   // OpenCL v1.2 s6.5.3: a string literal is in the constant address space.
4419   if (LangOpts.OpenCL)
4420     return LangAS::opencl_constant;
4421   if (LangOpts.SYCLIsDevice)
4422     return LangAS::sycl_global;
4423   if (LangOpts.HIP && LangOpts.CUDAIsDevice && getTriple().isSPIRV())
4424     // For HIPSPV map literals to cuda_device (maps to CrossWorkGroup in SPIR-V)
4425     // instead of default AS (maps to Generic in SPIR-V). Otherwise, we end up
4426     // with OpVariable instructions with Generic storage class which is not
4427     // allowed (SPIR-V V1.6 s3.42.8). Also, mapping literals to SPIR-V
4428     // UniformConstant storage class is not viable as pointers to it may not be
4429     // casted to Generic pointers which are used to model HIP's "flat" pointers.
4430     return LangAS::cuda_device;
4431   if (auto AS = getTarget().getConstantAddressSpace())
4432     return AS.getValue();
4433   return LangAS::Default;
4434 }
4435 
4436 // In address space agnostic languages, string literals are in default address
4437 // space in AST. However, certain targets (e.g. amdgcn) request them to be
4438 // emitted in constant address space in LLVM IR. To be consistent with other
4439 // parts of AST, string literal global variables in constant address space
4440 // need to be casted to default address space before being put into address
4441 // map and referenced by other part of CodeGen.
4442 // In OpenCL, string literals are in constant address space in AST, therefore
4443 // they should not be casted to default address space.
4444 static llvm::Constant *
4445 castStringLiteralToDefaultAddressSpace(CodeGenModule &CGM,
4446                                        llvm::GlobalVariable *GV) {
4447   llvm::Constant *Cast = GV;
4448   if (!CGM.getLangOpts().OpenCL) {
4449     auto AS = CGM.GetGlobalConstantAddressSpace();
4450     if (AS != LangAS::Default)
4451       Cast = CGM.getTargetCodeGenInfo().performAddrSpaceCast(
4452           CGM, GV, AS, LangAS::Default,
4453           GV->getValueType()->getPointerTo(
4454               CGM.getContext().getTargetAddressSpace(LangAS::Default)));
4455   }
4456   return Cast;
4457 }
4458 
4459 template<typename SomeDecl>
4460 void CodeGenModule::MaybeHandleStaticInExternC(const SomeDecl *D,
4461                                                llvm::GlobalValue *GV) {
4462   if (!getLangOpts().CPlusPlus)
4463     return;
4464 
4465   // Must have 'used' attribute, or else inline assembly can't rely on
4466   // the name existing.
4467   if (!D->template hasAttr<UsedAttr>())
4468     return;
4469 
4470   // Must have internal linkage and an ordinary name.
4471   if (!D->getIdentifier() || D->getFormalLinkage() != InternalLinkage)
4472     return;
4473 
4474   // Must be in an extern "C" context. Entities declared directly within
4475   // a record are not extern "C" even if the record is in such a context.
4476   const SomeDecl *First = D->getFirstDecl();
4477   if (First->getDeclContext()->isRecord() || !First->isInExternCContext())
4478     return;
4479 
4480   // OK, this is an internal linkage entity inside an extern "C" linkage
4481   // specification. Make a note of that so we can give it the "expected"
4482   // mangled name if nothing else is using that name.
4483   std::pair<StaticExternCMap::iterator, bool> R =
4484       StaticExternCValues.insert(std::make_pair(D->getIdentifier(), GV));
4485 
4486   // If we have multiple internal linkage entities with the same name
4487   // in extern "C" regions, none of them gets that name.
4488   if (!R.second)
4489     R.first->second = nullptr;
4490 }
4491 
4492 static bool shouldBeInCOMDAT(CodeGenModule &CGM, const Decl &D) {
4493   if (!CGM.supportsCOMDAT())
4494     return false;
4495 
4496   if (D.hasAttr<SelectAnyAttr>())
4497     return true;
4498 
4499   GVALinkage Linkage;
4500   if (auto *VD = dyn_cast<VarDecl>(&D))
4501     Linkage = CGM.getContext().GetGVALinkageForVariable(VD);
4502   else
4503     Linkage = CGM.getContext().GetGVALinkageForFunction(cast<FunctionDecl>(&D));
4504 
4505   switch (Linkage) {
4506   case GVA_Internal:
4507   case GVA_AvailableExternally:
4508   case GVA_StrongExternal:
4509     return false;
4510   case GVA_DiscardableODR:
4511   case GVA_StrongODR:
4512     return true;
4513   }
4514   llvm_unreachable("No such linkage");
4515 }
4516 
4517 void CodeGenModule::maybeSetTrivialComdat(const Decl &D,
4518                                           llvm::GlobalObject &GO) {
4519   if (!shouldBeInCOMDAT(*this, D))
4520     return;
4521   GO.setComdat(TheModule.getOrInsertComdat(GO.getName()));
4522 }
4523 
4524 /// Pass IsTentative as true if you want to create a tentative definition.
4525 void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D,
4526                                             bool IsTentative) {
4527   // OpenCL global variables of sampler type are translated to function calls,
4528   // therefore no need to be translated.
4529   QualType ASTTy = D->getType();
4530   if (getLangOpts().OpenCL && ASTTy->isSamplerT())
4531     return;
4532 
4533   // If this is OpenMP device, check if it is legal to emit this global
4534   // normally.
4535   if (LangOpts.OpenMPIsDevice && OpenMPRuntime &&
4536       OpenMPRuntime->emitTargetGlobalVariable(D))
4537     return;
4538 
4539   llvm::TrackingVH<llvm::Constant> Init;
4540   bool NeedsGlobalCtor = false;
4541   bool NeedsGlobalDtor =
4542       D->needsDestruction(getContext()) == QualType::DK_cxx_destructor;
4543 
4544   const VarDecl *InitDecl;
4545   const Expr *InitExpr = D->getAnyInitializer(InitDecl);
4546 
4547   Optional<ConstantEmitter> emitter;
4548 
4549   // CUDA E.2.4.1 "__shared__ variables cannot have an initialization
4550   // as part of their declaration."  Sema has already checked for
4551   // error cases, so we just need to set Init to UndefValue.
4552   bool IsCUDASharedVar =
4553       getLangOpts().CUDAIsDevice && D->hasAttr<CUDASharedAttr>();
4554   // Shadows of initialized device-side global variables are also left
4555   // undefined.
4556   // Managed Variables should be initialized on both host side and device side.
4557   bool IsCUDAShadowVar =
4558       !getLangOpts().CUDAIsDevice && !D->hasAttr<HIPManagedAttr>() &&
4559       (D->hasAttr<CUDAConstantAttr>() || D->hasAttr<CUDADeviceAttr>() ||
4560        D->hasAttr<CUDASharedAttr>());
4561   bool IsCUDADeviceShadowVar =
4562       getLangOpts().CUDAIsDevice && !D->hasAttr<HIPManagedAttr>() &&
4563       (D->getType()->isCUDADeviceBuiltinSurfaceType() ||
4564        D->getType()->isCUDADeviceBuiltinTextureType());
4565   if (getLangOpts().CUDA &&
4566       (IsCUDASharedVar || IsCUDAShadowVar || IsCUDADeviceShadowVar))
4567     Init = llvm::UndefValue::get(getTypes().ConvertTypeForMem(ASTTy));
4568   else if (D->hasAttr<LoaderUninitializedAttr>())
4569     Init = llvm::UndefValue::get(getTypes().ConvertTypeForMem(ASTTy));
4570   else if (!InitExpr) {
4571     // This is a tentative definition; tentative definitions are
4572     // implicitly initialized with { 0 }.
4573     //
4574     // Note that tentative definitions are only emitted at the end of
4575     // a translation unit, so they should never have incomplete
4576     // type. In addition, EmitTentativeDefinition makes sure that we
4577     // never attempt to emit a tentative definition if a real one
4578     // exists. A use may still exists, however, so we still may need
4579     // to do a RAUW.
4580     assert(!ASTTy->isIncompleteType() && "Unexpected incomplete type");
4581     Init = EmitNullConstant(D->getType());
4582   } else {
4583     initializedGlobalDecl = GlobalDecl(D);
4584     emitter.emplace(*this);
4585     llvm::Constant *Initializer = emitter->tryEmitForInitializer(*InitDecl);
4586     if (!Initializer) {
4587       QualType T = InitExpr->getType();
4588       if (D->getType()->isReferenceType())
4589         T = D->getType();
4590 
4591       if (getLangOpts().CPlusPlus) {
4592         Init = EmitNullConstant(T);
4593         NeedsGlobalCtor = true;
4594       } else {
4595         ErrorUnsupported(D, "static initializer");
4596         Init = llvm::UndefValue::get(getTypes().ConvertType(T));
4597       }
4598     } else {
4599       Init = Initializer;
4600       // We don't need an initializer, so remove the entry for the delayed
4601       // initializer position (just in case this entry was delayed) if we
4602       // also don't need to register a destructor.
4603       if (getLangOpts().CPlusPlus && !NeedsGlobalDtor)
4604         DelayedCXXInitPosition.erase(D);
4605     }
4606   }
4607 
4608   llvm::Type* InitType = Init->getType();
4609   llvm::Constant *Entry =
4610       GetAddrOfGlobalVar(D, InitType, ForDefinition_t(!IsTentative));
4611 
4612   // Strip off pointer casts if we got them.
4613   Entry = Entry->stripPointerCasts();
4614 
4615   // Entry is now either a Function or GlobalVariable.
4616   auto *GV = dyn_cast<llvm::GlobalVariable>(Entry);
4617 
4618   // We have a definition after a declaration with the wrong type.
4619   // We must make a new GlobalVariable* and update everything that used OldGV
4620   // (a declaration or tentative definition) with the new GlobalVariable*
4621   // (which will be a definition).
4622   //
4623   // This happens if there is a prototype for a global (e.g.
4624   // "extern int x[];") and then a definition of a different type (e.g.
4625   // "int x[10];"). This also happens when an initializer has a different type
4626   // from the type of the global (this happens with unions).
4627   if (!GV || GV->getValueType() != InitType ||
4628       GV->getType()->getAddressSpace() !=
4629           getContext().getTargetAddressSpace(GetGlobalVarAddressSpace(D))) {
4630 
4631     // Move the old entry aside so that we'll create a new one.
4632     Entry->setName(StringRef());
4633 
4634     // Make a new global with the correct type, this is now guaranteed to work.
4635     GV = cast<llvm::GlobalVariable>(
4636         GetAddrOfGlobalVar(D, InitType, ForDefinition_t(!IsTentative))
4637             ->stripPointerCasts());
4638 
4639     // Replace all uses of the old global with the new global
4640     llvm::Constant *NewPtrForOldDecl =
4641         llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(GV,
4642                                                              Entry->getType());
4643     Entry->replaceAllUsesWith(NewPtrForOldDecl);
4644 
4645     // Erase the old global, since it is no longer used.
4646     cast<llvm::GlobalValue>(Entry)->eraseFromParent();
4647   }
4648 
4649   MaybeHandleStaticInExternC(D, GV);
4650 
4651   if (D->hasAttr<AnnotateAttr>())
4652     AddGlobalAnnotations(D, GV);
4653 
4654   // Set the llvm linkage type as appropriate.
4655   llvm::GlobalValue::LinkageTypes Linkage =
4656       getLLVMLinkageVarDefinition(D, GV->isConstant());
4657 
4658   // CUDA B.2.1 "The __device__ qualifier declares a variable that resides on
4659   // the device. [...]"
4660   // CUDA B.2.2 "The __constant__ qualifier, optionally used together with
4661   // __device__, declares a variable that: [...]
4662   // Is accessible from all the threads within the grid and from the host
4663   // through the runtime library (cudaGetSymbolAddress() / cudaGetSymbolSize()
4664   // / cudaMemcpyToSymbol() / cudaMemcpyFromSymbol())."
4665   if (GV && LangOpts.CUDA) {
4666     if (LangOpts.CUDAIsDevice) {
4667       if (Linkage != llvm::GlobalValue::InternalLinkage &&
4668           (D->hasAttr<CUDADeviceAttr>() || D->hasAttr<CUDAConstantAttr>() ||
4669            D->getType()->isCUDADeviceBuiltinSurfaceType() ||
4670            D->getType()->isCUDADeviceBuiltinTextureType()))
4671         GV->setExternallyInitialized(true);
4672     } else {
4673       getCUDARuntime().internalizeDeviceSideVar(D, Linkage);
4674     }
4675     getCUDARuntime().handleVarRegistration(D, *GV);
4676   }
4677 
4678   GV->setInitializer(Init);
4679   if (emitter)
4680     emitter->finalize(GV);
4681 
4682   // If it is safe to mark the global 'constant', do so now.
4683   GV->setConstant(!NeedsGlobalCtor && !NeedsGlobalDtor &&
4684                   isTypeConstant(D->getType(), true));
4685 
4686   // If it is in a read-only section, mark it 'constant'.
4687   if (const SectionAttr *SA = D->getAttr<SectionAttr>()) {
4688     const ASTContext::SectionInfo &SI = Context.SectionInfos[SA->getName()];
4689     if ((SI.SectionFlags & ASTContext::PSF_Write) == 0)
4690       GV->setConstant(true);
4691   }
4692 
4693   GV->setAlignment(getContext().getDeclAlign(D).getAsAlign());
4694 
4695   // On Darwin, unlike other Itanium C++ ABI platforms, the thread-wrapper
4696   // function is only defined alongside the variable, not also alongside
4697   // callers. Normally, all accesses to a thread_local go through the
4698   // thread-wrapper in order to ensure initialization has occurred, underlying
4699   // variable will never be used other than the thread-wrapper, so it can be
4700   // converted to internal linkage.
4701   //
4702   // However, if the variable has the 'constinit' attribute, it _can_ be
4703   // referenced directly, without calling the thread-wrapper, so the linkage
4704   // must not be changed.
4705   //
4706   // Additionally, if the variable isn't plain external linkage, e.g. if it's
4707   // weak or linkonce, the de-duplication semantics are important to preserve,
4708   // so we don't change the linkage.
4709   if (D->getTLSKind() == VarDecl::TLS_Dynamic &&
4710       Linkage == llvm::GlobalValue::ExternalLinkage &&
4711       Context.getTargetInfo().getTriple().isOSDarwin() &&
4712       !D->hasAttr<ConstInitAttr>())
4713     Linkage = llvm::GlobalValue::InternalLinkage;
4714 
4715   GV->setLinkage(Linkage);
4716   if (D->hasAttr<DLLImportAttr>())
4717     GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
4718   else if (D->hasAttr<DLLExportAttr>())
4719     GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass);
4720   else
4721     GV->setDLLStorageClass(llvm::GlobalVariable::DefaultStorageClass);
4722 
4723   if (Linkage == llvm::GlobalVariable::CommonLinkage) {
4724     // common vars aren't constant even if declared const.
4725     GV->setConstant(false);
4726     // Tentative definition of global variables may be initialized with
4727     // non-zero null pointers. In this case they should have weak linkage
4728     // since common linkage must have zero initializer and must not have
4729     // explicit section therefore cannot have non-zero initial value.
4730     if (!GV->getInitializer()->isNullValue())
4731       GV->setLinkage(llvm::GlobalVariable::WeakAnyLinkage);
4732   }
4733 
4734   setNonAliasAttributes(D, GV);
4735 
4736   if (D->getTLSKind() && !GV->isThreadLocal()) {
4737     if (D->getTLSKind() == VarDecl::TLS_Dynamic)
4738       CXXThreadLocals.push_back(D);
4739     setTLSMode(GV, *D);
4740   }
4741 
4742   maybeSetTrivialComdat(*D, *GV);
4743 
4744   // Emit the initializer function if necessary.
4745   if (NeedsGlobalCtor || NeedsGlobalDtor)
4746     EmitCXXGlobalVarDeclInitFunc(D, GV, NeedsGlobalCtor);
4747 
4748   SanitizerMD->reportGlobalToASan(GV, *D, NeedsGlobalCtor);
4749 
4750   // Emit global variable debug information.
4751   if (CGDebugInfo *DI = getModuleDebugInfo())
4752     if (getCodeGenOpts().hasReducedDebugInfo())
4753       DI->EmitGlobalVariable(GV, D);
4754 }
4755 
4756 void CodeGenModule::EmitExternalVarDeclaration(const VarDecl *D) {
4757   if (CGDebugInfo *DI = getModuleDebugInfo())
4758     if (getCodeGenOpts().hasReducedDebugInfo()) {
4759       QualType ASTTy = D->getType();
4760       llvm::Type *Ty = getTypes().ConvertTypeForMem(D->getType());
4761       llvm::Constant *GV =
4762           GetOrCreateLLVMGlobal(D->getName(), Ty, ASTTy.getAddressSpace(), D);
4763       DI->EmitExternalVariable(
4764           cast<llvm::GlobalVariable>(GV->stripPointerCasts()), D);
4765     }
4766 }
4767 
4768 static bool isVarDeclStrongDefinition(const ASTContext &Context,
4769                                       CodeGenModule &CGM, const VarDecl *D,
4770                                       bool NoCommon) {
4771   // Don't give variables common linkage if -fno-common was specified unless it
4772   // was overridden by a NoCommon attribute.
4773   if ((NoCommon || D->hasAttr<NoCommonAttr>()) && !D->hasAttr<CommonAttr>())
4774     return true;
4775 
4776   // C11 6.9.2/2:
4777   //   A declaration of an identifier for an object that has file scope without
4778   //   an initializer, and without a storage-class specifier or with the
4779   //   storage-class specifier static, constitutes a tentative definition.
4780   if (D->getInit() || D->hasExternalStorage())
4781     return true;
4782 
4783   // A variable cannot be both common and exist in a section.
4784   if (D->hasAttr<SectionAttr>())
4785     return true;
4786 
4787   // A variable cannot be both common and exist in a section.
4788   // We don't try to determine which is the right section in the front-end.
4789   // If no specialized section name is applicable, it will resort to default.
4790   if (D->hasAttr<PragmaClangBSSSectionAttr>() ||
4791       D->hasAttr<PragmaClangDataSectionAttr>() ||
4792       D->hasAttr<PragmaClangRelroSectionAttr>() ||
4793       D->hasAttr<PragmaClangRodataSectionAttr>())
4794     return true;
4795 
4796   // Thread local vars aren't considered common linkage.
4797   if (D->getTLSKind())
4798     return true;
4799 
4800   // Tentative definitions marked with WeakImportAttr are true definitions.
4801   if (D->hasAttr<WeakImportAttr>())
4802     return true;
4803 
4804   // A variable cannot be both common and exist in a comdat.
4805   if (shouldBeInCOMDAT(CGM, *D))
4806     return true;
4807 
4808   // Declarations with a required alignment do not have common linkage in MSVC
4809   // mode.
4810   if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
4811     if (D->hasAttr<AlignedAttr>())
4812       return true;
4813     QualType VarType = D->getType();
4814     if (Context.isAlignmentRequired(VarType))
4815       return true;
4816 
4817     if (const auto *RT = VarType->getAs<RecordType>()) {
4818       const RecordDecl *RD = RT->getDecl();
4819       for (const FieldDecl *FD : RD->fields()) {
4820         if (FD->isBitField())
4821           continue;
4822         if (FD->hasAttr<AlignedAttr>())
4823           return true;
4824         if (Context.isAlignmentRequired(FD->getType()))
4825           return true;
4826       }
4827     }
4828   }
4829 
4830   // Microsoft's link.exe doesn't support alignments greater than 32 bytes for
4831   // common symbols, so symbols with greater alignment requirements cannot be
4832   // common.
4833   // Other COFF linkers (ld.bfd and LLD) support arbitrary power-of-two
4834   // alignments for common symbols via the aligncomm directive, so this
4835   // restriction only applies to MSVC environments.
4836   if (Context.getTargetInfo().getTriple().isKnownWindowsMSVCEnvironment() &&
4837       Context.getTypeAlignIfKnown(D->getType()) >
4838           Context.toBits(CharUnits::fromQuantity(32)))
4839     return true;
4840 
4841   return false;
4842 }
4843 
4844 llvm::GlobalValue::LinkageTypes CodeGenModule::getLLVMLinkageForDeclarator(
4845     const DeclaratorDecl *D, GVALinkage Linkage, bool IsConstantVariable) {
4846   if (Linkage == GVA_Internal)
4847     return llvm::Function::InternalLinkage;
4848 
4849   if (D->hasAttr<WeakAttr>()) {
4850     if (IsConstantVariable)
4851       return llvm::GlobalVariable::WeakODRLinkage;
4852     else
4853       return llvm::GlobalVariable::WeakAnyLinkage;
4854   }
4855 
4856   if (const auto *FD = D->getAsFunction())
4857     if (FD->isMultiVersion() && Linkage == GVA_AvailableExternally)
4858       return llvm::GlobalVariable::LinkOnceAnyLinkage;
4859 
4860   // We are guaranteed to have a strong definition somewhere else,
4861   // so we can use available_externally linkage.
4862   if (Linkage == GVA_AvailableExternally)
4863     return llvm::GlobalValue::AvailableExternallyLinkage;
4864 
4865   // Note that Apple's kernel linker doesn't support symbol
4866   // coalescing, so we need to avoid linkonce and weak linkages there.
4867   // Normally, this means we just map to internal, but for explicit
4868   // instantiations we'll map to external.
4869 
4870   // In C++, the compiler has to emit a definition in every translation unit
4871   // that references the function.  We should use linkonce_odr because
4872   // a) if all references in this translation unit are optimized away, we
4873   // don't need to codegen it.  b) if the function persists, it needs to be
4874   // merged with other definitions. c) C++ has the ODR, so we know the
4875   // definition is dependable.
4876   if (Linkage == GVA_DiscardableODR)
4877     return !Context.getLangOpts().AppleKext ? llvm::Function::LinkOnceODRLinkage
4878                                             : llvm::Function::InternalLinkage;
4879 
4880   // An explicit instantiation of a template has weak linkage, since
4881   // explicit instantiations can occur in multiple translation units
4882   // and must all be equivalent. However, we are not allowed to
4883   // throw away these explicit instantiations.
4884   //
4885   // CUDA/HIP: For -fno-gpu-rdc case, device code is limited to one TU,
4886   // so say that CUDA templates are either external (for kernels) or internal.
4887   // This lets llvm perform aggressive inter-procedural optimizations. For
4888   // -fgpu-rdc case, device function calls across multiple TU's are allowed,
4889   // therefore we need to follow the normal linkage paradigm.
4890   if (Linkage == GVA_StrongODR) {
4891     if (getLangOpts().AppleKext)
4892       return llvm::Function::ExternalLinkage;
4893     if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice &&
4894         !getLangOpts().GPURelocatableDeviceCode)
4895       return D->hasAttr<CUDAGlobalAttr>() ? llvm::Function::ExternalLinkage
4896                                           : llvm::Function::InternalLinkage;
4897     return llvm::Function::WeakODRLinkage;
4898   }
4899 
4900   // C++ doesn't have tentative definitions and thus cannot have common
4901   // linkage.
4902   if (!getLangOpts().CPlusPlus && isa<VarDecl>(D) &&
4903       !isVarDeclStrongDefinition(Context, *this, cast<VarDecl>(D),
4904                                  CodeGenOpts.NoCommon))
4905     return llvm::GlobalVariable::CommonLinkage;
4906 
4907   // selectany symbols are externally visible, so use weak instead of
4908   // linkonce.  MSVC optimizes away references to const selectany globals, so
4909   // all definitions should be the same and ODR linkage should be used.
4910   // http://msdn.microsoft.com/en-us/library/5tkz6s71.aspx
4911   if (D->hasAttr<SelectAnyAttr>())
4912     return llvm::GlobalVariable::WeakODRLinkage;
4913 
4914   // Otherwise, we have strong external linkage.
4915   assert(Linkage == GVA_StrongExternal);
4916   return llvm::GlobalVariable::ExternalLinkage;
4917 }
4918 
4919 llvm::GlobalValue::LinkageTypes CodeGenModule::getLLVMLinkageVarDefinition(
4920     const VarDecl *VD, bool IsConstant) {
4921   GVALinkage Linkage = getContext().GetGVALinkageForVariable(VD);
4922   return getLLVMLinkageForDeclarator(VD, Linkage, IsConstant);
4923 }
4924 
4925 /// Replace the uses of a function that was declared with a non-proto type.
4926 /// We want to silently drop extra arguments from call sites
4927 static void replaceUsesOfNonProtoConstant(llvm::Constant *old,
4928                                           llvm::Function *newFn) {
4929   // Fast path.
4930   if (old->use_empty()) return;
4931 
4932   llvm::Type *newRetTy = newFn->getReturnType();
4933   SmallVector<llvm::Value*, 4> newArgs;
4934 
4935   for (llvm::Value::use_iterator ui = old->use_begin(), ue = old->use_end();
4936          ui != ue; ) {
4937     llvm::Value::use_iterator use = ui++; // Increment before the use is erased.
4938     llvm::User *user = use->getUser();
4939 
4940     // Recognize and replace uses of bitcasts.  Most calls to
4941     // unprototyped functions will use bitcasts.
4942     if (auto *bitcast = dyn_cast<llvm::ConstantExpr>(user)) {
4943       if (bitcast->getOpcode() == llvm::Instruction::BitCast)
4944         replaceUsesOfNonProtoConstant(bitcast, newFn);
4945       continue;
4946     }
4947 
4948     // Recognize calls to the function.
4949     llvm::CallBase *callSite = dyn_cast<llvm::CallBase>(user);
4950     if (!callSite) continue;
4951     if (!callSite->isCallee(&*use))
4952       continue;
4953 
4954     // If the return types don't match exactly, then we can't
4955     // transform this call unless it's dead.
4956     if (callSite->getType() != newRetTy && !callSite->use_empty())
4957       continue;
4958 
4959     // Get the call site's attribute list.
4960     SmallVector<llvm::AttributeSet, 8> newArgAttrs;
4961     llvm::AttributeList oldAttrs = callSite->getAttributes();
4962 
4963     // If the function was passed too few arguments, don't transform.
4964     unsigned newNumArgs = newFn->arg_size();
4965     if (callSite->arg_size() < newNumArgs)
4966       continue;
4967 
4968     // If extra arguments were passed, we silently drop them.
4969     // If any of the types mismatch, we don't transform.
4970     unsigned argNo = 0;
4971     bool dontTransform = false;
4972     for (llvm::Argument &A : newFn->args()) {
4973       if (callSite->getArgOperand(argNo)->getType() != A.getType()) {
4974         dontTransform = true;
4975         break;
4976       }
4977 
4978       // Add any parameter attributes.
4979       newArgAttrs.push_back(oldAttrs.getParamAttrs(argNo));
4980       argNo++;
4981     }
4982     if (dontTransform)
4983       continue;
4984 
4985     // Okay, we can transform this.  Create the new call instruction and copy
4986     // over the required information.
4987     newArgs.append(callSite->arg_begin(), callSite->arg_begin() + argNo);
4988 
4989     // Copy over any operand bundles.
4990     SmallVector<llvm::OperandBundleDef, 1> newBundles;
4991     callSite->getOperandBundlesAsDefs(newBundles);
4992 
4993     llvm::CallBase *newCall;
4994     if (isa<llvm::CallInst>(callSite)) {
4995       newCall =
4996           llvm::CallInst::Create(newFn, newArgs, newBundles, "", callSite);
4997     } else {
4998       auto *oldInvoke = cast<llvm::InvokeInst>(callSite);
4999       newCall = llvm::InvokeInst::Create(newFn, oldInvoke->getNormalDest(),
5000                                          oldInvoke->getUnwindDest(), newArgs,
5001                                          newBundles, "", callSite);
5002     }
5003     newArgs.clear(); // for the next iteration
5004 
5005     if (!newCall->getType()->isVoidTy())
5006       newCall->takeName(callSite);
5007     newCall->setAttributes(
5008         llvm::AttributeList::get(newFn->getContext(), oldAttrs.getFnAttrs(),
5009                                  oldAttrs.getRetAttrs(), newArgAttrs));
5010     newCall->setCallingConv(callSite->getCallingConv());
5011 
5012     // Finally, remove the old call, replacing any uses with the new one.
5013     if (!callSite->use_empty())
5014       callSite->replaceAllUsesWith(newCall);
5015 
5016     // Copy debug location attached to CI.
5017     if (callSite->getDebugLoc())
5018       newCall->setDebugLoc(callSite->getDebugLoc());
5019 
5020     callSite->eraseFromParent();
5021   }
5022 }
5023 
5024 /// ReplaceUsesOfNonProtoTypeWithRealFunction - This function is called when we
5025 /// implement a function with no prototype, e.g. "int foo() {}".  If there are
5026 /// existing call uses of the old function in the module, this adjusts them to
5027 /// call the new function directly.
5028 ///
5029 /// This is not just a cleanup: the always_inline pass requires direct calls to
5030 /// functions to be able to inline them.  If there is a bitcast in the way, it
5031 /// won't inline them.  Instcombine normally deletes these calls, but it isn't
5032 /// run at -O0.
5033 static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old,
5034                                                       llvm::Function *NewFn) {
5035   // If we're redefining a global as a function, don't transform it.
5036   if (!isa<llvm::Function>(Old)) return;
5037 
5038   replaceUsesOfNonProtoConstant(Old, NewFn);
5039 }
5040 
5041 void CodeGenModule::HandleCXXStaticMemberVarInstantiation(VarDecl *VD) {
5042   auto DK = VD->isThisDeclarationADefinition();
5043   if (DK == VarDecl::Definition && VD->hasAttr<DLLImportAttr>())
5044     return;
5045 
5046   TemplateSpecializationKind TSK = VD->getTemplateSpecializationKind();
5047   // If we have a definition, this might be a deferred decl. If the
5048   // instantiation is explicit, make sure we emit it at the end.
5049   if (VD->getDefinition() && TSK == TSK_ExplicitInstantiationDefinition)
5050     GetAddrOfGlobalVar(VD);
5051 
5052   EmitTopLevelDecl(VD);
5053 }
5054 
5055 void CodeGenModule::EmitGlobalFunctionDefinition(GlobalDecl GD,
5056                                                  llvm::GlobalValue *GV) {
5057   const auto *D = cast<FunctionDecl>(GD.getDecl());
5058 
5059   // Compute the function info and LLVM type.
5060   const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
5061   llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
5062 
5063   // Get or create the prototype for the function.
5064   if (!GV || (GV->getValueType() != Ty))
5065     GV = cast<llvm::GlobalValue>(GetAddrOfFunction(GD, Ty, /*ForVTable=*/false,
5066                                                    /*DontDefer=*/true,
5067                                                    ForDefinition));
5068 
5069   // Already emitted.
5070   if (!GV->isDeclaration())
5071     return;
5072 
5073   // We need to set linkage and visibility on the function before
5074   // generating code for it because various parts of IR generation
5075   // want to propagate this information down (e.g. to local static
5076   // declarations).
5077   auto *Fn = cast<llvm::Function>(GV);
5078   setFunctionLinkage(GD, Fn);
5079 
5080   // FIXME: this is redundant with part of setFunctionDefinitionAttributes
5081   setGVProperties(Fn, GD);
5082 
5083   MaybeHandleStaticInExternC(D, Fn);
5084 
5085   maybeSetTrivialComdat(*D, *Fn);
5086 
5087   // Set CodeGen attributes that represent floating point environment.
5088   setLLVMFunctionFEnvAttributes(D, Fn);
5089 
5090   CodeGenFunction(*this).GenerateCode(GD, Fn, FI);
5091 
5092   setNonAliasAttributes(GD, Fn);
5093   SetLLVMFunctionAttributesForDefinition(D, Fn);
5094 
5095   if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>())
5096     AddGlobalCtor(Fn, CA->getPriority());
5097   if (const DestructorAttr *DA = D->getAttr<DestructorAttr>())
5098     AddGlobalDtor(Fn, DA->getPriority(), true);
5099   if (D->hasAttr<AnnotateAttr>())
5100     AddGlobalAnnotations(D, Fn);
5101 }
5102 
5103 void CodeGenModule::EmitAliasDefinition(GlobalDecl GD) {
5104   const auto *D = cast<ValueDecl>(GD.getDecl());
5105   const AliasAttr *AA = D->getAttr<AliasAttr>();
5106   assert(AA && "Not an alias?");
5107 
5108   StringRef MangledName = getMangledName(GD);
5109 
5110   if (AA->getAliasee() == MangledName) {
5111     Diags.Report(AA->getLocation(), diag::err_cyclic_alias) << 0;
5112     return;
5113   }
5114 
5115   // If there is a definition in the module, then it wins over the alias.
5116   // This is dubious, but allow it to be safe.  Just ignore the alias.
5117   llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
5118   if (Entry && !Entry->isDeclaration())
5119     return;
5120 
5121   Aliases.push_back(GD);
5122 
5123   llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType());
5124 
5125   // Create a reference to the named value.  This ensures that it is emitted
5126   // if a deferred decl.
5127   llvm::Constant *Aliasee;
5128   llvm::GlobalValue::LinkageTypes LT;
5129   if (isa<llvm::FunctionType>(DeclTy)) {
5130     Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GD,
5131                                       /*ForVTable=*/false);
5132     LT = getFunctionLinkage(GD);
5133   } else {
5134     Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(), DeclTy, LangAS::Default,
5135                                     /*D=*/nullptr);
5136     if (const auto *VD = dyn_cast<VarDecl>(GD.getDecl()))
5137       LT = getLLVMLinkageVarDefinition(VD, D->getType().isConstQualified());
5138     else
5139       LT = getFunctionLinkage(GD);
5140   }
5141 
5142   // Create the new alias itself, but don't set a name yet.
5143   unsigned AS = Aliasee->getType()->getPointerAddressSpace();
5144   auto *GA =
5145       llvm::GlobalAlias::create(DeclTy, AS, LT, "", Aliasee, &getModule());
5146 
5147   if (Entry) {
5148     if (GA->getAliasee() == Entry) {
5149       Diags.Report(AA->getLocation(), diag::err_cyclic_alias) << 0;
5150       return;
5151     }
5152 
5153     assert(Entry->isDeclaration());
5154 
5155     // If there is a declaration in the module, then we had an extern followed
5156     // by the alias, as in:
5157     //   extern int test6();
5158     //   ...
5159     //   int test6() __attribute__((alias("test7")));
5160     //
5161     // Remove it and replace uses of it with the alias.
5162     GA->takeName(Entry);
5163 
5164     Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GA,
5165                                                           Entry->getType()));
5166     Entry->eraseFromParent();
5167   } else {
5168     GA->setName(MangledName);
5169   }
5170 
5171   // Set attributes which are particular to an alias; this is a
5172   // specialization of the attributes which may be set on a global
5173   // variable/function.
5174   if (D->hasAttr<WeakAttr>() || D->hasAttr<WeakRefAttr>() ||
5175       D->isWeakImported()) {
5176     GA->setLinkage(llvm::Function::WeakAnyLinkage);
5177   }
5178 
5179   if (const auto *VD = dyn_cast<VarDecl>(D))
5180     if (VD->getTLSKind())
5181       setTLSMode(GA, *VD);
5182 
5183   SetCommonAttributes(GD, GA);
5184 
5185   // Emit global alias debug information.
5186   if (isa<VarDecl>(D))
5187     if (CGDebugInfo *DI = getModuleDebugInfo())
5188       DI->EmitGlobalAlias(cast<llvm::GlobalValue>(GA->getAliasee()), GD);
5189 }
5190 
5191 void CodeGenModule::emitIFuncDefinition(GlobalDecl GD) {
5192   const auto *D = cast<ValueDecl>(GD.getDecl());
5193   const IFuncAttr *IFA = D->getAttr<IFuncAttr>();
5194   assert(IFA && "Not an ifunc?");
5195 
5196   StringRef MangledName = getMangledName(GD);
5197 
5198   if (IFA->getResolver() == MangledName) {
5199     Diags.Report(IFA->getLocation(), diag::err_cyclic_alias) << 1;
5200     return;
5201   }
5202 
5203   // Report an error if some definition overrides ifunc.
5204   llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
5205   if (Entry && !Entry->isDeclaration()) {
5206     GlobalDecl OtherGD;
5207     if (lookupRepresentativeDecl(MangledName, OtherGD) &&
5208         DiagnosedConflictingDefinitions.insert(GD).second) {
5209       Diags.Report(D->getLocation(), diag::err_duplicate_mangled_name)
5210           << MangledName;
5211       Diags.Report(OtherGD.getDecl()->getLocation(),
5212                    diag::note_previous_definition);
5213     }
5214     return;
5215   }
5216 
5217   Aliases.push_back(GD);
5218 
5219   llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType());
5220   llvm::Type *ResolverTy = llvm::GlobalIFunc::getResolverFunctionType(DeclTy);
5221   llvm::Constant *Resolver =
5222       GetOrCreateLLVMFunction(IFA->getResolver(), ResolverTy, {},
5223                               /*ForVTable=*/false);
5224   llvm::GlobalIFunc *GIF =
5225       llvm::GlobalIFunc::create(DeclTy, 0, llvm::Function::ExternalLinkage,
5226                                 "", Resolver, &getModule());
5227   if (Entry) {
5228     if (GIF->getResolver() == Entry) {
5229       Diags.Report(IFA->getLocation(), diag::err_cyclic_alias) << 1;
5230       return;
5231     }
5232     assert(Entry->isDeclaration());
5233 
5234     // If there is a declaration in the module, then we had an extern followed
5235     // by the ifunc, as in:
5236     //   extern int test();
5237     //   ...
5238     //   int test() __attribute__((ifunc("resolver")));
5239     //
5240     // Remove it and replace uses of it with the ifunc.
5241     GIF->takeName(Entry);
5242 
5243     Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GIF,
5244                                                           Entry->getType()));
5245     Entry->eraseFromParent();
5246   } else
5247     GIF->setName(MangledName);
5248 
5249   SetCommonAttributes(GD, GIF);
5250 }
5251 
5252 llvm::Function *CodeGenModule::getIntrinsic(unsigned IID,
5253                                             ArrayRef<llvm::Type*> Tys) {
5254   return llvm::Intrinsic::getDeclaration(&getModule(), (llvm::Intrinsic::ID)IID,
5255                                          Tys);
5256 }
5257 
5258 static llvm::StringMapEntry<llvm::GlobalVariable *> &
5259 GetConstantCFStringEntry(llvm::StringMap<llvm::GlobalVariable *> &Map,
5260                          const StringLiteral *Literal, bool TargetIsLSB,
5261                          bool &IsUTF16, unsigned &StringLength) {
5262   StringRef String = Literal->getString();
5263   unsigned NumBytes = String.size();
5264 
5265   // Check for simple case.
5266   if (!Literal->containsNonAsciiOrNull()) {
5267     StringLength = NumBytes;
5268     return *Map.insert(std::make_pair(String, nullptr)).first;
5269   }
5270 
5271   // Otherwise, convert the UTF8 literals into a string of shorts.
5272   IsUTF16 = true;
5273 
5274   SmallVector<llvm::UTF16, 128> ToBuf(NumBytes + 1); // +1 for ending nulls.
5275   const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data();
5276   llvm::UTF16 *ToPtr = &ToBuf[0];
5277 
5278   (void)llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr,
5279                                  ToPtr + NumBytes, llvm::strictConversion);
5280 
5281   // ConvertUTF8toUTF16 returns the length in ToPtr.
5282   StringLength = ToPtr - &ToBuf[0];
5283 
5284   // Add an explicit null.
5285   *ToPtr = 0;
5286   return *Map.insert(std::make_pair(
5287                          StringRef(reinterpret_cast<const char *>(ToBuf.data()),
5288                                    (StringLength + 1) * 2),
5289                          nullptr)).first;
5290 }
5291 
5292 ConstantAddress
5293 CodeGenModule::GetAddrOfConstantCFString(const StringLiteral *Literal) {
5294   unsigned StringLength = 0;
5295   bool isUTF16 = false;
5296   llvm::StringMapEntry<llvm::GlobalVariable *> &Entry =
5297       GetConstantCFStringEntry(CFConstantStringMap, Literal,
5298                                getDataLayout().isLittleEndian(), isUTF16,
5299                                StringLength);
5300 
5301   if (auto *C = Entry.second)
5302     return ConstantAddress(
5303         C, C->getValueType(), CharUnits::fromQuantity(C->getAlignment()));
5304 
5305   llvm::Constant *Zero = llvm::Constant::getNullValue(Int32Ty);
5306   llvm::Constant *Zeros[] = { Zero, Zero };
5307 
5308   const ASTContext &Context = getContext();
5309   const llvm::Triple &Triple = getTriple();
5310 
5311   const auto CFRuntime = getLangOpts().CFRuntime;
5312   const bool IsSwiftABI =
5313       static_cast<unsigned>(CFRuntime) >=
5314       static_cast<unsigned>(LangOptions::CoreFoundationABI::Swift);
5315   const bool IsSwift4_1 = CFRuntime == LangOptions::CoreFoundationABI::Swift4_1;
5316 
5317   // If we don't already have it, get __CFConstantStringClassReference.
5318   if (!CFConstantStringClassRef) {
5319     const char *CFConstantStringClassName = "__CFConstantStringClassReference";
5320     llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
5321     Ty = llvm::ArrayType::get(Ty, 0);
5322 
5323     switch (CFRuntime) {
5324     default: break;
5325     case LangOptions::CoreFoundationABI::Swift: LLVM_FALLTHROUGH;
5326     case LangOptions::CoreFoundationABI::Swift5_0:
5327       CFConstantStringClassName =
5328           Triple.isOSDarwin() ? "$s15SwiftFoundation19_NSCFConstantStringCN"
5329                               : "$s10Foundation19_NSCFConstantStringCN";
5330       Ty = IntPtrTy;
5331       break;
5332     case LangOptions::CoreFoundationABI::Swift4_2:
5333       CFConstantStringClassName =
5334           Triple.isOSDarwin() ? "$S15SwiftFoundation19_NSCFConstantStringCN"
5335                               : "$S10Foundation19_NSCFConstantStringCN";
5336       Ty = IntPtrTy;
5337       break;
5338     case LangOptions::CoreFoundationABI::Swift4_1:
5339       CFConstantStringClassName =
5340           Triple.isOSDarwin() ? "__T015SwiftFoundation19_NSCFConstantStringCN"
5341                               : "__T010Foundation19_NSCFConstantStringCN";
5342       Ty = IntPtrTy;
5343       break;
5344     }
5345 
5346     llvm::Constant *C = CreateRuntimeVariable(Ty, CFConstantStringClassName);
5347 
5348     if (Triple.isOSBinFormatELF() || Triple.isOSBinFormatCOFF()) {
5349       llvm::GlobalValue *GV = nullptr;
5350 
5351       if ((GV = dyn_cast<llvm::GlobalValue>(C))) {
5352         IdentifierInfo &II = Context.Idents.get(GV->getName());
5353         TranslationUnitDecl *TUDecl = Context.getTranslationUnitDecl();
5354         DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl);
5355 
5356         const VarDecl *VD = nullptr;
5357         for (const auto *Result : DC->lookup(&II))
5358           if ((VD = dyn_cast<VarDecl>(Result)))
5359             break;
5360 
5361         if (Triple.isOSBinFormatELF()) {
5362           if (!VD)
5363             GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
5364         } else {
5365           GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
5366           if (!VD || !VD->hasAttr<DLLExportAttr>())
5367             GV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
5368           else
5369             GV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
5370         }
5371 
5372         setDSOLocal(GV);
5373       }
5374     }
5375 
5376     // Decay array -> ptr
5377     CFConstantStringClassRef =
5378         IsSwiftABI ? llvm::ConstantExpr::getPtrToInt(C, Ty)
5379                    : llvm::ConstantExpr::getGetElementPtr(Ty, C, Zeros);
5380   }
5381 
5382   QualType CFTy = Context.getCFConstantStringType();
5383 
5384   auto *STy = cast<llvm::StructType>(getTypes().ConvertType(CFTy));
5385 
5386   ConstantInitBuilder Builder(*this);
5387   auto Fields = Builder.beginStruct(STy);
5388 
5389   // Class pointer.
5390   Fields.add(cast<llvm::Constant>(CFConstantStringClassRef));
5391 
5392   // Flags.
5393   if (IsSwiftABI) {
5394     Fields.addInt(IntPtrTy, IsSwift4_1 ? 0x05 : 0x01);
5395     Fields.addInt(Int64Ty, isUTF16 ? 0x07d0 : 0x07c8);
5396   } else {
5397     Fields.addInt(IntTy, isUTF16 ? 0x07d0 : 0x07C8);
5398   }
5399 
5400   // String pointer.
5401   llvm::Constant *C = nullptr;
5402   if (isUTF16) {
5403     auto Arr = llvm::makeArrayRef(
5404         reinterpret_cast<uint16_t *>(const_cast<char *>(Entry.first().data())),
5405         Entry.first().size() / 2);
5406     C = llvm::ConstantDataArray::get(VMContext, Arr);
5407   } else {
5408     C = llvm::ConstantDataArray::getString(VMContext, Entry.first());
5409   }
5410 
5411   // Note: -fwritable-strings doesn't make the backing store strings of
5412   // CFStrings writable. (See <rdar://problem/10657500>)
5413   auto *GV =
5414       new llvm::GlobalVariable(getModule(), C->getType(), /*isConstant=*/true,
5415                                llvm::GlobalValue::PrivateLinkage, C, ".str");
5416   GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
5417   // Don't enforce the target's minimum global alignment, since the only use
5418   // of the string is via this class initializer.
5419   CharUnits Align = isUTF16 ? Context.getTypeAlignInChars(Context.ShortTy)
5420                             : Context.getTypeAlignInChars(Context.CharTy);
5421   GV->setAlignment(Align.getAsAlign());
5422 
5423   // FIXME: We set the section explicitly to avoid a bug in ld64 224.1.
5424   // Without it LLVM can merge the string with a non unnamed_addr one during
5425   // LTO.  Doing that changes the section it ends in, which surprises ld64.
5426   if (Triple.isOSBinFormatMachO())
5427     GV->setSection(isUTF16 ? "__TEXT,__ustring"
5428                            : "__TEXT,__cstring,cstring_literals");
5429   // Make sure the literal ends up in .rodata to allow for safe ICF and for
5430   // the static linker to adjust permissions to read-only later on.
5431   else if (Triple.isOSBinFormatELF())
5432     GV->setSection(".rodata");
5433 
5434   // String.
5435   llvm::Constant *Str =
5436       llvm::ConstantExpr::getGetElementPtr(GV->getValueType(), GV, Zeros);
5437 
5438   if (isUTF16)
5439     // Cast the UTF16 string to the correct type.
5440     Str = llvm::ConstantExpr::getBitCast(Str, Int8PtrTy);
5441   Fields.add(Str);
5442 
5443   // String length.
5444   llvm::IntegerType *LengthTy =
5445       llvm::IntegerType::get(getModule().getContext(),
5446                              Context.getTargetInfo().getLongWidth());
5447   if (IsSwiftABI) {
5448     if (CFRuntime == LangOptions::CoreFoundationABI::Swift4_1 ||
5449         CFRuntime == LangOptions::CoreFoundationABI::Swift4_2)
5450       LengthTy = Int32Ty;
5451     else
5452       LengthTy = IntPtrTy;
5453   }
5454   Fields.addInt(LengthTy, StringLength);
5455 
5456   // Swift ABI requires 8-byte alignment to ensure that the _Atomic(uint64_t) is
5457   // properly aligned on 32-bit platforms.
5458   CharUnits Alignment =
5459       IsSwiftABI ? Context.toCharUnitsFromBits(64) : getPointerAlign();
5460 
5461   // The struct.
5462   GV = Fields.finishAndCreateGlobal("_unnamed_cfstring_", Alignment,
5463                                     /*isConstant=*/false,
5464                                     llvm::GlobalVariable::PrivateLinkage);
5465   GV->addAttribute("objc_arc_inert");
5466   switch (Triple.getObjectFormat()) {
5467   case llvm::Triple::UnknownObjectFormat:
5468     llvm_unreachable("unknown file format");
5469   case llvm::Triple::GOFF:
5470     llvm_unreachable("GOFF is not yet implemented");
5471   case llvm::Triple::XCOFF:
5472     llvm_unreachable("XCOFF is not yet implemented");
5473   case llvm::Triple::DXContainer:
5474     llvm_unreachable("DXContainer is not yet implemented");
5475   case llvm::Triple::COFF:
5476   case llvm::Triple::ELF:
5477   case llvm::Triple::Wasm:
5478     GV->setSection("cfstring");
5479     break;
5480   case llvm::Triple::MachO:
5481     GV->setSection("__DATA,__cfstring");
5482     break;
5483   }
5484   Entry.second = GV;
5485 
5486   return ConstantAddress(GV, GV->getValueType(), Alignment);
5487 }
5488 
5489 bool CodeGenModule::getExpressionLocationsEnabled() const {
5490   return !CodeGenOpts.EmitCodeView || CodeGenOpts.DebugColumnInfo;
5491 }
5492 
5493 QualType CodeGenModule::getObjCFastEnumerationStateType() {
5494   if (ObjCFastEnumerationStateType.isNull()) {
5495     RecordDecl *D = Context.buildImplicitRecord("__objcFastEnumerationState");
5496     D->startDefinition();
5497 
5498     QualType FieldTypes[] = {
5499       Context.UnsignedLongTy,
5500       Context.getPointerType(Context.getObjCIdType()),
5501       Context.getPointerType(Context.UnsignedLongTy),
5502       Context.getConstantArrayType(Context.UnsignedLongTy,
5503                            llvm::APInt(32, 5), nullptr, ArrayType::Normal, 0)
5504     };
5505 
5506     for (size_t i = 0; i < 4; ++i) {
5507       FieldDecl *Field = FieldDecl::Create(Context,
5508                                            D,
5509                                            SourceLocation(),
5510                                            SourceLocation(), nullptr,
5511                                            FieldTypes[i], /*TInfo=*/nullptr,
5512                                            /*BitWidth=*/nullptr,
5513                                            /*Mutable=*/false,
5514                                            ICIS_NoInit);
5515       Field->setAccess(AS_public);
5516       D->addDecl(Field);
5517     }
5518 
5519     D->completeDefinition();
5520     ObjCFastEnumerationStateType = Context.getTagDeclType(D);
5521   }
5522 
5523   return ObjCFastEnumerationStateType;
5524 }
5525 
5526 llvm::Constant *
5527 CodeGenModule::GetConstantArrayFromStringLiteral(const StringLiteral *E) {
5528   assert(!E->getType()->isPointerType() && "Strings are always arrays");
5529 
5530   // Don't emit it as the address of the string, emit the string data itself
5531   // as an inline array.
5532   if (E->getCharByteWidth() == 1) {
5533     SmallString<64> Str(E->getString());
5534 
5535     // Resize the string to the right size, which is indicated by its type.
5536     const ConstantArrayType *CAT = Context.getAsConstantArrayType(E->getType());
5537     Str.resize(CAT->getSize().getZExtValue());
5538     return llvm::ConstantDataArray::getString(VMContext, Str, false);
5539   }
5540 
5541   auto *AType = cast<llvm::ArrayType>(getTypes().ConvertType(E->getType()));
5542   llvm::Type *ElemTy = AType->getElementType();
5543   unsigned NumElements = AType->getNumElements();
5544 
5545   // Wide strings have either 2-byte or 4-byte elements.
5546   if (ElemTy->getPrimitiveSizeInBits() == 16) {
5547     SmallVector<uint16_t, 32> Elements;
5548     Elements.reserve(NumElements);
5549 
5550     for(unsigned i = 0, e = E->getLength(); i != e; ++i)
5551       Elements.push_back(E->getCodeUnit(i));
5552     Elements.resize(NumElements);
5553     return llvm::ConstantDataArray::get(VMContext, Elements);
5554   }
5555 
5556   assert(ElemTy->getPrimitiveSizeInBits() == 32);
5557   SmallVector<uint32_t, 32> Elements;
5558   Elements.reserve(NumElements);
5559 
5560   for(unsigned i = 0, e = E->getLength(); i != e; ++i)
5561     Elements.push_back(E->getCodeUnit(i));
5562   Elements.resize(NumElements);
5563   return llvm::ConstantDataArray::get(VMContext, Elements);
5564 }
5565 
5566 static llvm::GlobalVariable *
5567 GenerateStringLiteral(llvm::Constant *C, llvm::GlobalValue::LinkageTypes LT,
5568                       CodeGenModule &CGM, StringRef GlobalName,
5569                       CharUnits Alignment) {
5570   unsigned AddrSpace = CGM.getContext().getTargetAddressSpace(
5571       CGM.GetGlobalConstantAddressSpace());
5572 
5573   llvm::Module &M = CGM.getModule();
5574   // Create a global variable for this string
5575   auto *GV = new llvm::GlobalVariable(
5576       M, C->getType(), !CGM.getLangOpts().WritableStrings, LT, C, GlobalName,
5577       nullptr, llvm::GlobalVariable::NotThreadLocal, AddrSpace);
5578   GV->setAlignment(Alignment.getAsAlign());
5579   GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
5580   if (GV->isWeakForLinker()) {
5581     assert(CGM.supportsCOMDAT() && "Only COFF uses weak string literals");
5582     GV->setComdat(M.getOrInsertComdat(GV->getName()));
5583   }
5584   CGM.setDSOLocal(GV);
5585 
5586   return GV;
5587 }
5588 
5589 /// GetAddrOfConstantStringFromLiteral - Return a pointer to a
5590 /// constant array for the given string literal.
5591 ConstantAddress
5592 CodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S,
5593                                                   StringRef Name) {
5594   CharUnits Alignment = getContext().getAlignOfGlobalVarInChars(S->getType());
5595 
5596   llvm::Constant *C = GetConstantArrayFromStringLiteral(S);
5597   llvm::GlobalVariable **Entry = nullptr;
5598   if (!LangOpts.WritableStrings) {
5599     Entry = &ConstantStringMap[C];
5600     if (auto GV = *Entry) {
5601       if (uint64_t(Alignment.getQuantity()) > GV->getAlignment())
5602         GV->setAlignment(Alignment.getAsAlign());
5603       return ConstantAddress(castStringLiteralToDefaultAddressSpace(*this, GV),
5604                              GV->getValueType(), Alignment);
5605     }
5606   }
5607 
5608   SmallString<256> MangledNameBuffer;
5609   StringRef GlobalVariableName;
5610   llvm::GlobalValue::LinkageTypes LT;
5611 
5612   // Mangle the string literal if that's how the ABI merges duplicate strings.
5613   // Don't do it if they are writable, since we don't want writes in one TU to
5614   // affect strings in another.
5615   if (getCXXABI().getMangleContext().shouldMangleStringLiteral(S) &&
5616       !LangOpts.WritableStrings) {
5617     llvm::raw_svector_ostream Out(MangledNameBuffer);
5618     getCXXABI().getMangleContext().mangleStringLiteral(S, Out);
5619     LT = llvm::GlobalValue::LinkOnceODRLinkage;
5620     GlobalVariableName = MangledNameBuffer;
5621   } else {
5622     LT = llvm::GlobalValue::PrivateLinkage;
5623     GlobalVariableName = Name;
5624   }
5625 
5626   auto GV = GenerateStringLiteral(C, LT, *this, GlobalVariableName, Alignment);
5627   if (Entry)
5628     *Entry = GV;
5629 
5630   SanitizerMD->reportGlobalToASan(GV, S->getStrTokenLoc(0), "<string literal>",
5631                                   QualType());
5632 
5633   return ConstantAddress(castStringLiteralToDefaultAddressSpace(*this, GV),
5634                          GV->getValueType(), Alignment);
5635 }
5636 
5637 /// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant
5638 /// array for the given ObjCEncodeExpr node.
5639 ConstantAddress
5640 CodeGenModule::GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *E) {
5641   std::string Str;
5642   getContext().getObjCEncodingForType(E->getEncodedType(), Str);
5643 
5644   return GetAddrOfConstantCString(Str);
5645 }
5646 
5647 /// GetAddrOfConstantCString - Returns a pointer to a character array containing
5648 /// the literal and a terminating '\0' character.
5649 /// The result has pointer to array type.
5650 ConstantAddress CodeGenModule::GetAddrOfConstantCString(
5651     const std::string &Str, const char *GlobalName) {
5652   StringRef StrWithNull(Str.c_str(), Str.size() + 1);
5653   CharUnits Alignment =
5654     getContext().getAlignOfGlobalVarInChars(getContext().CharTy);
5655 
5656   llvm::Constant *C =
5657       llvm::ConstantDataArray::getString(getLLVMContext(), StrWithNull, false);
5658 
5659   // Don't share any string literals if strings aren't constant.
5660   llvm::GlobalVariable **Entry = nullptr;
5661   if (!LangOpts.WritableStrings) {
5662     Entry = &ConstantStringMap[C];
5663     if (auto GV = *Entry) {
5664       if (uint64_t(Alignment.getQuantity()) > GV->getAlignment())
5665         GV->setAlignment(Alignment.getAsAlign());
5666       return ConstantAddress(castStringLiteralToDefaultAddressSpace(*this, GV),
5667                              GV->getValueType(), Alignment);
5668     }
5669   }
5670 
5671   // Get the default prefix if a name wasn't specified.
5672   if (!GlobalName)
5673     GlobalName = ".str";
5674   // Create a global variable for this.
5675   auto GV = GenerateStringLiteral(C, llvm::GlobalValue::PrivateLinkage, *this,
5676                                   GlobalName, Alignment);
5677   if (Entry)
5678     *Entry = GV;
5679 
5680   return ConstantAddress(castStringLiteralToDefaultAddressSpace(*this, GV),
5681                          GV->getValueType(), Alignment);
5682 }
5683 
5684 ConstantAddress CodeGenModule::GetAddrOfGlobalTemporary(
5685     const MaterializeTemporaryExpr *E, const Expr *Init) {
5686   assert((E->getStorageDuration() == SD_Static ||
5687           E->getStorageDuration() == SD_Thread) && "not a global temporary");
5688   const auto *VD = cast<VarDecl>(E->getExtendingDecl());
5689 
5690   // If we're not materializing a subobject of the temporary, keep the
5691   // cv-qualifiers from the type of the MaterializeTemporaryExpr.
5692   QualType MaterializedType = Init->getType();
5693   if (Init == E->getSubExpr())
5694     MaterializedType = E->getType();
5695 
5696   CharUnits Align = getContext().getTypeAlignInChars(MaterializedType);
5697 
5698   auto InsertResult = MaterializedGlobalTemporaryMap.insert({E, nullptr});
5699   if (!InsertResult.second) {
5700     // We've seen this before: either we already created it or we're in the
5701     // process of doing so.
5702     if (!InsertResult.first->second) {
5703       // We recursively re-entered this function, probably during emission of
5704       // the initializer. Create a placeholder. We'll clean this up in the
5705       // outer call, at the end of this function.
5706       llvm::Type *Type = getTypes().ConvertTypeForMem(MaterializedType);
5707       InsertResult.first->second = new llvm::GlobalVariable(
5708           getModule(), Type, false, llvm::GlobalVariable::InternalLinkage,
5709           nullptr);
5710     }
5711     return ConstantAddress(InsertResult.first->second,
5712                            llvm::cast<llvm::GlobalVariable>(
5713                                InsertResult.first->second->stripPointerCasts())
5714                                ->getValueType(),
5715                            Align);
5716   }
5717 
5718   // FIXME: If an externally-visible declaration extends multiple temporaries,
5719   // we need to give each temporary the same name in every translation unit (and
5720   // we also need to make the temporaries externally-visible).
5721   SmallString<256> Name;
5722   llvm::raw_svector_ostream Out(Name);
5723   getCXXABI().getMangleContext().mangleReferenceTemporary(
5724       VD, E->getManglingNumber(), Out);
5725 
5726   APValue *Value = nullptr;
5727   if (E->getStorageDuration() == SD_Static && VD && VD->evaluateValue()) {
5728     // If the initializer of the extending declaration is a constant
5729     // initializer, we should have a cached constant initializer for this
5730     // temporary. Note that this might have a different value from the value
5731     // computed by evaluating the initializer if the surrounding constant
5732     // expression modifies the temporary.
5733     Value = E->getOrCreateValue(false);
5734   }
5735 
5736   // Try evaluating it now, it might have a constant initializer.
5737   Expr::EvalResult EvalResult;
5738   if (!Value && Init->EvaluateAsRValue(EvalResult, getContext()) &&
5739       !EvalResult.hasSideEffects())
5740     Value = &EvalResult.Val;
5741 
5742   LangAS AddrSpace =
5743       VD ? GetGlobalVarAddressSpace(VD) : MaterializedType.getAddressSpace();
5744 
5745   Optional<ConstantEmitter> emitter;
5746   llvm::Constant *InitialValue = nullptr;
5747   bool Constant = false;
5748   llvm::Type *Type;
5749   if (Value) {
5750     // The temporary has a constant initializer, use it.
5751     emitter.emplace(*this);
5752     InitialValue = emitter->emitForInitializer(*Value, AddrSpace,
5753                                                MaterializedType);
5754     Constant = isTypeConstant(MaterializedType, /*ExcludeCtor*/Value);
5755     Type = InitialValue->getType();
5756   } else {
5757     // No initializer, the initialization will be provided when we
5758     // initialize the declaration which performed lifetime extension.
5759     Type = getTypes().ConvertTypeForMem(MaterializedType);
5760   }
5761 
5762   // Create a global variable for this lifetime-extended temporary.
5763   llvm::GlobalValue::LinkageTypes Linkage =
5764       getLLVMLinkageVarDefinition(VD, Constant);
5765   if (Linkage == llvm::GlobalVariable::ExternalLinkage) {
5766     const VarDecl *InitVD;
5767     if (VD->isStaticDataMember() && VD->getAnyInitializer(InitVD) &&
5768         isa<CXXRecordDecl>(InitVD->getLexicalDeclContext())) {
5769       // Temporaries defined inside a class get linkonce_odr linkage because the
5770       // class can be defined in multiple translation units.
5771       Linkage = llvm::GlobalVariable::LinkOnceODRLinkage;
5772     } else {
5773       // There is no need for this temporary to have external linkage if the
5774       // VarDecl has external linkage.
5775       Linkage = llvm::GlobalVariable::InternalLinkage;
5776     }
5777   }
5778   auto TargetAS = getContext().getTargetAddressSpace(AddrSpace);
5779   auto *GV = new llvm::GlobalVariable(
5780       getModule(), Type, Constant, Linkage, InitialValue, Name.c_str(),
5781       /*InsertBefore=*/nullptr, llvm::GlobalVariable::NotThreadLocal, TargetAS);
5782   if (emitter) emitter->finalize(GV);
5783   setGVProperties(GV, VD);
5784   if (GV->getDLLStorageClass() == llvm::GlobalVariable::DLLExportStorageClass)
5785     // The reference temporary should never be dllexport.
5786     GV->setDLLStorageClass(llvm::GlobalVariable::DefaultStorageClass);
5787   GV->setAlignment(Align.getAsAlign());
5788   if (supportsCOMDAT() && GV->isWeakForLinker())
5789     GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
5790   if (VD->getTLSKind())
5791     setTLSMode(GV, *VD);
5792   llvm::Constant *CV = GV;
5793   if (AddrSpace != LangAS::Default)
5794     CV = getTargetCodeGenInfo().performAddrSpaceCast(
5795         *this, GV, AddrSpace, LangAS::Default,
5796         Type->getPointerTo(
5797             getContext().getTargetAddressSpace(LangAS::Default)));
5798 
5799   // Update the map with the new temporary. If we created a placeholder above,
5800   // replace it with the new global now.
5801   llvm::Constant *&Entry = MaterializedGlobalTemporaryMap[E];
5802   if (Entry) {
5803     Entry->replaceAllUsesWith(
5804         llvm::ConstantExpr::getBitCast(CV, Entry->getType()));
5805     llvm::cast<llvm::GlobalVariable>(Entry)->eraseFromParent();
5806   }
5807   Entry = CV;
5808 
5809   return ConstantAddress(CV, Type, Align);
5810 }
5811 
5812 /// EmitObjCPropertyImplementations - Emit information for synthesized
5813 /// properties for an implementation.
5814 void CodeGenModule::EmitObjCPropertyImplementations(const
5815                                                     ObjCImplementationDecl *D) {
5816   for (const auto *PID : D->property_impls()) {
5817     // Dynamic is just for type-checking.
5818     if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
5819       ObjCPropertyDecl *PD = PID->getPropertyDecl();
5820 
5821       // Determine which methods need to be implemented, some may have
5822       // been overridden. Note that ::isPropertyAccessor is not the method
5823       // we want, that just indicates if the decl came from a
5824       // property. What we want to know is if the method is defined in
5825       // this implementation.
5826       auto *Getter = PID->getGetterMethodDecl();
5827       if (!Getter || Getter->isSynthesizedAccessorStub())
5828         CodeGenFunction(*this).GenerateObjCGetter(
5829             const_cast<ObjCImplementationDecl *>(D), PID);
5830       auto *Setter = PID->getSetterMethodDecl();
5831       if (!PD->isReadOnly() && (!Setter || Setter->isSynthesizedAccessorStub()))
5832         CodeGenFunction(*this).GenerateObjCSetter(
5833                                  const_cast<ObjCImplementationDecl *>(D), PID);
5834     }
5835   }
5836 }
5837 
5838 static bool needsDestructMethod(ObjCImplementationDecl *impl) {
5839   const ObjCInterfaceDecl *iface = impl->getClassInterface();
5840   for (const ObjCIvarDecl *ivar = iface->all_declared_ivar_begin();
5841        ivar; ivar = ivar->getNextIvar())
5842     if (ivar->getType().isDestructedType())
5843       return true;
5844 
5845   return false;
5846 }
5847 
5848 static bool AllTrivialInitializers(CodeGenModule &CGM,
5849                                    ObjCImplementationDecl *D) {
5850   CodeGenFunction CGF(CGM);
5851   for (ObjCImplementationDecl::init_iterator B = D->init_begin(),
5852        E = D->init_end(); B != E; ++B) {
5853     CXXCtorInitializer *CtorInitExp = *B;
5854     Expr *Init = CtorInitExp->getInit();
5855     if (!CGF.isTrivialInitializer(Init))
5856       return false;
5857   }
5858   return true;
5859 }
5860 
5861 /// EmitObjCIvarInitializations - Emit information for ivar initialization
5862 /// for an implementation.
5863 void CodeGenModule::EmitObjCIvarInitializations(ObjCImplementationDecl *D) {
5864   // We might need a .cxx_destruct even if we don't have any ivar initializers.
5865   if (needsDestructMethod(D)) {
5866     IdentifierInfo *II = &getContext().Idents.get(".cxx_destruct");
5867     Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
5868     ObjCMethodDecl *DTORMethod = ObjCMethodDecl::Create(
5869         getContext(), D->getLocation(), D->getLocation(), cxxSelector,
5870         getContext().VoidTy, nullptr, D,
5871         /*isInstance=*/true, /*isVariadic=*/false,
5872         /*isPropertyAccessor=*/true, /*isSynthesizedAccessorStub=*/false,
5873         /*isImplicitlyDeclared=*/true,
5874         /*isDefined=*/false, ObjCMethodDecl::Required);
5875     D->addInstanceMethod(DTORMethod);
5876     CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, DTORMethod, false);
5877     D->setHasDestructors(true);
5878   }
5879 
5880   // If the implementation doesn't have any ivar initializers, we don't need
5881   // a .cxx_construct.
5882   if (D->getNumIvarInitializers() == 0 ||
5883       AllTrivialInitializers(*this, D))
5884     return;
5885 
5886   IdentifierInfo *II = &getContext().Idents.get(".cxx_construct");
5887   Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
5888   // The constructor returns 'self'.
5889   ObjCMethodDecl *CTORMethod = ObjCMethodDecl::Create(
5890       getContext(), D->getLocation(), D->getLocation(), cxxSelector,
5891       getContext().getObjCIdType(), nullptr, D, /*isInstance=*/true,
5892       /*isVariadic=*/false,
5893       /*isPropertyAccessor=*/true, /*isSynthesizedAccessorStub=*/false,
5894       /*isImplicitlyDeclared=*/true,
5895       /*isDefined=*/false, ObjCMethodDecl::Required);
5896   D->addInstanceMethod(CTORMethod);
5897   CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, CTORMethod, true);
5898   D->setHasNonZeroConstructors(true);
5899 }
5900 
5901 // EmitLinkageSpec - Emit all declarations in a linkage spec.
5902 void CodeGenModule::EmitLinkageSpec(const LinkageSpecDecl *LSD) {
5903   if (LSD->getLanguage() != LinkageSpecDecl::lang_c &&
5904       LSD->getLanguage() != LinkageSpecDecl::lang_cxx) {
5905     ErrorUnsupported(LSD, "linkage spec");
5906     return;
5907   }
5908 
5909   EmitDeclContext(LSD);
5910 }
5911 
5912 void CodeGenModule::EmitDeclContext(const DeclContext *DC) {
5913   for (auto *I : DC->decls()) {
5914     // Unlike other DeclContexts, the contents of an ObjCImplDecl at TU scope
5915     // are themselves considered "top-level", so EmitTopLevelDecl on an
5916     // ObjCImplDecl does not recursively visit them. We need to do that in
5917     // case they're nested inside another construct (LinkageSpecDecl /
5918     // ExportDecl) that does stop them from being considered "top-level".
5919     if (auto *OID = dyn_cast<ObjCImplDecl>(I)) {
5920       for (auto *M : OID->methods())
5921         EmitTopLevelDecl(M);
5922     }
5923 
5924     EmitTopLevelDecl(I);
5925   }
5926 }
5927 
5928 /// EmitTopLevelDecl - Emit code for a single top level declaration.
5929 void CodeGenModule::EmitTopLevelDecl(Decl *D) {
5930   // Ignore dependent declarations.
5931   if (D->isTemplated())
5932     return;
5933 
5934   // Consteval function shouldn't be emitted.
5935   if (auto *FD = dyn_cast<FunctionDecl>(D))
5936     if (FD->isConsteval())
5937       return;
5938 
5939   switch (D->getKind()) {
5940   case Decl::CXXConversion:
5941   case Decl::CXXMethod:
5942   case Decl::Function:
5943     EmitGlobal(cast<FunctionDecl>(D));
5944     // Always provide some coverage mapping
5945     // even for the functions that aren't emitted.
5946     AddDeferredUnusedCoverageMapping(D);
5947     break;
5948 
5949   case Decl::CXXDeductionGuide:
5950     // Function-like, but does not result in code emission.
5951     break;
5952 
5953   case Decl::Var:
5954   case Decl::Decomposition:
5955   case Decl::VarTemplateSpecialization:
5956     EmitGlobal(cast<VarDecl>(D));
5957     if (auto *DD = dyn_cast<DecompositionDecl>(D))
5958       for (auto *B : DD->bindings())
5959         if (auto *HD = B->getHoldingVar())
5960           EmitGlobal(HD);
5961     break;
5962 
5963   // Indirect fields from global anonymous structs and unions can be
5964   // ignored; only the actual variable requires IR gen support.
5965   case Decl::IndirectField:
5966     break;
5967 
5968   // C++ Decls
5969   case Decl::Namespace:
5970     EmitDeclContext(cast<NamespaceDecl>(D));
5971     break;
5972   case Decl::ClassTemplateSpecialization: {
5973     const auto *Spec = cast<ClassTemplateSpecializationDecl>(D);
5974     if (CGDebugInfo *DI = getModuleDebugInfo())
5975       if (Spec->getSpecializationKind() ==
5976               TSK_ExplicitInstantiationDefinition &&
5977           Spec->hasDefinition())
5978         DI->completeTemplateDefinition(*Spec);
5979   } LLVM_FALLTHROUGH;
5980   case Decl::CXXRecord: {
5981     CXXRecordDecl *CRD = cast<CXXRecordDecl>(D);
5982     if (CGDebugInfo *DI = getModuleDebugInfo()) {
5983       if (CRD->hasDefinition())
5984         DI->EmitAndRetainType(getContext().getRecordType(cast<RecordDecl>(D)));
5985       if (auto *ES = D->getASTContext().getExternalSource())
5986         if (ES->hasExternalDefinitions(D) == ExternalASTSource::EK_Never)
5987           DI->completeUnusedClass(*CRD);
5988     }
5989     // Emit any static data members, they may be definitions.
5990     for (auto *I : CRD->decls())
5991       if (isa<VarDecl>(I) || isa<CXXRecordDecl>(I))
5992         EmitTopLevelDecl(I);
5993     break;
5994   }
5995     // No code generation needed.
5996   case Decl::UsingShadow:
5997   case Decl::ClassTemplate:
5998   case Decl::VarTemplate:
5999   case Decl::Concept:
6000   case Decl::VarTemplatePartialSpecialization:
6001   case Decl::FunctionTemplate:
6002   case Decl::TypeAliasTemplate:
6003   case Decl::Block:
6004   case Decl::Empty:
6005   case Decl::Binding:
6006     break;
6007   case Decl::Using:          // using X; [C++]
6008     if (CGDebugInfo *DI = getModuleDebugInfo())
6009         DI->EmitUsingDecl(cast<UsingDecl>(*D));
6010     break;
6011   case Decl::UsingEnum: // using enum X; [C++]
6012     if (CGDebugInfo *DI = getModuleDebugInfo())
6013       DI->EmitUsingEnumDecl(cast<UsingEnumDecl>(*D));
6014     break;
6015   case Decl::NamespaceAlias:
6016     if (CGDebugInfo *DI = getModuleDebugInfo())
6017         DI->EmitNamespaceAlias(cast<NamespaceAliasDecl>(*D));
6018     break;
6019   case Decl::UsingDirective: // using namespace X; [C++]
6020     if (CGDebugInfo *DI = getModuleDebugInfo())
6021       DI->EmitUsingDirective(cast<UsingDirectiveDecl>(*D));
6022     break;
6023   case Decl::CXXConstructor:
6024     getCXXABI().EmitCXXConstructors(cast<CXXConstructorDecl>(D));
6025     break;
6026   case Decl::CXXDestructor:
6027     getCXXABI().EmitCXXDestructors(cast<CXXDestructorDecl>(D));
6028     break;
6029 
6030   case Decl::StaticAssert:
6031     // Nothing to do.
6032     break;
6033 
6034   // Objective-C Decls
6035 
6036   // Forward declarations, no (immediate) code generation.
6037   case Decl::ObjCInterface:
6038   case Decl::ObjCCategory:
6039     break;
6040 
6041   case Decl::ObjCProtocol: {
6042     auto *Proto = cast<ObjCProtocolDecl>(D);
6043     if (Proto->isThisDeclarationADefinition())
6044       ObjCRuntime->GenerateProtocol(Proto);
6045     break;
6046   }
6047 
6048   case Decl::ObjCCategoryImpl:
6049     // Categories have properties but don't support synthesize so we
6050     // can ignore them here.
6051     ObjCRuntime->GenerateCategory(cast<ObjCCategoryImplDecl>(D));
6052     break;
6053 
6054   case Decl::ObjCImplementation: {
6055     auto *OMD = cast<ObjCImplementationDecl>(D);
6056     EmitObjCPropertyImplementations(OMD);
6057     EmitObjCIvarInitializations(OMD);
6058     ObjCRuntime->GenerateClass(OMD);
6059     // Emit global variable debug information.
6060     if (CGDebugInfo *DI = getModuleDebugInfo())
6061       if (getCodeGenOpts().hasReducedDebugInfo())
6062         DI->getOrCreateInterfaceType(getContext().getObjCInterfaceType(
6063             OMD->getClassInterface()), OMD->getLocation());
6064     break;
6065   }
6066   case Decl::ObjCMethod: {
6067     auto *OMD = cast<ObjCMethodDecl>(D);
6068     // If this is not a prototype, emit the body.
6069     if (OMD->getBody())
6070       CodeGenFunction(*this).GenerateObjCMethod(OMD);
6071     break;
6072   }
6073   case Decl::ObjCCompatibleAlias:
6074     ObjCRuntime->RegisterAlias(cast<ObjCCompatibleAliasDecl>(D));
6075     break;
6076 
6077   case Decl::PragmaComment: {
6078     const auto *PCD = cast<PragmaCommentDecl>(D);
6079     switch (PCD->getCommentKind()) {
6080     case PCK_Unknown:
6081       llvm_unreachable("unexpected pragma comment kind");
6082     case PCK_Linker:
6083       AppendLinkerOptions(PCD->getArg());
6084       break;
6085     case PCK_Lib:
6086         AddDependentLib(PCD->getArg());
6087       break;
6088     case PCK_Compiler:
6089     case PCK_ExeStr:
6090     case PCK_User:
6091       break; // We ignore all of these.
6092     }
6093     break;
6094   }
6095 
6096   case Decl::PragmaDetectMismatch: {
6097     const auto *PDMD = cast<PragmaDetectMismatchDecl>(D);
6098     AddDetectMismatch(PDMD->getName(), PDMD->getValue());
6099     break;
6100   }
6101 
6102   case Decl::LinkageSpec:
6103     EmitLinkageSpec(cast<LinkageSpecDecl>(D));
6104     break;
6105 
6106   case Decl::FileScopeAsm: {
6107     // File-scope asm is ignored during device-side CUDA compilation.
6108     if (LangOpts.CUDA && LangOpts.CUDAIsDevice)
6109       break;
6110     // File-scope asm is ignored during device-side OpenMP compilation.
6111     if (LangOpts.OpenMPIsDevice)
6112       break;
6113     // File-scope asm is ignored during device-side SYCL compilation.
6114     if (LangOpts.SYCLIsDevice)
6115       break;
6116     auto *AD = cast<FileScopeAsmDecl>(D);
6117     getModule().appendModuleInlineAsm(AD->getAsmString()->getString());
6118     break;
6119   }
6120 
6121   case Decl::Import: {
6122     auto *Import = cast<ImportDecl>(D);
6123 
6124     // If we've already imported this module, we're done.
6125     if (!ImportedModules.insert(Import->getImportedModule()))
6126       break;
6127 
6128     // Emit debug information for direct imports.
6129     if (!Import->getImportedOwningModule()) {
6130       if (CGDebugInfo *DI = getModuleDebugInfo())
6131         DI->EmitImportDecl(*Import);
6132     }
6133 
6134     // Find all of the submodules and emit the module initializers.
6135     llvm::SmallPtrSet<clang::Module *, 16> Visited;
6136     SmallVector<clang::Module *, 16> Stack;
6137     Visited.insert(Import->getImportedModule());
6138     Stack.push_back(Import->getImportedModule());
6139 
6140     while (!Stack.empty()) {
6141       clang::Module *Mod = Stack.pop_back_val();
6142       if (!EmittedModuleInitializers.insert(Mod).second)
6143         continue;
6144 
6145       for (auto *D : Context.getModuleInitializers(Mod))
6146         EmitTopLevelDecl(D);
6147 
6148       // Visit the submodules of this module.
6149       for (clang::Module::submodule_iterator Sub = Mod->submodule_begin(),
6150                                              SubEnd = Mod->submodule_end();
6151            Sub != SubEnd; ++Sub) {
6152         // Skip explicit children; they need to be explicitly imported to emit
6153         // the initializers.
6154         if ((*Sub)->IsExplicit)
6155           continue;
6156 
6157         if (Visited.insert(*Sub).second)
6158           Stack.push_back(*Sub);
6159       }
6160     }
6161     break;
6162   }
6163 
6164   case Decl::Export:
6165     EmitDeclContext(cast<ExportDecl>(D));
6166     break;
6167 
6168   case Decl::OMPThreadPrivate:
6169     EmitOMPThreadPrivateDecl(cast<OMPThreadPrivateDecl>(D));
6170     break;
6171 
6172   case Decl::OMPAllocate:
6173     EmitOMPAllocateDecl(cast<OMPAllocateDecl>(D));
6174     break;
6175 
6176   case Decl::OMPDeclareReduction:
6177     EmitOMPDeclareReduction(cast<OMPDeclareReductionDecl>(D));
6178     break;
6179 
6180   case Decl::OMPDeclareMapper:
6181     EmitOMPDeclareMapper(cast<OMPDeclareMapperDecl>(D));
6182     break;
6183 
6184   case Decl::OMPRequires:
6185     EmitOMPRequiresDecl(cast<OMPRequiresDecl>(D));
6186     break;
6187 
6188   case Decl::Typedef:
6189   case Decl::TypeAlias: // using foo = bar; [C++11]
6190     if (CGDebugInfo *DI = getModuleDebugInfo())
6191       DI->EmitAndRetainType(
6192           getContext().getTypedefType(cast<TypedefNameDecl>(D)));
6193     break;
6194 
6195   case Decl::Record:
6196     if (CGDebugInfo *DI = getModuleDebugInfo())
6197       if (cast<RecordDecl>(D)->getDefinition())
6198         DI->EmitAndRetainType(getContext().getRecordType(cast<RecordDecl>(D)));
6199     break;
6200 
6201   case Decl::Enum:
6202     if (CGDebugInfo *DI = getModuleDebugInfo())
6203       if (cast<EnumDecl>(D)->getDefinition())
6204         DI->EmitAndRetainType(getContext().getEnumType(cast<EnumDecl>(D)));
6205     break;
6206 
6207   default:
6208     // Make sure we handled everything we should, every other kind is a
6209     // non-top-level decl.  FIXME: Would be nice to have an isTopLevelDeclKind
6210     // function. Need to recode Decl::Kind to do that easily.
6211     assert(isa<TypeDecl>(D) && "Unsupported decl kind");
6212     break;
6213   }
6214 }
6215 
6216 void CodeGenModule::AddDeferredUnusedCoverageMapping(Decl *D) {
6217   // Do we need to generate coverage mapping?
6218   if (!CodeGenOpts.CoverageMapping)
6219     return;
6220   switch (D->getKind()) {
6221   case Decl::CXXConversion:
6222   case Decl::CXXMethod:
6223   case Decl::Function:
6224   case Decl::ObjCMethod:
6225   case Decl::CXXConstructor:
6226   case Decl::CXXDestructor: {
6227     if (!cast<FunctionDecl>(D)->doesThisDeclarationHaveABody())
6228       break;
6229     SourceManager &SM = getContext().getSourceManager();
6230     if (LimitedCoverage && SM.getMainFileID() != SM.getFileID(D->getBeginLoc()))
6231       break;
6232     auto I = DeferredEmptyCoverageMappingDecls.find(D);
6233     if (I == DeferredEmptyCoverageMappingDecls.end())
6234       DeferredEmptyCoverageMappingDecls[D] = true;
6235     break;
6236   }
6237   default:
6238     break;
6239   };
6240 }
6241 
6242 void CodeGenModule::ClearUnusedCoverageMapping(const Decl *D) {
6243   // Do we need to generate coverage mapping?
6244   if (!CodeGenOpts.CoverageMapping)
6245     return;
6246   if (const auto *Fn = dyn_cast<FunctionDecl>(D)) {
6247     if (Fn->isTemplateInstantiation())
6248       ClearUnusedCoverageMapping(Fn->getTemplateInstantiationPattern());
6249   }
6250   auto I = DeferredEmptyCoverageMappingDecls.find(D);
6251   if (I == DeferredEmptyCoverageMappingDecls.end())
6252     DeferredEmptyCoverageMappingDecls[D] = false;
6253   else
6254     I->second = false;
6255 }
6256 
6257 void CodeGenModule::EmitDeferredUnusedCoverageMappings() {
6258   // We call takeVector() here to avoid use-after-free.
6259   // FIXME: DeferredEmptyCoverageMappingDecls is getting mutated because
6260   // we deserialize function bodies to emit coverage info for them, and that
6261   // deserializes more declarations. How should we handle that case?
6262   for (const auto &Entry : DeferredEmptyCoverageMappingDecls.takeVector()) {
6263     if (!Entry.second)
6264       continue;
6265     const Decl *D = Entry.first;
6266     switch (D->getKind()) {
6267     case Decl::CXXConversion:
6268     case Decl::CXXMethod:
6269     case Decl::Function:
6270     case Decl::ObjCMethod: {
6271       CodeGenPGO PGO(*this);
6272       GlobalDecl GD(cast<FunctionDecl>(D));
6273       PGO.emitEmptyCounterMapping(D, getMangledName(GD),
6274                                   getFunctionLinkage(GD));
6275       break;
6276     }
6277     case Decl::CXXConstructor: {
6278       CodeGenPGO PGO(*this);
6279       GlobalDecl GD(cast<CXXConstructorDecl>(D), Ctor_Base);
6280       PGO.emitEmptyCounterMapping(D, getMangledName(GD),
6281                                   getFunctionLinkage(GD));
6282       break;
6283     }
6284     case Decl::CXXDestructor: {
6285       CodeGenPGO PGO(*this);
6286       GlobalDecl GD(cast<CXXDestructorDecl>(D), Dtor_Base);
6287       PGO.emitEmptyCounterMapping(D, getMangledName(GD),
6288                                   getFunctionLinkage(GD));
6289       break;
6290     }
6291     default:
6292       break;
6293     };
6294   }
6295 }
6296 
6297 void CodeGenModule::EmitMainVoidAlias() {
6298   // In order to transition away from "__original_main" gracefully, emit an
6299   // alias for "main" in the no-argument case so that libc can detect when
6300   // new-style no-argument main is in used.
6301   if (llvm::Function *F = getModule().getFunction("main")) {
6302     if (!F->isDeclaration() && F->arg_size() == 0 && !F->isVarArg() &&
6303         F->getReturnType()->isIntegerTy(Context.getTargetInfo().getIntWidth()))
6304       addUsedGlobal(llvm::GlobalAlias::create("__main_void", F));
6305   }
6306 }
6307 
6308 /// Turns the given pointer into a constant.
6309 static llvm::Constant *GetPointerConstant(llvm::LLVMContext &Context,
6310                                           const void *Ptr) {
6311   uintptr_t PtrInt = reinterpret_cast<uintptr_t>(Ptr);
6312   llvm::Type *i64 = llvm::Type::getInt64Ty(Context);
6313   return llvm::ConstantInt::get(i64, PtrInt);
6314 }
6315 
6316 static void EmitGlobalDeclMetadata(CodeGenModule &CGM,
6317                                    llvm::NamedMDNode *&GlobalMetadata,
6318                                    GlobalDecl D,
6319                                    llvm::GlobalValue *Addr) {
6320   if (!GlobalMetadata)
6321     GlobalMetadata =
6322       CGM.getModule().getOrInsertNamedMetadata("clang.global.decl.ptrs");
6323 
6324   // TODO: should we report variant information for ctors/dtors?
6325   llvm::Metadata *Ops[] = {llvm::ConstantAsMetadata::get(Addr),
6326                            llvm::ConstantAsMetadata::get(GetPointerConstant(
6327                                CGM.getLLVMContext(), D.getDecl()))};
6328   GlobalMetadata->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops));
6329 }
6330 
6331 bool CodeGenModule::CheckAndReplaceExternCIFuncs(llvm::GlobalValue *Elem,
6332                                                  llvm::GlobalValue *CppFunc) {
6333   // Store the list of ifuncs we need to replace uses in.
6334   llvm::SmallVector<llvm::GlobalIFunc *> IFuncs;
6335   // List of ConstantExprs that we should be able to delete when we're done
6336   // here.
6337   llvm::SmallVector<llvm::ConstantExpr *> CEs;
6338 
6339   // First make sure that all users of this are ifuncs (or ifuncs via a
6340   // bitcast), and collect the list of ifuncs and CEs so we can work on them
6341   // later.
6342   for (llvm::User *User : Elem->users()) {
6343     // Users can either be a bitcast ConstExpr that is used by the ifuncs, OR an
6344     // ifunc directly. In any other case, just give up, as we don't know what we
6345     // could break by changing those.
6346     if (auto *ConstExpr = dyn_cast<llvm::ConstantExpr>(User)) {
6347       if (ConstExpr->getOpcode() != llvm::Instruction::BitCast)
6348         return false;
6349 
6350       for (llvm::User *CEUser : ConstExpr->users()) {
6351         if (auto *IFunc = dyn_cast<llvm::GlobalIFunc>(CEUser)) {
6352           IFuncs.push_back(IFunc);
6353         } else {
6354           return false;
6355         }
6356       }
6357       CEs.push_back(ConstExpr);
6358     } else if (auto *IFunc = dyn_cast<llvm::GlobalIFunc>(User)) {
6359       IFuncs.push_back(IFunc);
6360     } else {
6361       // This user is one we don't know how to handle, so fail redirection. This
6362       // will result in an ifunc retaining a resolver name that will ultimately
6363       // fail to be resolved to a defined function.
6364       return false;
6365     }
6366   }
6367 
6368   // Now we know this is a valid case where we can do this alias replacement, we
6369   // need to remove all of the references to Elem (and the bitcasts!) so we can
6370   // delete it.
6371   for (llvm::GlobalIFunc *IFunc : IFuncs)
6372     IFunc->setResolver(nullptr);
6373   for (llvm::ConstantExpr *ConstExpr : CEs)
6374     ConstExpr->destroyConstant();
6375 
6376   // We should now be out of uses for the 'old' version of this function, so we
6377   // can erase it as well.
6378   Elem->eraseFromParent();
6379 
6380   for (llvm::GlobalIFunc *IFunc : IFuncs) {
6381     // The type of the resolver is always just a function-type that returns the
6382     // type of the IFunc, so create that here. If the type of the actual
6383     // resolver doesn't match, it just gets bitcast to the right thing.
6384     auto *ResolverTy =
6385         llvm::FunctionType::get(IFunc->getType(), /*isVarArg*/ false);
6386     llvm::Constant *Resolver = GetOrCreateLLVMFunction(
6387         CppFunc->getName(), ResolverTy, {}, /*ForVTable*/ false);
6388     IFunc->setResolver(Resolver);
6389   }
6390   return true;
6391 }
6392 
6393 /// For each function which is declared within an extern "C" region and marked
6394 /// as 'used', but has internal linkage, create an alias from the unmangled
6395 /// name to the mangled name if possible. People expect to be able to refer
6396 /// to such functions with an unmangled name from inline assembly within the
6397 /// same translation unit.
6398 void CodeGenModule::EmitStaticExternCAliases() {
6399   if (!getTargetCodeGenInfo().shouldEmitStaticExternCAliases())
6400     return;
6401   for (auto &I : StaticExternCValues) {
6402     IdentifierInfo *Name = I.first;
6403     llvm::GlobalValue *Val = I.second;
6404 
6405     // If Val is null, that implies there were multiple declarations that each
6406     // had a claim to the unmangled name. In this case, generation of the alias
6407     // is suppressed. See CodeGenModule::MaybeHandleStaticInExterC.
6408     if (!Val)
6409       break;
6410 
6411     llvm::GlobalValue *ExistingElem =
6412         getModule().getNamedValue(Name->getName());
6413 
6414     // If there is either not something already by this name, or we were able to
6415     // replace all uses from IFuncs, create the alias.
6416     if (!ExistingElem || CheckAndReplaceExternCIFuncs(ExistingElem, Val))
6417       addCompilerUsedGlobal(llvm::GlobalAlias::create(Name->getName(), Val));
6418   }
6419 }
6420 
6421 bool CodeGenModule::lookupRepresentativeDecl(StringRef MangledName,
6422                                              GlobalDecl &Result) const {
6423   auto Res = Manglings.find(MangledName);
6424   if (Res == Manglings.end())
6425     return false;
6426   Result = Res->getValue();
6427   return true;
6428 }
6429 
6430 /// Emits metadata nodes associating all the global values in the
6431 /// current module with the Decls they came from.  This is useful for
6432 /// projects using IR gen as a subroutine.
6433 ///
6434 /// Since there's currently no way to associate an MDNode directly
6435 /// with an llvm::GlobalValue, we create a global named metadata
6436 /// with the name 'clang.global.decl.ptrs'.
6437 void CodeGenModule::EmitDeclMetadata() {
6438   llvm::NamedMDNode *GlobalMetadata = nullptr;
6439 
6440   for (auto &I : MangledDeclNames) {
6441     llvm::GlobalValue *Addr = getModule().getNamedValue(I.second);
6442     // Some mangled names don't necessarily have an associated GlobalValue
6443     // in this module, e.g. if we mangled it for DebugInfo.
6444     if (Addr)
6445       EmitGlobalDeclMetadata(*this, GlobalMetadata, I.first, Addr);
6446   }
6447 }
6448 
6449 /// Emits metadata nodes for all the local variables in the current
6450 /// function.
6451 void CodeGenFunction::EmitDeclMetadata() {
6452   if (LocalDeclMap.empty()) return;
6453 
6454   llvm::LLVMContext &Context = getLLVMContext();
6455 
6456   // Find the unique metadata ID for this name.
6457   unsigned DeclPtrKind = Context.getMDKindID("clang.decl.ptr");
6458 
6459   llvm::NamedMDNode *GlobalMetadata = nullptr;
6460 
6461   for (auto &I : LocalDeclMap) {
6462     const Decl *D = I.first;
6463     llvm::Value *Addr = I.second.getPointer();
6464     if (auto *Alloca = dyn_cast<llvm::AllocaInst>(Addr)) {
6465       llvm::Value *DAddr = GetPointerConstant(getLLVMContext(), D);
6466       Alloca->setMetadata(
6467           DeclPtrKind, llvm::MDNode::get(
6468                            Context, llvm::ValueAsMetadata::getConstant(DAddr)));
6469     } else if (auto *GV = dyn_cast<llvm::GlobalValue>(Addr)) {
6470       GlobalDecl GD = GlobalDecl(cast<VarDecl>(D));
6471       EmitGlobalDeclMetadata(CGM, GlobalMetadata, GD, GV);
6472     }
6473   }
6474 }
6475 
6476 void CodeGenModule::EmitVersionIdentMetadata() {
6477   llvm::NamedMDNode *IdentMetadata =
6478     TheModule.getOrInsertNamedMetadata("llvm.ident");
6479   std::string Version = getClangFullVersion();
6480   llvm::LLVMContext &Ctx = TheModule.getContext();
6481 
6482   llvm::Metadata *IdentNode[] = {llvm::MDString::get(Ctx, Version)};
6483   IdentMetadata->addOperand(llvm::MDNode::get(Ctx, IdentNode));
6484 }
6485 
6486 void CodeGenModule::EmitCommandLineMetadata() {
6487   llvm::NamedMDNode *CommandLineMetadata =
6488     TheModule.getOrInsertNamedMetadata("llvm.commandline");
6489   std::string CommandLine = getCodeGenOpts().RecordCommandLine;
6490   llvm::LLVMContext &Ctx = TheModule.getContext();
6491 
6492   llvm::Metadata *CommandLineNode[] = {llvm::MDString::get(Ctx, CommandLine)};
6493   CommandLineMetadata->addOperand(llvm::MDNode::get(Ctx, CommandLineNode));
6494 }
6495 
6496 void CodeGenModule::EmitCoverageFile() {
6497   if (getCodeGenOpts().CoverageDataFile.empty() &&
6498       getCodeGenOpts().CoverageNotesFile.empty())
6499     return;
6500 
6501   llvm::NamedMDNode *CUNode = TheModule.getNamedMetadata("llvm.dbg.cu");
6502   if (!CUNode)
6503     return;
6504 
6505   llvm::NamedMDNode *GCov = TheModule.getOrInsertNamedMetadata("llvm.gcov");
6506   llvm::LLVMContext &Ctx = TheModule.getContext();
6507   auto *CoverageDataFile =
6508       llvm::MDString::get(Ctx, getCodeGenOpts().CoverageDataFile);
6509   auto *CoverageNotesFile =
6510       llvm::MDString::get(Ctx, getCodeGenOpts().CoverageNotesFile);
6511   for (int i = 0, e = CUNode->getNumOperands(); i != e; ++i) {
6512     llvm::MDNode *CU = CUNode->getOperand(i);
6513     llvm::Metadata *Elts[] = {CoverageNotesFile, CoverageDataFile, CU};
6514     GCov->addOperand(llvm::MDNode::get(Ctx, Elts));
6515   }
6516 }
6517 
6518 llvm::Constant *CodeGenModule::GetAddrOfRTTIDescriptor(QualType Ty,
6519                                                        bool ForEH) {
6520   // Return a bogus pointer if RTTI is disabled, unless it's for EH.
6521   // FIXME: should we even be calling this method if RTTI is disabled
6522   // and it's not for EH?
6523   if ((!ForEH && !getLangOpts().RTTI) || getLangOpts().CUDAIsDevice ||
6524       (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice &&
6525        getTriple().isNVPTX()))
6526     return llvm::Constant::getNullValue(Int8PtrTy);
6527 
6528   if (ForEH && Ty->isObjCObjectPointerType() &&
6529       LangOpts.ObjCRuntime.isGNUFamily())
6530     return ObjCRuntime->GetEHType(Ty);
6531 
6532   return getCXXABI().getAddrOfRTTIDescriptor(Ty);
6533 }
6534 
6535 void CodeGenModule::EmitOMPThreadPrivateDecl(const OMPThreadPrivateDecl *D) {
6536   // Do not emit threadprivates in simd-only mode.
6537   if (LangOpts.OpenMP && LangOpts.OpenMPSimd)
6538     return;
6539   for (auto RefExpr : D->varlists()) {
6540     auto *VD = cast<VarDecl>(cast<DeclRefExpr>(RefExpr)->getDecl());
6541     bool PerformInit =
6542         VD->getAnyInitializer() &&
6543         !VD->getAnyInitializer()->isConstantInitializer(getContext(),
6544                                                         /*ForRef=*/false);
6545 
6546     Address Addr(GetAddrOfGlobalVar(VD),
6547                  getTypes().ConvertTypeForMem(VD->getType()),
6548                  getContext().getDeclAlign(VD));
6549     if (auto InitFunction = getOpenMPRuntime().emitThreadPrivateVarDefinition(
6550             VD, Addr, RefExpr->getBeginLoc(), PerformInit))
6551       CXXGlobalInits.push_back(InitFunction);
6552   }
6553 }
6554 
6555 llvm::Metadata *
6556 CodeGenModule::CreateMetadataIdentifierImpl(QualType T, MetadataTypeMap &Map,
6557                                             StringRef Suffix) {
6558   if (auto *FnType = T->getAs<FunctionProtoType>())
6559     T = getContext().getFunctionType(
6560         FnType->getReturnType(), FnType->getParamTypes(),
6561         FnType->getExtProtoInfo().withExceptionSpec(EST_None));
6562 
6563   llvm::Metadata *&InternalId = Map[T.getCanonicalType()];
6564   if (InternalId)
6565     return InternalId;
6566 
6567   if (isExternallyVisible(T->getLinkage())) {
6568     std::string OutName;
6569     llvm::raw_string_ostream Out(OutName);
6570     getCXXABI().getMangleContext().mangleTypeName(T, Out);
6571     Out << Suffix;
6572 
6573     InternalId = llvm::MDString::get(getLLVMContext(), Out.str());
6574   } else {
6575     InternalId = llvm::MDNode::getDistinct(getLLVMContext(),
6576                                            llvm::ArrayRef<llvm::Metadata *>());
6577   }
6578 
6579   return InternalId;
6580 }
6581 
6582 llvm::Metadata *CodeGenModule::CreateMetadataIdentifierForType(QualType T) {
6583   return CreateMetadataIdentifierImpl(T, MetadataIdMap, "");
6584 }
6585 
6586 llvm::Metadata *
6587 CodeGenModule::CreateMetadataIdentifierForVirtualMemPtrType(QualType T) {
6588   return CreateMetadataIdentifierImpl(T, VirtualMetadataIdMap, ".virtual");
6589 }
6590 
6591 // Generalize pointer types to a void pointer with the qualifiers of the
6592 // originally pointed-to type, e.g. 'const char *' and 'char * const *'
6593 // generalize to 'const void *' while 'char *' and 'const char **' generalize to
6594 // 'void *'.
6595 static QualType GeneralizeType(ASTContext &Ctx, QualType Ty) {
6596   if (!Ty->isPointerType())
6597     return Ty;
6598 
6599   return Ctx.getPointerType(
6600       QualType(Ctx.VoidTy).withCVRQualifiers(
6601           Ty->getPointeeType().getCVRQualifiers()));
6602 }
6603 
6604 // Apply type generalization to a FunctionType's return and argument types
6605 static QualType GeneralizeFunctionType(ASTContext &Ctx, QualType Ty) {
6606   if (auto *FnType = Ty->getAs<FunctionProtoType>()) {
6607     SmallVector<QualType, 8> GeneralizedParams;
6608     for (auto &Param : FnType->param_types())
6609       GeneralizedParams.push_back(GeneralizeType(Ctx, Param));
6610 
6611     return Ctx.getFunctionType(
6612         GeneralizeType(Ctx, FnType->getReturnType()),
6613         GeneralizedParams, FnType->getExtProtoInfo());
6614   }
6615 
6616   if (auto *FnType = Ty->getAs<FunctionNoProtoType>())
6617     return Ctx.getFunctionNoProtoType(
6618         GeneralizeType(Ctx, FnType->getReturnType()));
6619 
6620   llvm_unreachable("Encountered unknown FunctionType");
6621 }
6622 
6623 llvm::Metadata *CodeGenModule::CreateMetadataIdentifierGeneralized(QualType T) {
6624   return CreateMetadataIdentifierImpl(GeneralizeFunctionType(getContext(), T),
6625                                       GeneralizedMetadataIdMap, ".generalized");
6626 }
6627 
6628 /// Returns whether this module needs the "all-vtables" type identifier.
6629 bool CodeGenModule::NeedAllVtablesTypeId() const {
6630   // Returns true if at least one of vtable-based CFI checkers is enabled and
6631   // is not in the trapping mode.
6632   return ((LangOpts.Sanitize.has(SanitizerKind::CFIVCall) &&
6633            !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIVCall)) ||
6634           (LangOpts.Sanitize.has(SanitizerKind::CFINVCall) &&
6635            !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFINVCall)) ||
6636           (LangOpts.Sanitize.has(SanitizerKind::CFIDerivedCast) &&
6637            !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIDerivedCast)) ||
6638           (LangOpts.Sanitize.has(SanitizerKind::CFIUnrelatedCast) &&
6639            !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIUnrelatedCast)));
6640 }
6641 
6642 void CodeGenModule::AddVTableTypeMetadata(llvm::GlobalVariable *VTable,
6643                                           CharUnits Offset,
6644                                           const CXXRecordDecl *RD) {
6645   llvm::Metadata *MD =
6646       CreateMetadataIdentifierForType(QualType(RD->getTypeForDecl(), 0));
6647   VTable->addTypeMetadata(Offset.getQuantity(), MD);
6648 
6649   if (CodeGenOpts.SanitizeCfiCrossDso)
6650     if (auto CrossDsoTypeId = CreateCrossDsoCfiTypeId(MD))
6651       VTable->addTypeMetadata(Offset.getQuantity(),
6652                               llvm::ConstantAsMetadata::get(CrossDsoTypeId));
6653 
6654   if (NeedAllVtablesTypeId()) {
6655     llvm::Metadata *MD = llvm::MDString::get(getLLVMContext(), "all-vtables");
6656     VTable->addTypeMetadata(Offset.getQuantity(), MD);
6657   }
6658 }
6659 
6660 llvm::SanitizerStatReport &CodeGenModule::getSanStats() {
6661   if (!SanStats)
6662     SanStats = std::make_unique<llvm::SanitizerStatReport>(&getModule());
6663 
6664   return *SanStats;
6665 }
6666 
6667 llvm::Value *
6668 CodeGenModule::createOpenCLIntToSamplerConversion(const Expr *E,
6669                                                   CodeGenFunction &CGF) {
6670   llvm::Constant *C = ConstantEmitter(CGF).emitAbstract(E, E->getType());
6671   auto *SamplerT = getOpenCLRuntime().getSamplerType(E->getType().getTypePtr());
6672   auto *FTy = llvm::FunctionType::get(SamplerT, {C->getType()}, false);
6673   auto *Call = CGF.EmitRuntimeCall(
6674       CreateRuntimeFunction(FTy, "__translate_sampler_initializer"), {C});
6675   return Call;
6676 }
6677 
6678 CharUnits CodeGenModule::getNaturalPointeeTypeAlignment(
6679     QualType T, LValueBaseInfo *BaseInfo, TBAAAccessInfo *TBAAInfo) {
6680   return getNaturalTypeAlignment(T->getPointeeType(), BaseInfo, TBAAInfo,
6681                                  /* forPointeeType= */ true);
6682 }
6683 
6684 CharUnits CodeGenModule::getNaturalTypeAlignment(QualType T,
6685                                                  LValueBaseInfo *BaseInfo,
6686                                                  TBAAAccessInfo *TBAAInfo,
6687                                                  bool forPointeeType) {
6688   if (TBAAInfo)
6689     *TBAAInfo = getTBAAAccessInfo(T);
6690 
6691   // FIXME: This duplicates logic in ASTContext::getTypeAlignIfKnown. But
6692   // that doesn't return the information we need to compute BaseInfo.
6693 
6694   // Honor alignment typedef attributes even on incomplete types.
6695   // We also honor them straight for C++ class types, even as pointees;
6696   // there's an expressivity gap here.
6697   if (auto TT = T->getAs<TypedefType>()) {
6698     if (auto Align = TT->getDecl()->getMaxAlignment()) {
6699       if (BaseInfo)
6700         *BaseInfo = LValueBaseInfo(AlignmentSource::AttributedType);
6701       return getContext().toCharUnitsFromBits(Align);
6702     }
6703   }
6704 
6705   bool AlignForArray = T->isArrayType();
6706 
6707   // Analyze the base element type, so we don't get confused by incomplete
6708   // array types.
6709   T = getContext().getBaseElementType(T);
6710 
6711   if (T->isIncompleteType()) {
6712     // We could try to replicate the logic from
6713     // ASTContext::getTypeAlignIfKnown, but nothing uses the alignment if the
6714     // type is incomplete, so it's impossible to test. We could try to reuse
6715     // getTypeAlignIfKnown, but that doesn't return the information we need
6716     // to set BaseInfo.  So just ignore the possibility that the alignment is
6717     // greater than one.
6718     if (BaseInfo)
6719       *BaseInfo = LValueBaseInfo(AlignmentSource::Type);
6720     return CharUnits::One();
6721   }
6722 
6723   if (BaseInfo)
6724     *BaseInfo = LValueBaseInfo(AlignmentSource::Type);
6725 
6726   CharUnits Alignment;
6727   const CXXRecordDecl *RD;
6728   if (T.getQualifiers().hasUnaligned()) {
6729     Alignment = CharUnits::One();
6730   } else if (forPointeeType && !AlignForArray &&
6731              (RD = T->getAsCXXRecordDecl())) {
6732     // For C++ class pointees, we don't know whether we're pointing at a
6733     // base or a complete object, so we generally need to use the
6734     // non-virtual alignment.
6735     Alignment = getClassPointerAlignment(RD);
6736   } else {
6737     Alignment = getContext().getTypeAlignInChars(T);
6738   }
6739 
6740   // Cap to the global maximum type alignment unless the alignment
6741   // was somehow explicit on the type.
6742   if (unsigned MaxAlign = getLangOpts().MaxTypeAlign) {
6743     if (Alignment.getQuantity() > MaxAlign &&
6744         !getContext().isAlignmentRequired(T))
6745       Alignment = CharUnits::fromQuantity(MaxAlign);
6746   }
6747   return Alignment;
6748 }
6749 
6750 bool CodeGenModule::stopAutoInit() {
6751   unsigned StopAfter = getContext().getLangOpts().TrivialAutoVarInitStopAfter;
6752   if (StopAfter) {
6753     // This number is positive only when -ftrivial-auto-var-init-stop-after=* is
6754     // used
6755     if (NumAutoVarInit >= StopAfter) {
6756       return true;
6757     }
6758     if (!NumAutoVarInit) {
6759       unsigned DiagID = getDiags().getCustomDiagID(
6760           DiagnosticsEngine::Warning,
6761           "-ftrivial-auto-var-init-stop-after=%0 has been enabled to limit the "
6762           "number of times ftrivial-auto-var-init=%1 gets applied.");
6763       getDiags().Report(DiagID)
6764           << StopAfter
6765           << (getContext().getLangOpts().getTrivialAutoVarInit() ==
6766                       LangOptions::TrivialAutoVarInitKind::Zero
6767                   ? "zero"
6768                   : "pattern");
6769     }
6770     ++NumAutoVarInit;
6771   }
6772   return false;
6773 }
6774 
6775 void CodeGenModule::printPostfixForExternalizedStaticVar(
6776     llvm::raw_ostream &OS) const {
6777   OS << "__static__" << getContext().getCUIDHash();
6778 }
6779