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