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